lean-ctx-cloud 3.12.7

The LeanCTX Cloud connector: enrollment, bus, knowledge sync, tasks and policy on top of LeanCTX | OSS.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
// SPDX-License-Identifier: Apache-2.0
//! Enrollment (device flow), access tokens and lease renewal.
//!
//! The instance's Ed25519 key is its only long-lived secret: every access
//! token is minted from a fresh signed assertion and cached until shortly
//! before it expires. Nothing here runs inside a tool call.

use std::time::Duration;

use lean_ctx_time::UtcDateTime;
use serde_json::{Value, json};

use super::CloudError;
use super::instance_key::InstanceKeys;
use super::lease::{VerifiedLease, load_lease, store_lease, verify_keyset, verify_lease};
use super::state::{CloudStore, INSTANCE_FILE, InstanceRecord, TOKEN_FILE, TokenRecord};
use super::transport::CloudClient;
use lean_ctx_protocol::cloud::enroll::{
    AccessTokenV1, DEVICE_SETUP_REQUEST_SCHEMA, DEVICE_TOKEN_REQUEST_SCHEMA, DeviceCodeRequestV1,
    DeviceCodeV1, DeviceSetupProjectV1, DeviceSetupRequestV1, EngineOs, EnrollmentV1,
    TOKEN_REQUEST_SCHEMA, TrialPlan, token_assertion_input,
};
use lean_ctx_protocol::cloud::lease::CloudLeaseEnvelopeV1;

/// Tokens are refreshed this long before they expire.
const TOKEN_REFRESH_MARGIN_SECONDS: i64 = 120;

pub fn engine_os() -> EngineOs {
    if cfg!(target_os = "macos") {
        EngineOs::Macos
    } else if cfg!(target_os = "linux") {
        EngineOs::Linux
    } else if cfg!(windows) {
        EngineOs::Windows
    } else {
        EngineOs::Other
    }
}

fn stamp(time: UtcDateTime) -> String {
    time.to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true)
}

fn protocol(what: &str) -> impl Fn(lean_ctx_protocol::ValidationError) -> CloudError + '_ {
    move |e| CloudError::Protocol(format!("{what}: {e}"))
}

fn decode<T: serde::de::DeserializeOwned>(value: Value, what: &str) -> Result<T, CloudError> {
    serde_json::from_value(value).map_err(|e| CloudError::Protocol(format!("{what}: {e}")))
}

/// Step 1: ask Cloud for a device code; `label` is the user's `--label`, if
/// any (the approval page shows it, Cloud task #11).
pub fn start_device_flow(
    client: &CloudClient,
    label: Option<&str>,
) -> Result<DeviceCodeV1, CloudError> {
    start_device_flow_for(client, label, None)
}

/// Step 1 for `cloud connect [--trial]`: `trial` names the plan whose
/// one-step trial the browser starts (`None`: a plain sign-in, whose
/// request is exactly the one older Clouds know).
pub fn start_device_flow_for(
    client: &CloudClient,
    label: Option<&str>,
    trial: Option<TrialPlan>,
) -> Result<DeviceCodeV1, CloudError> {
    let request = DeviceCodeRequestV1::new(env!("CARGO_PKG_VERSION"), engine_os())
        .with_label(label.map(str::to_string))
        .with_trial(trial);
    request.validate().map_err(protocol("--label"))?;
    let body = serde_json::to_value(&request).map_err(|e| CloudError::Protocol(e.to_string()))?;
    let answer = client.post("/device/code", &body).map_err(|error| {
        trial_refusal(error, trial.is_some(), client.origin()).with_origin(client.origin())
    })?;
    let code: DeviceCodeV1 = decode(answer, "device code")?;
    code.validate().map_err(protocol("device code"))?;
    // A Cloud that took the request but does not echo the trial would let
    // the person sign in without one: refused the same way as a 400.
    if let Some(plan) = trial
        && !code.starts_trial(plan)
    {
        return Err(CloudError::TrialUnsupported {
            origin: client.origin().trim_end_matches('/').to_string(),
        });
    }
    Ok(code)
}

/// A trial request an older Cloud refused for its unknown members (`400
/// invalid_request`) is [`CloudError::TrialUnsupported`]: it is never sent
/// again without them, so nobody signs in thinking a trial started.
pub fn trial_refusal(error: CloudError, trial: bool, origin: &str) -> CloudError {
    match error {
        CloudError::Server { status: 400, code } if trial && code == "invalid_request" => {
            CloudError::TrialUnsupported {
                origin: origin.trim_end_matches('/').to_string(),
            }
        }
        other => other,
    }
}

/// The project an engine names at connect (C0 2.1 device setup): the
/// checkout's folder name and the remote it sees, plus what it shares.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SetupAnnouncement {
    pub project: Option<(String, Option<String>)>,
    pub shares: Vec<String>,
}

/// Step 1b (C0 2.1): name the project and what this machine shares, so the
/// approval page asks "Share this project" too. Only when the Cloud offers
/// it; `false` when it did not take it (the terminal then asks, as before).
pub fn announce_setup(
    client: &CloudClient,
    code: &DeviceCodeV1,
    setup: &SetupAnnouncement,
) -> bool {
    if !code.offers_device_setup() {
        return false;
    }
    let request = DeviceSetupRequestV1 {
        schema: DEVICE_SETUP_REQUEST_SCHEMA.into(),
        device_code: code.device_code.clone(),
        project: setup
            .project
            .clone()
            .map(|(name, remote)| DeviceSetupProjectV1 { name, remote }),
        shares: setup.shares.clone(),
    };
    let Ok(body) = serde_json::to_value(&request) else {
        return false;
    };
    match client.post("/device/setup", &body) {
        Ok(_) => true,
        Err(error) => {
            tracing::info!("cloud device setup: {error}");
            false
        }
    }
}

/// What the device approval answered beyond the enrollment: the page's
/// answer to "Share this project" (C0 2.1). `None`: the page did not ask
/// (no setup, or an older Cloud); `Some(None)`: an older page approved it.
pub type SharingAnswer = Option<Option<bool>>;

/// Step 2: poll until the user approved (or the code expired), then verify
/// and persist the enrollment. `sleep` is injectable for tests.
pub fn finish_device_flow(
    store: &CloudStore,
    client: &CloudClient,
    code: &DeviceCodeV1,
    label: &str,
    root: &[u8; 32],
    sleep: &dyn Fn(Duration),
) -> Result<(InstanceRecord, SharingAnswer), CloudError> {
    let keys = InstanceKeys::load_or_create(store)?;
    let request = device_token_request(&keys, &code.device_code, label);
    let expires_in = u64::from(code.expires_in);
    let deadline = std::time::Instant::now() + Duration::from_secs(expires_in);
    let mut poll = DevicePoll::new(code.interval);
    // Seconds slept so far: the deadline also holds when `sleep` does not
    // pass real time (tests), and never later than the wall clock's.
    let mut slept = 0u64;
    let mut wait = poll.interval;
    loop {
        let left = expires_in.saturating_sub(slept);
        let pause = wait.min(left.max(1));
        sleep(Duration::from_secs(pause));
        slept = slept.saturating_add(pause);
        match client.post("/device/token", &request) {
            Ok(body) => {
                return accept_enrollment(store, client, body, label, root, UtcDateTime::now());
            }
            // A plans page named as a path is shown on this Cloud's origin.
            Err(error) => {
                wait = poll
                    .next_wait(error)
                    .map_err(|e| e.with_origin(client.origin()))?;
            }
        }
        if std::time::Instant::now() >= deadline || slept >= expires_in {
            return Err(CloudError::DeviceFlow(super::error::CODE_EXPIRED.into()));
        }
    }
}

/// The longest pause between two device-token polls after transient
/// failures without a `Retry-After` (seconds).
const DEVICE_POLL_BACKOFF_CAP_S: u64 = 60;

/// The pacing of the device-token polls (RFC 8628 §3.5): `authorization_pending`
/// keeps the interval, `slow_down` raises it by 5 s for good, a transient
/// failure (offline, timeout, 429, 5xx) waits its `Retry-After` or backs off
/// exponentially; every other answer (`access_denied`, `expired_token`,
/// `invalid_grant`, …) ends the flow.
#[derive(Debug)]
struct DevicePoll {
    interval: u64,
    /// Transient failures in a row.
    failures: u32,
}

impl DevicePoll {
    fn new(interval: u32) -> Self {
        Self {
            interval: u64::from(interval.max(1)),
            failures: 0,
        }
    }

    /// Seconds to wait before the next poll after `error`, or the error
    /// that ends the flow.
    fn next_wait(&mut self, error: CloudError) -> Result<u64, CloudError> {
        match &error {
            CloudError::Server { status: 400, code } if code == "authorization_pending" => {
                self.failures = 0;
                Ok(self.interval)
            }
            CloudError::Server { status: 400, code } if code == "slow_down" => {
                self.failures = 0;
                self.interval = self.interval.saturating_add(5);
                Ok(self.interval)
            }
            transient if transient.is_transient() => {
                self.failures = self.failures.saturating_add(1);
                let backoff = self
                    .interval
                    .saturating_mul(1u64 << self.failures.min(6))
                    .min(DEVICE_POLL_BACKOFF_CAP_S.max(self.interval));
                let asked = transient.retry_after_at(UtcDateTime::now()).unwrap_or(0);
                tracing::info!("cloud device token: {transient}; polling again");
                Ok(backoff.max(asked).max(self.interval))
            }
            _ => Err(error),
        }
    }
}

/// The `POST /v1/device/token` body: the device code (or an enrollment
/// token in its place) and this instance's public keys.
fn device_token_request(keys: &InstanceKeys, device_code: &str, label: &str) -> Value {
    json!({
        "schema": DEVICE_TOKEN_REQUEST_SCHEMA,
        "device_code": device_code,
        "instance_public_key": keys.public_key_b64(),
        "instance_kx_public_key": keys.kx_public_key_b64(),
        "instance_label": label,
        "instance_version": env!("CARGO_PKG_VERSION"),
        "os": engine_os(),
    })
}

/// Verify and persist the enrollment Cloud answered at `/device/token`.
fn accept_enrollment(
    store: &CloudStore,
    client: &CloudClient,
    body: Value,
    label: &str,
    root: &[u8; 32],
    local_now: UtcDateTime,
) -> Result<(InstanceRecord, SharingAnswer), CloudError> {
    let keys_raw = body["keys"].clone();
    let sharing: SharingAnswer = body
        .get("sharing")
        .filter(|s| s.is_object())
        .map(|s| s["share"].as_bool());
    decode::<EnrollmentV1>(body, "enrollment")
        .and_then(|enrollment| {
            complete_enrollment(
                store,
                client.origin(),
                &enrollment,
                &keys_raw,
                root,
                label,
                local_now,
            )
        })
        .map(|instance| (instance, sharing))
        .map_err(|error| unenrolled(store, label, error))
}

/// The plaintext prefix of a pre-issued Host enrollment token.
pub const ENROLLMENT_TOKEN_PREFIX: &str = "het_";

/// Why a Cloud refused an enrollment token, in the words a person acts on.
pub const ENROLLMENT_TOKEN_UNUSABLE: &str =
    "the enrollment token is unknown, expired, revoked or used up; ask a team admin for a new one";

/// A pre-issued Host enrollment token (`het_` and 64 hex digits) that a
/// team admin handed out, e.g. through MDM. It enrolls this machine without
/// a browser approval. The value is wiped on drop and never printed: its
/// `Debug` shows the prefix only, and no error names it.
pub struct EnrollmentToken(zeroize::Zeroizing<String>);

impl EnrollmentToken {
    /// Check the format before anything is sent: surrounding whitespace
    /// (a trailing newline from stdin) is dropped, everything else must be
    /// `het_` and exactly 64 hex digits.
    pub fn parse(raw: &str) -> Result<Self, CloudError> {
        let value = raw.trim();
        let well_formed = value
            .strip_prefix(ENROLLMENT_TOKEN_PREFIX)
            .is_some_and(|hex| hex.len() == 64 && hex.bytes().all(|b| b.is_ascii_hexdigit()));
        if !well_formed {
            return Err(CloudError::Config(
                "the enrollment token is malformed: it is `het_` followed by 64 hex digits, as the team's Hosts page issued it".into(),
            ));
        }
        Ok(Self(zeroize::Zeroizing::new(value.to_string())))
    }

    fn expose(&self) -> &str {
        &self.0
    }
}

impl std::fmt::Debug for EnrollmentToken {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "EnrollmentToken({ENROLLMENT_TOKEN_PREFIX}…)")
    }
}

/// Enroll this machine with a pre-issued enrollment token (no browser):
/// one `POST /v1/device/token` with the token as `device_code`, then the
/// enrollment is verified and persisted exactly as after a device approval.
pub fn enroll_with_token(
    store: &CloudStore,
    client: &CloudClient,
    token: &EnrollmentToken,
    label: &str,
    root: &[u8; 32],
) -> Result<(InstanceRecord, SharingAnswer), CloudError> {
    enroll_with_token_at(
        store,
        client,
        token,
        label,
        root,
        lean_ctx_time::UtcDateTime::now,
    )
}

fn enroll_with_token_at(
    store: &CloudStore,
    client: &CloudClient,
    token: &EnrollmentToken,
    label: &str,
    root: &[u8; 32],
    now: impl Fn() -> UtcDateTime,
) -> Result<(InstanceRecord, SharingAnswer), CloudError> {
    let keys = InstanceKeys::load_or_create(store)?;
    let request = device_token_request(&keys, token.expose(), label);
    match client.post("/device/token", &request) {
        Ok(body) => accept_enrollment(store, client, body, label, root, now()),
        Err(error) => Err(token_refusal(error)),
    }
}

/// An enrollment token's refusal: Cloud answers `expired_token` for an
/// unknown, expired, revoked or used-up token (mapped to the device
/// code's wording by the transport), named here for a token.
fn token_refusal(error: CloudError) -> CloudError {
    match error {
        CloudError::DeviceFlow(why) if why == super::error::CODE_EXPIRED => {
            CloudError::DeviceFlow(ENROLLMENT_TOKEN_UNUSABLE.into())
        }
        CloudError::Server { status: 400, code } if code == "expired_token" => {
            CloudError::DeviceFlow(ENROLLMENT_TOKEN_UNUSABLE.into())
        }
        other => other,
    }
}

/// Cloud enrolled the instance key, but this engine refused the answer
/// (Cloud task #1): the key is spent, since Cloud now knows it and refuses
/// it a second time ("instance key is already enrolled"). A machine without
/// an enrollment of its own drops it with whatever the refused answer left,
/// so the next connect starts from a fresh key, and the error says so.
fn unenrolled(store: &CloudStore, label: &str, error: CloudError) -> CloudError {
    if !matches!(store.instance(), Ok(None)) {
        return error;
    }
    let next = match store.forget(true) {
        Ok(()) => format!(
            "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."
        ),
        Err(e) => format!(
            "Its unused instance key could not be removed ({e}); run `lean-ctx cloud disconnect` before connecting again."
        ),
    };
    match error {
        CloudError::Protocol(m) => CloudError::Protocol(format!("{m}. {next}")),
        CloudError::Config(m) => CloudError::Config(format!("{m}. {next}")),
        other => other,
    }
}

/// Verify an enrollment answer against the root key and persist it.
pub fn complete_enrollment(
    store: &CloudStore,
    origin: &str,
    enrollment: &EnrollmentV1,
    keys_raw: &Value,
    root: &[u8; 32],
    label: &str,
    local_now: UtcDateTime,
) -> Result<InstanceRecord, CloudError> {
    enrollment.validate().map_err(protocol("enrollment"))?;
    let keyset = verify_keyset(keys_raw, root)?;
    let verified = verify_lease(
        &enrollment.lease,
        &keyset,
        &enrollment.instance_id,
        local_now,
        None,
    )?;
    if verified.lease.org_id != enrollment.org.id {
        return Err(CloudError::Protocol(
            "the lease is for another workspace".into(),
        ));
    }
    // `cloud.org` / `cloud.url` of a managed machine: refused before anything
    // of this enrollment is stored.
    if let Some(refusal) = super::config::managed_enrollment_refusal(&enrollment.org.id, origin) {
        return Err(refusal);
    }
    store_lease(store, &verified, keys_raw, local_now)?;
    let record = InstanceRecord {
        instance_id: enrollment.instance_id.clone(),
        org_id: enrollment.org.id.clone(),
        org_name: enrollment.org.name.clone(),
        org_kind: enrollment.org.kind.clone(),
        company_name: enrollment.org.company.as_ref().map(|c| c.name.clone()),
        label: label.to_string(),
        url: origin.to_string(),
        org_salt_id: enrollment.org_salt_id.clone(),
        web_url: enrollment
            .web_url
            .as_deref()
            .and_then(|url| super::config::normalize_origin(url).ok()),
        enrolled_at: stamp(local_now),
    };
    super::worker::prepare_enrollment(store)?;
    store.write_config(INSTANCE_FILE, &record)?;
    // A new enrolment starts a new sharing period (Cloud' `since`): an
    // earlier engine-side off no longer bounds it (K2 review 3, NEW-1).
    super::metrics_v2::buffer::clear_local_on_since(store.data_dir());
    store.remove_config(TOKEN_FILE)?;
    store.record_success("enroll", &stamp(verified.service_time(local_now).to_utc()));
    Ok(record)
}

/// A connected instance: its record, verified lease and keys.
pub struct Session {
    pub store: CloudStore,
    pub instance: InstanceRecord,
    pub lease: VerifiedLease,
    root: [u8; 32],
}

impl Session {
    /// Load and re-verify the local enrollment. `root` is the root key of the
    /// origin the instance is enrolled with.
    pub fn load(store: CloudStore, root: [u8; 32]) -> Result<Self, CloudError> {
        let instance = store.instance()?.ok_or(CloudError::NotConnected)?;
        // A revoked instance fails closed here, before any Cloud call.
        if let Some(revoked) = super::revoked::recorded(&store, &instance) {
            return Err(revoked);
        }
        // An enrollment from before the machine was managed, with another
        // org or Cloud, is not used.
        if let Some(refusal) =
            super::config::managed_enrollment_refusal(&instance.org_id, &instance.url)
        {
            return Err(refusal);
        }
        let lease = load_lease(&store, &root, &instance.instance_id)?;
        super::root_cert::check_lease_org(&store, &instance.url, &lease.lease)?;
        Ok(Self {
            store,
            instance,
            lease,
            root,
        })
    }

    /// The root key the enrollment was verified with.
    pub fn root_key(&self) -> &[u8; 32] {
        &self.root
    }

    fn service_now(&self) -> UtcDateTime {
        self.lease.service_time(UtcDateTime::now()).to_utc()
    }

    /// The current access token (minted when needed), for transports that
    /// authenticate outside [`CloudClient`] (the bus WebSocket upgrade).
    /// `force` mints a new one.
    pub fn bearer_token(&self, force: bool) -> Result<zeroize::Zeroizing<String>, CloudError> {
        self.access_token(force).map(zeroize::Zeroizing::new)
    }

    /// An authenticated client, minting an access token when needed.
    pub fn client(&self) -> Result<CloudClient, CloudError> {
        let token = self.access_token(false)?;
        Ok(CloudClient::new(&self.instance.url)?.with_token(&self.instance.instance_id, &token))
    }

    /// Run `call` with an authenticated client; on 401 mint a new token once.
    pub fn with_client<T>(
        &self,
        call: impl Fn(&CloudClient) -> Result<T, CloudError>,
    ) -> Result<T, CloudError> {
        let result = match call(&self.client()?) {
            Err(CloudError::Unauthorized) => {
                let token = self.access_token(true)?;
                let client = CloudClient::new(&self.instance.url)?
                    .with_token(&self.instance.instance_id, &token);
                call(&client)
            }
            other => other,
        };
        result.map_err(|e| self.noted(e))
    }

    /// A revocation answer is recorded (the engine then fails closed) and
    /// named with this workspace; a used-up quota holds the paths it counts
    /// (`throttle`); a feature's `plan_required` names the lease's plan;
    /// any other error passes unchanged.
    pub(crate) fn noted(&self, error: CloudError) -> CloudError {
        let error = super::revoked::note(&self.store, &self.instance, error)
            .with_plan(self.lease.lease.plan);
        super::throttle::note_on(&self.store, None, error, lean_ctx_time::UtcDateTime::now())
    }

    /// An authenticated client for one call that must end by `deadline`,
    /// minting the token (if needed) inside the same budget and without the
    /// 401 retry of [`Self::with_client`] (C5c, rule 3 exception).
    pub fn bounded_client(&self, deadline: std::time::Instant) -> Result<CloudClient, CloudError> {
        let left = |what: &str| {
            deadline
                .checked_duration_since(std::time::Instant::now())
                .filter(|d| !d.is_zero())
                .ok_or_else(|| CloudError::Offline(format!("{what}: time budget used up")))
        };
        let mint = CloudClient::bounded(&self.instance.url, left("token")?)?;
        let token = self.access_token_via(false, &mint)?;
        Ok(CloudClient::bounded(&self.instance.url, left("request")?)?
            .with_token(&self.instance.instance_id, &token))
    }

    /// The token is minted in C0 2.0 like every other request.
    fn access_token(&self, force: bool) -> Result<String, CloudError> {
        self.access_token_via(force, &CloudClient::new(&self.instance.url)?)
    }

    fn access_token_via(&self, force: bool, client: &CloudClient) -> Result<String, CloudError> {
        let now = self.service_now().timestamp();
        if !force
            && let Some(cached) = self.store.read_config::<TokenRecord>(TOKEN_FILE)?
            && cached.expires_at - TOKEN_REFRESH_MARGIN_SECONDS > now
        {
            return Ok(cached.access_token);
        }
        // A 429 of the mint holds every process of this machine (they share
        // the instance key and the server's budget, which counts refused
        // attempts too): nothing is sent until it ends, a forced or manual
        // mint neither.
        if let Some(held) = super::throttle::token_hold(&self.store, UtcDateTime::now()) {
            return Err(held);
        }
        let keys = InstanceKeys::load(&self.store)?;
        let mut nonce_bytes = [0u8; 18];
        getrandom::fill(&mut nonce_bytes).map_err(|e| CloudError::Local(format!("random: {e}")))?;
        use base64::Engine as _;
        let nonce = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(nonce_bytes);
        let assertion = keys.sign_b64(&token_assertion_input(
            &self.instance.instance_id,
            now,
            &nonce,
        ));
        let request = json!({
            "schema": TOKEN_REQUEST_SCHEMA, "iat": now, "nonce": nonce, "assertion": assertion,
        });
        let path = format!("/instances/{}/token", self.instance.instance_id);
        let answer = client.post(&path, &request).map_err(|e| {
            super::throttle::note_token_limit(&self.store, self.noted(e), UtcDateTime::now())
        })?;
        let token: AccessTokenV1 = decode(answer, "access token")?;
        token.validate().map_err(protocol("access token"))?;
        super::throttle::token_minted(&self.store);
        self.store.write_config(
            TOKEN_FILE,
            &TokenRecord {
                access_token: token.access_token.clone(),
                expires_at: now + i64::from(token.expires_in),
            },
        )?;
        self.store
            .record_success("token", &stamp(self.service_now()));
        Ok(token.access_token)
    }

    /// Renew the lease and persist it; returns the new lease. Asked in C0
    /// 2.0 like the enrollment whose lease it replaces, and checked against
    /// the key set that holds its `kid` (which also feeds the runtime lease):
    /// the stored one, else key set v3, by which a C0 2.x Cloud signs leases
    /// once it serves v3, fetched once when it is not stored yet. The key
    /// set the lease verified with is stored with it, so every later load
    /// re-verifies it the same way.
    pub fn renew(&mut self) -> Result<&VerifiedLease, CloudError> {
        let path = format!("/instances/{}/lease/renew", self.instance.instance_id);
        let body = self.with_client(|client| client.post(&path, &json!({})))?;
        let local_now = UtcDateTime::now();
        let envelope: CloudLeaseEnvelopeV1 = decode(body, "lease")?;
        let stored: Value = self
            .store
            .read_config(super::state::KEYS_FILE)?
            .ok_or(CloudError::NotConnected)?;
        let pick = |session: &Self| {
            super::lease::renewal_key_set(
                &stored,
                super::keyset_v3::stored_raw(&session.store).as_ref(),
                &session.root,
                &envelope.kid,
            )
        };
        let keys_raw = if let Some(raw) = pick(self) {
            raw
        } else {
            super::keyset_v3::refresh(self)?;
            pick(self).ok_or_else(|| {
                CloudError::Protocol(format!(
                    "the renewed lease names key {}, which no verified key set holds",
                    envelope.kid
                ))
            })?
        };
        let keyset = verify_keyset(&keys_raw, &self.root)?;
        let verified = verify_lease(
            &envelope,
            &keyset,
            &self.instance.instance_id,
            local_now,
            None,
        )?;
        store_lease(&self.store, &verified, &keys_raw, local_now)?;
        self.store
            .record_success("lease", &stamp(verified.service_time(local_now).to_utc()));
        self.store.record_renew_error(None);
        self.lease = verified;
        Ok(&self.lease)
    }

    /// Free the seat in Cloud.
    pub fn delete_instance(&self) -> Result<(), CloudError> {
        let path = format!("/instances/{}", self.instance.instance_id);
        self.with_client(|client| client.delete(&path))
    }
}

/// A session loaded from the enrollment fixture (key set v1) in a fresh
/// store, for tests of passes that take a [`Session`] but must send
/// nothing. Its origin is never contacted by such a test.
#[cfg(test)]
pub(crate) fn fixture_session() -> (tempfile::TempDir, Session) {
    let path = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../lean-ctx-protocol/tests/fixtures/cloud/enrollment.response.json"
    );
    let raw: Value = serde_json::from_slice(&std::fs::read(path).expect("fixture")).expect("json");
    let root = ed25519_dalek::SigningKey::from_bytes(&[0x52; 32])
        .verifying_key()
        .to_bytes();
    let dir = tempfile::tempdir().expect("tempdir");
    let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
    let enrollment: EnrollmentV1 = decode(raw.clone(), "enrollment").expect("enrollment");
    complete_enrollment(
        &store,
        "https://cloud.leanctx.com",
        &enrollment,
        &raw["keys"],
        &root,
        "studio-mac",
        lean_ctx_time::OffsetDateTime::parse_from_rfc3339("2026-10-20T12:00:00Z")
            .expect("time")
            .to_utc(),
    )
    .expect("enrolled");
    let session = Session::load(store, root).expect("session");
    (dir, session)
}

#[cfg(test)]
mod tests {
    use super::*;

    /// An older Cloud refuses the trial members (`deny_unknown_fields`):
    /// `trial_unsupported`, never a silent sign-in; a sign-in's own 400 and
    /// every other trial refusal stay what they were.
    #[test]
    fn trial_request_refused_as_unknown_is_trial_unsupported() {
        let refused = || CloudError::Server {
            status: 400,
            code: "invalid_request".into(),
        };
        let mapped = trial_refusal(refused(), true, "https://cloud.leanctx.com/");
        assert_eq!(
            mapped,
            CloudError::TrialUnsupported {
                origin: "https://cloud.leanctx.com".into()
            }
        );
        assert_eq!(mapped.event_code(), "trial_unsupported");
        assert_eq!(
            mapped.to_string(),
            "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`"
        );
        // Printed by the terminal and by LeanCTX Code alike.
        assert!(!mapped.to_string().contains("app"));
        assert_eq!(
            trial_refusal(refused(), false, "https://cloud.leanctx.com"),
            refused()
        );
        let offline = CloudError::Offline("reset".into());
        assert_eq!(
            trial_refusal(offline.clone(), true, "https://cloud.leanctx.com"),
            offline
        );
    }

    fn fixture(path: &str) -> Value {
        let path = format!(
            "{}/crates/lean-ctx-protocol/tests/fixtures/{path}",
            concat!(env!("CARGO_MANIFEST_DIR"), "/../..")
        );
        serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
    }

    fn at(t: &str) -> UtcDateTime {
        lean_ctx_time::OffsetDateTime::parse_from_rfc3339(t)
            .unwrap()
            .to_utc()
    }

    /// Enroll `raw` in a fresh store; the directory lives as long as the
    /// returned guard.
    fn enroll(
        raw: &Value,
        root: &[u8; 32],
    ) -> Result<(tempfile::TempDir, CloudStore, InstanceRecord), CloudError> {
        let dir = tempfile::tempdir().unwrap();
        let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
        let enrollment: EnrollmentV1 = decode(raw.clone(), "enrollment")?;
        let record = complete_enrollment(
            &store,
            "https://cloud.leanctx.com",
            &enrollment,
            &raw["keys"],
            root,
            "studio-mac",
            at("2026-10-20T12:00:00Z"),
        )?;
        let lease = load_lease(&store, root, &record.instance_id)?;
        assert_eq!(lease.envelope.kid, enrollment.lease.kid);
        Ok((dir, store, record))
    }

    /// Below Cloud-Protocol 2.1: key set v1, the lease signed by its `kid`.
    #[test]
    fn an_enrollment_with_key_set_v1_is_verified_and_kept() {
        use ed25519_dalek::SigningKey;
        let raw = fixture("cloud/enrollment.response.json");
        let root = SigningKey::from_bytes(&[0x52; 32])
            .verifying_key()
            .to_bytes();
        let (_dir, _store, record) = enroll(&raw, &root).unwrap();
        assert_eq!(record.org_id, "org_acme");
        let refused = enroll(&raw, &[7; 32]).expect_err("another root");
        assert!(
            refused
                .to_string()
                .contains(super::super::lease::ROOT_MISMATCH)
        );
    }

    /// Cloud-Protocol 2.1 (`routes/enrollment.for_2x.response.json`): key set
    /// v3, verified as every v3 set, and the lease signed by the key of
    /// purpose `policy` its `kid` names.
    #[test]
    fn an_enrollment_with_key_set_v3_is_verified_with_its_policy_key() {
        let raw = fixture("cloud-v2/routes/enrollment.for_2x.response.json");
        let mut root = [0u8; 32];
        hex::decode_to_slice(
            fixture("cloud-v2/vectors/signing.vectors.json")["keys"]["root_new"]["public_key_hex"]
                .as_str()
                .unwrap(),
            &mut root,
        )
        .unwrap();
        let (_dir, store, record) = enroll(&raw, &root).unwrap();
        assert_eq!(record.org_id, "org_acme");
        assert_eq!(raw["lease"]["kid"], "552e43422b3589fa");
        let kept: Value = store
            .read_config(super::super::state::KEYS_FILE)
            .unwrap()
            .unwrap();
        assert_eq!(kept, raw["keys"], "the v3 set is kept as received");
        // Another root, or a lease kid of a key that signs no leases: refused.
        assert!(enroll(&raw, &[7; 32]).is_err());
        let mut event_kid = raw;
        event_kid["lease"]["kid"] = "4fc7bebc302357bd".into();
        assert!(enroll(&event_kid, &root).is_err());
    }

    const TOKEN: &str = "het_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";

    #[test]
    fn an_enrollment_token_is_checked_before_anything_is_sent() {
        let token = EnrollmentToken::parse(&format!("  {TOKEN}\r\n")).unwrap();
        assert_eq!(
            token.expose(),
            TOKEN,
            "a trailing newline from stdin is dropped"
        );
        assert!(
            EnrollmentToken::parse(&TOKEN.to_ascii_uppercase().replace("HET_", "het_")).is_ok()
        );
        let short = &TOKEN[..TOKEN.len() - 1];
        let not_hex = format!("{}g", &TOKEN[..TOKEN.len() - 1]);
        let device_code = TOKEN.replace("het_", "hdc_");
        let inner_space = format!("{} {}", &TOKEN[..20], &TOKEN[20..]);
        for bad in [
            "",
            "het_",
            short,
            &not_hex,
            &device_code,
            &inner_space,
            &format!("{TOKEN}0"),
        ] {
            let error = EnrollmentToken::parse(bad).expect_err(bad).to_string();
            assert!(error.contains("malformed"), "{error}");
            assert!(
                bad.len() < 8 || !error.contains(bad),
                "the value is never echoed: {error}"
            );
        }
        assert_eq!(format!("{token:?}"), "EnrollmentToken(het_…)");
    }

    type Recorded = std::sync::Arc<std::sync::Mutex<Vec<(String, Value)>>>;

    /// A one-route Cloud on 127.0.0.1 that answers every request with
    /// `answer` and records what it was sent.
    #[allow(clippy::needless_pass_by_value)] // callers hand over a fresh `json!`
    fn fake_cloud(answer: (u16, Value)) -> (String, Recorded) {
        let (status, body) = answer;
        let raw = raw_answer(
            status,
            "Content-Type: application/json\r\n",
            &body.to_string(),
        );
        scripted_cloud(vec![raw])
    }

    /// A raw HTTP answer: status, extra header lines and body.
    fn raw_answer(status: u16, headers: &str, body: &str) -> String {
        format!(
            "HTTP/1.1 {status} X\r\n{headers}Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
            body.len()
        )
    }

    /// A Cloud on 127.0.0.1 that answers the n-th request with the n-th raw
    /// HTTP answer (the last one repeats) and records what it was sent.
    fn scripted_cloud(answers: Vec<String>) -> (String, Recorded) {
        use std::io::{BufRead as _, Read as _, Write as _};
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let origin = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());
        let recorded: Recorded = std::sync::Arc::default();
        let seen = std::sync::Arc::clone(&recorded);
        std::thread::spawn(move || {
            for stream in listener.incoming().flatten() {
                let mut writer = stream.try_clone().unwrap();
                let mut reader = std::io::BufReader::new(stream);
                let mut line = String::new();
                if reader.read_line(&mut line).unwrap_or(0) == 0 {
                    continue;
                }
                let path = line
                    .split_whitespace()
                    .nth(1)
                    .unwrap_or_default()
                    .to_owned();
                let mut length = 0;
                loop {
                    let mut header = String::new();
                    reader.read_line(&mut header).unwrap();
                    let header = header.trim_end();
                    if header.is_empty() {
                        break;
                    }
                    if let Some((name, value)) = header.split_once(':')
                        && name.eq_ignore_ascii_case("content-length")
                    {
                        length = value.trim().parse().unwrap();
                    }
                }
                let mut body = vec![0; length];
                reader.read_exact(&mut body).unwrap();
                let body = serde_json::from_slice(&body).unwrap_or(Value::Null);
                let n = {
                    let mut seen = seen.lock().unwrap();
                    seen.push((path, body));
                    seen.len() - 1
                };
                let raw = &answers[n.min(answers.len() - 1)];
                let _ = writer.write_all(raw.as_bytes());
            }
        });
        (origin, recorded)
    }

    fn device_code(interval: u32, expires_in: u32) -> DeviceCodeV1 {
        DeviceCodeV1 {
            schema: lean_ctx_protocol::cloud::enroll::DEVICE_CODE_SCHEMA.into(),
            device_code: "hdc_test".into(),
            user_code: "WDJB-MJHT".into(),
            verification_uri: "https://cloud.example.com/device".into(),
            verification_uri_complete: "https://cloud.example.com/device?c=WDJB-MJHT".into(),
            interval,
            expires_in,
            features: Vec::new(),
            intent: None,
            plan: None,
        }
    }

    const EDGE_502: &str = "<html><body><h1>502 Bad Gateway</h1></body></html>";

    /// Review fix: an edge error page (502/503 HTML, 429 with only a
    /// `Retry-After` header) or a refused connection does not end the
    /// device flow; the poll waits (`Retry-After`, else backoff) and goes
    /// on, `slow_down` raises the interval, `access_denied` ends it.
    #[test]
    fn the_device_flow_rides_out_transient_failures_until_a_final_answer() {
        let json = "Content-Type: application/json\r\n";
        let html = "Content-Type: text/html\r\n";
        let (origin, recorded) = scripted_cloud(vec![
            raw_answer(502, html, EDGE_502),
            raw_answer(
                429,
                &format!("{html}Retry-After: 30\r\n"),
                "Too Many Requests",
            ),
            raw_answer(503, html, ""),
            raw_answer(
                400,
                json,
                r#"{"error":{"code":"authorization_pending","message":"x"}}"#,
            ),
            raw_answer(400, json, r#"{"error":{"code":"slow_down","message":"x"}}"#),
            raw_answer(
                400,
                json,
                r#"{"error":{"code":"access_denied","message":"x"}}"#,
            ),
        ]);
        let dir = tempfile::tempdir().unwrap();
        let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
        let client = CloudClient::new(&origin).unwrap();
        let sleeps = std::cell::RefCell::new(Vec::new());
        let error = finish_device_flow(
            &store,
            &client,
            &device_code(2, 600),
            "studio-mac",
            &[7; 32],
            &|d| sleeps.borrow_mut().push(d.as_secs()),
        )
        .expect_err("denied");
        assert!(matches!(error, CloudError::DeviceFlow(_)), "{error:?}");
        assert!(error.to_string().contains("Not mine"), "{error}");
        assert_eq!(recorded.lock().unwrap().len(), 6);
        // interval 2; 502 → 4 (backoff); 429 → its Retry-After 30; 503 →
        // 16 (third failure in a row); pending → 2; slow_down → 2 + 5.
        assert_eq!(sleeps.into_inner(), vec![2, 4, 30, 16, 2, 7]);
        assert!(store.instance().unwrap().is_none(), "nothing enrolled");
    }

    #[test]
    fn transient_failures_end_the_device_flow_only_at_its_deadline() {
        let (origin, recorded) = scripted_cloud(vec![raw_answer(
            503,
            "Content-Type: text/html\r\n",
            EDGE_502,
        )]);
        let dir = tempfile::tempdir().unwrap();
        let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
        let client = CloudClient::new(&origin).unwrap();
        let sleeps = std::cell::RefCell::new(Vec::new());
        let error = finish_device_flow(
            &store,
            &client,
            &device_code(5, 120),
            "studio-mac",
            &[7; 32],
            &|d| sleeps.borrow_mut().push(d.as_secs()),
        )
        .expect_err("expired");
        assert_eq!(
            error,
            CloudError::DeviceFlow(super::super::error::CODE_EXPIRED.into())
        );
        let sleeps = sleeps.into_inner();
        assert_eq!(sleeps.iter().sum::<u64>(), 120, "{sleeps:?}");
        assert!(sleeps.iter().all(|s| *s <= DEVICE_POLL_BACKOFF_CAP_S));
        assert_eq!(recorded.lock().unwrap().len(), sleeps.len());
    }

    #[test]
    fn device_poll_pacing_keeps_final_refusals_fatal() {
        let mut poll = DevicePoll::new(0);
        assert_eq!(poll.interval, 1, "an interval of 0 polls each second");
        for fatal in [
            CloudError::DeviceFlow(super::super::error::CODE_EXPIRED.into()),
            CloudError::Server {
                status: 400,
                code: "unknown".into(),
            },
            CloudError::Unauthorized,
            CloudError::Server {
                status: 413,
                code: "payload_too_large".into(),
            },
        ] {
            assert_eq!(poll.next_wait(fatal.clone()), Err(fatal));
        }
        let offline = CloudError::Offline("timeout".into());
        assert_eq!(poll.next_wait(offline.clone()), Ok(2));
        assert_eq!(poll.next_wait(offline.clone()), Ok(4));
        for _ in 0..10 {
            assert!(poll.next_wait(offline.clone()).unwrap() <= DEVICE_POLL_BACKOFF_CAP_S);
        }
        let limited = CloudError::RateLimited {
            retry_after: Some(90),
        };
        assert_eq!(poll.next_wait(limited), Ok(90), "Retry-After wins");
    }

    #[test]
    fn an_enrollment_token_enrolls_in_one_request_without_a_browser() {
        use ed25519_dalek::SigningKey;
        let raw = fixture("cloud/enrollment.response.json");
        let root = SigningKey::from_bytes(&[0x52; 32])
            .verifying_key()
            .to_bytes();
        let (origin, recorded) = fake_cloud((200, raw));
        let dir = tempfile::tempdir().unwrap();
        let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
        let client = CloudClient::new(&origin).unwrap();
        let token = EnrollmentToken::parse(TOKEN).unwrap();
        let (record, sharing) =
            enroll_with_token_at(&store, &client, &token, "ci-runner-7", &root, || {
                at("2026-10-20T12:00:00Z")
            })
            .unwrap();
        assert_eq!(record.org_id, "org_acme");
        assert_eq!(record.label, "ci-runner-7");
        assert_eq!(sharing, None, "no approval page asked anything");
        assert_eq!(
            store.instance().unwrap().unwrap().instance_id,
            record.instance_id
        );
        let sent = recorded.lock().unwrap().clone();
        assert_eq!(sent.len(), 1, "one request, no device code, no polling");
        let (path, body) = &sent[0];
        assert_eq!(path, "/v1/device/token");
        assert_eq!(body["schema"], DEVICE_TOKEN_REQUEST_SCHEMA);
        assert_eq!(body["device_code"], TOKEN);
        assert_eq!(body["instance_label"], "ci-runner-7");
        let keys = InstanceKeys::load(&store).unwrap();
        assert_eq!(body["instance_public_key"], keys.public_key_b64());
        assert_eq!(body["instance_kx_public_key"], keys.kx_public_key_b64());
        assert_eq!(body["instance_version"], env!("CARGO_PKG_VERSION"));
    }

    #[test]
    fn a_refused_enrollment_token_says_why_without_naming_it() {
        let refusal = json!({"error": {"code": "expired_token", "message":
            "Unknown, expired, revoked or used-up enrollment token; ask a team admin for a new one."}});
        let (origin, recorded) = fake_cloud((400, refusal));
        let dir = tempfile::tempdir().unwrap();
        let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
        let client = CloudClient::new(&origin).unwrap();
        let token = EnrollmentToken::parse(TOKEN).unwrap();
        let error = enroll_with_token(&store, &client, &token, "ci", &[7; 32])
            .expect_err("refused")
            .to_string();
        assert!(error.contains(ENROLLMENT_TOKEN_UNUSABLE), "{error}");
        assert!(!error.contains(&TOKEN[4..]), "{error}");
        assert!(store.instance().unwrap().is_none(), "nothing enrolled");
        assert_eq!(recorded.lock().unwrap().len(), 1);
        // The transport's code-expired wording and a bare code map the same.
        for raw in [
            CloudError::DeviceFlow(super::super::error::CODE_EXPIRED.into()),
            CloudError::Server {
                status: 400,
                code: "expired_token".into(),
            },
        ] {
            assert!(
                token_refusal(raw)
                    .to_string()
                    .contains(ENROLLMENT_TOKEN_UNUSABLE)
            );
        }
    }

    /// Cloud contact findings A: a `429 rate_limited` of the token mint
    /// holds every process sharing `throttles.json` until `Retry-After`;
    /// none of them (a forced mint, a manual sync's, neither) calls the
    /// cloud again before it ends.
    #[test]
    fn a_token_mint_429_holds_every_session_sharing_the_store() {
        let limited = json!({"error": {"code": "rate_limited",
            "message": "Too many requests.", "retry_after_s": 420}});
        let (origin, recorded) = fake_cloud((429, limited));
        let (dir, mut first) = fixture_session();
        first.instance.url.clone_from(&origin);
        // The fixture enrolls without an instance key; a mint signs with one.
        InstanceKeys::load_or_create(&first.store).expect("instance key");
        let error = first.client().map(|_| ()).expect_err("limited");
        assert!(
            matches!(
                error,
                CloudError::RateLimited {
                    retry_after: Some(420)
                }
            ),
            "{error:?}"
        );
        assert_eq!(recorded.lock().unwrap().len(), 1, "one mint sent");

        // Another process: its own Session on the same store.
        let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
        let mut second = Session::load(store, *first.root_key()).unwrap();
        second.instance.url.clone_from(&origin);
        for attempt in [
            second.client().map(|_| ()),
            second.bearer_token(true).map(|_| ()),
            first.bearer_token(true).map(|_| ()),
        ] {
            match attempt.expect_err("held") {
                CloudError::RateLimited {
                    retry_after: Some(left),
                } => assert!((400..=420).contains(&left), "{left}"),
                other => panic!("{other:?}"),
            }
        }
        assert_eq!(
            recorded.lock().unwrap().len(),
            1,
            "no HTTP call before retry_after"
        );
        let held = super::super::throttle::status_lines(&second.store, UtcDateTime::now());
        assert_eq!(held.len(), 1, "{held:?}");
        assert!(held[0].contains("token until"), "{held:?}");
    }
}