Skip to main content

lean_ctx_protocol/cloud/
lease.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Instance lease and the Cloud signing key set.
4//!
5//! - `GET /v1/keys` → [`CloudKeySetV1`], signed by the Cloud root key that is
6//!   compiled into the engine (self-host: `[cloud] root_key`).
7//! - The lease arrives in enrollment and from `lease/renew` as
8//!   [`CloudLeaseEnvelopeV1`], signed by a key of the key set.
9//! - Cloud-Protocol 2.1: an enrollment of a 2.1+ engine carries key set v3
10//!   ([`CloudKeySetV3`], C0 2.x `keyset.schema.json`) instead of v1; the
11//!   lease `kid` then names the v3 key of purpose `policy`
12//!   ([`EnrollmentKeySet`]).
13//!
14//! A lease is `Valid` until `expires_at`, `Grace` until `grace_until`, then
15//! `Lapsed`. Local tools never depend on the lease; only Cloud traffic does.
16
17use lean_ctx_time::{Duration, OffsetDateTime};
18use serde::{Deserialize, Deserializer, Serialize};
19use serde_json::Value;
20
21use super::{
22    KEYSET_SIGNATURE_DOMAIN, LEASE_SIGNATURE_DOMAIN, parse_time, require_schema, signing_input,
23    signing_input_without_signature, validate_b64_len, validate_id,
24};
25use crate::{UtcTimestamp, ValidationError};
26
27pub const LEASE_SCHEMA: &str = "leanctx.cloud.lease/v1";
28pub const LEASE_ENVELOPE_SCHEMA: &str = "leanctx.cloud.lease-envelope/v1";
29pub const KEYSET_SCHEMA: &str = "leanctx.cloud.keyset/v1";
30/// Key set v3 (C0 2.x E13), in enrollments of Cloud-Protocol 2.1+.
31pub const KEYSET_V3_SCHEMA: &str = "leanctx.cloud.keyset/v3";
32/// The v3 purpose of the keys that sign leases (and policy bundles).
33pub const LEASE_KEY_PURPOSE: &str = "policy";
34
35/// Longest `expires_at - issued_at`.
36pub const MAX_LEASE_VALIDITY_HOURS: i64 = 24;
37/// Longest `grace_until - expires_at`.
38pub const MAX_LEASE_GRACE_DAYS: i64 = 7;
39/// A lease issued further than this in the future (after offset correction) is refused.
40pub const MAX_LEASE_FUTURE_SKEW_MINUTES: i64 = 15;
41/// The engine renews when less than this remains before `expires_at`.
42pub const LEASE_RENEW_BEFORE_HOURS: i64 = 6;
43
44/// Plan of the organization.
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
46#[serde(rename_all = "snake_case")]
47pub enum CloudPlan {
48    /// A workspace without a paid plan: Cloud sends `none`.
49    #[serde(rename = "none")]
50    NoPlan,
51    Personal,
52    Team,
53    Enterprise,
54    #[serde(other)]
55    Unknown,
56}
57
58impl CloudPlan {
59    /// The plan's name as people read it: Personal, Team and Enterprise.
60    pub fn display_name(self) -> &'static str {
61        match self {
62            Self::NoPlan => "No plan",
63            Self::Personal => "Personal",
64            Self::Team => "Team",
65            Self::Enterprise => "Enterprise",
66            Self::Unknown => "unknown",
67        }
68    }
69
70    /// The plan's product name: Personal, Team, Enterprise.
71    pub fn product_name(self) -> &'static str {
72        match self {
73            Self::NoPlan => "No plan",
74            Self::Personal => "Personal",
75            Self::Team => "Team",
76            Self::Enterprise => "Enterprise",
77            Self::Unknown => "Unknown",
78        }
79    }
80}
81
82/// A right granted to this instance. Unknown rights decode as `Unknown` and grant nothing.
83#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
84pub enum CloudRight {
85    #[serde(rename = "knowledge.read")]
86    KnowledgeRead,
87    #[serde(rename = "knowledge.draft")]
88    KnowledgeDraft,
89    #[serde(rename = "knowledge.merge")]
90    KnowledgeMerge,
91    #[serde(rename = "metrics.upload")]
92    MetricsUpload,
93    #[serde(rename = "receipts.upload")]
94    ReceiptsUpload,
95    #[serde(rename = "policy.pull")]
96    PolicyPull,
97    #[serde(rename = "bus.relay")]
98    BusRelay,
99    #[serde(rename = "bus.control")]
100    BusControl,
101    /// Decoded and grants nothing: an engine does not use sealed vaults.
102    #[serde(rename = "sealed")]
103    Sealed,
104    /// 1.2: the Intelligence runtime may run for this instance (what it
105    /// enables stays gated by `plan`).
106    #[serde(rename = "runtime")]
107    Runtime,
108    /// 1.9: read the vault's tasks.
109    #[serde(rename = "tasks.read")]
110    TasksRead,
111    /// 1.9: claim tasks, report updates and submit results.
112    #[serde(rename = "tasks.work")]
113    TasksWork,
114    /// 1.9: propose tasks. Cloud answers with the state: a member agent's
115    /// task opens at once; a Cloud that still asks for approval keeps it
116    /// `proposed`.
117    #[serde(rename = "tasks.propose")]
118    TasksPropose,
119    /// mz6: the subscription models (`leanctx/<model>`) may be served to
120    /// this instance through the Cloud models gateway; plan and credit stay
121    /// the gateway's check on every request.
122    #[serde(rename = "models.subscription")]
123    ModelsSubscription,
124    #[serde(other)]
125    Unknown,
126}
127
128/// The signed lease statement.
129#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
130pub struct CloudLeaseV1 {
131    pub schema: String,
132    pub lease_id: String,
133    pub org_id: String,
134    pub instance_id: String,
135    pub plan: CloudPlan,
136    /// The organization's limit of engine instances (Personal 2,
137    /// Team 2 per seat, Enterprise 3 per seat and at least 25); the wire
138    /// name is frozen in v1.
139    pub seats_limit: u32,
140    pub rights: Vec<CloudRight>,
141    pub issued_at: UtcTimestamp,
142    pub expires_at: UtcTimestamp,
143    pub grace_until: UtcTimestamp,
144    /// Service clock at signing; the engine keeps `server_time - local_now` as offset.
145    pub server_time: UtcTimestamp,
146    /// 1.4: what the organization allows its engines to upload. Absent
147    /// (an older service) allows both.
148    #[serde(default, skip_serializing_if = "Option::is_none")]
149    pub org_settings: Option<CloudOrgSettingsV1>,
150    /// One-step trial: RFC 3339 end of the workspace's free trial, present
151    /// only while it runs (`lean-ctx cloud status` shows it). Older services
152    /// and paid workspaces omit it; signatures cover the raw lease, so a
153    /// lease without it verifies unchanged.
154    #[serde(default, skip_serializing_if = "Option::is_none")]
155    pub trial_ends_at: Option<String>,
156}
157
158/// Organization-wide switches the lease carries (1.4). They only narrow:
159/// an engine uploads only what both its own `[cloud]` setting and these
160/// allow, and receipts still need the `receipts.upload` right.
161#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
162pub struct CloudOrgSettingsV1 {
163    #[serde(default = "allowed")]
164    pub metrics_upload: bool,
165    #[serde(default = "allowed")]
166    pub receipts_upload: bool,
167}
168
169const fn allowed() -> bool {
170    true
171}
172
173/// Where a lease stands at a given (offset-corrected) time.
174#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
175#[serde(rename_all = "snake_case")]
176pub enum LeaseState {
177    Valid,
178    Grace,
179    Lapsed,
180}
181
182impl CloudLeaseV1 {
183    pub fn validate(&self) -> Result<(), ValidationError> {
184        require_schema(&self.schema, LEASE_SCHEMA)?;
185        validate_id(&self.lease_id, "lease_id")?;
186        validate_id(&self.org_id, "org_id")?;
187        validate_id(&self.instance_id, "instance_id")?;
188        if self.seats_limit == 0 {
189            return Err(ValidationError::new("seats_limit must be positive"));
190        }
191        if self.rights.len() > 64 {
192            return Err(ValidationError::new("lease lists are too long"));
193        }
194        let issued = parse_time(&self.issued_at)?;
195        let expires = parse_time(&self.expires_at)?;
196        let grace = parse_time(&self.grace_until)?;
197        parse_time(&self.server_time)?;
198        if expires <= issued || expires - issued > Duration::hours(MAX_LEASE_VALIDITY_HOURS) {
199            return Err(ValidationError::new(
200                "expires_at must be after issued_at and at most 24 h later",
201            ));
202        }
203        if grace < expires || grace - expires > Duration::days(MAX_LEASE_GRACE_DAYS) {
204            return Err(ValidationError::new(
205                "grace_until must be within 7 days after expires_at",
206            ));
207        }
208        Ok(())
209    }
210
211    /// Whether the lease grants `right`.
212    pub fn grants(&self, right: CloudRight) -> bool {
213        right != CloudRight::Unknown && self.rights.contains(&right)
214    }
215
216    /// Whether the organization allows metrics uploads (absent settings allow).
217    pub fn org_allows_metrics_upload(&self) -> bool {
218        self.org_settings
219            .is_none_or(|settings| settings.metrics_upload)
220    }
221
222    /// Whether the organization allows receipt uploads (absent settings allow).
223    pub fn org_allows_receipts_upload(&self) -> bool {
224        self.org_settings
225            .is_none_or(|settings| settings.receipts_upload)
226    }
227
228    /// State at `now` (service time: local clock plus the stored offset).
229    /// A lease issued more than 15 minutes after `now` counts as `Lapsed`.
230    pub fn state_at(&self, now: OffsetDateTime) -> Result<LeaseState, ValidationError> {
231        let issued = parse_time(&self.issued_at)?;
232        if issued - now > Duration::minutes(MAX_LEASE_FUTURE_SKEW_MINUTES) {
233            return Ok(LeaseState::Lapsed);
234        }
235        Ok(if now < parse_time(&self.expires_at)? {
236            LeaseState::Valid
237        } else if now < parse_time(&self.grace_until)? {
238            LeaseState::Grace
239        } else {
240            LeaseState::Lapsed
241        })
242    }
243
244    /// Whether the engine should renew now.
245    pub fn renew_due(&self, now: OffsetDateTime) -> Result<bool, ValidationError> {
246        Ok(parse_time(&self.expires_at)? - now < Duration::hours(LEASE_RENEW_BEFORE_HOURS))
247    }
248}
249
250/// Lease as it travels: the raw lease object plus its signature.
251///
252/// `lease` stays raw JSON so the signature covers exactly what the service
253/// signed, including fields this engine does not know.
254#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
255pub struct CloudLeaseEnvelopeV1 {
256    pub schema: String,
257    pub lease: Value,
258    /// Key id within [`CloudKeySetV1`].
259    pub kid: String,
260    /// Ed25519 signature (base64) over [`CloudLeaseEnvelopeV1::signing_input`].
261    pub signature: String,
262}
263
264impl CloudLeaseEnvelopeV1 {
265    /// Envelope fields only; call [`Self::lease`] after verifying the signature.
266    pub fn validate_shape(&self) -> Result<(), ValidationError> {
267        require_schema(&self.schema, LEASE_ENVELOPE_SCHEMA)?;
268        validate_id(&self.kid, "kid")?;
269        validate_b64_len(&self.signature, 64, "signature")?;
270        if !self.lease.is_object() {
271            return Err(ValidationError::new("lease must be a JSON object"));
272        }
273        Ok(())
274    }
275
276    /// `"leanctx.cloud.lease.v1\n" || canonical_json(lease)`.
277    pub fn signing_input(&self) -> Result<Vec<u8>, ValidationError> {
278        signing_input(LEASE_SIGNATURE_DOMAIN, &self.lease)
279    }
280
281    /// Signing input for a lease the service is about to sign.
282    pub fn signing_input_for(lease: &CloudLeaseV1) -> Result<Vec<u8>, ValidationError> {
283        lease.validate()?;
284        signing_input(LEASE_SIGNATURE_DOMAIN, &lease_value(lease)?)
285    }
286
287    /// Build the envelope for a signed lease.
288    pub fn seal(
289        lease: &CloudLeaseV1,
290        kid: impl Into<String>,
291        signature: impl Into<String>,
292    ) -> Result<Self, ValidationError> {
293        lease.validate()?;
294        let envelope = Self {
295            schema: LEASE_ENVELOPE_SCHEMA.into(),
296            lease: lease_value(lease)?,
297            kid: kid.into(),
298            signature: signature.into(),
299        };
300        envelope.validate_shape()?;
301        Ok(envelope)
302    }
303
304    /// The typed, validated lease.
305    pub fn lease(&self) -> Result<CloudLeaseV1, ValidationError> {
306        let lease: CloudLeaseV1 = serde_json::from_value(self.lease.clone())
307            .map_err(|error| ValidationError::new(format!("lease: {error}")))?;
308        lease.validate()?;
309        Ok(lease)
310    }
311}
312
313fn lease_value(lease: &CloudLeaseV1) -> Result<Value, ValidationError> {
314    serde_json::to_value(lease).map_err(|error| ValidationError::new(format!("lease: {error}")))
315}
316
317/// One Cloud signing key.
318#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
319pub struct CloudKeyV1 {
320    pub kid: String,
321    /// Ed25519 public key, 32 bytes base64.
322    pub ed25519_pub: String,
323    /// The key signs nothing after this time; signatures made before stay valid
324    /// until the signed object itself expires.
325    pub not_after: UtcTimestamp,
326}
327
328/// `GET /v1/keys`. The signature covers the object without `signature`.
329/// Engines keep the raw JSON (`keys.json`) and verify it with
330/// [`CloudKeySetV1::signing_input_raw`].
331#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
332pub struct CloudKeySetV1 {
333    pub schema: String,
334    pub keys: Vec<CloudKeyV1>,
335    /// Ed25519 signature (base64) of the Cloud root key.
336    pub signature: String,
337}
338
339impl CloudKeySetV1 {
340    pub fn validate(&self) -> Result<(), ValidationError> {
341        require_schema(&self.schema, KEYSET_SCHEMA)?;
342        if self.keys.is_empty() || self.keys.len() > 16 {
343            return Err(ValidationError::new("keys must list 1-16 keys"));
344        }
345        let mut seen = std::collections::BTreeSet::new();
346        for key in &self.keys {
347            validate_id(&key.kid, "kid")?;
348            validate_b64_len(&key.ed25519_pub, 32, "ed25519_pub")?;
349            parse_time(&key.not_after)?;
350            if !seen.insert(key.kid.as_str()) {
351                return Err(ValidationError::new("kid repeats in key set"));
352            }
353        }
354        validate_b64_len(&self.signature, 64, "signature")
355    }
356
357    /// Signing input of a key set as received.
358    pub fn signing_input_raw(raw: &Value) -> Result<Vec<u8>, ValidationError> {
359        signing_input_without_signature(KEYSET_SIGNATURE_DOMAIN, raw)
360    }
361
362    /// Signing input of a key set the service is about to sign (`signature` ignored).
363    pub fn signing_input(&self) -> Result<Vec<u8>, ValidationError> {
364        let value = serde_json::to_value(self)
365            .map_err(|error| ValidationError::new(format!("keyset: {error}")))?;
366        Self::signing_input_raw(&value)
367    }
368
369    /// Key `kid`, if listed.
370    pub fn key(&self, kid: &str) -> Option<&CloudKeyV1> {
371        self.keys.iter().find(|key| key.kid == kid)
372    }
373}
374
375/// One key of a key set v3. Purposes stay strings here: the set's root
376/// signature covers them, and the engine checks each use against them.
377#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
378pub struct CloudKeyV3 {
379    /// `hex(blake3(public key))[..16]`.
380    pub key_id: String,
381    /// base64url (no padding) of the raw 32-byte Ed25519 key.
382    pub public_key: String,
383    pub purposes: Vec<String>,
384    /// Unix milliseconds.
385    pub created_at: u64,
386    /// Unix milliseconds; `None` while the key is in use.
387    pub revoked_at: Option<u64>,
388}
389
390/// One root signature of a key set v3.
391#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
392pub struct CloudRootSignatureV3 {
393    pub key_id: String,
394    /// hex Ed25519 over `"leanctx.cloud.keyset.v3\n" ‖ canonical_json({schema, keys})`.
395    pub signature: String,
396}
397
398/// Key set v3 as an enrollment of Cloud-Protocol 2.1+ carries it. The
399/// engine verifies `signatures` against its trusted roots; the legacy
400/// single `signature` is for pre-3.12 engines.
401#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
402pub struct CloudKeySetV3 {
403    pub schema: String,
404    pub keys: Vec<CloudKeyV3>,
405    pub signatures: Vec<CloudRootSignatureV3>,
406    pub signature: String,
407}
408
409fn lower_hex(value: &str, len: usize) -> bool {
410    value.len() == len
411        && value
412            .bytes()
413            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
414}
415
416impl CloudKeySetV3 {
417    pub fn validate(&self) -> Result<(), ValidationError> {
418        require_schema(&self.schema, KEYSET_V3_SCHEMA)?;
419        if self.keys.is_empty() || self.keys.len() > 64 {
420            return Err(ValidationError::new("keys must list 1-64 keys"));
421        }
422        let mut seen = std::collections::BTreeSet::new();
423        for key in &self.keys {
424            if !lower_hex(&key.key_id, 16) || !seen.insert(key.key_id.as_str()) {
425                return Err(ValidationError::new(
426                    "key_id must be 16 lowercase hex characters, once per set",
427                ));
428            }
429            if key.public_key.len() != 43
430                || !key
431                    .public_key
432                    .bytes()
433                    .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_'))
434            {
435                return Err(ValidationError::new(
436                    "public_key must be base64url of 32 bytes",
437                ));
438            }
439            let mut purposes = std::collections::BTreeSet::new();
440            if key.purposes.is_empty() || !key.purposes.iter().all(|p| purposes.insert(p)) {
441                return Err(ValidationError::new("purposes must list each purpose once"));
442            }
443            if key.revoked_at.is_some_and(|at| at <= key.created_at) {
444                return Err(ValidationError::new("revoked_at must follow created_at"));
445            }
446        }
447        if self.signatures.is_empty() || self.signatures.len() > 2 {
448            return Err(ValidationError::new(
449                "signatures must list 1-2 root signatures",
450            ));
451        }
452        if !self
453            .signatures
454            .iter()
455            .all(|s| lower_hex(&s.key_id, 16) && lower_hex(&s.signature, 128))
456        {
457            return Err(ValidationError::new(
458                "a root signature is a 16-hex key_id and a 128-hex signature",
459            ));
460        }
461        validate_b64_len(&self.signature, 64, "signature")
462    }
463
464    /// The key that may sign a lease named `kid`: listed with purpose
465    /// [`LEASE_KEY_PURPOSE`].
466    pub fn lease_key(&self, kid: &str) -> Option<&CloudKeyV3> {
467        self.keys
468            .iter()
469            .find(|key| key.key_id == kid && key.purposes.iter().any(|p| p == LEASE_KEY_PURPOSE))
470    }
471}
472
473/// The key set of an enrollment: v1 for an engine below Cloud-Protocol 2.1,
474/// v3 from 2.1 (told apart by `schema`). Either way the lease `kid` names a
475/// key of this set, and the engine verifies the set as it verifies that
476/// version everywhere else.
477#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
478#[serde(untagged)]
479pub enum EnrollmentKeySet {
480    V1(CloudKeySetV1),
481    V3(CloudKeySetV3),
482}
483
484impl<'de> Deserialize<'de> for EnrollmentKeySet {
485    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
486        use serde::de::Error as _;
487        let raw = Value::deserialize(deserializer)?;
488        if raw["schema"] == KEYSET_V3_SCHEMA {
489            serde_json::from_value(raw)
490                .map(Self::V3)
491                .map_err(D::Error::custom)
492        } else {
493            serde_json::from_value(raw)
494                .map(Self::V1)
495                .map_err(D::Error::custom)
496        }
497    }
498}
499
500impl EnrollmentKeySet {
501    pub fn validate(&self) -> Result<(), ValidationError> {
502        match self {
503            Self::V1(set) => set.validate(),
504            Self::V3(set) => set.validate(),
505        }
506    }
507
508    /// Whether the set lists a key that may sign a lease named `kid`.
509    pub fn signs_leases_as(&self, kid: &str) -> bool {
510        match self {
511            Self::V1(set) => set.key(kid).is_some(),
512            Self::V3(set) => set.lease_key(kid).is_some(),
513        }
514    }
515}
516
517#[cfg(test)]
518mod tests {
519    use super::*;
520
521    #[test]
522    fn product_names_are_personal_team_enterprise() {
523        let names: Vec<&str> = [
524            CloudPlan::NoPlan,
525            CloudPlan::Personal,
526            CloudPlan::Team,
527            CloudPlan::Enterprise,
528        ]
529        .into_iter()
530        .map(CloudPlan::product_name)
531        .collect();
532        assert_eq!(names, ["No plan", "Personal", "Team", "Enterprise"]);
533        // the wire name stays
534        assert_eq!(
535            serde_json::to_value(CloudPlan::Enterprise).unwrap(),
536            serde_json::json!("enterprise")
537        );
538    }
539
540    fn lease() -> CloudLeaseV1 {
541        CloudLeaseV1 {
542            schema: LEASE_SCHEMA.into(),
543            lease_id: "lse_1".into(),
544            org_id: "org_1".into(),
545            instance_id: "inst_1".into(),
546            plan: CloudPlan::Team,
547            seats_limit: 25,
548            rights: vec![CloudRight::KnowledgeRead],
549            issued_at: UtcTimestamp::new("2026-10-20T12:00:00Z").unwrap(),
550            expires_at: UtcTimestamp::new("2026-10-21T12:00:00Z").unwrap(),
551            grace_until: UtcTimestamp::new("2026-10-28T12:00:00Z").unwrap(),
552            server_time: UtcTimestamp::new("2026-10-20T12:00:00Z").unwrap(),
553            org_settings: None,
554            trial_ends_at: None,
555        }
556    }
557
558    fn at(value: &str) -> OffsetDateTime {
559        OffsetDateTime::parse_from_rfc3339(value).unwrap()
560    }
561
562    /// Dogfood 25.10.: a personal workspace (plan `none`) showed "unknown
563    /// plan" at connect.
564    #[test]
565    fn plan_wire_ids_are_none_personal_team_enterprise() {
566        let plan = |s: &str| serde_json::from_value::<CloudPlan>(serde_json::json!(s)).unwrap();
567        assert_eq!(plan("none"), CloudPlan::NoPlan);
568        assert_eq!(plan("personal"), CloudPlan::Personal);
569        assert_eq!(plan("none").display_name(), "No plan");
570        assert_eq!(plan("team").display_name(), "Team");
571        assert_eq!(plan("enterprise").display_name(), "Enterprise");
572        // Other ids are not aliases.
573        assert_eq!(plan("pro"), CloudPlan::Unknown);
574        assert_eq!(plan("business"), CloudPlan::Unknown);
575        assert_eq!(plan("community"), CloudPlan::Unknown);
576        assert_eq!(
577            plan("galaxy"),
578            CloudPlan::Unknown,
579            "new plans stay tolerated"
580        );
581        assert_eq!(serde_json::to_value(CloudPlan::NoPlan).unwrap(), "none");
582        assert_eq!(
583            serde_json::to_value(CloudPlan::Personal).unwrap(),
584            "personal"
585        );
586    }
587
588    #[test]
589    fn lease_moves_from_valid_to_grace_to_lapsed() {
590        let lease = lease();
591        assert_eq!(
592            lease.state_at(at("2026-10-21T11:59:59Z")).unwrap(),
593            LeaseState::Valid
594        );
595        assert_eq!(
596            lease.state_at(at("2026-10-21T12:00:00Z")).unwrap(),
597            LeaseState::Grace
598        );
599        assert_eq!(
600            lease.state_at(at("2026-10-28T12:00:00Z")).unwrap(),
601            LeaseState::Lapsed
602        );
603        assert_eq!(
604            lease.state_at(at("2026-10-20T11:44:59Z")).unwrap(),
605            LeaseState::Lapsed
606        );
607        assert!(lease.renew_due(at("2026-10-21T06:00:01Z")).unwrap());
608        assert!(!lease.renew_due(at("2026-10-21T05:59:59Z")).unwrap());
609    }
610
611    #[test]
612    fn lease_windows_are_bounded() {
613        let mut long = lease();
614        long.expires_at = UtcTimestamp::new("2026-10-21T12:00:01Z").unwrap();
615        assert!(long.validate().is_err());
616        let mut grace = lease();
617        grace.grace_until = UtcTimestamp::new("2026-10-28T12:00:01Z").unwrap();
618        assert!(grace.validate().is_err());
619        assert!(lease().validate().is_ok());
620    }
621
622    #[test]
623    fn signature_covers_unknown_lease_fields() {
624        let mut envelope =
625            CloudLeaseEnvelopeV1::seal(&lease(), "k1", "A".repeat(86) + "==").unwrap();
626        let before = envelope.signing_input().unwrap();
627        envelope.lease["future_field"] = Value::from(1);
628        assert_ne!(before, envelope.signing_input().unwrap());
629        assert!(envelope.lease().is_ok());
630    }
631
632    #[test]
633    fn trial_end_rides_the_lease_only_when_set() {
634        let plain = CloudLeaseEnvelopeV1::seal(&lease(), "k1", "A".repeat(86) + "==").unwrap();
635        assert!(plain.lease.get("trial_ends_at").is_none());
636        assert_eq!(plain.lease().unwrap().trial_ends_at, None);
637        let mut trialing = lease();
638        trialing.trial_ends_at = Some("2026-12-02T10:00:00Z".into());
639        let sealed = CloudLeaseEnvelopeV1::seal(&trialing, "k1", "A".repeat(86) + "==").unwrap();
640        assert_eq!(sealed.lease["trial_ends_at"], "2026-12-02T10:00:00Z");
641        assert_eq!(
642            sealed.lease().unwrap().trial_ends_at.as_deref(),
643            Some("2026-12-02T10:00:00Z")
644        );
645        // p37 !134 contract fixture: a trialing lease names its end.
646        let fixture: CloudLeaseEnvelopeV1 = serde_json::from_str(include_str!(
647            "../../tests/fixtures/cloud/lease_envelope.trialing.response.json"
648        ))
649        .unwrap();
650        assert_eq!(
651            fixture.lease().unwrap().trial_ends_at.as_deref(),
652            Some("2026-11-03T12:00:00Z")
653        );
654    }
655
656    #[test]
657    fn unknown_rights_grant_nothing() {
658        let mut lease = lease();
659        lease.rights.push(CloudRight::Unknown);
660        assert!(!lease.grants(CloudRight::Unknown));
661        assert!(lease.grants(CloudRight::KnowledgeRead));
662        assert!(!lease.grants(CloudRight::KnowledgeMerge));
663    }
664}