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