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 = "The 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. The 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    // Read before the new record replaces it: the Cloud and account a vault
1152    // map without an origin (or with a Cloud alone) was resolved for (rc3-81).
1153    let previous = store.instance().ok().flatten().map(|own| own.vault_scope());
1154    let record = InstanceRecord {
1155        instance_id: enrollment.instance_id.clone(),
1156        org_id: enrollment.org.id.clone(),
1157        org_name: enrollment.org.name.clone(),
1158        org_kind: enrollment.org.kind.clone(),
1159        company_name: enrollment.org.company.as_ref().map(|c| c.name.clone()),
1160        // rc4-1: the name chosen on the approval page wins over the one sent.
1161        label: enrollment.chosen_label().unwrap_or(label).to_string(),
1162        url: origin.to_string(),
1163        org_salt_id: enrollment.org_salt_id.clone(),
1164        web_url: enrollment
1165            .web_url
1166            .as_deref()
1167            .and_then(|url| super::config::normalize_origin(url).ok()),
1168        enrolled_at: stamp(local_now),
1169    };
1170    // Local Cloud data of another server or team goes before anything of
1171    // this enrolment reads it (3.12.8 account scope).
1172    store.scope_to_enrollment(&record)?;
1173    super::worker::prepare_enrollment(store)?;
1174    // Vaults another Cloud or account resolved are never shown or synced here. It runs
1175    // before the instance record is written: when it fails, the enrollment
1176    // fails, `projects.json` stays as it was (written only when the switch
1177    // is saved whole), and `unenrolled` drops the new lease and keys of a
1178    // machine without an earlier enrollment (`forget(true)`); a retry
1179    // starts the switch again.
1180    super::vault::enter_scope(store.data_dir(), &record.vault_scope(), previous.as_deref())?;
1181    store.write_config(INSTANCE_FILE, &record)?;
1182    // A new enrolment starts a new sharing period (Cloud' `since`): an
1183    // earlier engine-side off no longer bounds it (K2 review 3, NEW-1).
1184    super::metrics_v2::buffer::clear_local_on_since(store.data_dir());
1185    store.remove_config(TOKEN_FILE)?;
1186    store.record_success("enroll", &stamp(verified.service_time(local_now).to_utc()));
1187    Ok(record)
1188}
1189
1190/// A connected instance: its record, verified lease and keys.
1191pub struct Session {
1192    pub store: CloudStore,
1193    pub instance: InstanceRecord,
1194    pub lease: VerifiedLease,
1195    root: [u8; 32],
1196}
1197
1198impl Session {
1199    /// Load and re-verify the local enrollment. `root` is the root key of the
1200    /// origin the instance is enrolled with.
1201    pub fn load(store: CloudStore, root: [u8; 32]) -> Result<Self, CloudError> {
1202        // Scoped: local data of another account is gone before a session
1203        // reads or sends any of it (3.12.8 account scope).
1204        let instance = store.instance()?.ok_or(CloudError::NotConnected)?;
1205        // A revoked instance fails closed here, before any Cloud call.
1206        if let Some(revoked) = super::revoked::recorded(&store, &instance) {
1207            return Err(revoked);
1208        }
1209        // An enrollment from before the machine was managed, with another
1210        // org or Cloud, is not used.
1211        if let Some(refusal) =
1212            super::config::managed_enrollment_refusal(&instance.org_id, &instance.url)
1213        {
1214            return Err(refusal);
1215        }
1216        let lease = load_lease(&store, &root, &instance.instance_id)?;
1217        super::root_cert::check_lease_org(&store, &instance.url, &lease.lease)?;
1218        Ok(Self {
1219            store,
1220            instance,
1221            lease,
1222            root,
1223        })
1224    }
1225
1226    /// The root key the enrollment was verified with.
1227    pub fn root_key(&self) -> &[u8; 32] {
1228        &self.root
1229    }
1230
1231    fn service_now(&self) -> UtcDateTime {
1232        self.lease.service_time(UtcDateTime::now()).to_utc()
1233    }
1234
1235    /// The current access token (minted when needed), for transports that
1236    /// authenticate outside [`CloudClient`] (the bus WebSocket upgrade).
1237    /// `force` mints a new one.
1238    pub fn bearer_token(&self, force: bool) -> Result<zeroize::Zeroizing<String>, CloudError> {
1239        self.access_token(force).map(zeroize::Zeroizing::new)
1240    }
1241
1242    /// An authenticated client, minting an access token when needed.
1243    pub fn client(&self) -> Result<CloudClient, CloudError> {
1244        let token = self.access_token(false)?;
1245        Ok(CloudClient::new(&self.instance.url)?.with_token(&self.instance.instance_id, &token))
1246    }
1247
1248    /// Run `call` with an authenticated client; on 401 mint a new token once.
1249    pub fn with_client<T>(
1250        &self,
1251        call: impl Fn(&CloudClient) -> Result<T, CloudError>,
1252    ) -> Result<T, CloudError> {
1253        let result = match call(&self.client()?) {
1254            Err(CloudError::Unauthorized) => {
1255                let token = self.access_token(true)?;
1256                let client = CloudClient::new(&self.instance.url)?
1257                    .with_token(&self.instance.instance_id, &token);
1258                call(&client)
1259            }
1260            other => other,
1261        };
1262        result.map_err(|e| self.noted(e))
1263    }
1264
1265    /// A revocation answer is recorded (the engine then fails closed) and
1266    /// named with this workspace; a used-up quota holds the paths it counts
1267    /// (`throttle`); a feature's `plan_required` names the lease's plan;
1268    /// any other error passes unchanged.
1269    pub(crate) fn noted(&self, error: CloudError) -> CloudError {
1270        let error = super::revoked::note(&self.store, &self.instance, error)
1271            .with_plan(self.lease.lease.plan);
1272        super::throttle::note_on(&self.store, None, error, lean_ctx_time::UtcDateTime::now())
1273    }
1274
1275    /// An authenticated client for one call that must end by `deadline`,
1276    /// minting the token (if needed) inside the same budget and without the
1277    /// 401 retry of [`Self::with_client`] (C5c, rule 3 exception).
1278    pub fn bounded_client(&self, deadline: std::time::Instant) -> Result<CloudClient, CloudError> {
1279        let left = |what: &str| {
1280            deadline
1281                .checked_duration_since(std::time::Instant::now())
1282                .filter(|d| !d.is_zero())
1283                .ok_or_else(|| CloudError::Offline(format!("{what}: time budget used up")))
1284        };
1285        let mint = CloudClient::bounded(&self.instance.url, left("token")?)?;
1286        let token = self.access_token_via(false, &mint)?;
1287        Ok(CloudClient::bounded(&self.instance.url, left("request")?)?
1288            .with_token(&self.instance.instance_id, &token))
1289    }
1290
1291    /// The token is minted in C0 2.0 like every other request.
1292    fn access_token(&self, force: bool) -> Result<String, CloudError> {
1293        self.access_token_via(force, &CloudClient::new(&self.instance.url)?)
1294    }
1295
1296    fn access_token_via(&self, force: bool, client: &CloudClient) -> Result<String, CloudError> {
1297        let now = self.service_now().timestamp();
1298        if !force
1299            && let Some(cached) = self.store.read_config::<TokenRecord>(TOKEN_FILE)?
1300            && cached.expires_at - TOKEN_REFRESH_MARGIN_SECONDS > now
1301        {
1302            return Ok(cached.access_token);
1303        }
1304        // A 429 of the mint holds every process of this machine (they share
1305        // the instance key and the server's budget, which counts refused
1306        // attempts too): nothing is sent until it ends, a forced or manual
1307        // mint neither.
1308        if let Some(held) = super::throttle::token_hold(&self.store, UtcDateTime::now()) {
1309            return Err(held);
1310        }
1311        let keys = InstanceKeys::load(&self.store)?;
1312        let mut nonce_bytes = [0u8; 18];
1313        getrandom::fill(&mut nonce_bytes).map_err(|e| CloudError::Local(format!("random: {e}")))?;
1314        use base64::Engine as _;
1315        let nonce = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(nonce_bytes);
1316        let assertion = keys.sign_b64(&token_assertion_input(
1317            &self.instance.instance_id,
1318            now,
1319            &nonce,
1320        ));
1321        let request = json!({
1322            "schema": TOKEN_REQUEST_SCHEMA, "iat": now, "nonce": nonce, "assertion": assertion,
1323        });
1324        let path = format!("/instances/{}/token", self.instance.instance_id);
1325        let answer = client.post(&path, &request).map_err(|e| {
1326            super::throttle::note_token_limit(&self.store, self.noted(e), UtcDateTime::now())
1327        })?;
1328        let token: AccessTokenV1 = decode(answer, "access token")?;
1329        token.validate().map_err(protocol("access token"))?;
1330        super::throttle::token_minted(&self.store);
1331        self.store.write_config(
1332            TOKEN_FILE,
1333            &TokenRecord {
1334                access_token: token.access_token.clone(),
1335                expires_at: now + i64::from(token.expires_in),
1336            },
1337        )?;
1338        self.store
1339            .record_success("token", &stamp(self.service_now()));
1340        Ok(token.access_token)
1341    }
1342
1343    /// Renew the lease and persist it; returns the new lease. Asked in C0
1344    /// 2.0 like the enrollment whose lease it replaces, and checked against
1345    /// the key set that holds its `kid` (which also feeds the runtime lease):
1346    /// the stored one, else key set v3, by which a C0 2.x Cloud signs leases
1347    /// once it serves v3, fetched once when it is not stored yet. The key
1348    /// set the lease verified with is stored with it, so every later load
1349    /// re-verifies it the same way.
1350    pub fn renew(&mut self) -> Result<&VerifiedLease, CloudError> {
1351        let path = format!("/instances/{}/lease/renew", self.instance.instance_id);
1352        let body = self.with_client(|client| client.post(&path, &json!({})))?;
1353        let local_now = UtcDateTime::now();
1354        let envelope: CloudLeaseEnvelopeV1 = decode(body, "lease")?;
1355        let stored: Value = self
1356            .store
1357            .read_config(super::state::KEYS_FILE)?
1358            .ok_or(CloudError::NotConnected)?;
1359        let pick = |session: &Self| {
1360            super::lease::renewal_key_set(
1361                &stored,
1362                super::keyset_v3::stored_raw(&session.store).as_ref(),
1363                &session.root,
1364                &envelope.kid,
1365            )
1366        };
1367        let keys_raw = if let Some(raw) = pick(self) {
1368            raw
1369        } else {
1370            super::keyset_v3::refresh(self)?;
1371            pick(self).ok_or_else(|| {
1372                CloudError::Protocol(format!(
1373                    "the renewed lease names key {}, which no verified key set holds",
1374                    envelope.kid
1375                ))
1376            })?
1377        };
1378        let keyset = verify_keyset(&keys_raw, &self.root)?;
1379        let verified = verify_lease(
1380            &envelope,
1381            &keyset,
1382            &self.instance.instance_id,
1383            local_now,
1384            None,
1385        )?;
1386        store_lease(&self.store, &verified, &keys_raw, local_now)?;
1387        self.store
1388            .record_success("lease", &stamp(verified.service_time(local_now).to_utc()));
1389        self.store.record_renew_error(None);
1390        self.lease = verified;
1391        Ok(&self.lease)
1392    }
1393
1394    /// Free the seat in Cloud.
1395    pub fn delete_instance(&self) -> Result<(), CloudError> {
1396        let path = format!("/instances/{}", self.instance.instance_id);
1397        self.with_client(|client| client.delete(&path))
1398    }
1399}
1400
1401/// A session loaded from the enrollment fixture (key set v1) in a fresh
1402/// store, for tests of passes that take a [`Session`] but must send
1403/// nothing. Its origin is never contacted by such a test.
1404#[cfg(test)]
1405pub(crate) fn fixture_session() -> (tempfile::TempDir, Session) {
1406    fixture_session_at("https://cloud.leanctx.com")
1407}
1408
1409/// [`fixture_session`] enrolled with `origin` (a loopback Cloud of a test).
1410#[cfg(test)]
1411pub(crate) fn fixture_session_at(origin: &str) -> (tempfile::TempDir, Session) {
1412    let path = concat!(
1413        env!("CARGO_MANIFEST_DIR"),
1414        "/../lean-ctx-protocol/tests/fixtures/cloud/enrollment.response.json"
1415    );
1416    let raw: Value = serde_json::from_slice(&std::fs::read(path).expect("fixture")).expect("json");
1417    let root = ed25519_dalek::SigningKey::from_bytes(&[0x52; 32])
1418        .verifying_key()
1419        .to_bytes();
1420    let dir = tempfile::tempdir().expect("tempdir");
1421    let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
1422    let enrollment: EnrollmentV1 = decode(raw.clone(), "enrollment").expect("enrollment");
1423    complete_enrollment(
1424        &store,
1425        origin,
1426        &enrollment,
1427        &raw["keys"],
1428        &root,
1429        "studio-mac",
1430        lean_ctx_time::OffsetDateTime::parse_from_rfc3339("2026-10-20T12:00:00Z")
1431            .expect("time")
1432            .to_utc(),
1433    )
1434    .expect("enrolled");
1435    let session = Session::load(store, root).expect("session");
1436    (dir, session)
1437}
1438
1439#[cfg(test)]
1440mod tests {
1441    use super::*;
1442
1443    /// rc3-5: the approval page names the machine from `/device/code`; a
1444    /// label Cloud would refuse is trimmed, cut or dropped, never a 400.
1445    #[test]
1446    fn the_device_code_request_names_the_machine() {
1447        let long = "m".repeat(MAX_INSTANCE_LABEL_CHARS + 9);
1448        for (label, sent) in [
1449            ("  build-host  ", Some("build-host".to_string())),
1450            (long.as_str(), Some("m".repeat(MAX_INSTANCE_LABEL_CHARS))),
1451            ("bad\u{7}label", None),
1452            ("   ", None),
1453        ] {
1454            let (origin, recorded) = fake_cloud((200, fixture("cloud/device_code.response.json")));
1455            let client = CloudClient::new(&origin).unwrap();
1456            start_device_flow(&client, Some(label)).expect("login still starts");
1457            let body = recorded.lock().unwrap()[0].1.clone();
1458            assert_eq!(recorded.lock().unwrap()[0].0, "/v1/device/code");
1459            assert_eq!(body.get("instance_label").cloned(), sent.map(Value::from));
1460        }
1461    }
1462
1463    /// An older Cloud refuses the trial members (`deny_unknown_fields`):
1464    /// `trial_unsupported`, never a silent sign-in; a sign-in's own 400 and
1465    /// every other trial refusal stay what they were.
1466    #[test]
1467    fn trial_request_refused_as_unknown_is_trial_unsupported() {
1468        let refused = || CloudError::Server {
1469            status: 400,
1470            code: "invalid_request".into(),
1471        };
1472        let mapped = trial_refusal(refused(), true, "https://cloud.leanctx.com/");
1473        assert_eq!(
1474            mapped,
1475            CloudError::TrialUnsupported {
1476                origin: "https://cloud.leanctx.com".into()
1477            }
1478        );
1479        assert_eq!(mapped.event_code(), "trial_unsupported");
1480        assert_eq!(
1481            mapped.to_string(),
1482            "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`"
1483        );
1484        // Printed by the terminal and by LeanCTX Code alike.
1485        assert!(!mapped.to_string().contains("app"));
1486        assert_eq!(
1487            trial_refusal(refused(), false, "https://cloud.leanctx.com"),
1488            refused()
1489        );
1490        let offline = CloudError::Offline("reset".into());
1491        assert_eq!(
1492            trial_refusal(offline.clone(), true, "https://cloud.leanctx.com"),
1493            offline
1494        );
1495    }
1496
1497    fn fixture(path: &str) -> Value {
1498        let path = format!(
1499            "{}/crates/lean-ctx-protocol/tests/fixtures/{path}",
1500            concat!(env!("CARGO_MANIFEST_DIR"), "/../..")
1501        );
1502        serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
1503    }
1504
1505    fn at(t: &str) -> UtcDateTime {
1506        lean_ctx_time::OffsetDateTime::parse_from_rfc3339(t)
1507            .unwrap()
1508            .to_utc()
1509    }
1510
1511    /// Enroll `raw` in a fresh store; the directory lives as long as the
1512    /// returned guard.
1513    fn enroll(
1514        raw: &Value,
1515        root: &[u8; 32],
1516    ) -> Result<(tempfile::TempDir, CloudStore, InstanceRecord), CloudError> {
1517        let dir = tempfile::tempdir().unwrap();
1518        let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
1519        let enrollment: EnrollmentV1 = decode(raw.clone(), "enrollment")?;
1520        let record = complete_enrollment(
1521            &store,
1522            "https://cloud.leanctx.com",
1523            &enrollment,
1524            &raw["keys"],
1525            root,
1526            "studio-mac",
1527            at("2026-10-20T12:00:00Z"),
1528        )?;
1529        let lease = load_lease(&store, root, &record.instance_id)?;
1530        assert_eq!(lease.envelope.kid, enrollment.lease.kid);
1531        Ok((dir, store, record))
1532    }
1533
1534    /// rc4-274: in a single-dir layout (a legacy `~/.lean-ctx`, a custom
1535    /// `LEAN_CTX_DATA_DIR`) `<config>/cloud` is `<data>/cloud`. The account
1536    /// scope of the enrolment removes only the data there: the instance key
1537    /// made before the approval, the lease and the key set stay, so the
1538    /// approved connect is connected.
1539    #[test]
1540    fn enrolling_in_a_single_dir_layout_keeps_the_keys_and_the_lease() {
1541        let raw = fixture("cloud/enrollment.response.json");
1542        let root = ed25519_dalek::SigningKey::from_bytes(&[0x52; 32])
1543            .verifying_key()
1544            .to_bytes();
1545        let dir = tempfile::tempdir().unwrap();
1546        let cloud = dir.path().join("cloud");
1547        let store = CloudStore::at(&cloud, &cloud);
1548        let keys = crate::instance_key::InstanceKeys::load_or_create(&store).unwrap();
1549        // Data an older version left without a stamp: another account's.
1550        std::fs::write(cloud.join("projects.json"), b"{\"projects\":{}}").unwrap();
1551        let enrollment: EnrollmentV1 = decode(raw.clone(), "enrollment").unwrap();
1552        let record = complete_enrollment(
1553            &store,
1554            "https://cloud.leanctx.com",
1555            &enrollment,
1556            &raw["keys"],
1557            &root,
1558            "studio-mac",
1559            at("2026-10-20T12:00:00Z"),
1560        )
1561        .unwrap();
1562
1563        assert!(!cloud.join("projects.json").exists(), "the data goes");
1564        let kept = crate::instance_key::InstanceKeys::load(&store).unwrap();
1565        assert_eq!(kept.public_key_b64(), keys.public_key_b64());
1566        assert_eq!(kept.kx_public_key_b64(), keys.kx_public_key_b64());
1567        load_lease(&store, &root, &record.instance_id).unwrap();
1568        assert_eq!(store.instance().unwrap(), Some(record));
1569        assert!(Session::load(store, root).is_ok(), "connected");
1570    }
1571
1572    /// Below Cloud-Protocol 2.1: key set v1, the lease signed by its `kid`.
1573    #[test]
1574    fn an_enrollment_with_key_set_v1_is_verified_and_kept() {
1575        use ed25519_dalek::SigningKey;
1576        let raw = fixture("cloud/enrollment.response.json");
1577        let root = SigningKey::from_bytes(&[0x52; 32])
1578            .verifying_key()
1579            .to_bytes();
1580        let (_dir, _store, record) = enroll(&raw, &root).unwrap();
1581        assert_eq!(record.org_id, "org_acme");
1582        let refused = enroll(&raw, &[7; 32]).expect_err("another root");
1583        assert!(
1584            refused
1585                .to_string()
1586                .contains(super::super::lease::ROOT_MISMATCH)
1587        );
1588    }
1589
1590    /// rc3-81: connect to prod, disconnect keeping local data, connect to
1591    /// staging: the project's prod vault is not shown there (and not
1592    /// synced into). The 3.12.8 account scope removes the local data of
1593    /// the other server at that connect, so a connect back to prod finds
1594    /// nothing of it.
1595    #[test]
1596    fn vault_origin_staging_after_prod_with_keep_local_is_not_shared() {
1597        use crate::vault::{VaultMap, VaultRecord};
1598        use ed25519_dalek::SigningKey;
1599        let raw = fixture("cloud/enrollment.response.json");
1600        let root = SigningKey::from_bytes(&[0x52; 32])
1601            .verifying_key()
1602            .to_bytes();
1603        let enrollment: EnrollmentV1 = decode(raw.clone(), "enrollment").unwrap();
1604        let dir = tempfile::tempdir().unwrap();
1605        let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
1606        let repo = dir.path().join("repo");
1607        std::fs::create_dir_all(&repo).unwrap();
1608        let connect = |origin: &str| {
1609            complete_enrollment(
1610                &store,
1611                origin,
1612                &enrollment,
1613                &raw["keys"],
1614                &root,
1615                "studio-mac",
1616                at("2026-10-20T12:00:00Z"),
1617            )
1618            .unwrap();
1619        };
1620        let shared = || {
1621            VaultMap::load(store.data_dir())
1622                .for_root(&repo.to_string_lossy())
1623                .map(|record| record.vault_id.clone())
1624        };
1625        let prod = "https://cloud.leanctx.com";
1626        connect(prod);
1627        let mut map = VaultMap::load(store.data_dir());
1628        map.vaults.insert(
1629            "s1".into(),
1630            VaultRecord {
1631                vault_id: "vault_prod".into(),
1632                ns: "acme".into(),
1633                name: "payments".into(),
1634                sealed: false,
1635                roots: vec![repo.to_string_lossy().into_owned()],
1636            },
1637        );
1638        map.save(store.data_dir()).unwrap();
1639        assert_eq!(shared().as_deref(), Some("vault_prod"));
1640
1641        store.forget(true).unwrap();
1642        connect("https://cloud-staging.leanctx.com");
1643        assert_eq!(shared(), None, "the prod vault is not shared on staging");
1644        assert!(VaultMap::load(store.data_dir()).vaults.is_empty());
1645
1646        store.forget(true).unwrap();
1647        connect(prod);
1648        assert_eq!(shared(), None, "gone after the switch, also back on prod");
1649        assert!(VaultMap::load(store.data_dir()).vaults.is_empty());
1650    }
1651
1652    /// rc3-81 review M1: connect to `first`, a sync records a vault, a
1653    /// disconnect keeps the local data, then connects follow in `then`
1654    /// order. Returns the vault shown after each of them. `writer_stamps`:
1655    /// the record is written the way the pull resolver writes it (claim
1656    /// under the lock); otherwise unstamped, as an older engine wrote it.
1657    fn vault_after_keep_local(
1658        first: &str,
1659        then: &[&str],
1660        writer_stamps: bool,
1661    ) -> Vec<Option<String>> {
1662        use crate::vault::{VaultMap, VaultRecord, update_map};
1663        use ed25519_dalek::SigningKey;
1664        let raw = fixture("cloud/enrollment.response.json");
1665        let root = SigningKey::from_bytes(&[0x52; 32])
1666            .verifying_key()
1667            .to_bytes();
1668        let enrollment: EnrollmentV1 = decode(raw.clone(), "enrollment").unwrap();
1669        let dir = tempfile::tempdir().unwrap();
1670        let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
1671        let repo = dir.path().join("repo");
1672        std::fs::create_dir_all(&repo).unwrap();
1673        let connect = |origin: &str| {
1674            complete_enrollment(
1675                &store,
1676                origin,
1677                &enrollment,
1678                &raw["keys"],
1679                &root,
1680                "studio-mac",
1681                at("2026-10-20T12:00:00Z"),
1682            )
1683            .unwrap();
1684        };
1685        connect(first);
1686        let record = VaultRecord {
1687            vault_id: "vault_first".into(),
1688            ns: "acme".into(),
1689            name: "payments".into(),
1690            sealed: false,
1691            roots: vec![repo.to_string_lossy().into_owned()],
1692        };
1693        if writer_stamps {
1694            let (claimed, _) = update_map(store.data_dir(), |map| {
1695                let claimed = map.claim(first);
1696                map.vaults.insert("s1".into(), record);
1697                claimed
1698            })
1699            .unwrap();
1700            assert!(claimed);
1701        } else {
1702            let mut map = VaultMap::default();
1703            map.vaults.insert("s1".into(), record);
1704            map.save(store.data_dir()).unwrap();
1705        }
1706        then.iter()
1707            .map(|origin| {
1708                store.forget(true).unwrap();
1709                connect(origin);
1710                VaultMap::load(store.data_dir())
1711                    .for_root(&repo.to_string_lossy())
1712                    .map(|record| record.vault_id.clone())
1713            })
1714            .collect()
1715    }
1716
1717    /// rc3-81 review M1: staging first, then prod. The staging vault is not
1718    /// active on prod (also when the file was written unstamped: the
1719    /// disconnect stamps it). Back on staging it is gone: the 3.12.8
1720    /// account scope removed it at the switch to prod.
1721    #[test]
1722    fn vault_origin_prod_after_staging_with_keep_local_is_not_shared() {
1723        let staging = "https://cloud-staging.leanctx.com";
1724        let prod = "https://cloud.leanctx.com";
1725        for writer_stamps in [true, false] {
1726            assert_eq!(
1727                vault_after_keep_local(staging, &[prod, staging], writer_stamps),
1728                vec![None, None],
1729                "writer_stamps = {writer_stamps}"
1730            );
1731        }
1732    }
1733
1734    /// rc3-81 review M1: a self-hosted Cloud finds its records after a
1735    /// disconnect that keeps local data; the hosted Cloud never shows them,
1736    /// and after that switch they are gone (3.12.8 account scope).
1737    #[test]
1738    fn vault_origin_self_hosted_reconnect_after_keep_local_finds_its_records() {
1739        let own = "https://ctx.example.com";
1740        let prod = "https://cloud.leanctx.com";
1741        for writer_stamps in [true, false] {
1742            assert_eq!(
1743                vault_after_keep_local(own, &[own, prod, own], writer_stamps),
1744                vec![Some("vault_first".to_string()), None, None],
1745                "writer_stamps = {writer_stamps}"
1746            );
1747        }
1748    }
1749
1750    /// Cloud-Protocol 2.1 (`routes/enrollment.for_2x.response.json`): key set
1751    /// v3, verified as every v3 set, and the lease signed by the key of
1752    /// purpose `policy` its `kid` names.
1753    #[test]
1754    fn an_enrollment_with_key_set_v3_is_verified_with_its_policy_key() {
1755        let raw = fixture("cloud-v2/routes/enrollment.for_2x.response.json");
1756        let mut root = [0u8; 32];
1757        hex::decode_to_slice(
1758            fixture("cloud-v2/vectors/signing.vectors.json")["keys"]["root_new"]["public_key_hex"]
1759                .as_str()
1760                .unwrap(),
1761            &mut root,
1762        )
1763        .unwrap();
1764        let (_dir, store, record) = enroll(&raw, &root).unwrap();
1765        assert_eq!(record.org_id, "org_acme");
1766        assert_eq!(raw["lease"]["kid"], "552e43422b3589fa");
1767        let kept: Value = store
1768            .read_config(super::super::state::KEYS_FILE)
1769            .unwrap()
1770            .unwrap();
1771        assert_eq!(kept, raw["keys"], "the v3 set is kept as received");
1772        // Another root, or a lease kid of a key that signs no leases: refused.
1773        assert!(enroll(&raw, &[7; 32]).is_err());
1774        let mut event_kid = raw;
1775        event_kid["lease"]["kid"] = "4fc7bebc302357bd".into();
1776        assert!(enroll(&event_kid, &root).is_err());
1777    }
1778
1779    const TOKEN: &str = "het_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
1780
1781    #[test]
1782    fn an_enrollment_token_is_checked_before_anything_is_sent() {
1783        let token = EnrollmentToken::parse(&format!("  {TOKEN}\r\n")).unwrap();
1784        assert_eq!(
1785            token.expose(),
1786            TOKEN,
1787            "a trailing newline from stdin is dropped"
1788        );
1789        assert!(
1790            EnrollmentToken::parse(&TOKEN.to_ascii_uppercase().replace("HET_", "het_")).is_ok()
1791        );
1792        let short = &TOKEN[..TOKEN.len() - 1];
1793        let not_hex = format!("{}g", &TOKEN[..TOKEN.len() - 1]);
1794        let device_code = TOKEN.replace("het_", "hdc_");
1795        let inner_space = format!("{} {}", &TOKEN[..20], &TOKEN[20..]);
1796        for bad in [
1797            "",
1798            "het_",
1799            short,
1800            &not_hex,
1801            &device_code,
1802            &inner_space,
1803            &format!("{TOKEN}0"),
1804        ] {
1805            let error = EnrollmentToken::parse(bad).expect_err(bad).to_string();
1806            assert!(error.contains("malformed"), "{error}");
1807            assert!(
1808                bad.len() < 8 || !error.contains(bad),
1809                "the value is never echoed: {error}"
1810            );
1811        }
1812        assert_eq!(format!("{token:?}"), "EnrollmentToken(het_…)");
1813    }
1814
1815    type Recorded = std::sync::Arc<std::sync::Mutex<Vec<(String, Value)>>>;
1816
1817    /// A one-route Cloud on 127.0.0.1 that answers every request with
1818    /// `answer` and records what it was sent.
1819    #[allow(clippy::needless_pass_by_value)] // callers hand over a fresh `json!`
1820    fn fake_cloud(answer: (u16, Value)) -> (String, Recorded) {
1821        let (status, body) = answer;
1822        let raw = raw_answer(
1823            status,
1824            "Content-Type: application/json\r\n",
1825            &body.to_string(),
1826        );
1827        scripted_cloud(vec![raw])
1828    }
1829
1830    /// A raw HTTP answer: status, extra header lines and body.
1831    fn raw_answer(status: u16, headers: &str, body: &str) -> String {
1832        format!(
1833            "HTTP/1.1 {status} X\r\n{headers}Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
1834            body.len()
1835        )
1836    }
1837
1838    /// A Cloud on 127.0.0.1 that answers the n-th request with the n-th raw
1839    /// HTTP answer (the last one repeats) and records what it was sent.
1840    fn scripted_cloud(answers: Vec<String>) -> (String, Recorded) {
1841        use std::io::{BufRead as _, Read as _, Write as _};
1842        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1843        let origin = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());
1844        let recorded: Recorded = std::sync::Arc::default();
1845        let seen = std::sync::Arc::clone(&recorded);
1846        std::thread::spawn(move || {
1847            for stream in listener.incoming().flatten() {
1848                let mut writer = stream.try_clone().unwrap();
1849                let mut reader = std::io::BufReader::new(stream);
1850                let mut line = String::new();
1851                if reader.read_line(&mut line).unwrap_or(0) == 0 {
1852                    continue;
1853                }
1854                let path = line
1855                    .split_whitespace()
1856                    .nth(1)
1857                    .unwrap_or_default()
1858                    .to_owned();
1859                let mut length = 0;
1860                loop {
1861                    let mut header = String::new();
1862                    reader.read_line(&mut header).unwrap();
1863                    let header = header.trim_end();
1864                    if header.is_empty() {
1865                        break;
1866                    }
1867                    if let Some((name, value)) = header.split_once(':')
1868                        && name.eq_ignore_ascii_case("content-length")
1869                    {
1870                        length = value.trim().parse().unwrap();
1871                    }
1872                }
1873                let mut body = vec![0; length];
1874                reader.read_exact(&mut body).unwrap();
1875                let body = serde_json::from_slice(&body).unwrap_or(Value::Null);
1876                let n = {
1877                    let mut seen = seen.lock().unwrap();
1878                    seen.push((path, body));
1879                    seen.len() - 1
1880                };
1881                let raw = &answers[n.min(answers.len() - 1)];
1882                let _ = writer.write_all(raw.as_bytes());
1883            }
1884        });
1885        (origin, recorded)
1886    }
1887
1888    fn device_code(interval: u32, expires_in: u32) -> DeviceCodeV1 {
1889        DeviceCodeV1 {
1890            schema: lean_ctx_protocol::cloud::enroll::DEVICE_CODE_SCHEMA.into(),
1891            device_code: "hdc_test".into(),
1892            user_code: "WDJB-MJHT".into(),
1893            verification_uri: "https://cloud.example.com/device".into(),
1894            verification_uri_complete: "https://cloud.example.com/device?c=WDJB-MJHT".into(),
1895            interval,
1896            expires_in,
1897            features: Vec::new(),
1898            intent: None,
1899            plan: None,
1900        }
1901    }
1902
1903    const EDGE_502: &str = "<html><body><h1>502 Bad Gateway</h1></body></html>";
1904
1905    /// Review fix: an edge error page (502/503 HTML, 429 with only a
1906    /// `Retry-After` header) or a refused connection does not end the
1907    /// device flow; the poll waits (`Retry-After`, else backoff) and goes
1908    /// on, `slow_down` raises the interval, `access_denied` ends it.
1909    #[test]
1910    fn the_device_flow_rides_out_transient_failures_until_a_final_answer() {
1911        let json = "Content-Type: application/json\r\n";
1912        let html = "Content-Type: text/html\r\n";
1913        let (origin, recorded) = scripted_cloud(vec![
1914            raw_answer(502, html, EDGE_502),
1915            raw_answer(
1916                429,
1917                &format!("{html}Retry-After: 30\r\n"),
1918                "Too Many Requests",
1919            ),
1920            raw_answer(503, html, ""),
1921            raw_answer(
1922                400,
1923                json,
1924                r#"{"error":{"code":"authorization_pending","message":"x"}}"#,
1925            ),
1926            raw_answer(400, json, r#"{"error":{"code":"slow_down","message":"x"}}"#),
1927            raw_answer(
1928                400,
1929                json,
1930                r#"{"error":{"code":"access_denied","message":"x"}}"#,
1931            ),
1932        ]);
1933        let dir = tempfile::tempdir().unwrap();
1934        let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
1935        let client = CloudClient::new(&origin).unwrap();
1936        let sleeps = std::cell::RefCell::new(Vec::new());
1937        let error = finish_device_flow(
1938            &store,
1939            &client,
1940            &device_code(2, 600),
1941            "studio-mac",
1942            &[7; 32],
1943            &|d| sleeps.borrow_mut().push(d.as_secs()),
1944        )
1945        .expect_err("denied");
1946        assert!(matches!(error, CloudError::DeviceFlow(_)), "{error:?}");
1947        assert!(error.to_string().contains("Not mine"), "{error}");
1948        assert_eq!(recorded.lock().unwrap().len(), 6);
1949        // interval 2; 502 → 4 (backoff); 429 → its Retry-After 30; 503 →
1950        // 16 (third failure in a row); pending → 2; slow_down → 2 + 5.
1951        assert_eq!(sleeps.into_inner(), vec![2, 4, 30, 16, 2, 7]);
1952        assert!(store.instance().unwrap().is_none(), "nothing enrolled");
1953    }
1954
1955    #[test]
1956    fn transient_failures_end_the_device_flow_only_at_its_deadline() {
1957        let (origin, recorded) = scripted_cloud(vec![raw_answer(
1958            503,
1959            "Content-Type: text/html\r\n",
1960            EDGE_502,
1961        )]);
1962        let dir = tempfile::tempdir().unwrap();
1963        let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
1964        let client = CloudClient::new(&origin).unwrap();
1965        let sleeps = std::cell::RefCell::new(Vec::new());
1966        let error = finish_device_flow(
1967            &store,
1968            &client,
1969            &device_code(5, 120),
1970            "studio-mac",
1971            &[7; 32],
1972            &|d| sleeps.borrow_mut().push(d.as_secs()),
1973        )
1974        .expect_err("expired");
1975        assert_eq!(
1976            error,
1977            CloudError::DeviceFlow(super::super::error::CODE_EXPIRED.into())
1978        );
1979        let sleeps = sleeps.into_inner();
1980        assert_eq!(sleeps.iter().sum::<u64>(), 120, "{sleeps:?}");
1981        assert!(sleeps.iter().all(|s| *s <= DEVICE_POLL_BACKOFF_CAP_S));
1982        assert_eq!(recorded.lock().unwrap().len(), sleeps.len());
1983    }
1984
1985    #[test]
1986    fn device_poll_pacing_keeps_final_refusals_fatal() {
1987        let mut poll = DevicePoll::new(0);
1988        assert_eq!(poll.interval, 1, "an interval of 0 polls each second");
1989        for fatal in [
1990            CloudError::DeviceFlow(super::super::error::CODE_EXPIRED.into()),
1991            CloudError::Server {
1992                status: 400,
1993                code: "unknown".into(),
1994            },
1995            CloudError::Unauthorized,
1996            CloudError::Server {
1997                status: 413,
1998                code: "payload_too_large".into(),
1999            },
2000        ] {
2001            assert_eq!(poll.next_wait(fatal.clone()), Err(fatal));
2002        }
2003        let offline = CloudError::Offline("timeout".into());
2004        assert_eq!(poll.next_wait(offline.clone()), Ok(2));
2005        assert_eq!(poll.next_wait(offline.clone()), Ok(4));
2006        for _ in 0..10 {
2007            assert!(poll.next_wait(offline.clone()).unwrap() <= DEVICE_POLL_BACKOFF_CAP_S);
2008        }
2009        let limited = CloudError::RateLimited {
2010            retry_after: Some(90),
2011        };
2012        assert_eq!(poll.next_wait(limited), Ok(90), "Retry-After wins");
2013    }
2014
2015    #[test]
2016    fn an_enrollment_token_enrolls_in_one_request_without_a_browser() {
2017        use ed25519_dalek::SigningKey;
2018        let raw = fixture("cloud/enrollment.response.json");
2019        let root = SigningKey::from_bytes(&[0x52; 32])
2020            .verifying_key()
2021            .to_bytes();
2022        let (origin, recorded) = fake_cloud((200, raw));
2023        let dir = tempfile::tempdir().unwrap();
2024        let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
2025        let client = CloudClient::new(&origin).unwrap();
2026        let token = EnrollmentToken::parse(TOKEN).unwrap();
2027        let (record, sharing) =
2028            enroll_with_token_at(&store, &client, &token, "ci-runner-7", &root, || {
2029                at("2026-10-20T12:00:00Z")
2030            })
2031            .unwrap();
2032        assert_eq!(record.org_id, "org_acme");
2033        assert_eq!(record.label, "ci-runner-7");
2034        assert_eq!(sharing, None, "no approval page asked anything");
2035        assert_eq!(
2036            store.instance().unwrap().unwrap().instance_id,
2037            record.instance_id
2038        );
2039        let sent = recorded.lock().unwrap().clone();
2040        assert_eq!(sent.len(), 1, "one request, no device code, no polling");
2041        let (path, body) = &sent[0];
2042        assert_eq!(path, "/v1/device/token");
2043        assert_eq!(body["schema"], DEVICE_TOKEN_REQUEST_SCHEMA);
2044        assert_eq!(body["device_code"], TOKEN);
2045        assert_eq!(body["instance_label"], "ci-runner-7");
2046        let keys = InstanceKeys::load(&store).unwrap();
2047        assert_eq!(body["instance_public_key"], keys.public_key_b64());
2048        assert_eq!(body["instance_kx_public_key"], keys.kx_public_key_b64());
2049        assert_eq!(body["instance_version"], env!("CARGO_PKG_VERSION"));
2050    }
2051
2052    /// rc4-1: the name typed on the approval page (`instance_label` in the
2053    /// enrollment answer) becomes this computer's name; an unusable one is
2054    /// ignored and the sent name stays.
2055    #[test]
2056    fn the_name_chosen_on_the_approval_page_names_this_computer() {
2057        use ed25519_dalek::SigningKey;
2058        let root = SigningKey::from_bytes(&[0x52; 32])
2059            .verifying_key()
2060            .to_bytes();
2061        let enroll = |answer_label: Option<&str>| {
2062            let mut raw = fixture("cloud/enrollment.response.json");
2063            if let Some(label) = answer_label {
2064                raw["instance_label"] = json!(label);
2065            }
2066            let (origin, _) = fake_cloud((200, raw));
2067            let dir = tempfile::tempdir().unwrap();
2068            let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
2069            let client = CloudClient::new(&origin).unwrap();
2070            let token = EnrollmentToken::parse(TOKEN).unwrap();
2071            let (record, _) =
2072                enroll_with_token_at(&store, &client, &token, "host-7", &root, || {
2073                    at("2026-10-20T12:00:00Z")
2074                })
2075                .unwrap();
2076            let stored = store.instance().unwrap().unwrap().label;
2077            assert_eq!(stored, record.label, "the stored record names it too");
2078            stored
2079        };
2080        assert_eq!(enroll(Some("Ada's laptop")), "Ada's laptop");
2081        assert_eq!(enroll(Some(" Ada")), "host-7", "no space at the start");
2082        assert_eq!(
2083            enroll(Some("Ada\u{a0}")),
2084            "host-7",
2085            "no no-break space at the end"
2086        );
2087        assert_eq!(enroll(None), "host-7", "an older Cloud keeps today's name");
2088        assert_eq!(enroll(Some(" ")), "host-7");
2089        assert_eq!(enroll(Some("bad\u{1b}[31m")), "host-7");
2090        assert_eq!(enroll(Some(&"x".repeat(65))), "host-7");
2091    }
2092
2093    #[test]
2094    fn a_refused_enrollment_token_says_why_without_naming_it() {
2095        let refusal = json!({"error": {"code": "expired_token", "message":
2096            "Unknown, expired, revoked or used-up enrollment token; ask a team admin for a new one."}});
2097        let (origin, recorded) = fake_cloud((400, refusal));
2098        let dir = tempfile::tempdir().unwrap();
2099        let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
2100        let client = CloudClient::new(&origin).unwrap();
2101        let token = EnrollmentToken::parse(TOKEN).unwrap();
2102        let error = enroll_with_token(&store, &client, &token, "ci", &[7; 32])
2103            .expect_err("refused")
2104            .to_string();
2105        assert!(error.contains(ENROLLMENT_TOKEN_UNUSABLE), "{error}");
2106        assert!(!error.contains(&TOKEN[4..]), "{error}");
2107        assert!(store.instance().unwrap().is_none(), "nothing enrolled");
2108        assert_eq!(recorded.lock().unwrap().len(), 1);
2109        // The transport's code-expired wording and a bare code map the same.
2110        for raw in [
2111            CloudError::DeviceFlow(super::super::error::CODE_EXPIRED.into()),
2112            CloudError::Server {
2113                status: 400,
2114                code: "expired_token".into(),
2115            },
2116        ] {
2117            assert!(
2118                token_refusal(raw)
2119                    .to_string()
2120                    .contains(ENROLLMENT_TOKEN_UNUSABLE)
2121            );
2122        }
2123    }
2124
2125    /// Cloud contact findings A: a `429 rate_limited` of the token mint
2126    /// holds every process sharing `throttles.json` until `Retry-After`;
2127    /// none of them (a forced mint, a manual sync's, neither) calls the
2128    /// cloud again before it ends.
2129    #[test]
2130    fn a_token_mint_429_holds_every_session_sharing_the_store() {
2131        let limited = json!({"error": {"code": "rate_limited",
2132            "message": "Too many requests.", "retry_after_s": 420}});
2133        let (origin, recorded) = fake_cloud((429, limited));
2134        let (dir, mut first) = fixture_session();
2135        first.instance.url.clone_from(&origin);
2136        // The fixture enrolls without an instance key; a mint signs with one.
2137        InstanceKeys::load_or_create(&first.store).expect("instance key");
2138        let error = first.client().map(|_| ()).expect_err("limited");
2139        assert!(
2140            matches!(
2141                error,
2142                CloudError::RateLimited {
2143                    retry_after: Some(420)
2144                }
2145            ),
2146            "{error:?}"
2147        );
2148        assert_eq!(recorded.lock().unwrap().len(), 1, "one mint sent");
2149
2150        // Another process: its own Session on the same store.
2151        let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
2152        let mut second = Session::load(store, *first.root_key()).unwrap();
2153        second.instance.url.clone_from(&origin);
2154        for attempt in [
2155            second.client().map(|_| ()),
2156            second.bearer_token(true).map(|_| ()),
2157            first.bearer_token(true).map(|_| ()),
2158        ] {
2159            match attempt.expect_err("held") {
2160                CloudError::RateLimited {
2161                    retry_after: Some(left),
2162                } => assert!((400..=420).contains(&left), "{left}"),
2163                other => panic!("{other:?}"),
2164            }
2165        }
2166        assert_eq!(
2167            recorded.lock().unwrap().len(),
2168            1,
2169            "no HTTP call before retry_after"
2170        );
2171        let held = super::super::throttle::status_lines(&second.store, UtcDateTime::now());
2172        assert_eq!(held.len(), 1, "{held:?}");
2173        assert!(held[0].contains("token until"), "{held:?}");
2174    }
2175}
2176
2177#[cfg(test)]
2178mod task_key_tests {
2179    use super::*;
2180    use crate::consent::task_key::tests::{instance_public_key, offer, test_key};
2181
2182    /// rc4-67: the offer binds to the `instance_public_key` the request
2183    /// sends, travels as `task_propose_key`, and only its public part stays.
2184    #[test]
2185    fn a_task_key_offer_binds_to_the_instance_public_key_the_request_sends() {
2186        let dir = tempfile::tempdir().unwrap();
2187        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
2188        let keys = InstanceKeys::load_or_create(&store).unwrap();
2189        let plain = device_token_request(&keys, "dc", "label", AppKeyOffers::default()).unwrap();
2190        assert!(plain.get("task_propose_key").is_none());
2191        // Bound to another instance key: refused before anything is sent.
2192        let foreign = offer(&test_key(), &instance_public_key());
2193        assert!(check_task_key(&keys, Some(&foreign)).is_err());
2194        let good = offer(&test_key(), &keys.public_key_b64());
2195        check_task_key(&keys, Some(&good)).unwrap();
2196        let offers = AppKeyOffers {
2197            task: Some(&good),
2198            ..AppKeyOffers::default()
2199        };
2200        let request = device_token_request(&keys, "dc", "label", offers).unwrap();
2201        assert_eq!(request["task_propose_key"], good.request_member());
2202        assert!(request.get("chat_key").is_none());
2203        keep_task_key(&store, Some(&good), Pairing::New).unwrap();
2204        assert_eq!(task_key::bound_task_key(&store), Some(good.public()));
2205        keep_task_key(&store, None, Pairing::New).unwrap();
2206        assert_eq!(task_key::bound_task_key(&store), None);
2207    }
2208
2209    /// The Cloud's pairing refusals of a task key become plain words; the
2210    /// same codes without an offer stay as they are.
2211    #[test]
2212    fn task_key_pairing_refusals_are_plain_words() {
2213        let refusal = |status: u16, body: Value| CloudError::from_response(status, &body);
2214        let invalid = refusal(
2215            400,
2216            json!({"error": {"code": "invalid_field", "field": "task_propose_key",
2217                "reason": "token_enrollment", "message": "x"}}),
2218        );
2219        let bound = refusal(
2220            409,
2221            json!({"error": {"code": "invalid_state", "reason": "task_propose_key_bound",
2222                "message": "x"}}),
2223        );
2224        let cleared = refusal(
2225            409,
2226            json!({"error": {"code": "invalid_state", "reason": "task_propose_key_cleared",
2227                "message": "x"}}),
2228        );
2229        for (error, words, code) in [
2230            (
2231                invalid.clone(),
2232                TASK_KEY_REFUSED,
2233                crate::error::TASK_KEY_INVALID,
2234            ),
2235            (bound, TASK_KEY_ALREADY_BOUND, crate::error::TASK_KEY_BOUND),
2236            (
2237                cleared,
2238                TASK_KEY_WAS_REMOVED,
2239                crate::error::TASK_KEY_CLEARED,
2240            ),
2241        ] {
2242            let refused = task_key_refusal(error, true);
2243            // The `connect --json` error event keeps the reason as its code.
2244            assert_eq!(refused.event_code(), code);
2245            match refused {
2246                CloudError::DeviceFlow(text) => assert_eq!(text, words),
2247                other => panic!("{other:?}"),
2248            }
2249        }
2250        assert!(matches!(
2251            task_key_refusal(invalid, false),
2252            CloudError::Server { status: 400, .. }
2253        ));
2254    }
2255
2256    /// rc4-32 + rc4-67: LeanCTX Code may offer its chat key and its task key
2257    /// in one pairing; each is checked, both travel in the one request, both
2258    /// are kept, and each refusal keeps its own words.
2259    #[test]
2260    fn a_pairing_carries_a_chat_key_and_a_task_key_together() {
2261        use crate::consent::chat_key::tests as chat;
2262        let dir = tempfile::tempdir().unwrap();
2263        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
2264        let keys = InstanceKeys::load_or_create(&store).unwrap();
2265        let chat_offer = chat::offer_for(&chat::test_key(), &keys.public_key_b64());
2266        let task_offer = offer(&test_key(), &keys.public_key_b64());
2267        let both = AppKeyOffers {
2268            chat: Some(&chat_offer),
2269            task: Some(&task_offer),
2270            optin: None,
2271        };
2272        both.check(&keys).unwrap();
2273        // One foreign offer stops the pairing, whichever it is.
2274        let foreign_task = offer(&test_key(), &instance_public_key());
2275        let bad_task = AppKeyOffers {
2276            task: Some(&foreign_task),
2277            ..both
2278        };
2279        assert!(bad_task.check(&keys).is_err());
2280        let foreign_chat = chat::offer(&chat::test_key());
2281        let bad_chat = AppKeyOffers {
2282            chat: Some(&foreign_chat),
2283            ..both
2284        };
2285        assert!(bad_chat.check(&keys).is_err());
2286        let request = device_token_request(&keys, "dc", "label", both).unwrap();
2287        assert_eq!(request["chat_key"], chat_offer.request_member());
2288        assert_eq!(
2289            request[task_key::REQUEST_MEMBER],
2290            task_offer.request_member()
2291        );
2292        both.keep(&store, Pairing::New).unwrap();
2293        assert_eq!(
2294            crate::consent::chat_key::bound_chat_key(&store),
2295            Some(chat_offer.public())
2296        );
2297        assert_eq!(task_key::bound_task_key(&store), Some(task_offer.public()));
2298        // Each kind's refusal maps to its own words.
2299        let task_refused = CloudError::from_response(
2300            409,
2301            &json!({"error": {"code": "invalid_state", "reason": "task_propose_key_bound",
2302                "message": "x"}}),
2303        );
2304        assert!(matches!(
2305            both.refusal(task_refused, CHAT_KEY_REFUSED),
2306            CloudError::DeviceFlow(text) if text == TASK_KEY_ALREADY_BOUND
2307        ));
2308        let chat_refused = CloudError::Server {
2309            status: 400,
2310            code: "invalid_field".into(),
2311        };
2312        assert!(matches!(
2313            both.refusal(chat_refused, CHAT_KEY_REFUSED),
2314            CloudError::DeviceFlow(text) if text == CHAT_KEY_REFUSED
2315        ));
2316        // bd 40011 S1: a Cloud that needs the keys announced (f3129) is
2317        // named as "update lean-ctx", even when it names the task key field.
2318        let not_announced = CloudError::from_response(
2319            400,
2320            &json!({"error": {"code": "invalid_field", "field": "task_propose_key",
2321                "reason": "app_key_not_announced", "message": "x"}}),
2322        );
2323        assert!(matches!(
2324            both.refusal(not_announced, CHAT_KEY_REFUSED),
2325            CloudError::DeviceFlow(text) if text == APP_KEY_PAIRING_FAILED
2326        ));
2327        // bd 40011 M2: a rebind of the same instance offering only a new
2328        // task key keeps the bound chat key (the Cloud keeps it bound).
2329        let task_only = AppKeyOffers {
2330            chat: None,
2331            task: Some(&task_offer),
2332            optin: None,
2333        };
2334        task_only.keep(&store, Pairing::Rebind).unwrap();
2335        assert_eq!(
2336            crate::consent::chat_key::bound_chat_key(&store),
2337            Some(chat_offer.public())
2338        );
2339        assert_eq!(task_key::bound_task_key(&store), Some(task_offer.public()));
2340        // A rebind without offers keeps both.
2341        AppKeyOffers::default()
2342            .keep(&store, Pairing::Rebind)
2343            .unwrap();
2344        assert_eq!(
2345            crate::consent::chat_key::bound_chat_key(&store),
2346            Some(chat_offer.public())
2347        );
2348        assert_eq!(task_key::bound_task_key(&store), Some(task_offer.public()));
2349        // A new enrollment without offers forgets both.
2350        AppKeyOffers::default().keep(&store, Pairing::New).unwrap();
2351        assert_eq!(crate::consent::chat_key::bound_chat_key(&store), None);
2352        assert_eq!(task_key::bound_task_key(&store), None);
2353    }
2354}
2355
2356#[cfg(test)]
2357mod optin_key_tests {
2358    use super::*;
2359    use crate::consent::optin_key::test_key::{INSTANCE_PUBLIC_KEY, key, offer};
2360
2361    fn store() -> (tempfile::TempDir, CloudStore, InstanceKeys) {
2362        let dir = tempfile::tempdir().unwrap();
2363        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
2364        let keys = InstanceKeys::load_or_create(&store).unwrap();
2365        (dir, store, keys)
2366    }
2367
2368    /// rc4-16: the opt-in key binds to the `instance_public_key` the request
2369    /// sends (a foreign or broken bind stops the pairing before anything is
2370    /// sent) and travels as `optin_key` beside the other offers.
2371    #[test]
2372    fn an_optin_key_offer_is_checked_then_sent_as_optin_key() {
2373        let (_dir, _store, keys) = store();
2374        let plain = device_token_request(&keys, "dc", "label", AppKeyOffers::default()).unwrap();
2375        assert!(plain.get("optin_key").is_none());
2376        let foreign = offer(&key(), INSTANCE_PUBLIC_KEY);
2377        let refused = AppKeyOffers {
2378            optin: Some(&foreign),
2379            ..AppKeyOffers::default()
2380        };
2381        assert!(matches!(refused.check(&keys), Err(CloudError::Config(_))));
2382        let mut forged = offer(&key(), &keys.public_key_b64());
2383        forged.bind_signature = foreign.bind_signature.clone();
2384        assert!(check_optin_key(&keys, Some(&forged)).is_err());
2385        let good = offer(&key(), &keys.public_key_b64());
2386        let offers = AppKeyOffers {
2387            optin: Some(&good),
2388            ..AppKeyOffers::default()
2389        };
2390        offers.check(&keys).unwrap();
2391        let request = device_token_request(&keys, "dc", "label", offers).unwrap();
2392        assert_eq!(request["optin_key"], good.request_member());
2393        assert_eq!(
2394            serde_json::from_value::<OptinKeyOffer>(request["optin_key"].clone()).unwrap(),
2395            good
2396        );
2397        assert!(request.get("chat_key").is_none());
2398        assert!(request.get("task_propose_key").is_none());
2399    }
2400
2401    /// rc4-16: an accepted pairing keeps the offered key accepted (pending
2402    /// before); a new enrollment without it puts it back to pending, a
2403    /// rebind without it keeps it.
2404    #[test]
2405    fn a_paired_optin_key_is_kept_accepted_until_a_new_enrollment() {
2406        let (_dir, store, keys) = store();
2407        let good = offer(&key(), &keys.public_key_b64());
2408        // Handed over by `cloud.pickup.key` first: pending.
2409        optin_key::store_pending(&store, &good).unwrap();
2410        assert!(!optin_key::pending_optin_key(&store).unwrap().accepted);
2411        let offers = AppKeyOffers {
2412            optin: Some(&good),
2413            ..AppKeyOffers::default()
2414        };
2415        offers.keep(&store, Pairing::New).unwrap();
2416        let kept = optin_key::pending_optin_key(&store).unwrap();
2417        assert!(kept.accepted);
2418        assert_eq!(kept.key_id, good.key_id);
2419        AppKeyOffers::default()
2420            .keep(&store, Pairing::Rebind)
2421            .unwrap();
2422        assert!(optin_key::pending_optin_key(&store).unwrap().accepted);
2423        AppKeyOffers::default().keep(&store, Pairing::New).unwrap();
2424        let pending = optin_key::pending_optin_key(&store).unwrap();
2425        assert!(
2426            !pending.accepted,
2427            "a key of an earlier enrollment is not usable"
2428        );
2429        assert!(optin_key::bound_optin_key(&store).is_none());
2430    }
2431
2432    /// The Cloud's pairing refusals of an opt-in key become the §46.4 texts
2433    /// with their own codes; `optin_key_cleared` puts the kept key back to
2434    /// pending.
2435    #[test]
2436    fn optin_key_pairing_refusals_keep_their_reasons() {
2437        let refusal = |status: u16, body: Value| CloudError::from_response(status, &body);
2438        let invalid = refusal(
2439            400,
2440            json!({"error": {"code": "invalid_field", "field": "optin_key.bind_signature",
2441                "message": "x"}}),
2442        );
2443        let bound = refusal(
2444            409,
2445            json!({"error": {"code": "conflict", "reason": "optin_key_bound", "message": "x"}}),
2446        );
2447        let cleared = refusal(
2448            409,
2449            json!({"error": {"code": "optin_key_cleared", "message": "x"}}),
2450        );
2451        let foreign = offer(&key(), INSTANCE_PUBLIC_KEY);
2452        let offered = AppKeyOffers {
2453            optin: Some(&foreign),
2454            ..AppKeyOffers::default()
2455        };
2456        for (error, words, code) in [
2457            (invalid.clone(), OPTIN_KEY_REFUSED, "optin_key_invalid"),
2458            (bound, OPTIN_KEY_ALREADY_BOUND, "optin_key_bound"),
2459            (cleared.clone(), OPTIN_KEY_WAS_REMOVED, "optin_key_cleared"),
2460        ] {
2461            let refused = offered.refusal(error, CHAT_KEY_REFUSED);
2462            assert_eq!(refused.event_code(), code);
2463            match refused {
2464                CloudError::DeviceFlow(text) => assert_eq!(text, words),
2465                other => panic!("{other:?}"),
2466            }
2467        }
2468        assert!(matches!(
2469            AppKeyOffers::default().refusal(invalid, CHAT_KEY_REFUSED),
2470            CloudError::Server { status: 400, .. }
2471        ));
2472        // A cleared key that is the one kept here is pending again.
2473        let (_dir, store, keys) = store();
2474        let good = offer(&key(), &keys.public_key_b64());
2475        keep_optin_key(&store, Some(&good), Pairing::New).unwrap();
2476        let mut other = offer(&key(), &keys.public_key_b64());
2477        other.key_id = "0000000000000000".into();
2478        forget_cleared_optin_key(&store, Some(&other), &cleared);
2479        assert!(
2480            optin_key::pending_optin_key(&store).unwrap().accepted,
2481            "another key's removal keeps this one"
2482        );
2483        forget_cleared_optin_key(&store, Some(&good), &CloudError::Unauthorized);
2484        assert!(optin_key::pending_optin_key(&store).unwrap().accepted);
2485        forget_cleared_optin_key(&store, Some(&good), &cleared);
2486        assert!(!optin_key::pending_optin_key(&store).unwrap().accepted);
2487    }
2488}
2489
2490#[cfg(test)]
2491mod chat_key_tests {
2492    use super::*;
2493    use crate::consent::chat_key::tests::{offer, offer_for, test_key};
2494
2495    #[test]
2496    fn a_chat_key_offer_binds_to_the_instance_public_key_the_request_sends() {
2497        let dir = tempfile::tempdir().unwrap();
2498        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
2499        let keys = InstanceKeys::load_or_create(&store).unwrap();
2500        let plain = device_token_request(&keys, "dc", "label", AppKeyOffers::default()).unwrap();
2501        assert!(plain.get("chat_key").is_none());
2502        // Bound to another instance key: refused before anything is sent.
2503        assert!(check_chat_key(&keys, Some(&offer(&test_key()))).is_err());
2504        let good = offer_for(&test_key(), &keys.public_key_b64());
2505        check_chat_key(&keys, Some(&good)).unwrap();
2506        let offers = AppKeyOffers {
2507            chat: Some(&good),
2508            ..AppKeyOffers::default()
2509        };
2510        let request = device_token_request(&keys, "dc", "label", offers).unwrap();
2511        assert_eq!(request["chat_key"], good.request_member());
2512        assert!(request.get("task_propose_key").is_none());
2513        keep_chat_key(&store, Some(&good), Pairing::New).unwrap();
2514        assert_eq!(
2515            crate::consent::chat_key::bound_chat_key(&store),
2516            Some(good.public())
2517        );
2518    }
2519
2520    fn fixture_answer() -> (Value, [u8; 32]) {
2521        let path = concat!(
2522            env!("CARGO_MANIFEST_DIR"),
2523            "/../lean-ctx-protocol/tests/fixtures/cloud/enrollment.response.json"
2524        );
2525        let raw: Value = serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
2526        let root = ed25519_dalek::SigningKey::from_bytes(&[0x52; 32])
2527            .verifying_key()
2528            .to_bytes();
2529        (raw, root)
2530    }
2531
2532    fn fixture_now() -> UtcDateTime {
2533        lean_ctx_time::OffsetDateTime::parse_from_rfc3339("2026-10-20T12:00:00Z")
2534            .unwrap()
2535            .to_utc()
2536    }
2537
2538    fn code() -> DeviceCodeV1 {
2539        DeviceCodeV1 {
2540            schema: lean_ctx_protocol::cloud::enroll::DEVICE_CODE_SCHEMA.into(),
2541            device_code: "hdc_repair".into(),
2542            user_code: "WDJB-MJHT".into(),
2543            verification_uri: "https://cloud.example.com/device".into(),
2544            verification_uri_complete: "https://cloud.example.com/device?c=WDJB-MJHT".into(),
2545            interval: 1,
2546            expires_in: 60,
2547            features: vec![lean_ctx_protocol::cloud::app_keys::FEATURE_DEVICE_APP_KEYS.into()],
2548            intent: None,
2549            plan: None,
2550        }
2551    }
2552
2553    /// One-answer Cloud on 127.0.0.1 recording each request body.
2554    fn one_answer_cloud(
2555        status: u16,
2556        body: &Value,
2557    ) -> (String, std::sync::Arc<std::sync::Mutex<Vec<Value>>>) {
2558        use std::io::{BufRead as _, Read as _, Write as _};
2559        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
2560        let origin = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());
2561        let seen: std::sync::Arc<std::sync::Mutex<Vec<Value>>> = std::sync::Arc::default();
2562        let record = std::sync::Arc::clone(&seen);
2563        let text = body.to_string();
2564        let raw = format!(
2565            "HTTP/1.1 {status} X\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{text}",
2566            text.len()
2567        );
2568        std::thread::spawn(move || {
2569            for stream in listener.incoming().flatten() {
2570                let mut writer = stream.try_clone().unwrap();
2571                let mut reader = std::io::BufReader::new(stream);
2572                let mut line = String::new();
2573                if reader.read_line(&mut line).unwrap_or(0) == 0 {
2574                    continue;
2575                }
2576                let mut length = 0;
2577                loop {
2578                    let mut header = String::new();
2579                    reader.read_line(&mut header).unwrap();
2580                    let header = header.trim_end();
2581                    if header.is_empty() {
2582                        break;
2583                    }
2584                    if let Some((name, value)) = header.split_once(':')
2585                        && name.eq_ignore_ascii_case("content-length")
2586                    {
2587                        length = value.trim().parse().unwrap();
2588                    }
2589                }
2590                let mut body = vec![0; length];
2591                reader.read_exact(&mut body).unwrap();
2592                record
2593                    .lock()
2594                    .unwrap()
2595                    .push(serde_json::from_slice(&body).unwrap_or(Value::Null));
2596                let _ = writer.write_all(raw.as_bytes());
2597            }
2598        });
2599        (origin, seen)
2600    }
2601
2602    /// A connected computer, its instance keys made.
2603    fn connected(origin: &str) -> (tempfile::TempDir, CloudStore, InstanceKeys) {
2604        let (dir, session) = fixture_session_at(origin);
2605        let store = session.store;
2606        let keys = InstanceKeys::load_or_create(&store).unwrap();
2607        (dir, store, keys)
2608    }
2609
2610    /// rc4-32 re-pair: the device flow of a connected computer sends its
2611    /// existing instance key plus the chat key, never `replaces`; the
2612    /// enrollment record stays, the chat key is bound.
2613    #[test]
2614    fn a_chat_key_repair_keeps_the_instance_and_sends_no_replaces() {
2615        let (answer, root) = fixture_answer();
2616        let (origin, seen) = one_answer_cloud(200, &answer);
2617        let (_dir, store, keys) = connected(&origin);
2618        let before = store.instance().unwrap().unwrap();
2619        let client = CloudClient::new(&origin).unwrap();
2620        let good = offer_for(&test_key(), &keys.public_key_b64());
2621        let outcome =
2622            repair_chat_key_at(&store, &client, &code(), &root, &|_| {}, &good, fixture_now)
2623                .unwrap();
2624        assert_eq!(outcome, ChatKeyRepair::Bound);
2625        assert_eq!(outcome.reason(), "bound");
2626        let sent = seen.lock().unwrap().clone();
2627        assert_eq!(sent.len(), 1);
2628        assert_eq!(sent[0]["device_code"], "hdc_repair");
2629        assert_eq!(sent[0]["instance_public_key"], keys.public_key_b64());
2630        assert_eq!(sent[0]["instance_label"], before.label.as_str());
2631        assert_eq!(sent[0]["chat_key"], good.request_member());
2632        assert!(sent[0].get("replaces").is_none(), "{}", sent[0]);
2633        let after = store.instance().unwrap().unwrap();
2634        assert_eq!(after.instance_id, before.instance_id);
2635        assert_eq!(after.enrolled_at, before.enrolled_at, "the record is kept");
2636        assert_eq!(
2637            InstanceKeys::load(&store).unwrap().public_key_b64(),
2638            keys.public_key_b64()
2639        );
2640        assert_eq!(
2641            crate::consent::chat_key::bound_chat_key(&store),
2642            Some(good.public())
2643        );
2644        // The same key again: unchanged.
2645        let again =
2646            repair_chat_key_at(&store, &client, &code(), &root, &|_| {}, &good, fixture_now)
2647                .unwrap();
2648        assert_eq!(again.reason(), "unchanged");
2649    }
2650
2651    #[test]
2652    fn each_chat_key_repair_refusal_maps_to_its_reason_and_text() {
2653        let (_, root) = fixture_answer();
2654        for (status, error, reason, text) in [
2655            (
2656                409,
2657                json!({"code": "invalid_state", "reason": "chat_key_bound", "message": "x"}),
2658                Some("chat_key_bound"),
2659                CHAT_KEY_BOUND,
2660            ),
2661            (
2662                409,
2663                json!({"code": "invalid_state", "reason": "chat_key_cleared", "message": "x"}),
2664                Some("chat_key_cleared"),
2665                CHAT_KEY_CLEARED,
2666            ),
2667            (
2668                400,
2669                json!({"code": "invalid_field", "field": "chat_key", "message": "x"}),
2670                None,
2671                CHAT_KEY_REFUSED,
2672            ),
2673            (
2674                400,
2675                json!({"code": "token_enrollment", "message": "x"}),
2676                None,
2677                CHAT_KEY_TOKEN_ENROLLMENT,
2678            ),
2679            // bd 40051: a Cloud that needs the keys announced (f3129).
2680            (
2681                400,
2682                json!({"code": "invalid_field", "field": "chat_key",
2683                    "reason": "app_key_not_announced", "message": "x"}),
2684                None,
2685                APP_KEY_PAIRING_FAILED,
2686            ),
2687        ] {
2688            let (origin, seen) = one_answer_cloud(status, &json!({ "error": error }));
2689            let (_dir, store, keys) = connected(&origin);
2690            let client = CloudClient::new(&origin).unwrap();
2691            let good = offer_for(&test_key(), &keys.public_key_b64());
2692            let refused =
2693                repair_chat_key_at(&store, &client, &code(), &root, &|_| {}, &good, fixture_now)
2694                    .expect_err("refused");
2695            assert_eq!(
2696                chat_key_repair_refusal(&refused),
2697                Some((reason, text)),
2698                "{status} {error}: {refused:?}"
2699            );
2700            if text == APP_KEY_PAIRING_FAILED {
2701                // The app's `connect --json` error event says which.
2702                assert_eq!(refused.event_code(), "app_key_not_announced");
2703            }
2704            assert_eq!(seen.lock().unwrap().len(), 1, "a final answer: no polling");
2705            assert!(store.instance().unwrap().is_some(), "still connected");
2706            assert_eq!(crate::consent::chat_key::bound_chat_key(&store), None);
2707        }
2708        assert_eq!(chat_key_repair_refusal(&CloudError::Unauthorized), None);
2709    }
2710
2711    /// bd 40051 S2: "the same instance" is the same id, team and Cloud; any
2712    /// other record, none, or an unreadable one is a new enrollment.
2713    #[test]
2714    fn a_rebind_is_the_same_instance_id_team_and_cloud() {
2715        let (_dir, session) = fixture_session_at("https://cloud.example.com");
2716        let store = session.store;
2717        let after = store.instance().unwrap().unwrap();
2718        let held = HeldInstance::read(&store).expect("held");
2719        assert_eq!(Pairing::of(Some(&held), &after), Pairing::Rebind);
2720        assert_eq!(Pairing::of(None, &after), Pairing::New);
2721        for other in [
2722            HeldInstance {
2723                instance_id: "inst_other".into(),
2724                ..held.clone()
2725            },
2726            HeldInstance {
2727                org_id: "org_other".into(),
2728                ..held.clone()
2729            },
2730            HeldInstance {
2731                url: "https://other.example.com".into(),
2732                ..held.clone()
2733            },
2734        ] {
2735            assert_eq!(Pairing::of(Some(&other), &after), Pairing::New, "{other:?}");
2736        }
2737        // Unreadable: none held, so a new enrollment (fail closed).
2738        std::fs::write(store.config_dir().join(INSTANCE_FILE), b"{ not json").unwrap();
2739        assert_eq!(HeldInstance::read(&store), None);
2740    }
2741
2742    /// bd 40051 S1: the device flow reads the held instance before the
2743    /// enrollment is accepted (which overwrites it). A rebind of the same
2744    /// instance offering only a task key keeps the bound chat key; a pairing
2745    /// that enrolls another instance forgets it.
2746    #[test]
2747    fn a_task_only_pairing_keeps_the_chat_key_of_the_same_instance_only() {
2748        use crate::consent::task_key::tests as task;
2749        let (answer, root) = fixture_answer();
2750        let (origin, seen) = one_answer_cloud(200, &answer);
2751        for same in [true, false] {
2752            let (_dir, store, keys) = connected(&origin);
2753            let chat = offer_for(&test_key(), &keys.public_key_b64());
2754            keep_chat_key(&store, Some(&chat), Pairing::New).unwrap();
2755            if !same {
2756                let mut record = store.instance().unwrap().unwrap();
2757                record.instance_id = "inst_held_before".into();
2758                store.write_config(INSTANCE_FILE, &record).unwrap();
2759            }
2760            let task_offer = task::offer(&task::test_key(), &keys.public_key_b64());
2761            let offers = AppKeyOffers {
2762                chat: None,
2763                task: Some(&task_offer),
2764                optin: None,
2765            };
2766            let client = CloudClient::new(&origin).unwrap();
2767            let (record, _) = poll_device_flow(
2768                &store,
2769                &client,
2770                &code(),
2771                "studio-mac",
2772                &root,
2773                &|_| {},
2774                offers,
2775                fixture_now,
2776            )
2777            .unwrap();
2778            assert_eq!(record.instance_id, "inst_01jb8z3k4m5n6p7q8r9s0t1v2w");
2779            assert_eq!(task_key::bound_task_key(&store), Some(task_offer.public()));
2780            let kept = crate::consent::chat_key::bound_chat_key(&store);
2781            if same {
2782                assert_eq!(kept, Some(chat.public()), "a rebind keeps the chat key");
2783            } else {
2784                assert_eq!(kept, None, "a new instance forgets the chat key");
2785            }
2786        }
2787        assert_eq!(seen.lock().unwrap().len(), 2);
2788    }
2789
2790    /// rc4-16 (bd 40254 S2): through the device flow against a Cloud, the
2791    /// opt-in key travels as `optin_key` in `POST /v1/device/token`; a 2xx
2792    /// keeps it accepted, a `409 optin_key_cleared` for that key puts it back
2793    /// to pending with the §46.4 text, and a `400 token_enrollment` gives the
2794    /// §46.2 text with its own code.
2795    #[test]
2796    fn an_optin_key_pairing_flow_sends_keeps_and_clears_the_optin_key() {
2797        use crate::consent::optin_key::test_key as optin;
2798        let (answer, root) = fixture_answer();
2799        let offered = |keys: &InstanceKeys| optin::offer(&optin::key(), &keys.public_key_b64());
2800
2801        // 2xx: sent as `optin_key`, kept accepted.
2802        let (origin, seen) = one_answer_cloud(200, &answer);
2803        let (_dir, store, keys) = connected(&origin);
2804        let good = offered(&keys);
2805        optin_key::store_pending(&store, &good).unwrap();
2806        let offers = AppKeyOffers {
2807            optin: Some(&good),
2808            ..AppKeyOffers::default()
2809        };
2810        offers.verify(&store).unwrap();
2811        let client = CloudClient::new(&origin).unwrap();
2812        finish_device_flow_at(
2813            &store,
2814            &client,
2815            &code(),
2816            "studio-mac",
2817            &root,
2818            &|_| {},
2819            offers,
2820            fixture_now,
2821        )
2822        .unwrap();
2823        let sent = seen.lock().unwrap().clone();
2824        assert_eq!(sent.len(), 1);
2825        assert_eq!(sent[0]["instance_public_key"], keys.public_key_b64());
2826        assert_eq!(sent[0]["optin_key"], good.request_member());
2827        let kept = optin_key::pending_optin_key(&store).unwrap();
2828        assert!(kept.accepted, "a 2xx keeps the key accepted");
2829        assert_eq!(kept.key_id, good.key_id);
2830
2831        // 409 optin_key_cleared for the same key: pending again, §46.4 text.
2832        let cleared = json!({"error": {"code": "optin_key_cleared", "message": "x"}});
2833        let (origin, seen) = one_answer_cloud(409, &cleared);
2834        let (_dir, store, keys) = connected(&origin);
2835        let good = offered(&keys);
2836        keep_optin_key(&store, Some(&good), Pairing::New).unwrap();
2837        assert!(optin_key::pending_optin_key(&store).unwrap().accepted);
2838        let offers = AppKeyOffers {
2839            optin: Some(&good),
2840            ..AppKeyOffers::default()
2841        };
2842        let client = CloudClient::new(&origin).unwrap();
2843        let refused = finish_device_flow_at(
2844            &store,
2845            &client,
2846            &code(),
2847            "studio-mac",
2848            &root,
2849            &|_| {},
2850            offers,
2851            fixture_now,
2852        )
2853        .expect_err("cleared");
2854        assert_eq!(seen.lock().unwrap()[0]["optin_key"], good.request_member());
2855        assert_eq!(refused.event_code(), "optin_key_cleared");
2856        assert!(
2857            matches!(&refused, CloudError::DeviceFlow(text) if text == OPTIN_KEY_WAS_REMOVED),
2858            "{refused:?}"
2859        );
2860        let pending = optin_key::pending_optin_key(&store).unwrap();
2861        assert!(!pending.accepted, "the cleared key is pending again");
2862        assert_eq!(pending.key_id, good.key_id);
2863
2864        // A computer enrolled with a token: §46.2 text, own code.
2865        let token = json!({"error": {"code": "token_enrollment", "message": "x"}});
2866        let (origin, _seen) = one_answer_cloud(400, &token);
2867        let (_dir, store, keys) = connected(&origin);
2868        let good = offered(&keys);
2869        let client = CloudClient::new(&origin).unwrap();
2870        let refused = finish_device_flow_at(
2871            &store,
2872            &client,
2873            &code(),
2874            "studio-mac",
2875            &root,
2876            &|_| {},
2877            AppKeyOffers {
2878                optin: Some(&good),
2879                ..AppKeyOffers::default()
2880            },
2881            fixture_now,
2882        )
2883        .expect_err("token enrollment");
2884        assert_eq!(refused.event_code(), "token_enrollment");
2885        assert!(
2886            matches!(&refused, CloudError::DeviceFlow(text) if text == OPTIN_KEY_TOKEN_ENROLLMENT),
2887            "{refused:?}"
2888        );
2889    }
2890
2891    /// bd 40254 S1: the offers are verified against this computer's instance
2892    /// key before the connect contacts the Cloud; nothing offered makes no
2893    /// key.
2894    #[test]
2895    fn app_key_offers_verify_before_the_cloud_is_contacted_for_optin_key() {
2896        use crate::consent::optin_key::test_key as optin;
2897        let dir = tempfile::tempdir().unwrap();
2898        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
2899        AppKeyOffers::default().verify(&store).unwrap();
2900        assert!(
2901            InstanceKeys::load(&store).is_err(),
2902            "nothing offered: no key made"
2903        );
2904        let keys = InstanceKeys::load_or_create(&store).unwrap();
2905        let foreign = optin::offer(&optin::key(), optin::INSTANCE_PUBLIC_KEY);
2906        let chat_foreign = offer(&test_key());
2907        for refused in [
2908            AppKeyOffers {
2909                optin: Some(&foreign),
2910                ..AppKeyOffers::default()
2911            },
2912            AppKeyOffers {
2913                chat: Some(&chat_foreign),
2914                ..AppKeyOffers::default()
2915            },
2916        ] {
2917            assert!(matches!(refused.verify(&store), Err(CloudError::Config(_))));
2918        }
2919        let good = optin::offer(&optin::key(), &keys.public_key_b64());
2920        AppKeyOffers {
2921            optin: Some(&good),
2922            ..AppKeyOffers::default()
2923        }
2924        .verify(&store)
2925        .unwrap();
2926    }
2927
2928    /// The device-code answer of a Cloud with or without `device_app_keys`.
2929    fn code_answer(app_keys: bool) -> Value {
2930        let mut answer = code();
2931        if !app_keys {
2932            answer.features.clear();
2933        }
2934        serde_json::to_value(answer).unwrap()
2935    }
2936
2937    /// f3129 S2: every offer is announced at `POST /v1/device/code` as
2938    /// `app_keys`, sorted chat < optin < task_propose; without offers the
2939    /// request carries no `app_keys` member and is the plain pairing's.
2940    #[test]
2941    fn f3129_app_keys_are_announced_sorted_at_the_device_code() {
2942        use crate::consent::optin_key::test_key as optin;
2943        use crate::consent::task_key::tests as task;
2944        let dir = tempfile::tempdir().unwrap();
2945        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
2946        let pk = InstanceKeys::load_or_create(&store)
2947            .unwrap()
2948            .public_key_b64();
2949        let chat = offer_for(&test_key(), &pk);
2950        let task_offer = task::offer(&task::test_key(), &pk);
2951        let optin_offer = optin::offer(&optin::key(), &pk);
2952        let offers = AppKeyOffers {
2953            chat: Some(&chat),
2954            task: Some(&task_offer),
2955            optin: Some(&optin_offer),
2956        };
2957        let (origin, seen) = one_answer_cloud(200, &code_answer(true));
2958        let client = CloudClient::new(&origin).unwrap();
2959        start_device_flow_with(&client, Some("studio-mac"), None, offers).unwrap();
2960        let announced = offers.announcements();
2961        assert_eq!(
2962            announced.iter().map(|a| a.kind).collect::<Vec<_>>(),
2963            [AppKeyKind::Chat, AppKeyKind::Optin, AppKeyKind::TaskPropose]
2964        );
2965        for (a, (public_key, key_id)) in announced.iter().zip([
2966            (&chat.public_key, &chat.key_id),
2967            (&optin_offer.public_key, &optin_offer.key_id),
2968            (&task_offer.public_key, &task_offer.key_id),
2969        ]) {
2970            assert_eq!(a.alg, "ed25519");
2971            assert_eq!((&a.public_key, &a.key_id), (public_key, key_id));
2972        }
2973        let sent = seen.lock().unwrap().clone();
2974        assert_eq!(sent.len(), 1);
2975        assert_eq!(
2976            sent[0]["app_keys"],
2977            serde_json::to_value(&announced).unwrap()
2978        );
2979        assert_eq!(sent[0]["app_keys"][0]["kind"], "chat");
2980        assert_eq!(sent[0]["app_keys"][2]["kind"], "task_propose");
2981
2982        // No offers: no `app_keys`, byte for byte the plain pairing.
2983        let (origin, seen) = one_answer_cloud(200, &code_answer(false));
2984        let client = CloudClient::new(&origin).unwrap();
2985        start_device_flow_with(&client, Some("studio-mac"), None, AppKeyOffers::default()).unwrap();
2986        start_device_flow_for(&client, Some("studio-mac"), None).unwrap();
2987        let sent = seen.lock().unwrap().clone();
2988        assert_eq!(sent.len(), 2);
2989        assert!(sent[0].get("app_keys").is_none(), "{}", sent[0]);
2990        assert_eq!(sent[0].to_string(), sent[1].to_string());
2991        let plain = DeviceCodeRequestV1::new(env!("CARGO_PKG_VERSION"), engine_os())
2992            .with_label(Some("studio-mac".into()));
2993        assert_eq!(sent[0], serde_json::to_value(plain).unwrap());
2994    }
2995
2996    /// f3129: a Cloud without `device_app_keys` (or one refusing `app_keys`
2997    /// as an unknown member) gets no offer: a clear `config` error before
2998    /// any polling; the pairing without offers is unaffected.
2999    #[test]
3000    fn f3129_app_keys_fail_closed_without_the_cloud_feature() {
3001        let dir = tempfile::tempdir().unwrap();
3002        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
3003        let keys = InstanceKeys::load_or_create(&store).unwrap();
3004        let chat = offer_for(&test_key(), &keys.public_key_b64());
3005        let offers = AppKeyOffers {
3006            chat: Some(&chat),
3007            ..AppKeyOffers::default()
3008        };
3009        let (origin, seen) = one_answer_cloud(200, &code_answer(false));
3010        let client = CloudClient::new(&origin).unwrap();
3011        let refused = start_device_flow_with(&client, None, None, offers).expect_err("no feature");
3012        assert!(
3013            matches!(&refused, CloudError::Config(text) if text == APP_KEYS_UNSUPPORTED),
3014            "{refused:?}"
3015        );
3016        assert_eq!(seen.lock().unwrap().len(), 1, "no polling");
3017        // Polling with offers on such a code is refused before it is sent.
3018        let (_, root) = fixture_answer();
3019        let mut old = code();
3020        old.features.clear();
3021        let refused = poll_device_flow(
3022            &store,
3023            &client,
3024            &old,
3025            "m",
3026            &root,
3027            &|_| {},
3028            offers,
3029            fixture_now,
3030        )
3031        .expect_err("no feature");
3032        assert!(matches!(&refused, CloudError::Config(_)), "{refused:?}");
3033        assert_eq!(seen.lock().unwrap().len(), 1, "nothing sent");
3034        start_device_flow_with(&client, None, None, AppKeyOffers::default()).unwrap();
3035        // An older Cloud's 400 on the unknown member reads the same.
3036        let old_cloud = json!({"error": {"code": "invalid_request", "message": "x"}});
3037        let (origin, _) = one_answer_cloud(400, &old_cloud);
3038        let client = CloudClient::new(&origin).unwrap();
3039        let refused = start_device_flow_with(&client, None, None, offers).expect_err("old");
3040        assert!(
3041            matches!(&refused, CloudError::Config(text) if text == APP_KEYS_UNSUPPORTED),
3042            "{refused:?}"
3043        );
3044    }
3045
3046    /// f3129 S3: the device-token request carries `app_keys_bind_signature`,
3047    /// the instance key's signature over the bind statement of the device
3048    /// code, the sent instance key and the announced set; none without
3049    /// offers.
3050    #[test]
3051    fn f3129_app_keys_bind_signature_verifies_with_the_instance_key() {
3052        use crate::consent::task_key::tests as task;
3053        use base64::Engine as _;
3054        use ed25519_dalek::Verifier as _;
3055        let (answer, root) = fixture_answer();
3056        let (origin, seen) = one_answer_cloud(200, &answer);
3057        let (_dir, store, keys) = connected(&origin);
3058        let pk = keys.public_key_b64();
3059        let chat = offer_for(&test_key(), &pk);
3060        let task_offer = task::offer(&task::test_key(), &pk);
3061        let offers = AppKeyOffers {
3062            chat: Some(&chat),
3063            task: Some(&task_offer),
3064            optin: None,
3065        };
3066        let client = CloudClient::new(&origin).unwrap();
3067        poll_device_flow(
3068            &store,
3069            &client,
3070            &code(),
3071            "m",
3072            &root,
3073            &|_| {},
3074            offers,
3075            fixture_now,
3076        )
3077        .unwrap();
3078        let sent = seen.lock().unwrap().clone();
3079        assert_eq!(sent.len(), 1);
3080        assert_eq!(sent[0]["instance_public_key"], pk);
3081        let signature = sent[0]["app_keys_bind_signature"].as_str().expect("signed");
3082        let raw = base64::engine::general_purpose::URL_SAFE_NO_PAD
3083            .decode(signature)
3084            .unwrap();
3085        let signature = ed25519_dalek::Signature::from_slice(&raw).unwrap();
3086        let verifying = keys.signing_key().verifying_key();
3087        let input = app_key_bind_signing_input("hdc_repair", &pk, &offers.announcements()).unwrap();
3088        verifying
3089            .verify(&input, &signature)
3090            .expect("the instance key signed the statement");
3091        // Another device code does not verify.
3092        let other = app_key_bind_signing_input("hdc_other", &pk, &offers.announcements()).unwrap();
3093        assert!(verifying.verify(&other, &signature).is_err());
3094        // No offers, no signature.
3095        let plain = device_token_request(&keys, "dc", "m", AppKeyOffers::default()).unwrap();
3096        assert!(plain.get("app_keys_bind_signature").is_none());
3097    }
3098
3099    /// f3129 §11: `400 invalid_field` with reason `app_key_not_announced` or
3100    /// `app_key_bind_invalid` reads "Pairing failed" with the app's code.
3101    #[test]
3102    fn f3129_app_keys_refusals_read_pairing_failed() {
3103        let (_, root) = fixture_answer();
3104        for reason in ["app_key_not_announced", "app_key_bind_invalid"] {
3105            let error = json!({"error": {"code": "invalid_field",
3106                "field": "app_keys_bind_signature", "reason": reason, "message": "x"}});
3107            let (origin, seen) = one_answer_cloud(400, &error);
3108            let (_dir, store, keys) = connected(&origin);
3109            let chat = offer_for(&test_key(), &keys.public_key_b64());
3110            let client = CloudClient::new(&origin).unwrap();
3111            let refused = finish_device_flow_at(
3112                &store,
3113                &client,
3114                &code(),
3115                "m",
3116                &root,
3117                &|_| {},
3118                AppKeyOffers {
3119                    chat: Some(&chat),
3120                    ..AppKeyOffers::default()
3121                },
3122                fixture_now,
3123            )
3124            .expect_err("refused");
3125            assert!(
3126                matches!(&refused, CloudError::DeviceFlow(text) if text == PAIRING_FAILED_TEXT),
3127                "{reason}: {refused:?}"
3128            );
3129            assert_eq!(refused.event_code(), "app_key_not_announced");
3130            assert_eq!(seen.lock().unwrap().len(), 1, "a final answer");
3131            assert_eq!(crate::consent::chat_key::bound_chat_key(&store), None);
3132        }
3133    }
3134
3135    /// f3129: a newer Cloud refusing the announcement itself at the device
3136    /// code (`400 invalid_field`, field `app_keys`) is a clear Config error
3137    /// that the re-pair names; without an announcement it stays as it was.
3138    #[test]
3139    fn f3129_app_keys_bad_announcement_is_a_clear_config_error() {
3140        let dir = tempfile::tempdir().unwrap();
3141        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
3142        let keys = InstanceKeys::load_or_create(&store).unwrap();
3143        let chat = offer_for(&test_key(), &keys.public_key_b64());
3144        let offers = AppKeyOffers {
3145            chat: Some(&chat),
3146            ..AppKeyOffers::default()
3147        };
3148        let refusal = json!({"error": {"code": "invalid_field", "field": "app_keys",
3149            "message": "x"}});
3150        let (origin, seen) = one_answer_cloud(400, &refusal);
3151        let client = CloudClient::new(&origin).unwrap();
3152        let refused = start_device_flow_with(&client, None, None, offers).expect_err("refused");
3153        assert!(
3154            matches!(&refused, CloudError::Config(text) if text == APP_KEY_PAIRING_FAILED),
3155            "{refused:?}"
3156        );
3157        assert_eq!(
3158            chat_key_repair_refusal(&refused),
3159            Some((None, APP_KEY_PAIRING_FAILED))
3160        );
3161        assert_eq!(
3162            seen.lock().unwrap().len(),
3163            1,
3164            "sent once, never without them"
3165        );
3166        // Without an announcement the same answer is not remapped.
3167        let (origin, _) = one_answer_cloud(400, &refusal);
3168        let client = CloudClient::new(&origin).unwrap();
3169        let plain = start_device_flow_with(&client, None, None, AppKeyOffers::default())
3170            .expect_err("refused");
3171        assert!(!matches!(&plain, CloudError::Config(_)), "{plain:?}");
3172    }
3173
3174    /// f3129: a re-pair against a code answer without `device_app_keys`
3175    /// sends nothing and binds nothing.
3176    #[test]
3177    fn f3129_chat_key_repair_fails_closed_without_the_cloud_feature() {
3178        let (answer, root) = fixture_answer();
3179        let (origin, seen) = one_answer_cloud(200, &answer);
3180        let (_dir, store, keys) = connected(&origin);
3181        let client = CloudClient::new(&origin).unwrap();
3182        let good = offer_for(&test_key(), &keys.public_key_b64());
3183        let mut old = code();
3184        old.features.clear();
3185        let refused = repair_chat_key_at(&store, &client, &old, &root, &|_| {}, &good, fixture_now)
3186            .expect_err("no feature");
3187        assert!(
3188            matches!(&refused, CloudError::Config(text) if text == APP_KEYS_UNSUPPORTED),
3189            "{refused:?}"
3190        );
3191        assert_eq!(
3192            chat_key_repair_refusal(&refused),
3193            Some((None, APP_KEYS_UNSUPPORTED))
3194        );
3195        assert!(seen.lock().unwrap().is_empty(), "nothing sent");
3196        assert_eq!(crate::consent::chat_key::bound_chat_key(&store), None);
3197    }
3198
3199    /// bd 40488: an older Cloud's 400 on a trial with keys names the trial.
3200    #[test]
3201    fn f3129_an_old_cloud_refusing_a_trial_with_keys_names_the_trial() {
3202        let dir = tempfile::tempdir().unwrap();
3203        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
3204        let keys = InstanceKeys::load_or_create(&store).unwrap();
3205        let chat = offer_for(&test_key(), &keys.public_key_b64());
3206        let offers = AppKeyOffers {
3207            chat: Some(&chat),
3208            ..AppKeyOffers::default()
3209        };
3210        let old_cloud = json!({"error": {"code": "invalid_request", "message": "x"}});
3211        let (origin, _) = one_answer_cloud(400, &old_cloud);
3212        let client = CloudClient::new(&origin).unwrap();
3213        let refused = start_device_flow_with(&client, None, Some(TrialPlan::Personal), offers)
3214            .expect_err("old");
3215        assert!(
3216            matches!(&refused, CloudError::TrialUnsupported { .. }),
3217            "{refused:?}"
3218        );
3219    }
3220
3221    /// f3129 S3: a token has no device code to sign over, so a chat key with
3222    /// a token is refused before anything is sent.
3223    #[test]
3224    fn f3129_app_keys_never_go_with_an_enrollment_token() {
3225        let (answer, root) = fixture_answer();
3226        let (origin, seen) = one_answer_cloud(200, &answer);
3227        let (_dir, store, keys) = connected(&origin);
3228        let chat = offer_for(&test_key(), &keys.public_key_b64());
3229        let client = CloudClient::new(&origin).unwrap();
3230        let token = EnrollmentToken::parse(
3231            "het_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
3232        )
3233        .unwrap();
3234        let refused = enroll_with_token_chat(&store, &client, &token, "m", &root, Some(&chat))
3235            .expect_err("refused");
3236        assert!(
3237            matches!(&refused, CloudError::Config(text) if text == CHAT_KEY_WITH_TOKEN),
3238            "{refused:?}"
3239        );
3240        assert!(seen.lock().unwrap().is_empty(), "nothing sent");
3241    }
3242}