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
19pub use super::app_keys::{
20    AppKeyAnnouncementV1, AppKeyKind, AppKeyOfferV1, FEATURE_DEVICE_APP_KEYS,
21    app_key_bind_signing_input,
22};
23use super::app_keys::{decode_b64url_exact, validate_app_keys};
24use super::lease::{CloudLeaseEnvelopeV1, EnrollmentKeySet};
25use super::{
26    CLOUD_ENGINE_CLIENT_ID, TOKEN_ASSERTION_DOMAIN, require_schema, validate_b64_len, validate_id,
27    validate_text,
28};
29use crate::ValidationError;
30
31pub const DEVICE_CODE_REQUEST_SCHEMA: &str = "leanctx.cloud.device-code-request/v1";
32pub const DEVICE_CODE_SCHEMA: &str = "leanctx.cloud.device-code/v1";
33pub const DEVICE_TOKEN_REQUEST_SCHEMA: &str = "leanctx.cloud.device-token-request/v1";
34pub const ENROLLMENT_SCHEMA: &str = "leanctx.cloud.enrollment/v1";
35pub const TOKEN_REQUEST_SCHEMA: &str = "leanctx.cloud.token-request/v1";
36pub const ACCESS_TOKEN_SCHEMA: &str = "leanctx.cloud.access-token/v1";
37
38/// Longest instance label, in characters.
39pub const MAX_INSTANCE_LABEL_CHARS: usize = 64;
40/// Accepted distance between `iat` and service time.
41pub const MAX_ASSERTION_SKEW_SECONDS: i64 = 300;
42/// Longest access-token lifetime the service issues.
43pub const MAX_ACCESS_TOKEN_SECONDS: u32 = 3600;
44
45/// Operating-system family of the engine.
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
47#[serde(rename_all = "snake_case")]
48pub enum EngineOs {
49    Macos,
50    Linux,
51    Windows,
52    Other,
53}
54
55fn validate_engine_version(value: &str) -> Result<(), ValidationError> {
56    let ok = !value.is_empty()
57        && value.len() <= 32
58        && value.as_bytes()[0].is_ascii_digit()
59        && value
60            .bytes()
61            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'+'));
62    if ok {
63        Ok(())
64    } else {
65        Err(ValidationError::new(
66            "instance_version must be a semantic version of at most 32 characters",
67        ))
68    }
69}
70
71/// `POST /v1/device/code`.
72#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
73#[serde(deny_unknown_fields)]
74pub struct DeviceCodeRequestV1 {
75    pub schema: String,
76    /// Always [`CLOUD_ENGINE_CLIENT_ID`].
77    pub client_id: String,
78    pub instance_version: String,
79    pub os: EngineOs,
80    /// The name the user gave this engine (`--label`), shown on the approval
81    /// page and prefilled as its name (Cloud task #11). Like `instance_version`
82    /// and `os` it is the requester's claim. Absent when the user gave none:
83    /// the host-name default goes only into [`DeviceTokenRequestV1`].
84    #[serde(default, skip_serializing_if = "Option::is_none")]
85    pub instance_label: Option<String>,
86    /// One-step trial (`lean-ctx cloud connect --trial`): why the code is
87    /// asked for. Absent for a sign-in, so a Cloud that does not know the
88    /// member (it refuses unknown fields) still serves every plain connect.
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    pub intent: Option<DeviceIntent>,
91    /// Only with `intent: "trial"`: the plan whose trial the browser starts.
92    #[serde(default, skip_serializing_if = "Option::is_none")]
93    pub plan: Option<TrialPlan>,
94    /// f3129 S2: the app keys this pairing binds, sorted by kind, one per
95    /// kind. Sent before the code answer shows [`FEATURE_DEVICE_APP_KEYS`]:
96    /// a Cloud without it refuses the unknown member and nothing is bound.
97    /// Absent when empty, so every older request stays byte-identical.
98    #[serde(default, skip_serializing_if = "Vec::is_empty")]
99    pub app_keys: Vec<AppKeyAnnouncementV1>,
100}
101
102/// `DeviceCodeRequestV1.intent`.
103#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
104#[serde(rename_all = "snake_case")]
105pub enum DeviceIntent {
106    SignIn,
107    Trial,
108}
109
110/// `DeviceCodeRequestV1.plan`: the plan a one-step trial starts.
111#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
112#[serde(rename_all = "snake_case")]
113pub enum TrialPlan {
114    Personal,
115    Team,
116}
117
118impl TrialPlan {
119    /// The wire name (`personal`, `team`).
120    pub fn as_str(self) -> &'static str {
121        match self {
122            Self::Personal => "personal",
123            Self::Team => "team",
124        }
125    }
126
127    /// `--plan personal|team`.
128    pub fn parse(value: &str) -> Option<Self> {
129        match value {
130            "personal" => Some(Self::Personal),
131            "team" => Some(Self::Team),
132            _ => None,
133        }
134    }
135}
136
137impl DeviceCodeRequestV1 {
138    pub fn new(instance_version: impl Into<String>, os: EngineOs) -> Self {
139        Self {
140            schema: DEVICE_CODE_REQUEST_SCHEMA.into(),
141            client_id: CLOUD_ENGINE_CLIENT_ID.into(),
142            instance_version: instance_version.into(),
143            os,
144            instance_label: None,
145            intent: None,
146            plan: None,
147            app_keys: Vec::new(),
148        }
149    }
150
151    /// The same request announcing `keys` (f3129 S2), sorted by kind.
152    #[must_use]
153    pub fn with_app_keys(mut self, mut keys: Vec<AppKeyAnnouncementV1>) -> Self {
154        keys.sort_by_key(|key| key.kind);
155        self.app_keys = keys;
156        self
157    }
158
159    /// The same request naming the engine (`--label`).
160    #[must_use]
161    pub fn with_label(mut self, label: Option<String>) -> Self {
162        self.instance_label = label;
163        self
164    }
165
166    /// The same request asking for a one-step trial of `plan` (`None`: a
167    /// plain sign-in, which sends neither member).
168    #[must_use]
169    pub fn with_trial(mut self, plan: Option<TrialPlan>) -> Self {
170        self.intent = plan.map(|_| DeviceIntent::Trial);
171        self.plan = plan;
172        self
173    }
174
175    pub fn validate(&self) -> Result<(), ValidationError> {
176        require_schema(&self.schema, DEVICE_CODE_REQUEST_SCHEMA)?;
177        if self.client_id != CLOUD_ENGINE_CLIENT_ID {
178            return Err(ValidationError::new(format!(
179                "client_id must be {CLOUD_ENGINE_CLIENT_ID}"
180            )));
181        }
182        if let Some(label) = &self.instance_label {
183            validate_text(label, MAX_INSTANCE_LABEL_CHARS, "instance_label", false)?;
184        }
185        if self.plan.is_some() && self.intent != Some(DeviceIntent::Trial) {
186            return Err(ValidationError::new(
187                "plan is only allowed with intent trial",
188            ));
189        }
190        validate_app_keys(&self.app_keys)?;
191        validate_engine_version(&self.instance_version)
192    }
193}
194
195/// Response of `POST /v1/device/code`.
196#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
197pub struct DeviceCodeV1 {
198    pub schema: String,
199    /// Secret polling handle; never shown or logged.
200    pub device_code: String,
201    /// Short code the user confirms in the browser, e.g. `WDJB-MJHT`.
202    pub user_code: String,
203    pub verification_uri: String,
204    pub verification_uri_complete: String,
205    /// Minimum seconds between token polls.
206    pub interval: u32,
207    /// Seconds until `device_code` expires.
208    pub expires_in: u32,
209    /// C0 2.1: what this Cloud offers beyond C0 1, e.g.
210    /// [`FEATURE_DEVICE_SETUP`]; empty (absent) on older ones.
211    #[serde(default, skip_serializing_if = "Vec::is_empty")]
212    pub features: Vec<String>,
213    /// One-step trial: the Cloud echoes the request's `intent` and `plan`
214    /// (`device_code_trial.response.json`); absent for a sign-in.
215    #[serde(default, skip_serializing_if = "Option::is_none")]
216    pub intent: Option<DeviceIntent>,
217    #[serde(default, skip_serializing_if = "Option::is_none")]
218    pub plan: Option<TrialPlan>,
219}
220
221impl DeviceCodeV1 {
222    /// Whether this code starts the trial of `plan` the request asked for.
223    pub fn starts_trial(&self, plan: TrialPlan) -> bool {
224        self.intent == Some(DeviceIntent::Trial) && self.plan.is_none_or(|p| p == plan)
225    }
226
227    /// Whether this Cloud takes `POST /v1/device/setup` for this code.
228    pub fn offers_device_setup(&self) -> bool {
229        self.features.iter().any(|f| f == FEATURE_DEVICE_SETUP)
230    }
231
232    /// Whether this Cloud binds app keys in the device flow (f3129 S2+S3).
233    /// Without it the engine announces, offers and binds none.
234    pub fn offers_app_keys(&self) -> bool {
235        self.features.iter().any(|f| f == FEATURE_DEVICE_APP_KEYS)
236    }
237}
238
239/// C0 2.1 `features` entry: the approval page shares the project too.
240pub const FEATURE_DEVICE_SETUP: &str = "device_setup";
241pub const DEVICE_SETUP_REQUEST_SCHEMA: &str = "leanctx.cloud.device-setup/v1";
242pub const DEVICE_SETUP_RESULT_SCHEMA: &str = "leanctx.cloud.device-setup-result/v1";
243
244/// C0 2.1 `POST /v1/device/setup` (no token; the pending `device_code`):
245/// the project this engine runs in and what it shares, shown on the
246/// approval page (`routes/device_setup.request.json`). Requester's claims.
247#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
248#[serde(deny_unknown_fields)]
249pub struct DeviceSetupRequestV1 {
250    pub schema: String,
251    pub device_code: String,
252    pub project: Option<DeviceSetupProjectV1>,
253    /// `knowledge`, `usage`, `receipts`, `bus`, sorted.
254    pub shares: Vec<String>,
255}
256
257#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
258#[serde(deny_unknown_fields)]
259pub struct DeviceSetupProjectV1 {
260    /// The checkout's folder name, 1-64 characters.
261    pub name: String,
262    /// The git remote as the engine sees it, for the person to recognise.
263    pub remote: Option<String>,
264}
265
266/// C0 2.1 `POST /v1/device/setup/result` (instance token):
267/// `routes/device_setup_result.request.json`.
268#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
269#[serde(deny_unknown_fields)]
270pub struct DeviceSetupResultV1 {
271    pub schema: String,
272    /// `shared`, `kept_local`, `no_project` or `failed`.
273    pub state: String,
274    #[serde(default, skip_serializing_if = "Option::is_none")]
275    pub vault: Option<String>,
276}
277
278impl fmt::Debug for DeviceCodeV1 {
279    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
280        formatter
281            .debug_struct("DeviceCodeV1")
282            .field("device_code", &"<redacted>")
283            .field("user_code", &self.user_code)
284            .field("verification_uri", &self.verification_uri)
285            .field("interval", &self.interval)
286            .field("expires_in", &self.expires_in)
287            .finish_non_exhaustive()
288    }
289}
290
291/// `http://localhost[:port]…` or `http://127.0.0.1[:port]…`.
292fn is_loopback_http(uri: &str) -> bool {
293    uri.strip_prefix("http://")
294        .and_then(|rest| rest.split(['/', ':', '?']).next())
295        .is_some_and(|host| host == "localhost" || host == "127.0.0.1")
296}
297
298impl DeviceCodeV1 {
299    pub fn validate(&self) -> Result<(), ValidationError> {
300        require_schema(&self.schema, DEVICE_CODE_SCHEMA)?;
301        validate_text(&self.device_code, 256, "device_code", false)?;
302        validate_text(&self.user_code, 16, "user_code", false)?;
303        for uri in [&self.verification_uri, &self.verification_uri_complete] {
304            if !(uri.starts_with("https://") || is_loopback_http(uri)) || uri.len() > 512 {
305                return Err(ValidationError::new(
306                    "verification uri must be https (http only on localhost/127.0.0.1)",
307                ));
308            }
309        }
310        if !(1..=60).contains(&self.interval) || !(60..=3600).contains(&self.expires_in) {
311            return Err(ValidationError::new(
312                "interval must be 1-60 s and expires_in 60-3600 s",
313            ));
314        }
315        Ok(())
316    }
317}
318
319/// `POST /v1/device/token`: poll until the user approved, then enroll the
320/// instance with its public keys.
321#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
322#[serde(deny_unknown_fields)]
323pub struct DeviceTokenRequestV1 {
324    pub schema: String,
325    pub device_code: String,
326    /// Ed25519 public key (32 bytes, base64) the instance signs assertions with.
327    pub instance_public_key: String,
328    /// X25519 public key (32 bytes, base64); enrollment carries it.
329    pub instance_kx_public_key: String,
330    /// User-visible name, e.g. the host name when labels are on.
331    pub instance_label: String,
332    pub instance_version: String,
333    pub os: EngineOs,
334    /// f3129 offers of the announced app keys, each with its own
335    /// `bind_signature`. Together they must equal `app_keys` of the code
336    /// request; absent when none was announced.
337    #[serde(default, skip_serializing_if = "Option::is_none")]
338    pub chat_key: Option<AppKeyOfferV1>,
339    #[serde(default, skip_serializing_if = "Option::is_none")]
340    pub optin_key: Option<AppKeyOfferV1>,
341    #[serde(default, skip_serializing_if = "Option::is_none")]
342    pub task_propose_key: Option<AppKeyOfferV1>,
343    /// f3129 S3: base64url (no padding) Ed25519 signature of
344    /// `instance_public_key` over [`app_key_bind_signing_input`]. Required
345    /// whenever app keys were announced; absent otherwise.
346    #[serde(default, skip_serializing_if = "Option::is_none")]
347    pub app_keys_bind_signature: Option<String>,
348}
349
350impl fmt::Debug for DeviceTokenRequestV1 {
351    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
352        formatter
353            .debug_struct("DeviceTokenRequestV1")
354            .field("device_code", &"<redacted>")
355            .field("instance_public_key", &self.instance_public_key)
356            .field("instance_label", &self.instance_label)
357            .field("instance_version", &self.instance_version)
358            .field("os", &self.os)
359            .finish_non_exhaustive()
360    }
361}
362
363impl DeviceTokenRequestV1 {
364    pub fn validate(&self) -> Result<(), ValidationError> {
365        require_schema(&self.schema, DEVICE_TOKEN_REQUEST_SCHEMA)?;
366        validate_text(&self.device_code, 256, "device_code", false)?;
367        validate_b64_len(&self.instance_public_key, 32, "instance_public_key")?;
368        validate_b64_len(&self.instance_kx_public_key, 32, "instance_kx_public_key")?;
369        validate_text(
370            &self.instance_label,
371            MAX_INSTANCE_LABEL_CHARS,
372            "instance_label",
373            false,
374        )?;
375        let offers = self.app_key_offers();
376        for (kind, offer) in &offers {
377            offer.validate(*kind)?;
378        }
379        match &self.app_keys_bind_signature {
380            Some(signature) if !offers.is_empty() => {
381                decode_b64url_exact(signature, 64, "app_keys_bind_signature")?;
382            }
383            Some(_) => {
384                return Err(ValidationError::new(
385                    "app_keys_bind_signature needs at least one offered app key",
386                ));
387            }
388            None if !offers.is_empty() => {
389                return Err(ValidationError::new(
390                    "offered app keys need app_keys_bind_signature",
391                ));
392            }
393            None => {}
394        }
395        validate_engine_version(&self.instance_version)
396    }
397
398    /// The offered app keys, sorted by kind.
399    pub fn app_key_offers(&self) -> Vec<(AppKeyKind, &AppKeyOfferV1)> {
400        [
401            (AppKeyKind::Chat, &self.chat_key),
402            (AppKeyKind::Optin, &self.optin_key),
403            (AppKeyKind::TaskPropose, &self.task_propose_key),
404        ]
405        .into_iter()
406        .filter_map(|(kind, offer)| offer.as_ref().map(|offer| (kind, offer)))
407        .collect()
408    }
409
410    /// The offer member of `kind`.
411    pub fn app_key_offer_mut(&mut self, kind: AppKeyKind) -> &mut Option<AppKeyOfferV1> {
412        match kind {
413            AppKeyKind::Chat => &mut self.chat_key,
414            AppKeyKind::Optin => &mut self.optin_key,
415            AppKeyKind::TaskPropose => &mut self.task_propose_key,
416        }
417    }
418}
419
420/// Organization reference: the workspace the instance enrolls in.
421#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
422pub struct OrgRefV1 {
423    pub id: String,
424    pub name: String,
425    /// `personal` | `team` (Cloud C line, additive); older servers omit it.
426    #[serde(default, skip_serializing_if = "Option::is_none")]
427    pub kind: Option<String>,
428    /// The company a team belongs to (Cloud C line, additive).
429    #[serde(default, skip_serializing_if = "Option::is_none")]
430    pub company: Option<CompanyRefV1>,
431}
432
433/// The company of a team: the business that holds its Enterprise plan.
434#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
435pub struct CompanyRefV1 {
436    pub name: String,
437}
438
439/// Successful `POST /v1/device/token`.
440#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
441pub struct EnrollmentV1 {
442    pub schema: String,
443    pub instance_id: String,
444    pub org: OrgRefV1,
445    pub lease: CloudLeaseEnvelopeV1,
446    /// Signed by the Cloud root key; verified before the lease. v1 for an
447    /// engine below Cloud-Protocol 2.1, v3 from 2.1.
448    pub keys: EnrollmentKeySet,
449    /// Id of the org salt the engine fetches with `GET /v1/org/salt`.
450    pub org_salt_id: String,
451    /// 1.3: origin of the LeanCTX Cloud web app (its "Open" link); may equal the API origin.
452    #[serde(default, skip_serializing_if = "Option::is_none")]
453    pub web_url: Option<String>,
454    /// The name the person gave this computer on the approval page, as the
455    /// Cloud stored it (rc4-1). Additive: an older Cloud omits it and the
456    /// engine keeps the label it sent in [`DeviceTokenRequestV1`]. Display
457    /// only; a value that fails [`EnrollmentV1::chosen_label`] is ignored,
458    /// never a reason to refuse the enrollment. `null` reads as absent. The
459    /// rule is the Cloud's (`keyset.schema.json` `enrollment_for_2x`
460    /// pattern, `vectors/instance_label.vectors.json`): no whitespace at the
461    /// start or end (a space, a no-break space or any other Unicode
462    /// whitespace), 1–64 characters, no control or [`super::invisible`]
463    /// character.
464    #[serde(default, skip_serializing_if = "Option::is_none")]
465    pub instance_label: Option<String>,
466}
467
468impl EnrollmentV1 {
469    /// The name chosen on the approval page when it is 1–64 characters of
470    /// printable text without whitespace at either end; `None` when absent
471    /// or unusable, so the engine keeps the name it sent.
472    pub fn chosen_label(&self) -> Option<&str> {
473        let label = self.instance_label.as_deref()?;
474        if label.trim() != label {
475            return None;
476        }
477        validate_text(label, MAX_INSTANCE_LABEL_CHARS, "instance_label", false)
478            .ok()
479            .map(|()| label)
480    }
481
482    /// Structural checks; signature checks are the engine's
483    /// (`keys` against the root key, then `lease` against `keys`).
484    pub fn validate(&self) -> Result<(), ValidationError> {
485        require_schema(&self.schema, ENROLLMENT_SCHEMA)?;
486        validate_id(&self.instance_id, "instance_id")?;
487        validate_id(&self.org.id, "org.id")?;
488        validate_text(&self.org.name, 128, "org.name", false)?;
489        validate_id(&self.org_salt_id, "org_salt_id")?;
490        if let Some(web_url) = &self.web_url {
491            super::validate_origin(web_url, "web_url")?;
492        }
493        self.keys.validate()?;
494        self.lease.validate_shape()?;
495        if !self.keys.signs_leases_as(&self.lease.kid) {
496            return Err(ValidationError::new(
497                "the lease kid names no lease key of the enrollment's key set",
498            ));
499        }
500        Ok(())
501    }
502}
503
504/// `POST /v1/instances/{instance_id}/token`.
505#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
506#[serde(deny_unknown_fields)]
507pub struct InstanceTokenRequestV1 {
508    pub schema: String,
509    /// Unix seconds; the service accepts ±[`MAX_ASSERTION_SKEW_SECONDS`].
510    pub iat: i64,
511    /// 16–64 chars of `[A-Za-z0-9_-]`, single use within the skew window.
512    pub nonce: String,
513    /// Ed25519 signature (base64) over [`token_assertion_input`].
514    pub assertion: String,
515}
516
517impl InstanceTokenRequestV1 {
518    pub fn validate(&self) -> Result<(), ValidationError> {
519        require_schema(&self.schema, TOKEN_REQUEST_SCHEMA)?;
520        if self.iat <= 0 {
521            return Err(ValidationError::new("iat must be positive unix seconds"));
522        }
523        validate_nonce(&self.nonce)?;
524        validate_b64_len(&self.assertion, 64, "assertion")
525    }
526}
527
528fn validate_nonce(nonce: &str) -> Result<(), ValidationError> {
529    if (16..=64).contains(&nonce.len())
530        && nonce
531            .bytes()
532            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
533    {
534        Ok(())
535    } else {
536        Err(ValidationError::new(
537            "nonce must be 16-64 characters of [A-Za-z0-9_-]",
538        ))
539    }
540}
541
542/// Bytes the instance key signs: `"leanctx.cloud.token.v1\n" + instance_id +
543/// "\n" + iat + "\n" + nonce` (iat in decimal unix seconds).
544pub fn token_assertion_input(instance_id: &str, iat: i64, nonce: &str) -> Vec<u8> {
545    format!("{TOKEN_ASSERTION_DOMAIN}{instance_id}\n{iat}\n{nonce}").into_bytes()
546}
547
548/// Response of `POST /v1/instances/{instance_id}/token`.
549#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
550pub struct AccessTokenV1 {
551    pub schema: String,
552    /// Bearer token; never logged, printed or persisted outside `token.json`.
553    pub access_token: String,
554    /// Seconds, at most [`MAX_ACCESS_TOKEN_SECONDS`].
555    pub expires_in: u32,
556}
557
558impl fmt::Debug for AccessTokenV1 {
559    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
560        formatter
561            .debug_struct("AccessTokenV1")
562            .field("access_token", &"<redacted>")
563            .field("expires_in", &self.expires_in)
564            .finish_non_exhaustive()
565    }
566}
567
568impl AccessTokenV1 {
569    pub fn validate(&self) -> Result<(), ValidationError> {
570        require_schema(&self.schema, ACCESS_TOKEN_SCHEMA)?;
571        validate_text(&self.access_token, 4096, "access_token", false)?;
572        if !(1..=MAX_ACCESS_TOKEN_SECONDS).contains(&self.expires_in) {
573            return Err(ValidationError::new("expires_in must be 1-3600 s"));
574        }
575        Ok(())
576    }
577}
578
579#[cfg(test)]
580mod tests {
581    use super::*;
582
583    #[test]
584    fn a_device_code_label_follows_the_text_rule() {
585        let request = |label: Option<&str>| {
586            DeviceCodeRequestV1::new("3.12.0", EngineOs::Macos)
587                .with_label(label.map(str::to_string))
588        };
589        assert!(request(None).validate().is_ok());
590        assert!(request(Some("build-box")).validate().is_ok());
591        let long = "x".repeat(MAX_INSTANCE_LABEL_CHARS + 1);
592        for bad in [
593            "",
594            "line\nbreak",
595            "zero\u{200b}width",
596            "a\u{202e}b",
597            long.as_str(),
598        ] {
599            assert!(request(Some(bad)).validate().is_err(), "{bad:?}");
600        }
601        let unlabelled = serde_json::to_value(request(None)).unwrap();
602        assert!(
603            unlabelled.get("instance_label").is_none(),
604            "older services refuse unknown fields"
605        );
606    }
607
608    /// `cloud connect --trial`: intent and plan travel only on a trial
609    /// request; a sign-in sends neither (older Clouds refuse unknown fields).
610    #[test]
611    fn trial_device_code_request_carries_intent_and_plan() {
612        let plain = DeviceCodeRequestV1::new("3.12.0", EngineOs::Macos).with_trial(None);
613        let json = serde_json::to_value(&plain).unwrap();
614        assert!(json.get("intent").is_none() && json.get("plan").is_none());
615        let trial =
616            DeviceCodeRequestV1::new("3.12.0", EngineOs::Macos).with_trial(Some(TrialPlan::Team));
617        assert!(trial.validate().is_ok());
618        let json = serde_json::to_value(&trial).unwrap();
619        assert_eq!(json["intent"], "trial");
620        assert_eq!(json["plan"], "team");
621        assert_eq!(
622            serde_json::from_value::<DeviceCodeRequestV1>(json).unwrap(),
623            trial
624        );
625        let personal = DeviceCodeRequestV1::new("3.12.0", EngineOs::Linux)
626            .with_trial(Some(TrialPlan::Personal));
627        assert_eq!(serde_json::to_value(&personal).unwrap()["plan"], "personal");
628        let mut plan_only = plain.clone();
629        plan_only.plan = Some(TrialPlan::Personal);
630        assert!(plan_only.validate().is_err(), "plan needs intent trial");
631        assert_eq!(TrialPlan::parse("team"), Some(TrialPlan::Team));
632        assert_eq!(TrialPlan::parse("enterprise"), None);
633    }
634
635    /// p37 !134 contract fixtures: the trial request is the engine's own,
636    /// byte for byte, and the answer echoes the trial it starts.
637    #[test]
638    fn trial_device_code_documents_are_the_contract_fixtures() {
639        let request: serde_json::Value = serde_json::from_str(include_str!(
640            "../../tests/fixtures/cloud/device_code_trial.request.json"
641        ))
642        .unwrap();
643        let ours = DeviceCodeRequestV1::new("3.12.1", EngineOs::Macos)
644            .with_trial(Some(TrialPlan::Personal));
645        assert_eq!(serde_json::to_value(&ours).unwrap(), request);
646        let answer: serde_json::Value = serde_json::from_str(include_str!(
647            "../../tests/fixtures/cloud/device_code_trial.response.json"
648        ))
649        .unwrap();
650        let code: DeviceCodeV1 = serde_json::from_value(answer.clone()).unwrap();
651        code.validate().unwrap();
652        assert_eq!(serde_json::to_value(&code).unwrap(), answer);
653        assert!(code.starts_trial(TrialPlan::Personal));
654        assert!(!code.starts_trial(TrialPlan::Team));
655        assert!(
656            code.verification_uri_complete
657                .ends_with("&intent=trial&plan=personal")
658        );
659        let sign_in: DeviceCodeV1 = serde_json::from_str(include_str!(
660            "../../tests/fixtures/cloud/device_code.response.json"
661        ))
662        .unwrap();
663        assert!(
664            !sign_in.starts_trial(TrialPlan::Personal),
665            "no echo, no trial"
666        );
667    }
668
669    #[test]
670    fn assertion_input_is_the_documented_text() {
671        assert_eq!(
672            token_assertion_input("inst_1", 1_792_500_000, "n0nce-n0nce-n0nce"),
673            b"leanctx.cloud.token.v1\ninst_1\n1792500000\nn0nce-n0nce-n0nce".to_vec()
674        );
675    }
676
677    #[test]
678    fn secrets_stay_out_of_debug() {
679        let token = AccessTokenV1 {
680            schema: ACCESS_TOKEN_SCHEMA.into(),
681            access_token: "atl_secret_value".into(),
682            expires_in: 3600,
683        };
684        assert!(!format!("{token:?}").contains("atl_secret_value"));
685        let code = DeviceCodeV1 {
686            schema: DEVICE_CODE_SCHEMA.into(),
687            device_code: "dc_secret_value".into(),
688            user_code: "WDJB-MJHT".into(),
689            verification_uri: "https://cloud.leanctx.com/device".into(),
690            verification_uri_complete: "https://cloud.leanctx.com/device?code=WDJB-MJHT".into(),
691            interval: 5,
692            expires_in: 900,
693            features: Vec::new(),
694            intent: None,
695            plan: None,
696        };
697        assert!(!format!("{code:?}").contains("dc_secret_value"));
698        assert!(!code.offers_device_setup());
699    }
700
701    /// C0 2.1 device setup: the contract fixtures round-trip byte for byte
702    /// through the engine's types, and the features list is optional.
703    #[test]
704    fn device_setup_documents_are_the_contract_fixtures() {
705        fn round<T: serde::de::DeserializeOwned + Serialize>(raw: &str) {
706            let value: serde_json::Value = serde_json::from_str(raw).unwrap();
707            let typed: T = serde_json::from_value(value.clone()).unwrap();
708            assert_eq!(serde_json::to_value(typed).unwrap(), value);
709        }
710        round::<DeviceSetupRequestV1>(include_str!(
711            "../../tests/fixtures/cloud-v2/routes/device_setup.request.json"
712        ));
713        round::<DeviceSetupResultV1>(include_str!(
714            "../../tests/fixtures/cloud-v2/routes/device_setup_result.request.json"
715        ));
716        let mut answer = serde_json::json!({
717            "schema": DEVICE_CODE_SCHEMA, "device_code": "dc_x", "user_code": "WDJB-MJHT",
718            "verification_uri": "https://cloud.leanctx.com/device",
719            "verification_uri_complete": "https://cloud.leanctx.com/device?user_code=WDJB-MJHT",
720            "interval": 5, "expires_in": 900,
721        });
722        let old: DeviceCodeV1 = serde_json::from_value(answer.clone()).unwrap();
723        assert!(
724            !old.offers_device_setup(),
725            "a LeanCTX Cloud server with C0 2.0 lists nothing"
726        );
727        answer["features"] = serde_json::json!([FEATURE_DEVICE_SETUP, "later"]);
728        let new: DeviceCodeV1 = serde_json::from_value(answer).unwrap();
729        assert!(new.offers_device_setup());
730    }
731
732    /// An enrollment as a Cloud-Protocol 1.x/2.0 engine receives it: key
733    /// set v1, the lease signed by a `kid` of it.
734    #[test]
735    fn an_enrollment_with_key_set_v1_decodes_and_names_its_lease_key() {
736        let raw: serde_json::Value = serde_json::from_str(include_str!(
737            "../../tests/fixtures/cloud/enrollment.response.json"
738        ))
739        .unwrap();
740        let enrollment: EnrollmentV1 = serde_json::from_value(raw.clone()).unwrap();
741        enrollment.validate().unwrap();
742        assert!(matches!(enrollment.keys, EnrollmentKeySet::V1(_)));
743        assert_eq!(serde_json::to_value(&enrollment).unwrap(), raw);
744        let mut other_kid = enrollment;
745        other_kid.lease.kid = "k-unknown".into();
746        assert!(other_kid.validate().is_err(), "the kid follows the set");
747    }
748
749    /// An enrollment as a Cloud-Protocol 2.1+ engine receives it
750    /// (`routes/enrollment.for_2x.response.json`): key set v3, the lease of
751    /// a 2.x engine signed by the v3 key of purpose `policy` its `kid`
752    /// names.
753    #[test]
754    fn an_enrollment_with_key_set_v3_decodes_and_names_its_policy_key() {
755        let raw: serde_json::Value = serde_json::from_str(include_str!(
756            "../../tests/fixtures/cloud-v2/routes/enrollment.for_2x.response.json"
757        ))
758        .unwrap();
759        let enrollment: EnrollmentV1 = serde_json::from_value(raw.clone()).unwrap();
760        enrollment.validate().unwrap();
761        let EnrollmentKeySet::V3(set) = &enrollment.keys else {
762            panic!("a v3 set decodes as v3");
763        };
764        assert_eq!(
765            set.lease_key(&enrollment.lease.kid)
766                .map(|k| k.key_id.as_str()),
767            Some("552e43422b3589fa")
768        );
769        assert_eq!(serde_json::to_value(&enrollment).unwrap(), raw);
770        // The kid of a key without purpose `policy` signs no lease.
771        let mut event_kid = enrollment.clone();
772        event_kid.lease.kid = "4fc7bebc302357bd".into();
773        assert!(event_kid.validate().is_err());
774        // A v3 key without its v3 fields is refused, not read as v1.
775        let mut broken = raw;
776        broken["keys"]["keys"][0]
777            .as_object_mut()
778            .unwrap()
779            .remove("key_id");
780        assert!(serde_json::from_value::<EnrollmentV1>(broken).is_err());
781    }
782
783    fn fixture(rel: &str) -> serde_json::Value {
784        let path = format!(
785            "{}/tests/fixtures/cloud-v2/{rel}",
786            env!("CARGO_MANIFEST_DIR")
787        );
788        serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap()
789    }
790
791    fn enrollment_from(answer: serde_json::Value) -> EnrollmentV1 {
792        let enrollment: EnrollmentV1 = serde_json::from_value(answer).unwrap();
793        enrollment.validate().unwrap();
794        enrollment
795    }
796
797    /// rc4-1: the name typed on the approval page comes back as
798    /// `instance_label` (`routes/enrollment.for_2x.response.json`); a Cloud
799    /// that stored none sends no member (`….unlabelled.response.json`) or,
800    /// tolerated, `null`.
801    #[test]
802    fn an_enrollment_names_the_label_chosen_on_the_approval_page() {
803        let labelled = fixture("routes/enrollment.for_2x.response.json");
804        let enrollment = enrollment_from(labelled.clone());
805        assert_eq!(enrollment.chosen_label(), Some("Ada's MacBook Air"));
806        assert_eq!(serde_json::to_value(&enrollment).unwrap(), labelled);
807
808        let unlabelled = fixture("routes/enrollment.for_2x.unlabelled.response.json");
809        let enrollment = enrollment_from(unlabelled.clone());
810        assert_eq!(enrollment.instance_label, None);
811        assert_eq!(enrollment.chosen_label(), None);
812        assert_eq!(serde_json::to_value(&enrollment).unwrap(), unlabelled);
813
814        let mut null = labelled;
815        null["instance_label"] = serde_json::Value::Null;
816        assert_eq!(enrollment_from(null).chosen_label(), None);
817    }
818
819    /// `vectors/instance_label.vectors.json`: the engine takes a name exactly
820    /// as the Cloud does (1–64 characters, no control or invisible
821    /// character), and a refused one leaves the enrollment valid.
822    #[test]
823    fn the_chosen_label_follows_the_instance_label_vectors() {
824        let vectors = fixture("vectors/instance_label.vectors.json");
825        assert_eq!(vectors["max_chars"], MAX_INSTANCE_LABEL_CHARS);
826        let base = fixture("routes/enrollment.for_2x.unlabelled.response.json");
827        let cases = vectors["cases"].as_array().unwrap();
828        assert!(cases.len() >= 40, "only {} vectors", cases.len());
829        for case in cases {
830            let input = case["input"].as_str().unwrap();
831            // The vectors trim what a person types; the stored name the
832            // enrollment answer carries has no whitespace at either end
833            // (keyset.schema.json pattern), so the engine refuses one.
834            let name = if input.trim() == input {
835                case["name"].as_str()
836            } else {
837                None
838            };
839            let mut answer = base.clone();
840            answer["instance_label"] = case["input"].clone();
841            let enrollment = enrollment_from(answer);
842            assert_eq!(
843                enrollment.chosen_label(),
844                name,
845                "{}: {:?}",
846                case["why"],
847                case["input"]
848            );
849        }
850    }
851
852    /// p37 !290: whitespace at the start or end, a space or a no-break space,
853    /// is refused rather than trimmed.
854    #[test]
855    fn a_label_with_whitespace_at_either_end_is_ignored() {
856        let base = fixture("routes/enrollment.for_2x.unlabelled.response.json");
857        let chosen = |label: &str| {
858            let mut answer = base.clone();
859            answer["instance_label"] = serde_json::Value::from(label);
860            enrollment_from(answer).chosen_label().map(str::to_string)
861        };
862        assert_eq!(chosen("Ada").as_deref(), Some("Ada"));
863        assert_eq!(chosen("Ada\u{a0}Mac").as_deref(), Some("Ada\u{a0}Mac"));
864        for bad in [
865            " Ada",
866            "Ada ",
867            "\u{a0}Ada",
868            "Ada\u{a0}",
869            "\u{3000}Ada",
870            "Ada\u{2003}",
871        ] {
872            assert_eq!(chosen(bad), None, "{bad:?}");
873        }
874    }
875
876    /// The Cloud's schema refuses the `routes/invalid/enrollment_instance_label_*`
877    /// answers; the engine reads each as an enrollment without a chosen name
878    /// rather than failing the connect.
879    #[test]
880    fn an_invalid_instance_label_is_ignored_not_fatal() {
881        let dir = format!(
882            "{}/tests/fixtures/cloud-v2/routes/invalid",
883            env!("CARGO_MANIFEST_DIR")
884        );
885        let mut checked = 0;
886        for entry in std::fs::read_dir(&dir).unwrap() {
887            let name = entry.unwrap().file_name().to_string_lossy().into_owned();
888            if !name.starts_with("enrollment_instance_label_") {
889                continue;
890            }
891            let case = fixture(&format!("routes/invalid/{name}"));
892            let mut answer = fixture(case["base"].as_str().unwrap());
893            for op in case["patch"].as_array().unwrap() {
894                assert_eq!(op["op"], "replace", "{name}");
895                let member = op["path"].as_str().unwrap().strip_prefix('/').unwrap();
896                answer[member] = op["value"].clone();
897            }
898            assert_eq!(enrollment_from(answer).chosen_label(), None, "{name}");
899            checked += 1;
900        }
901        assert!(
902            checked >= 9,
903            "only {checked} invalid instance_label fixtures"
904        );
905    }
906
907    #[test]
908    fn requests_refuse_unknown_fields() {
909        let json = r#"{"schema":"leanctx.cloud.device-code-request/v1","client_id":"lean-ctx-engine","instance_version":"3.12.0","os":"macos","extra":true}"#;
910        assert!(serde_json::from_str::<DeviceCodeRequestV1>(json).is_err());
911    }
912}