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::instance_key::InstanceKeys;
15use super::lease::{VerifiedLease, load_lease, store_lease, verify_keyset, verify_lease};
16use super::state::{CloudStore, INSTANCE_FILE, InstanceRecord, TOKEN_FILE, TokenRecord};
17use super::transport::CloudClient;
18use lean_ctx_protocol::cloud::enroll::{
19    AccessTokenV1, DEVICE_SETUP_REQUEST_SCHEMA, DEVICE_TOKEN_REQUEST_SCHEMA, DeviceCodeRequestV1,
20    DeviceCodeV1, DeviceSetupProjectV1, DeviceSetupRequestV1, EngineOs, EnrollmentV1,
21    TOKEN_REQUEST_SCHEMA, TrialPlan, token_assertion_input,
22};
23use lean_ctx_protocol::cloud::lease::CloudLeaseEnvelopeV1;
24
25/// Tokens are refreshed this long before they expire.
26const TOKEN_REFRESH_MARGIN_SECONDS: i64 = 120;
27
28pub fn engine_os() -> EngineOs {
29    if cfg!(target_os = "macos") {
30        EngineOs::Macos
31    } else if cfg!(target_os = "linux") {
32        EngineOs::Linux
33    } else if cfg!(windows) {
34        EngineOs::Windows
35    } else {
36        EngineOs::Other
37    }
38}
39
40fn stamp(time: UtcDateTime) -> String {
41    time.to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true)
42}
43
44fn protocol(what: &str) -> impl Fn(lean_ctx_protocol::ValidationError) -> CloudError + '_ {
45    move |e| CloudError::Protocol(format!("{what}: {e}"))
46}
47
48fn decode<T: serde::de::DeserializeOwned>(value: Value, what: &str) -> Result<T, CloudError> {
49    serde_json::from_value(value).map_err(|e| CloudError::Protocol(format!("{what}: {e}")))
50}
51
52/// Step 1: ask Cloud for a device code; `label` is the user's `--label`, if
53/// any (the approval page shows it, Cloud task #11).
54pub fn start_device_flow(
55    client: &CloudClient,
56    label: Option<&str>,
57) -> Result<DeviceCodeV1, CloudError> {
58    start_device_flow_for(client, label, None)
59}
60
61/// Step 1 for `cloud connect [--trial]`: `trial` names the plan whose
62/// one-step trial the browser starts (`None`: a plain sign-in, whose
63/// request is exactly the one older Clouds know).
64pub fn start_device_flow_for(
65    client: &CloudClient,
66    label: Option<&str>,
67    trial: Option<TrialPlan>,
68) -> Result<DeviceCodeV1, CloudError> {
69    let request = DeviceCodeRequestV1::new(env!("CARGO_PKG_VERSION"), engine_os())
70        .with_label(label.map(str::to_string))
71        .with_trial(trial);
72    request.validate().map_err(protocol("--label"))?;
73    let body = serde_json::to_value(&request).map_err(|e| CloudError::Protocol(e.to_string()))?;
74    let answer = client.post("/device/code", &body).map_err(|error| {
75        trial_refusal(error, trial.is_some(), client.origin()).with_origin(client.origin())
76    })?;
77    let code: DeviceCodeV1 = decode(answer, "device code")?;
78    code.validate().map_err(protocol("device code"))?;
79    // A Cloud that took the request but does not echo the trial would let
80    // the person sign in without one: refused the same way as a 400.
81    if let Some(plan) = trial
82        && !code.starts_trial(plan)
83    {
84        return Err(CloudError::TrialUnsupported {
85            origin: client.origin().trim_end_matches('/').to_string(),
86        });
87    }
88    Ok(code)
89}
90
91/// A trial request an older Cloud refused for its unknown members (`400
92/// invalid_request`) is [`CloudError::TrialUnsupported`]: it is never sent
93/// again without them, so nobody signs in thinking a trial started.
94pub fn trial_refusal(error: CloudError, trial: bool, origin: &str) -> CloudError {
95    match error {
96        CloudError::Server { status: 400, code } if trial && code == "invalid_request" => {
97            CloudError::TrialUnsupported {
98                origin: origin.trim_end_matches('/').to_string(),
99            }
100        }
101        other => other,
102    }
103}
104
105/// The project an engine names at connect (C0 2.1 device setup): the
106/// checkout's folder name and the remote it sees, plus what it shares.
107#[derive(Debug, Clone, PartialEq, Eq)]
108pub struct SetupAnnouncement {
109    pub project: Option<(String, Option<String>)>,
110    pub shares: Vec<String>,
111}
112
113/// Step 1b (C0 2.1): name the project and what this machine shares, so the
114/// approval page asks "Share this project" too. Only when the Cloud offers
115/// it; `false` when it did not take it (the terminal then asks, as before).
116pub fn announce_setup(
117    client: &CloudClient,
118    code: &DeviceCodeV1,
119    setup: &SetupAnnouncement,
120) -> bool {
121    if !code.offers_device_setup() {
122        return false;
123    }
124    let request = DeviceSetupRequestV1 {
125        schema: DEVICE_SETUP_REQUEST_SCHEMA.into(),
126        device_code: code.device_code.clone(),
127        project: setup
128            .project
129            .clone()
130            .map(|(name, remote)| DeviceSetupProjectV1 { name, remote }),
131        shares: setup.shares.clone(),
132    };
133    let Ok(body) = serde_json::to_value(&request) else {
134        return false;
135    };
136    match client.post("/device/setup", &body) {
137        Ok(_) => true,
138        Err(error) => {
139            tracing::info!("cloud device setup: {error}");
140            false
141        }
142    }
143}
144
145/// What the device approval answered beyond the enrollment: the page's
146/// answer to "Share this project" (C0 2.1). `None`: the page did not ask
147/// (no setup, or an older Cloud); `Some(None)`: an older page approved it.
148pub type SharingAnswer = Option<Option<bool>>;
149
150/// Step 2: poll until the user approved (or the code expired), then verify
151/// and persist the enrollment. `sleep` is injectable for tests.
152pub fn finish_device_flow(
153    store: &CloudStore,
154    client: &CloudClient,
155    code: &DeviceCodeV1,
156    label: &str,
157    root: &[u8; 32],
158    sleep: &dyn Fn(Duration),
159) -> Result<(InstanceRecord, SharingAnswer), CloudError> {
160    let keys = InstanceKeys::load_or_create(store)?;
161    let request = device_token_request(&keys, &code.device_code, label);
162    let expires_in = u64::from(code.expires_in);
163    let deadline = std::time::Instant::now() + Duration::from_secs(expires_in);
164    let mut poll = DevicePoll::new(code.interval);
165    // Seconds slept so far: the deadline also holds when `sleep` does not
166    // pass real time (tests), and never later than the wall clock's.
167    let mut slept = 0u64;
168    let mut wait = poll.interval;
169    loop {
170        let left = expires_in.saturating_sub(slept);
171        let pause = wait.min(left.max(1));
172        sleep(Duration::from_secs(pause));
173        slept = slept.saturating_add(pause);
174        match client.post("/device/token", &request) {
175            Ok(body) => {
176                return accept_enrollment(store, client, body, label, root, UtcDateTime::now());
177            }
178            // A plans page named as a path is shown on this Cloud's origin.
179            Err(error) => {
180                wait = poll
181                    .next_wait(error)
182                    .map_err(|e| e.with_origin(client.origin()))?;
183            }
184        }
185        if std::time::Instant::now() >= deadline || slept >= expires_in {
186            return Err(CloudError::DeviceFlow(super::error::CODE_EXPIRED.into()));
187        }
188    }
189}
190
191/// The longest pause between two device-token polls after transient
192/// failures without a `Retry-After` (seconds).
193const DEVICE_POLL_BACKOFF_CAP_S: u64 = 60;
194
195/// The pacing of the device-token polls (RFC 8628 §3.5): `authorization_pending`
196/// keeps the interval, `slow_down` raises it by 5 s for good, a transient
197/// failure (offline, timeout, 429, 5xx) waits its `Retry-After` or backs off
198/// exponentially; every other answer (`access_denied`, `expired_token`,
199/// `invalid_grant`, …) ends the flow.
200#[derive(Debug)]
201struct DevicePoll {
202    interval: u64,
203    /// Transient failures in a row.
204    failures: u32,
205}
206
207impl DevicePoll {
208    fn new(interval: u32) -> Self {
209        Self {
210            interval: u64::from(interval.max(1)),
211            failures: 0,
212        }
213    }
214
215    /// Seconds to wait before the next poll after `error`, or the error
216    /// that ends the flow.
217    fn next_wait(&mut self, error: CloudError) -> Result<u64, CloudError> {
218        match &error {
219            CloudError::Server { status: 400, code } if code == "authorization_pending" => {
220                self.failures = 0;
221                Ok(self.interval)
222            }
223            CloudError::Server { status: 400, code } if code == "slow_down" => {
224                self.failures = 0;
225                self.interval = self.interval.saturating_add(5);
226                Ok(self.interval)
227            }
228            transient if transient.is_transient() => {
229                self.failures = self.failures.saturating_add(1);
230                let backoff = self
231                    .interval
232                    .saturating_mul(1u64 << self.failures.min(6))
233                    .min(DEVICE_POLL_BACKOFF_CAP_S.max(self.interval));
234                let asked = transient.retry_after_at(UtcDateTime::now()).unwrap_or(0);
235                tracing::info!("cloud device token: {transient}; polling again");
236                Ok(backoff.max(asked).max(self.interval))
237            }
238            _ => Err(error),
239        }
240    }
241}
242
243/// The `POST /v1/device/token` body: the device code (or an enrollment
244/// token in its place) and this instance's public keys.
245fn device_token_request(keys: &InstanceKeys, device_code: &str, label: &str) -> Value {
246    json!({
247        "schema": DEVICE_TOKEN_REQUEST_SCHEMA,
248        "device_code": device_code,
249        "instance_public_key": keys.public_key_b64(),
250        "instance_kx_public_key": keys.kx_public_key_b64(),
251        "instance_label": label,
252        "instance_version": env!("CARGO_PKG_VERSION"),
253        "os": engine_os(),
254    })
255}
256
257/// Verify and persist the enrollment Cloud answered at `/device/token`.
258fn accept_enrollment(
259    store: &CloudStore,
260    client: &CloudClient,
261    body: Value,
262    label: &str,
263    root: &[u8; 32],
264    local_now: UtcDateTime,
265) -> Result<(InstanceRecord, SharingAnswer), CloudError> {
266    let keys_raw = body["keys"].clone();
267    let sharing: SharingAnswer = body
268        .get("sharing")
269        .filter(|s| s.is_object())
270        .map(|s| s["share"].as_bool());
271    decode::<EnrollmentV1>(body, "enrollment")
272        .and_then(|enrollment| {
273            complete_enrollment(
274                store,
275                client.origin(),
276                &enrollment,
277                &keys_raw,
278                root,
279                label,
280                local_now,
281            )
282        })
283        .map(|instance| (instance, sharing))
284        .map_err(|error| unenrolled(store, label, error))
285}
286
287/// The plaintext prefix of a pre-issued Host enrollment token.
288pub const ENROLLMENT_TOKEN_PREFIX: &str = "het_";
289
290/// Why a Cloud refused an enrollment token, in the words a person acts on.
291pub const ENROLLMENT_TOKEN_UNUSABLE: &str =
292    "the enrollment token is unknown, expired, revoked or used up; ask a team admin for a new one";
293
294/// A pre-issued Host enrollment token (`het_` and 64 hex digits) that a
295/// team admin handed out, e.g. through MDM. It enrolls this machine without
296/// a browser approval. The value is wiped on drop and never printed: its
297/// `Debug` shows the prefix only, and no error names it.
298pub struct EnrollmentToken(zeroize::Zeroizing<String>);
299
300impl EnrollmentToken {
301    /// Check the format before anything is sent: surrounding whitespace
302    /// (a trailing newline from stdin) is dropped, everything else must be
303    /// `het_` and exactly 64 hex digits.
304    pub fn parse(raw: &str) -> Result<Self, CloudError> {
305        let value = raw.trim();
306        let well_formed = value
307            .strip_prefix(ENROLLMENT_TOKEN_PREFIX)
308            .is_some_and(|hex| hex.len() == 64 && hex.bytes().all(|b| b.is_ascii_hexdigit()));
309        if !well_formed {
310            return Err(CloudError::Config(
311                "the enrollment token is malformed: it is `het_` followed by 64 hex digits, as the team's Hosts page issued it".into(),
312            ));
313        }
314        Ok(Self(zeroize::Zeroizing::new(value.to_string())))
315    }
316
317    fn expose(&self) -> &str {
318        &self.0
319    }
320}
321
322impl std::fmt::Debug for EnrollmentToken {
323    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
324        write!(f, "EnrollmentToken({ENROLLMENT_TOKEN_PREFIX}…)")
325    }
326}
327
328/// Enroll this machine with a pre-issued enrollment token (no browser):
329/// one `POST /v1/device/token` with the token as `device_code`, then the
330/// enrollment is verified and persisted exactly as after a device approval.
331pub fn enroll_with_token(
332    store: &CloudStore,
333    client: &CloudClient,
334    token: &EnrollmentToken,
335    label: &str,
336    root: &[u8; 32],
337) -> Result<(InstanceRecord, SharingAnswer), CloudError> {
338    enroll_with_token_at(
339        store,
340        client,
341        token,
342        label,
343        root,
344        lean_ctx_time::UtcDateTime::now,
345    )
346}
347
348fn enroll_with_token_at(
349    store: &CloudStore,
350    client: &CloudClient,
351    token: &EnrollmentToken,
352    label: &str,
353    root: &[u8; 32],
354    now: impl Fn() -> UtcDateTime,
355) -> Result<(InstanceRecord, SharingAnswer), CloudError> {
356    let keys = InstanceKeys::load_or_create(store)?;
357    let request = device_token_request(&keys, token.expose(), label);
358    match client.post("/device/token", &request) {
359        Ok(body) => accept_enrollment(store, client, body, label, root, now()),
360        Err(error) => Err(token_refusal(error)),
361    }
362}
363
364/// An enrollment token's refusal: Cloud answers `expired_token` for an
365/// unknown, expired, revoked or used-up token (mapped to the device
366/// code's wording by the transport), named here for a token.
367fn token_refusal(error: CloudError) -> CloudError {
368    match error {
369        CloudError::DeviceFlow(why) if why == super::error::CODE_EXPIRED => {
370            CloudError::DeviceFlow(ENROLLMENT_TOKEN_UNUSABLE.into())
371        }
372        CloudError::Server { status: 400, code } if code == "expired_token" => {
373            CloudError::DeviceFlow(ENROLLMENT_TOKEN_UNUSABLE.into())
374        }
375        other => other,
376    }
377}
378
379/// Cloud enrolled the instance key, but this engine refused the answer
380/// (Cloud task #1): the key is spent, since Cloud now knows it and refuses
381/// it a second time ("instance key is already enrolled"). A machine without
382/// an enrollment of its own drops it with whatever the refused answer left,
383/// so the next connect starts from a fresh key, and the error says so.
384fn unenrolled(store: &CloudStore, label: &str, error: CloudError) -> CloudError {
385    if !matches!(store.instance(), Ok(None)) {
386        return error;
387    }
388    let next = match store.forget(true) {
389        Ok(()) => format!(
390            "Its unused instance key was removed: fix the cause and run `lean-ctx cloud connect` again. LeanCTX Cloud may list an instance \"{label}\" that never connected; remove it there."
391        ),
392        Err(e) => format!(
393            "Its unused instance key could not be removed ({e}); run `lean-ctx cloud disconnect` before connecting again."
394        ),
395    };
396    match error {
397        CloudError::Protocol(m) => CloudError::Protocol(format!("{m}. {next}")),
398        CloudError::Config(m) => CloudError::Config(format!("{m}. {next}")),
399        other => other,
400    }
401}
402
403/// Verify an enrollment answer against the root key and persist it.
404pub fn complete_enrollment(
405    store: &CloudStore,
406    origin: &str,
407    enrollment: &EnrollmentV1,
408    keys_raw: &Value,
409    root: &[u8; 32],
410    label: &str,
411    local_now: UtcDateTime,
412) -> Result<InstanceRecord, CloudError> {
413    enrollment.validate().map_err(protocol("enrollment"))?;
414    let keyset = verify_keyset(keys_raw, root)?;
415    let verified = verify_lease(
416        &enrollment.lease,
417        &keyset,
418        &enrollment.instance_id,
419        local_now,
420        None,
421    )?;
422    if verified.lease.org_id != enrollment.org.id {
423        return Err(CloudError::Protocol(
424            "the lease is for another workspace".into(),
425        ));
426    }
427    // `cloud.org` / `cloud.url` of a managed machine: refused before anything
428    // of this enrollment is stored.
429    if let Some(refusal) = super::config::managed_enrollment_refusal(&enrollment.org.id, origin) {
430        return Err(refusal);
431    }
432    store_lease(store, &verified, keys_raw, local_now)?;
433    let record = InstanceRecord {
434        instance_id: enrollment.instance_id.clone(),
435        org_id: enrollment.org.id.clone(),
436        org_name: enrollment.org.name.clone(),
437        org_kind: enrollment.org.kind.clone(),
438        company_name: enrollment.org.company.as_ref().map(|c| c.name.clone()),
439        label: label.to_string(),
440        url: origin.to_string(),
441        org_salt_id: enrollment.org_salt_id.clone(),
442        web_url: enrollment
443            .web_url
444            .as_deref()
445            .and_then(|url| super::config::normalize_origin(url).ok()),
446        enrolled_at: stamp(local_now),
447    };
448    super::worker::prepare_enrollment(store)?;
449    store.write_config(INSTANCE_FILE, &record)?;
450    // A new enrolment starts a new sharing period (Cloud' `since`): an
451    // earlier engine-side off no longer bounds it (K2 review 3, NEW-1).
452    super::metrics_v2::buffer::clear_local_on_since(store.data_dir());
453    store.remove_config(TOKEN_FILE)?;
454    store.record_success("enroll", &stamp(verified.service_time(local_now).to_utc()));
455    Ok(record)
456}
457
458/// A connected instance: its record, verified lease and keys.
459pub struct Session {
460    pub store: CloudStore,
461    pub instance: InstanceRecord,
462    pub lease: VerifiedLease,
463    root: [u8; 32],
464}
465
466impl Session {
467    /// Load and re-verify the local enrollment. `root` is the root key of the
468    /// origin the instance is enrolled with.
469    pub fn load(store: CloudStore, root: [u8; 32]) -> Result<Self, CloudError> {
470        let instance = store.instance()?.ok_or(CloudError::NotConnected)?;
471        // A revoked instance fails closed here, before any Cloud call.
472        if let Some(revoked) = super::revoked::recorded(&store, &instance) {
473            return Err(revoked);
474        }
475        // An enrollment from before the machine was managed, with another
476        // org or Cloud, is not used.
477        if let Some(refusal) =
478            super::config::managed_enrollment_refusal(&instance.org_id, &instance.url)
479        {
480            return Err(refusal);
481        }
482        let lease = load_lease(&store, &root, &instance.instance_id)?;
483        super::root_cert::check_lease_org(&store, &instance.url, &lease.lease)?;
484        Ok(Self {
485            store,
486            instance,
487            lease,
488            root,
489        })
490    }
491
492    /// The root key the enrollment was verified with.
493    pub fn root_key(&self) -> &[u8; 32] {
494        &self.root
495    }
496
497    fn service_now(&self) -> UtcDateTime {
498        self.lease.service_time(UtcDateTime::now()).to_utc()
499    }
500
501    /// The current access token (minted when needed), for transports that
502    /// authenticate outside [`CloudClient`] (the bus WebSocket upgrade).
503    /// `force` mints a new one.
504    pub fn bearer_token(&self, force: bool) -> Result<zeroize::Zeroizing<String>, CloudError> {
505        self.access_token(force).map(zeroize::Zeroizing::new)
506    }
507
508    /// An authenticated client, minting an access token when needed.
509    pub fn client(&self) -> Result<CloudClient, CloudError> {
510        let token = self.access_token(false)?;
511        Ok(CloudClient::new(&self.instance.url)?.with_token(&self.instance.instance_id, &token))
512    }
513
514    /// Run `call` with an authenticated client; on 401 mint a new token once.
515    pub fn with_client<T>(
516        &self,
517        call: impl Fn(&CloudClient) -> Result<T, CloudError>,
518    ) -> Result<T, CloudError> {
519        let result = match call(&self.client()?) {
520            Err(CloudError::Unauthorized) => {
521                let token = self.access_token(true)?;
522                let client = CloudClient::new(&self.instance.url)?
523                    .with_token(&self.instance.instance_id, &token);
524                call(&client)
525            }
526            other => other,
527        };
528        result.map_err(|e| self.noted(e))
529    }
530
531    /// A revocation answer is recorded (the engine then fails closed) and
532    /// named with this workspace; a used-up quota holds the paths it counts
533    /// (`throttle`); a feature's `plan_required` names the lease's plan;
534    /// any other error passes unchanged.
535    pub(crate) fn noted(&self, error: CloudError) -> CloudError {
536        let error = super::revoked::note(&self.store, &self.instance, error)
537            .with_plan(self.lease.lease.plan);
538        super::throttle::note_on(&self.store, None, error, lean_ctx_time::UtcDateTime::now())
539    }
540
541    /// An authenticated client for one call that must end by `deadline`,
542    /// minting the token (if needed) inside the same budget and without the
543    /// 401 retry of [`Self::with_client`] (C5c, rule 3 exception).
544    pub fn bounded_client(&self, deadline: std::time::Instant) -> Result<CloudClient, CloudError> {
545        let left = |what: &str| {
546            deadline
547                .checked_duration_since(std::time::Instant::now())
548                .filter(|d| !d.is_zero())
549                .ok_or_else(|| CloudError::Offline(format!("{what}: time budget used up")))
550        };
551        let mint = CloudClient::bounded(&self.instance.url, left("token")?)?;
552        let token = self.access_token_via(false, &mint)?;
553        Ok(CloudClient::bounded(&self.instance.url, left("request")?)?
554            .with_token(&self.instance.instance_id, &token))
555    }
556
557    /// The token is minted in C0 2.0 like every other request.
558    fn access_token(&self, force: bool) -> Result<String, CloudError> {
559        self.access_token_via(force, &CloudClient::new(&self.instance.url)?)
560    }
561
562    fn access_token_via(&self, force: bool, client: &CloudClient) -> Result<String, CloudError> {
563        let now = self.service_now().timestamp();
564        if !force
565            && let Some(cached) = self.store.read_config::<TokenRecord>(TOKEN_FILE)?
566            && cached.expires_at - TOKEN_REFRESH_MARGIN_SECONDS > now
567        {
568            return Ok(cached.access_token);
569        }
570        // A 429 of the mint holds every process of this machine (they share
571        // the instance key and the server's budget, which counts refused
572        // attempts too): nothing is sent until it ends, a forced or manual
573        // mint neither.
574        if let Some(held) = super::throttle::token_hold(&self.store, UtcDateTime::now()) {
575            return Err(held);
576        }
577        let keys = InstanceKeys::load(&self.store)?;
578        let mut nonce_bytes = [0u8; 18];
579        getrandom::fill(&mut nonce_bytes).map_err(|e| CloudError::Local(format!("random: {e}")))?;
580        use base64::Engine as _;
581        let nonce = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(nonce_bytes);
582        let assertion = keys.sign_b64(&token_assertion_input(
583            &self.instance.instance_id,
584            now,
585            &nonce,
586        ));
587        let request = json!({
588            "schema": TOKEN_REQUEST_SCHEMA, "iat": now, "nonce": nonce, "assertion": assertion,
589        });
590        let path = format!("/instances/{}/token", self.instance.instance_id);
591        let answer = client.post(&path, &request).map_err(|e| {
592            super::throttle::note_token_limit(&self.store, self.noted(e), UtcDateTime::now())
593        })?;
594        let token: AccessTokenV1 = decode(answer, "access token")?;
595        token.validate().map_err(protocol("access token"))?;
596        super::throttle::token_minted(&self.store);
597        self.store.write_config(
598            TOKEN_FILE,
599            &TokenRecord {
600                access_token: token.access_token.clone(),
601                expires_at: now + i64::from(token.expires_in),
602            },
603        )?;
604        self.store
605            .record_success("token", &stamp(self.service_now()));
606        Ok(token.access_token)
607    }
608
609    /// Renew the lease and persist it; returns the new lease. Asked in C0
610    /// 2.0 like the enrollment whose lease it replaces, and checked against
611    /// the key set that holds its `kid` (which also feeds the runtime lease):
612    /// the stored one, else key set v3, by which a C0 2.x Cloud signs leases
613    /// once it serves v3, fetched once when it is not stored yet. The key
614    /// set the lease verified with is stored with it, so every later load
615    /// re-verifies it the same way.
616    pub fn renew(&mut self) -> Result<&VerifiedLease, CloudError> {
617        let path = format!("/instances/{}/lease/renew", self.instance.instance_id);
618        let body = self.with_client(|client| client.post(&path, &json!({})))?;
619        let local_now = UtcDateTime::now();
620        let envelope: CloudLeaseEnvelopeV1 = decode(body, "lease")?;
621        let stored: Value = self
622            .store
623            .read_config(super::state::KEYS_FILE)?
624            .ok_or(CloudError::NotConnected)?;
625        let pick = |session: &Self| {
626            super::lease::renewal_key_set(
627                &stored,
628                super::keyset_v3::stored_raw(&session.store).as_ref(),
629                &session.root,
630                &envelope.kid,
631            )
632        };
633        let keys_raw = if let Some(raw) = pick(self) {
634            raw
635        } else {
636            super::keyset_v3::refresh(self)?;
637            pick(self).ok_or_else(|| {
638                CloudError::Protocol(format!(
639                    "the renewed lease names key {}, which no verified key set holds",
640                    envelope.kid
641                ))
642            })?
643        };
644        let keyset = verify_keyset(&keys_raw, &self.root)?;
645        let verified = verify_lease(
646            &envelope,
647            &keyset,
648            &self.instance.instance_id,
649            local_now,
650            None,
651        )?;
652        store_lease(&self.store, &verified, &keys_raw, local_now)?;
653        self.store
654            .record_success("lease", &stamp(verified.service_time(local_now).to_utc()));
655        self.store.record_renew_error(None);
656        self.lease = verified;
657        Ok(&self.lease)
658    }
659
660    /// Free the seat in Cloud.
661    pub fn delete_instance(&self) -> Result<(), CloudError> {
662        let path = format!("/instances/{}", self.instance.instance_id);
663        self.with_client(|client| client.delete(&path))
664    }
665}
666
667/// A session loaded from the enrollment fixture (key set v1) in a fresh
668/// store, for tests of passes that take a [`Session`] but must send
669/// nothing. Its origin is never contacted by such a test.
670#[cfg(test)]
671pub(crate) fn fixture_session() -> (tempfile::TempDir, Session) {
672    let path = concat!(
673        env!("CARGO_MANIFEST_DIR"),
674        "/../lean-ctx-protocol/tests/fixtures/cloud/enrollment.response.json"
675    );
676    let raw: Value = serde_json::from_slice(&std::fs::read(path).expect("fixture")).expect("json");
677    let root = ed25519_dalek::SigningKey::from_bytes(&[0x52; 32])
678        .verifying_key()
679        .to_bytes();
680    let dir = tempfile::tempdir().expect("tempdir");
681    let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
682    let enrollment: EnrollmentV1 = decode(raw.clone(), "enrollment").expect("enrollment");
683    complete_enrollment(
684        &store,
685        "https://cloud.leanctx.com",
686        &enrollment,
687        &raw["keys"],
688        &root,
689        "studio-mac",
690        lean_ctx_time::OffsetDateTime::parse_from_rfc3339("2026-10-20T12:00:00Z")
691            .expect("time")
692            .to_utc(),
693    )
694    .expect("enrolled");
695    let session = Session::load(store, root).expect("session");
696    (dir, session)
697}
698
699#[cfg(test)]
700mod tests {
701    use super::*;
702
703    /// An older Cloud refuses the trial members (`deny_unknown_fields`):
704    /// `trial_unsupported`, never a silent sign-in; a sign-in's own 400 and
705    /// every other trial refusal stay what they were.
706    #[test]
707    fn trial_request_refused_as_unknown_is_trial_unsupported() {
708        let refused = || CloudError::Server {
709            status: 400,
710            code: "invalid_request".into(),
711        };
712        let mapped = trial_refusal(refused(), true, "https://cloud.leanctx.com/");
713        assert_eq!(
714            mapped,
715            CloudError::TrialUnsupported {
716                origin: "https://cloud.leanctx.com".into()
717            }
718        );
719        assert_eq!(mapped.event_code(), "trial_unsupported");
720        assert_eq!(
721            mapped.to_string(),
722            "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`"
723        );
724        // Printed by the terminal and by LeanCTX Code alike.
725        assert!(!mapped.to_string().contains("app"));
726        assert_eq!(
727            trial_refusal(refused(), false, "https://cloud.leanctx.com"),
728            refused()
729        );
730        let offline = CloudError::Offline("reset".into());
731        assert_eq!(
732            trial_refusal(offline.clone(), true, "https://cloud.leanctx.com"),
733            offline
734        );
735    }
736
737    fn fixture(path: &str) -> Value {
738        let path = format!(
739            "{}/crates/lean-ctx-protocol/tests/fixtures/{path}",
740            concat!(env!("CARGO_MANIFEST_DIR"), "/../..")
741        );
742        serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
743    }
744
745    fn at(t: &str) -> UtcDateTime {
746        lean_ctx_time::OffsetDateTime::parse_from_rfc3339(t)
747            .unwrap()
748            .to_utc()
749    }
750
751    /// Enroll `raw` in a fresh store; the directory lives as long as the
752    /// returned guard.
753    fn enroll(
754        raw: &Value,
755        root: &[u8; 32],
756    ) -> Result<(tempfile::TempDir, CloudStore, InstanceRecord), CloudError> {
757        let dir = tempfile::tempdir().unwrap();
758        let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
759        let enrollment: EnrollmentV1 = decode(raw.clone(), "enrollment")?;
760        let record = complete_enrollment(
761            &store,
762            "https://cloud.leanctx.com",
763            &enrollment,
764            &raw["keys"],
765            root,
766            "studio-mac",
767            at("2026-10-20T12:00:00Z"),
768        )?;
769        let lease = load_lease(&store, root, &record.instance_id)?;
770        assert_eq!(lease.envelope.kid, enrollment.lease.kid);
771        Ok((dir, store, record))
772    }
773
774    /// Below Cloud-Protocol 2.1: key set v1, the lease signed by its `kid`.
775    #[test]
776    fn an_enrollment_with_key_set_v1_is_verified_and_kept() {
777        use ed25519_dalek::SigningKey;
778        let raw = fixture("cloud/enrollment.response.json");
779        let root = SigningKey::from_bytes(&[0x52; 32])
780            .verifying_key()
781            .to_bytes();
782        let (_dir, _store, record) = enroll(&raw, &root).unwrap();
783        assert_eq!(record.org_id, "org_acme");
784        let refused = enroll(&raw, &[7; 32]).expect_err("another root");
785        assert!(
786            refused
787                .to_string()
788                .contains(super::super::lease::ROOT_MISMATCH)
789        );
790    }
791
792    /// Cloud-Protocol 2.1 (`routes/enrollment.for_2x.response.json`): key set
793    /// v3, verified as every v3 set, and the lease signed by the key of
794    /// purpose `policy` its `kid` names.
795    #[test]
796    fn an_enrollment_with_key_set_v3_is_verified_with_its_policy_key() {
797        let raw = fixture("cloud-v2/routes/enrollment.for_2x.response.json");
798        let mut root = [0u8; 32];
799        hex::decode_to_slice(
800            fixture("cloud-v2/vectors/signing.vectors.json")["keys"]["root_new"]["public_key_hex"]
801                .as_str()
802                .unwrap(),
803            &mut root,
804        )
805        .unwrap();
806        let (_dir, store, record) = enroll(&raw, &root).unwrap();
807        assert_eq!(record.org_id, "org_acme");
808        assert_eq!(raw["lease"]["kid"], "552e43422b3589fa");
809        let kept: Value = store
810            .read_config(super::super::state::KEYS_FILE)
811            .unwrap()
812            .unwrap();
813        assert_eq!(kept, raw["keys"], "the v3 set is kept as received");
814        // Another root, or a lease kid of a key that signs no leases: refused.
815        assert!(enroll(&raw, &[7; 32]).is_err());
816        let mut event_kid = raw;
817        event_kid["lease"]["kid"] = "4fc7bebc302357bd".into();
818        assert!(enroll(&event_kid, &root).is_err());
819    }
820
821    const TOKEN: &str = "het_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
822
823    #[test]
824    fn an_enrollment_token_is_checked_before_anything_is_sent() {
825        let token = EnrollmentToken::parse(&format!("  {TOKEN}\r\n")).unwrap();
826        assert_eq!(
827            token.expose(),
828            TOKEN,
829            "a trailing newline from stdin is dropped"
830        );
831        assert!(
832            EnrollmentToken::parse(&TOKEN.to_ascii_uppercase().replace("HET_", "het_")).is_ok()
833        );
834        let short = &TOKEN[..TOKEN.len() - 1];
835        let not_hex = format!("{}g", &TOKEN[..TOKEN.len() - 1]);
836        let device_code = TOKEN.replace("het_", "hdc_");
837        let inner_space = format!("{} {}", &TOKEN[..20], &TOKEN[20..]);
838        for bad in [
839            "",
840            "het_",
841            short,
842            &not_hex,
843            &device_code,
844            &inner_space,
845            &format!("{TOKEN}0"),
846        ] {
847            let error = EnrollmentToken::parse(bad).expect_err(bad).to_string();
848            assert!(error.contains("malformed"), "{error}");
849            assert!(
850                bad.len() < 8 || !error.contains(bad),
851                "the value is never echoed: {error}"
852            );
853        }
854        assert_eq!(format!("{token:?}"), "EnrollmentToken(het_…)");
855    }
856
857    type Recorded = std::sync::Arc<std::sync::Mutex<Vec<(String, Value)>>>;
858
859    /// A one-route Cloud on 127.0.0.1 that answers every request with
860    /// `answer` and records what it was sent.
861    #[allow(clippy::needless_pass_by_value)] // callers hand over a fresh `json!`
862    fn fake_cloud(answer: (u16, Value)) -> (String, Recorded) {
863        let (status, body) = answer;
864        let raw = raw_answer(
865            status,
866            "Content-Type: application/json\r\n",
867            &body.to_string(),
868        );
869        scripted_cloud(vec![raw])
870    }
871
872    /// A raw HTTP answer: status, extra header lines and body.
873    fn raw_answer(status: u16, headers: &str, body: &str) -> String {
874        format!(
875            "HTTP/1.1 {status} X\r\n{headers}Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
876            body.len()
877        )
878    }
879
880    /// A Cloud on 127.0.0.1 that answers the n-th request with the n-th raw
881    /// HTTP answer (the last one repeats) and records what it was sent.
882    fn scripted_cloud(answers: Vec<String>) -> (String, Recorded) {
883        use std::io::{BufRead as _, Read as _, Write as _};
884        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
885        let origin = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());
886        let recorded: Recorded = std::sync::Arc::default();
887        let seen = std::sync::Arc::clone(&recorded);
888        std::thread::spawn(move || {
889            for stream in listener.incoming().flatten() {
890                let mut writer = stream.try_clone().unwrap();
891                let mut reader = std::io::BufReader::new(stream);
892                let mut line = String::new();
893                if reader.read_line(&mut line).unwrap_or(0) == 0 {
894                    continue;
895                }
896                let path = line
897                    .split_whitespace()
898                    .nth(1)
899                    .unwrap_or_default()
900                    .to_owned();
901                let mut length = 0;
902                loop {
903                    let mut header = String::new();
904                    reader.read_line(&mut header).unwrap();
905                    let header = header.trim_end();
906                    if header.is_empty() {
907                        break;
908                    }
909                    if let Some((name, value)) = header.split_once(':')
910                        && name.eq_ignore_ascii_case("content-length")
911                    {
912                        length = value.trim().parse().unwrap();
913                    }
914                }
915                let mut body = vec![0; length];
916                reader.read_exact(&mut body).unwrap();
917                let body = serde_json::from_slice(&body).unwrap_or(Value::Null);
918                let n = {
919                    let mut seen = seen.lock().unwrap();
920                    seen.push((path, body));
921                    seen.len() - 1
922                };
923                let raw = &answers[n.min(answers.len() - 1)];
924                let _ = writer.write_all(raw.as_bytes());
925            }
926        });
927        (origin, recorded)
928    }
929
930    fn device_code(interval: u32, expires_in: u32) -> DeviceCodeV1 {
931        DeviceCodeV1 {
932            schema: lean_ctx_protocol::cloud::enroll::DEVICE_CODE_SCHEMA.into(),
933            device_code: "hdc_test".into(),
934            user_code: "WDJB-MJHT".into(),
935            verification_uri: "https://cloud.example.com/device".into(),
936            verification_uri_complete: "https://cloud.example.com/device?c=WDJB-MJHT".into(),
937            interval,
938            expires_in,
939            features: Vec::new(),
940            intent: None,
941            plan: None,
942        }
943    }
944
945    const EDGE_502: &str = "<html><body><h1>502 Bad Gateway</h1></body></html>";
946
947    /// Review fix: an edge error page (502/503 HTML, 429 with only a
948    /// `Retry-After` header) or a refused connection does not end the
949    /// device flow; the poll waits (`Retry-After`, else backoff) and goes
950    /// on, `slow_down` raises the interval, `access_denied` ends it.
951    #[test]
952    fn the_device_flow_rides_out_transient_failures_until_a_final_answer() {
953        let json = "Content-Type: application/json\r\n";
954        let html = "Content-Type: text/html\r\n";
955        let (origin, recorded) = scripted_cloud(vec![
956            raw_answer(502, html, EDGE_502),
957            raw_answer(
958                429,
959                &format!("{html}Retry-After: 30\r\n"),
960                "Too Many Requests",
961            ),
962            raw_answer(503, html, ""),
963            raw_answer(
964                400,
965                json,
966                r#"{"error":{"code":"authorization_pending","message":"x"}}"#,
967            ),
968            raw_answer(400, json, r#"{"error":{"code":"slow_down","message":"x"}}"#),
969            raw_answer(
970                400,
971                json,
972                r#"{"error":{"code":"access_denied","message":"x"}}"#,
973            ),
974        ]);
975        let dir = tempfile::tempdir().unwrap();
976        let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
977        let client = CloudClient::new(&origin).unwrap();
978        let sleeps = std::cell::RefCell::new(Vec::new());
979        let error = finish_device_flow(
980            &store,
981            &client,
982            &device_code(2, 600),
983            "studio-mac",
984            &[7; 32],
985            &|d| sleeps.borrow_mut().push(d.as_secs()),
986        )
987        .expect_err("denied");
988        assert!(matches!(error, CloudError::DeviceFlow(_)), "{error:?}");
989        assert!(error.to_string().contains("Not mine"), "{error}");
990        assert_eq!(recorded.lock().unwrap().len(), 6);
991        // interval 2; 502 → 4 (backoff); 429 → its Retry-After 30; 503 →
992        // 16 (third failure in a row); pending → 2; slow_down → 2 + 5.
993        assert_eq!(sleeps.into_inner(), vec![2, 4, 30, 16, 2, 7]);
994        assert!(store.instance().unwrap().is_none(), "nothing enrolled");
995    }
996
997    #[test]
998    fn transient_failures_end_the_device_flow_only_at_its_deadline() {
999        let (origin, recorded) = scripted_cloud(vec![raw_answer(
1000            503,
1001            "Content-Type: text/html\r\n",
1002            EDGE_502,
1003        )]);
1004        let dir = tempfile::tempdir().unwrap();
1005        let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
1006        let client = CloudClient::new(&origin).unwrap();
1007        let sleeps = std::cell::RefCell::new(Vec::new());
1008        let error = finish_device_flow(
1009            &store,
1010            &client,
1011            &device_code(5, 120),
1012            "studio-mac",
1013            &[7; 32],
1014            &|d| sleeps.borrow_mut().push(d.as_secs()),
1015        )
1016        .expect_err("expired");
1017        assert_eq!(
1018            error,
1019            CloudError::DeviceFlow(super::super::error::CODE_EXPIRED.into())
1020        );
1021        let sleeps = sleeps.into_inner();
1022        assert_eq!(sleeps.iter().sum::<u64>(), 120, "{sleeps:?}");
1023        assert!(sleeps.iter().all(|s| *s <= DEVICE_POLL_BACKOFF_CAP_S));
1024        assert_eq!(recorded.lock().unwrap().len(), sleeps.len());
1025    }
1026
1027    #[test]
1028    fn device_poll_pacing_keeps_final_refusals_fatal() {
1029        let mut poll = DevicePoll::new(0);
1030        assert_eq!(poll.interval, 1, "an interval of 0 polls each second");
1031        for fatal in [
1032            CloudError::DeviceFlow(super::super::error::CODE_EXPIRED.into()),
1033            CloudError::Server {
1034                status: 400,
1035                code: "unknown".into(),
1036            },
1037            CloudError::Unauthorized,
1038            CloudError::Server {
1039                status: 413,
1040                code: "payload_too_large".into(),
1041            },
1042        ] {
1043            assert_eq!(poll.next_wait(fatal.clone()), Err(fatal));
1044        }
1045        let offline = CloudError::Offline("timeout".into());
1046        assert_eq!(poll.next_wait(offline.clone()), Ok(2));
1047        assert_eq!(poll.next_wait(offline.clone()), Ok(4));
1048        for _ in 0..10 {
1049            assert!(poll.next_wait(offline.clone()).unwrap() <= DEVICE_POLL_BACKOFF_CAP_S);
1050        }
1051        let limited = CloudError::RateLimited {
1052            retry_after: Some(90),
1053        };
1054        assert_eq!(poll.next_wait(limited), Ok(90), "Retry-After wins");
1055    }
1056
1057    #[test]
1058    fn an_enrollment_token_enrolls_in_one_request_without_a_browser() {
1059        use ed25519_dalek::SigningKey;
1060        let raw = fixture("cloud/enrollment.response.json");
1061        let root = SigningKey::from_bytes(&[0x52; 32])
1062            .verifying_key()
1063            .to_bytes();
1064        let (origin, recorded) = fake_cloud((200, raw));
1065        let dir = tempfile::tempdir().unwrap();
1066        let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
1067        let client = CloudClient::new(&origin).unwrap();
1068        let token = EnrollmentToken::parse(TOKEN).unwrap();
1069        let (record, sharing) =
1070            enroll_with_token_at(&store, &client, &token, "ci-runner-7", &root, || {
1071                at("2026-10-20T12:00:00Z")
1072            })
1073            .unwrap();
1074        assert_eq!(record.org_id, "org_acme");
1075        assert_eq!(record.label, "ci-runner-7");
1076        assert_eq!(sharing, None, "no approval page asked anything");
1077        assert_eq!(
1078            store.instance().unwrap().unwrap().instance_id,
1079            record.instance_id
1080        );
1081        let sent = recorded.lock().unwrap().clone();
1082        assert_eq!(sent.len(), 1, "one request, no device code, no polling");
1083        let (path, body) = &sent[0];
1084        assert_eq!(path, "/v1/device/token");
1085        assert_eq!(body["schema"], DEVICE_TOKEN_REQUEST_SCHEMA);
1086        assert_eq!(body["device_code"], TOKEN);
1087        assert_eq!(body["instance_label"], "ci-runner-7");
1088        let keys = InstanceKeys::load(&store).unwrap();
1089        assert_eq!(body["instance_public_key"], keys.public_key_b64());
1090        assert_eq!(body["instance_kx_public_key"], keys.kx_public_key_b64());
1091        assert_eq!(body["instance_version"], env!("CARGO_PKG_VERSION"));
1092    }
1093
1094    #[test]
1095    fn a_refused_enrollment_token_says_why_without_naming_it() {
1096        let refusal = json!({"error": {"code": "expired_token", "message":
1097            "Unknown, expired, revoked or used-up enrollment token; ask a team admin for a new one."}});
1098        let (origin, recorded) = fake_cloud((400, refusal));
1099        let dir = tempfile::tempdir().unwrap();
1100        let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
1101        let client = CloudClient::new(&origin).unwrap();
1102        let token = EnrollmentToken::parse(TOKEN).unwrap();
1103        let error = enroll_with_token(&store, &client, &token, "ci", &[7; 32])
1104            .expect_err("refused")
1105            .to_string();
1106        assert!(error.contains(ENROLLMENT_TOKEN_UNUSABLE), "{error}");
1107        assert!(!error.contains(&TOKEN[4..]), "{error}");
1108        assert!(store.instance().unwrap().is_none(), "nothing enrolled");
1109        assert_eq!(recorded.lock().unwrap().len(), 1);
1110        // The transport's code-expired wording and a bare code map the same.
1111        for raw in [
1112            CloudError::DeviceFlow(super::super::error::CODE_EXPIRED.into()),
1113            CloudError::Server {
1114                status: 400,
1115                code: "expired_token".into(),
1116            },
1117        ] {
1118            assert!(
1119                token_refusal(raw)
1120                    .to_string()
1121                    .contains(ENROLLMENT_TOKEN_UNUSABLE)
1122            );
1123        }
1124    }
1125
1126    /// Cloud contact findings A: a `429 rate_limited` of the token mint
1127    /// holds every process sharing `throttles.json` until `Retry-After`;
1128    /// none of them (a forced mint, a manual sync's, neither) calls the
1129    /// cloud again before it ends.
1130    #[test]
1131    fn a_token_mint_429_holds_every_session_sharing_the_store() {
1132        let limited = json!({"error": {"code": "rate_limited",
1133            "message": "Too many requests.", "retry_after_s": 420}});
1134        let (origin, recorded) = fake_cloud((429, limited));
1135        let (dir, mut first) = fixture_session();
1136        first.instance.url.clone_from(&origin);
1137        // The fixture enrolls without an instance key; a mint signs with one.
1138        InstanceKeys::load_or_create(&first.store).expect("instance key");
1139        let error = first.client().map(|_| ()).expect_err("limited");
1140        assert!(
1141            matches!(
1142                error,
1143                CloudError::RateLimited {
1144                    retry_after: Some(420)
1145                }
1146            ),
1147            "{error:?}"
1148        );
1149        assert_eq!(recorded.lock().unwrap().len(), 1, "one mint sent");
1150
1151        // Another process: its own Session on the same store.
1152        let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
1153        let mut second = Session::load(store, *first.root_key()).unwrap();
1154        second.instance.url.clone_from(&origin);
1155        for attempt in [
1156            second.client().map(|_| ()),
1157            second.bearer_token(true).map(|_| ()),
1158            first.bearer_token(true).map(|_| ()),
1159        ] {
1160            match attempt.expect_err("held") {
1161                CloudError::RateLimited {
1162                    retry_after: Some(left),
1163                } => assert!((400..=420).contains(&left), "{left}"),
1164                other => panic!("{other:?}"),
1165            }
1166        }
1167        assert_eq!(
1168            recorded.lock().unwrap().len(),
1169            1,
1170            "no HTTP call before retry_after"
1171        );
1172        let held = super::super::throttle::status_lines(&second.store, UtcDateTime::now());
1173        assert_eq!(held.len(), 1, "{held:?}");
1174        assert!(held[0].contains("token until"), "{held:?}");
1175    }
1176}