Skip to main content

lean_ctx_protocol/cloud/
enroll.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Device-flow enrollment and instance access tokens.
4//!
5//! - `POST /v1/device/code` [`DeviceCodeRequestV1`] → [`DeviceCodeV1`]
6//! - `POST /v1/device/token` [`DeviceTokenRequestV1`] → [`EnrollmentV1`], or
7//!   400 `authorization_pending` / `slow_down` / `expired_token` / `access_denied`,
8//!   402 `plan_required`, 409 `instance_limit`
9//! - `POST /v1/instances/{instance_id}/token` [`InstanceTokenRequestV1`] → [`AccessTokenV1`]
10//! - `POST /v1/instances/{instance_id}/lease/renew` (empty body) → lease envelope
11//! - `DELETE /v1/instances/{instance_id}` → 204, frees the seat
12//!
13//! There is no refresh token: the instance's Ed25519 key is its only
14//! long-lived secret and mints short access tokens through a signed assertion.
15
16use serde::{Deserialize, Serialize};
17use std::fmt;
18
19use super::lease::{CloudLeaseEnvelopeV1, EnrollmentKeySet};
20use super::{
21    CLOUD_ENGINE_CLIENT_ID, TOKEN_ASSERTION_DOMAIN, require_schema, validate_b64_len, validate_id,
22    validate_text,
23};
24use crate::ValidationError;
25
26pub const DEVICE_CODE_REQUEST_SCHEMA: &str = "leanctx.cloud.device-code-request/v1";
27pub const DEVICE_CODE_SCHEMA: &str = "leanctx.cloud.device-code/v1";
28pub const DEVICE_TOKEN_REQUEST_SCHEMA: &str = "leanctx.cloud.device-token-request/v1";
29pub const ENROLLMENT_SCHEMA: &str = "leanctx.cloud.enrollment/v1";
30pub const TOKEN_REQUEST_SCHEMA: &str = "leanctx.cloud.token-request/v1";
31pub const ACCESS_TOKEN_SCHEMA: &str = "leanctx.cloud.access-token/v1";
32
33/// Longest instance label, in characters.
34pub const MAX_INSTANCE_LABEL_CHARS: usize = 64;
35/// Accepted distance between `iat` and service time.
36pub const MAX_ASSERTION_SKEW_SECONDS: i64 = 300;
37/// Longest access-token lifetime the service issues.
38pub const MAX_ACCESS_TOKEN_SECONDS: u32 = 3600;
39
40/// Operating-system family of the engine.
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
42#[serde(rename_all = "snake_case")]
43pub enum EngineOs {
44    Macos,
45    Linux,
46    Windows,
47    Other,
48}
49
50fn validate_engine_version(value: &str) -> Result<(), ValidationError> {
51    let ok = !value.is_empty()
52        && value.len() <= 32
53        && value.as_bytes()[0].is_ascii_digit()
54        && value
55            .bytes()
56            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'+'));
57    if ok {
58        Ok(())
59    } else {
60        Err(ValidationError::new(
61            "instance_version must be a semantic version of at most 32 characters",
62        ))
63    }
64}
65
66/// `POST /v1/device/code`.
67#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
68#[serde(deny_unknown_fields)]
69pub struct DeviceCodeRequestV1 {
70    pub schema: String,
71    /// Always [`CLOUD_ENGINE_CLIENT_ID`].
72    pub client_id: String,
73    pub instance_version: String,
74    pub os: EngineOs,
75    /// The name the user gave this engine (`--label`), shown on the approval
76    /// page and prefilled as its name (Cloud task #11). Like `instance_version`
77    /// and `os` it is the requester's claim. Absent when the user gave none:
78    /// the host-name default goes only into [`DeviceTokenRequestV1`].
79    #[serde(default, skip_serializing_if = "Option::is_none")]
80    pub instance_label: Option<String>,
81    /// One-step trial (`lean-ctx cloud connect --trial`): why the code is
82    /// asked for. Absent for a sign-in, so a Cloud that does not know the
83    /// member (it refuses unknown fields) still serves every plain connect.
84    #[serde(default, skip_serializing_if = "Option::is_none")]
85    pub intent: Option<DeviceIntent>,
86    /// Only with `intent: "trial"`: the plan whose trial the browser starts.
87    #[serde(default, skip_serializing_if = "Option::is_none")]
88    pub plan: Option<TrialPlan>,
89}
90
91/// `DeviceCodeRequestV1.intent`.
92#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
93#[serde(rename_all = "snake_case")]
94pub enum DeviceIntent {
95    SignIn,
96    Trial,
97}
98
99/// `DeviceCodeRequestV1.plan`: the plan a one-step trial starts.
100#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
101#[serde(rename_all = "snake_case")]
102pub enum TrialPlan {
103    Personal,
104    Team,
105}
106
107impl TrialPlan {
108    /// The wire name (`personal`, `team`).
109    pub fn as_str(self) -> &'static str {
110        match self {
111            Self::Personal => "personal",
112            Self::Team => "team",
113        }
114    }
115
116    /// `--plan personal|team`.
117    pub fn parse(value: &str) -> Option<Self> {
118        match value {
119            "personal" => Some(Self::Personal),
120            "team" => Some(Self::Team),
121            _ => None,
122        }
123    }
124}
125
126impl DeviceCodeRequestV1 {
127    pub fn new(instance_version: impl Into<String>, os: EngineOs) -> Self {
128        Self {
129            schema: DEVICE_CODE_REQUEST_SCHEMA.into(),
130            client_id: CLOUD_ENGINE_CLIENT_ID.into(),
131            instance_version: instance_version.into(),
132            os,
133            instance_label: None,
134            intent: None,
135            plan: None,
136        }
137    }
138
139    /// The same request naming the engine (`--label`).
140    #[must_use]
141    pub fn with_label(mut self, label: Option<String>) -> Self {
142        self.instance_label = label;
143        self
144    }
145
146    /// The same request asking for a one-step trial of `plan` (`None`: a
147    /// plain sign-in, which sends neither member).
148    #[must_use]
149    pub fn with_trial(mut self, plan: Option<TrialPlan>) -> Self {
150        self.intent = plan.map(|_| DeviceIntent::Trial);
151        self.plan = plan;
152        self
153    }
154
155    pub fn validate(&self) -> Result<(), ValidationError> {
156        require_schema(&self.schema, DEVICE_CODE_REQUEST_SCHEMA)?;
157        if self.client_id != CLOUD_ENGINE_CLIENT_ID {
158            return Err(ValidationError::new(format!(
159                "client_id must be {CLOUD_ENGINE_CLIENT_ID}"
160            )));
161        }
162        if let Some(label) = &self.instance_label {
163            validate_text(label, MAX_INSTANCE_LABEL_CHARS, "instance_label", false)?;
164        }
165        if self.plan.is_some() && self.intent != Some(DeviceIntent::Trial) {
166            return Err(ValidationError::new(
167                "plan is only allowed with intent trial",
168            ));
169        }
170        validate_engine_version(&self.instance_version)
171    }
172}
173
174/// Response of `POST /v1/device/code`.
175#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
176pub struct DeviceCodeV1 {
177    pub schema: String,
178    /// Secret polling handle; never shown or logged.
179    pub device_code: String,
180    /// Short code the user confirms in the browser, e.g. `WDJB-MJHT`.
181    pub user_code: String,
182    pub verification_uri: String,
183    pub verification_uri_complete: String,
184    /// Minimum seconds between token polls.
185    pub interval: u32,
186    /// Seconds until `device_code` expires.
187    pub expires_in: u32,
188    /// C0 2.1: what this Cloud offers beyond C0 1, e.g.
189    /// [`FEATURE_DEVICE_SETUP`]; empty (absent) on older ones.
190    #[serde(default, skip_serializing_if = "Vec::is_empty")]
191    pub features: Vec<String>,
192    /// One-step trial: the Cloud echoes the request's `intent` and `plan`
193    /// (`device_code_trial.response.json`); absent for a sign-in.
194    #[serde(default, skip_serializing_if = "Option::is_none")]
195    pub intent: Option<DeviceIntent>,
196    #[serde(default, skip_serializing_if = "Option::is_none")]
197    pub plan: Option<TrialPlan>,
198}
199
200impl DeviceCodeV1 {
201    /// Whether this code starts the trial of `plan` the request asked for.
202    pub fn starts_trial(&self, plan: TrialPlan) -> bool {
203        self.intent == Some(DeviceIntent::Trial) && self.plan.is_none_or(|p| p == plan)
204    }
205
206    /// Whether this Cloud takes `POST /v1/device/setup` for this code.
207    pub fn offers_device_setup(&self) -> bool {
208        self.features.iter().any(|f| f == FEATURE_DEVICE_SETUP)
209    }
210}
211
212/// C0 2.1 `features` entry: the approval page shares the project too.
213pub const FEATURE_DEVICE_SETUP: &str = "device_setup";
214pub const DEVICE_SETUP_REQUEST_SCHEMA: &str = "leanctx.cloud.device-setup/v1";
215pub const DEVICE_SETUP_RESULT_SCHEMA: &str = "leanctx.cloud.device-setup-result/v1";
216
217/// C0 2.1 `POST /v1/device/setup` (no token; the pending `device_code`):
218/// the project this engine runs in and what it shares, shown on the
219/// approval page (`routes/device_setup.request.json`). Requester's claims.
220#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
221#[serde(deny_unknown_fields)]
222pub struct DeviceSetupRequestV1 {
223    pub schema: String,
224    pub device_code: String,
225    pub project: Option<DeviceSetupProjectV1>,
226    /// `knowledge`, `usage`, `receipts`, `bus`, sorted.
227    pub shares: Vec<String>,
228}
229
230#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
231#[serde(deny_unknown_fields)]
232pub struct DeviceSetupProjectV1 {
233    /// The checkout's folder name, 1-64 characters.
234    pub name: String,
235    /// The git remote as the engine sees it, for the person to recognise.
236    pub remote: Option<String>,
237}
238
239/// C0 2.1 `POST /v1/device/setup/result` (instance token):
240/// `routes/device_setup_result.request.json`.
241#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
242#[serde(deny_unknown_fields)]
243pub struct DeviceSetupResultV1 {
244    pub schema: String,
245    /// `shared`, `kept_local`, `no_project` or `failed`.
246    pub state: String,
247    #[serde(default, skip_serializing_if = "Option::is_none")]
248    pub vault: Option<String>,
249}
250
251impl fmt::Debug for DeviceCodeV1 {
252    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
253        formatter
254            .debug_struct("DeviceCodeV1")
255            .field("device_code", &"<redacted>")
256            .field("user_code", &self.user_code)
257            .field("verification_uri", &self.verification_uri)
258            .field("interval", &self.interval)
259            .field("expires_in", &self.expires_in)
260            .finish_non_exhaustive()
261    }
262}
263
264/// `http://localhost[:port]…` or `http://127.0.0.1[:port]…`.
265fn is_loopback_http(uri: &str) -> bool {
266    uri.strip_prefix("http://")
267        .and_then(|rest| rest.split(['/', ':', '?']).next())
268        .is_some_and(|host| host == "localhost" || host == "127.0.0.1")
269}
270
271impl DeviceCodeV1 {
272    pub fn validate(&self) -> Result<(), ValidationError> {
273        require_schema(&self.schema, DEVICE_CODE_SCHEMA)?;
274        validate_text(&self.device_code, 256, "device_code", false)?;
275        validate_text(&self.user_code, 16, "user_code", false)?;
276        for uri in [&self.verification_uri, &self.verification_uri_complete] {
277            if !(uri.starts_with("https://") || is_loopback_http(uri)) || uri.len() > 512 {
278                return Err(ValidationError::new(
279                    "verification uri must be https (http only on localhost/127.0.0.1)",
280                ));
281            }
282        }
283        if !(1..=60).contains(&self.interval) || !(60..=3600).contains(&self.expires_in) {
284            return Err(ValidationError::new(
285                "interval must be 1-60 s and expires_in 60-3600 s",
286            ));
287        }
288        Ok(())
289    }
290}
291
292/// `POST /v1/device/token`: poll until the user approved, then enroll the
293/// instance with its public keys.
294#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
295#[serde(deny_unknown_fields)]
296pub struct DeviceTokenRequestV1 {
297    pub schema: String,
298    pub device_code: String,
299    /// Ed25519 public key (32 bytes, base64) the instance signs assertions with.
300    pub instance_public_key: String,
301    /// X25519 public key (32 bytes, base64); enrollment carries it.
302    pub instance_kx_public_key: String,
303    /// User-visible name, e.g. the host name when labels are on.
304    pub instance_label: String,
305    pub instance_version: String,
306    pub os: EngineOs,
307}
308
309impl fmt::Debug for DeviceTokenRequestV1 {
310    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
311        formatter
312            .debug_struct("DeviceTokenRequestV1")
313            .field("device_code", &"<redacted>")
314            .field("instance_public_key", &self.instance_public_key)
315            .field("instance_label", &self.instance_label)
316            .field("instance_version", &self.instance_version)
317            .field("os", &self.os)
318            .finish_non_exhaustive()
319    }
320}
321
322impl DeviceTokenRequestV1 {
323    pub fn validate(&self) -> Result<(), ValidationError> {
324        require_schema(&self.schema, DEVICE_TOKEN_REQUEST_SCHEMA)?;
325        validate_text(&self.device_code, 256, "device_code", false)?;
326        validate_b64_len(&self.instance_public_key, 32, "instance_public_key")?;
327        validate_b64_len(&self.instance_kx_public_key, 32, "instance_kx_public_key")?;
328        validate_text(
329            &self.instance_label,
330            MAX_INSTANCE_LABEL_CHARS,
331            "instance_label",
332            false,
333        )?;
334        validate_engine_version(&self.instance_version)
335    }
336}
337
338/// Organization reference: the workspace the instance enrolls in.
339#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
340pub struct OrgRefV1 {
341    pub id: String,
342    pub name: String,
343    /// `personal` | `team` (Cloud C line, additive); older servers omit it.
344    #[serde(default, skip_serializing_if = "Option::is_none")]
345    pub kind: Option<String>,
346    /// The company a team belongs to (Cloud C line, additive).
347    #[serde(default, skip_serializing_if = "Option::is_none")]
348    pub company: Option<CompanyRefV1>,
349}
350
351/// The company of a team: the business that holds its Enterprise plan.
352#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
353pub struct CompanyRefV1 {
354    pub name: String,
355}
356
357/// Successful `POST /v1/device/token`.
358#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
359pub struct EnrollmentV1 {
360    pub schema: String,
361    pub instance_id: String,
362    pub org: OrgRefV1,
363    pub lease: CloudLeaseEnvelopeV1,
364    /// Signed by the Cloud root key; verified before the lease. v1 for an
365    /// engine below Cloud-Protocol 2.1, v3 from 2.1.
366    pub keys: EnrollmentKeySet,
367    /// Id of the org salt the engine fetches with `GET /v1/org/salt`.
368    pub org_salt_id: String,
369    /// 1.3: origin of the LeanCTX Cloud web app (its "Open" link); may equal the API origin.
370    #[serde(default, skip_serializing_if = "Option::is_none")]
371    pub web_url: Option<String>,
372}
373
374impl EnrollmentV1 {
375    /// Structural checks; signature checks are the engine's
376    /// (`keys` against the root key, then `lease` against `keys`).
377    pub fn validate(&self) -> Result<(), ValidationError> {
378        require_schema(&self.schema, ENROLLMENT_SCHEMA)?;
379        validate_id(&self.instance_id, "instance_id")?;
380        validate_id(&self.org.id, "org.id")?;
381        validate_text(&self.org.name, 128, "org.name", false)?;
382        validate_id(&self.org_salt_id, "org_salt_id")?;
383        if let Some(web_url) = &self.web_url {
384            super::validate_origin(web_url, "web_url")?;
385        }
386        self.keys.validate()?;
387        self.lease.validate_shape()?;
388        if !self.keys.signs_leases_as(&self.lease.kid) {
389            return Err(ValidationError::new(
390                "the lease kid names no lease key of the enrollment's key set",
391            ));
392        }
393        Ok(())
394    }
395}
396
397/// `POST /v1/instances/{instance_id}/token`.
398#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
399#[serde(deny_unknown_fields)]
400pub struct InstanceTokenRequestV1 {
401    pub schema: String,
402    /// Unix seconds; the service accepts ±[`MAX_ASSERTION_SKEW_SECONDS`].
403    pub iat: i64,
404    /// 16–64 chars of `[A-Za-z0-9_-]`, single use within the skew window.
405    pub nonce: String,
406    /// Ed25519 signature (base64) over [`token_assertion_input`].
407    pub assertion: String,
408}
409
410impl InstanceTokenRequestV1 {
411    pub fn validate(&self) -> Result<(), ValidationError> {
412        require_schema(&self.schema, TOKEN_REQUEST_SCHEMA)?;
413        if self.iat <= 0 {
414            return Err(ValidationError::new("iat must be positive unix seconds"));
415        }
416        validate_nonce(&self.nonce)?;
417        validate_b64_len(&self.assertion, 64, "assertion")
418    }
419}
420
421fn validate_nonce(nonce: &str) -> Result<(), ValidationError> {
422    if (16..=64).contains(&nonce.len())
423        && nonce
424            .bytes()
425            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
426    {
427        Ok(())
428    } else {
429        Err(ValidationError::new(
430            "nonce must be 16-64 characters of [A-Za-z0-9_-]",
431        ))
432    }
433}
434
435/// Bytes the instance key signs: `"leanctx.cloud.token.v1\n" + instance_id +
436/// "\n" + iat + "\n" + nonce` (iat in decimal unix seconds).
437pub fn token_assertion_input(instance_id: &str, iat: i64, nonce: &str) -> Vec<u8> {
438    format!("{TOKEN_ASSERTION_DOMAIN}{instance_id}\n{iat}\n{nonce}").into_bytes()
439}
440
441/// Response of `POST /v1/instances/{instance_id}/token`.
442#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
443pub struct AccessTokenV1 {
444    pub schema: String,
445    /// Bearer token; never logged, printed or persisted outside `token.json`.
446    pub access_token: String,
447    /// Seconds, at most [`MAX_ACCESS_TOKEN_SECONDS`].
448    pub expires_in: u32,
449}
450
451impl fmt::Debug for AccessTokenV1 {
452    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
453        formatter
454            .debug_struct("AccessTokenV1")
455            .field("access_token", &"<redacted>")
456            .field("expires_in", &self.expires_in)
457            .finish_non_exhaustive()
458    }
459}
460
461impl AccessTokenV1 {
462    pub fn validate(&self) -> Result<(), ValidationError> {
463        require_schema(&self.schema, ACCESS_TOKEN_SCHEMA)?;
464        validate_text(&self.access_token, 4096, "access_token", false)?;
465        if !(1..=MAX_ACCESS_TOKEN_SECONDS).contains(&self.expires_in) {
466            return Err(ValidationError::new("expires_in must be 1-3600 s"));
467        }
468        Ok(())
469    }
470}
471
472#[cfg(test)]
473mod tests {
474    use super::*;
475
476    #[test]
477    fn a_device_code_label_follows_the_text_rule() {
478        let request = |label: Option<&str>| {
479            DeviceCodeRequestV1::new("3.12.0", EngineOs::Macos)
480                .with_label(label.map(str::to_string))
481        };
482        assert!(request(None).validate().is_ok());
483        assert!(request(Some("build-box")).validate().is_ok());
484        let long = "x".repeat(MAX_INSTANCE_LABEL_CHARS + 1);
485        for bad in [
486            "",
487            "line\nbreak",
488            "zero\u{200b}width",
489            "a\u{202e}b",
490            long.as_str(),
491        ] {
492            assert!(request(Some(bad)).validate().is_err(), "{bad:?}");
493        }
494        let unlabelled = serde_json::to_value(request(None)).unwrap();
495        assert!(
496            unlabelled.get("instance_label").is_none(),
497            "older services refuse unknown fields"
498        );
499    }
500
501    /// `cloud connect --trial`: intent and plan travel only on a trial
502    /// request; a sign-in sends neither (older Clouds refuse unknown fields).
503    #[test]
504    fn trial_device_code_request_carries_intent_and_plan() {
505        let plain = DeviceCodeRequestV1::new("3.12.0", EngineOs::Macos).with_trial(None);
506        let json = serde_json::to_value(&plain).unwrap();
507        assert!(json.get("intent").is_none() && json.get("plan").is_none());
508        let trial =
509            DeviceCodeRequestV1::new("3.12.0", EngineOs::Macos).with_trial(Some(TrialPlan::Team));
510        assert!(trial.validate().is_ok());
511        let json = serde_json::to_value(&trial).unwrap();
512        assert_eq!(json["intent"], "trial");
513        assert_eq!(json["plan"], "team");
514        assert_eq!(
515            serde_json::from_value::<DeviceCodeRequestV1>(json).unwrap(),
516            trial
517        );
518        let personal = DeviceCodeRequestV1::new("3.12.0", EngineOs::Linux)
519            .with_trial(Some(TrialPlan::Personal));
520        assert_eq!(serde_json::to_value(&personal).unwrap()["plan"], "personal");
521        let mut plan_only = plain.clone();
522        plan_only.plan = Some(TrialPlan::Personal);
523        assert!(plan_only.validate().is_err(), "plan needs intent trial");
524        assert_eq!(TrialPlan::parse("team"), Some(TrialPlan::Team));
525        assert_eq!(TrialPlan::parse("enterprise"), None);
526    }
527
528    /// p37 !134 contract fixtures: the trial request is the engine's own,
529    /// byte for byte, and the answer echoes the trial it starts.
530    #[test]
531    fn trial_device_code_documents_are_the_contract_fixtures() {
532        let request: serde_json::Value = serde_json::from_str(include_str!(
533            "../../tests/fixtures/cloud/device_code_trial.request.json"
534        ))
535        .unwrap();
536        let ours = DeviceCodeRequestV1::new("3.12.1", EngineOs::Macos)
537            .with_trial(Some(TrialPlan::Personal));
538        assert_eq!(serde_json::to_value(&ours).unwrap(), request);
539        let answer: serde_json::Value = serde_json::from_str(include_str!(
540            "../../tests/fixtures/cloud/device_code_trial.response.json"
541        ))
542        .unwrap();
543        let code: DeviceCodeV1 = serde_json::from_value(answer.clone()).unwrap();
544        code.validate().unwrap();
545        assert_eq!(serde_json::to_value(&code).unwrap(), answer);
546        assert!(code.starts_trial(TrialPlan::Personal));
547        assert!(!code.starts_trial(TrialPlan::Team));
548        assert!(
549            code.verification_uri_complete
550                .ends_with("&intent=trial&plan=personal")
551        );
552        let sign_in: DeviceCodeV1 = serde_json::from_str(include_str!(
553            "../../tests/fixtures/cloud/device_code.response.json"
554        ))
555        .unwrap();
556        assert!(
557            !sign_in.starts_trial(TrialPlan::Personal),
558            "no echo, no trial"
559        );
560    }
561
562    #[test]
563    fn assertion_input_is_the_documented_text() {
564        assert_eq!(
565            token_assertion_input("inst_1", 1_792_500_000, "n0nce-n0nce-n0nce"),
566            b"leanctx.cloud.token.v1\ninst_1\n1792500000\nn0nce-n0nce-n0nce".to_vec()
567        );
568    }
569
570    #[test]
571    fn secrets_stay_out_of_debug() {
572        let token = AccessTokenV1 {
573            schema: ACCESS_TOKEN_SCHEMA.into(),
574            access_token: "atl_secret_value".into(),
575            expires_in: 3600,
576        };
577        assert!(!format!("{token:?}").contains("atl_secret_value"));
578        let code = DeviceCodeV1 {
579            schema: DEVICE_CODE_SCHEMA.into(),
580            device_code: "dc_secret_value".into(),
581            user_code: "WDJB-MJHT".into(),
582            verification_uri: "https://cloud.leanctx.com/device".into(),
583            verification_uri_complete: "https://cloud.leanctx.com/device?code=WDJB-MJHT".into(),
584            interval: 5,
585            expires_in: 900,
586            features: Vec::new(),
587            intent: None,
588            plan: None,
589        };
590        assert!(!format!("{code:?}").contains("dc_secret_value"));
591        assert!(!code.offers_device_setup());
592    }
593
594    /// C0 2.1 device setup: the contract fixtures round-trip byte for byte
595    /// through the engine's types, and the features list is optional.
596    #[test]
597    fn device_setup_documents_are_the_contract_fixtures() {
598        fn round<T: serde::de::DeserializeOwned + Serialize>(raw: &str) {
599            let value: serde_json::Value = serde_json::from_str(raw).unwrap();
600            let typed: T = serde_json::from_value(value.clone()).unwrap();
601            assert_eq!(serde_json::to_value(typed).unwrap(), value);
602        }
603        round::<DeviceSetupRequestV1>(include_str!(
604            "../../tests/fixtures/cloud-v2/routes/device_setup.request.json"
605        ));
606        round::<DeviceSetupResultV1>(include_str!(
607            "../../tests/fixtures/cloud-v2/routes/device_setup_result.request.json"
608        ));
609        let mut answer = serde_json::json!({
610            "schema": DEVICE_CODE_SCHEMA, "device_code": "dc_x", "user_code": "WDJB-MJHT",
611            "verification_uri": "https://cloud.leanctx.com/device",
612            "verification_uri_complete": "https://cloud.leanctx.com/device?user_code=WDJB-MJHT",
613            "interval": 5, "expires_in": 900,
614        });
615        let old: DeviceCodeV1 = serde_json::from_value(answer.clone()).unwrap();
616        assert!(
617            !old.offers_device_setup(),
618            "a LeanCTX Cloud server with C0 2.0 lists nothing"
619        );
620        answer["features"] = serde_json::json!([FEATURE_DEVICE_SETUP, "later"]);
621        let new: DeviceCodeV1 = serde_json::from_value(answer).unwrap();
622        assert!(new.offers_device_setup());
623    }
624
625    /// An enrollment as a Cloud-Protocol 1.x/2.0 engine receives it: key
626    /// set v1, the lease signed by a `kid` of it.
627    #[test]
628    fn an_enrollment_with_key_set_v1_decodes_and_names_its_lease_key() {
629        let raw: serde_json::Value = serde_json::from_str(include_str!(
630            "../../tests/fixtures/cloud/enrollment.response.json"
631        ))
632        .unwrap();
633        let enrollment: EnrollmentV1 = serde_json::from_value(raw.clone()).unwrap();
634        enrollment.validate().unwrap();
635        assert!(matches!(enrollment.keys, EnrollmentKeySet::V1(_)));
636        assert_eq!(serde_json::to_value(&enrollment).unwrap(), raw);
637        let mut other_kid = enrollment;
638        other_kid.lease.kid = "k-unknown".into();
639        assert!(other_kid.validate().is_err(), "the kid follows the set");
640    }
641
642    /// An enrollment as a Cloud-Protocol 2.1+ engine receives it
643    /// (`routes/enrollment.for_2x.response.json`): key set v3, the lease of
644    /// a 2.x engine signed by the v3 key of purpose `policy` its `kid`
645    /// names.
646    #[test]
647    fn an_enrollment_with_key_set_v3_decodes_and_names_its_policy_key() {
648        let raw: serde_json::Value = serde_json::from_str(include_str!(
649            "../../tests/fixtures/cloud-v2/routes/enrollment.for_2x.response.json"
650        ))
651        .unwrap();
652        let enrollment: EnrollmentV1 = serde_json::from_value(raw.clone()).unwrap();
653        enrollment.validate().unwrap();
654        let EnrollmentKeySet::V3(set) = &enrollment.keys else {
655            panic!("a v3 set decodes as v3");
656        };
657        assert_eq!(
658            set.lease_key(&enrollment.lease.kid)
659                .map(|k| k.key_id.as_str()),
660            Some("552e43422b3589fa")
661        );
662        assert_eq!(serde_json::to_value(&enrollment).unwrap(), raw);
663        // The kid of a key without purpose `policy` signs no lease.
664        let mut event_kid = enrollment.clone();
665        event_kid.lease.kid = "4fc7bebc302357bd".into();
666        assert!(event_kid.validate().is_err());
667        // A v3 key without its v3 fields is refused, not read as v1.
668        let mut broken = raw;
669        broken["keys"]["keys"][0]
670            .as_object_mut()
671            .unwrap()
672            .remove("key_id");
673        assert!(serde_json::from_value::<EnrollmentV1>(broken).is_err());
674    }
675
676    #[test]
677    fn requests_refuse_unknown_fields() {
678        let json = r#"{"schema":"leanctx.cloud.device-code-request/v1","client_id":"lean-ctx-engine","instance_version":"3.12.0","os":"macos","extra":true}"#;
679        assert!(serde_json::from_str::<DeviceCodeRequestV1>(json).is_err());
680    }
681}