Skip to main content

lean_ctx_protocol/hive/
lease.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Instance lease and the Hive signing key set.
4//!
5//! - `GET /v1/keys` → [`HiveKeySetV1`], signed by the Hive root key that is
6//!   compiled into the engine (self-host: `[hive] root_key`).
7//! - The lease arrives in enrollment and from `lease/renew` as
8//!   [`HiveLeaseEnvelopeV1`], signed by a key of the key set.
9//! - Hive-Protocol 2.1: an enrollment of a 2.1+ engine carries key set v3
10//!   ([`HiveKeySetV3`], 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 Hive traffic does.
16
17use chrono::{DateTime, Duration, FixedOffset};
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.hive.lease/v1";
28pub const LEASE_ENVELOPE_SCHEMA: &str = "leanctx.hive.lease-envelope/v1";
29pub const KEYSET_SCHEMA: &str = "leanctx.hive.keyset/v1";
30/// Key set v3 (C0 2.x E13), in enrollments of Hive-Protocol 2.1+.
31pub const KEYSET_V3_SCHEMA: &str = "leanctx.hive.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 HivePlan {
48    /// A workspace without a paid plan: Hive sends `none`.
49    #[serde(rename = "none")]
50    NoPlan,
51    Personal,
52    Team,
53    Enterprise,
54    #[serde(other)]
55    Unknown,
56}
57
58impl HivePlan {
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 HiveRight {
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 (a person approves them).
115    #[serde(rename = "tasks.propose")]
116    TasksPropose,
117    #[serde(other)]
118    Unknown,
119}
120
121/// The signed lease statement.
122#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
123pub struct HiveLeaseV1 {
124    pub schema: String,
125    pub lease_id: String,
126    pub org_id: String,
127    pub instance_id: String,
128    pub plan: HivePlan,
129    /// The organization's limit of engine instances (Personal 2,
130    /// Team 2 per seat, Enterprise 3 per seat and at least 25); the wire
131    /// name is frozen in v1.
132    pub seats_limit: u32,
133    pub rights: Vec<HiveRight>,
134    pub issued_at: UtcTimestamp,
135    pub expires_at: UtcTimestamp,
136    pub grace_until: UtcTimestamp,
137    /// Service clock at signing; the engine keeps `server_time - local_now` as offset.
138    pub server_time: UtcTimestamp,
139    /// 1.4: what the organization allows its engines to upload. Absent
140    /// (an older service) allows both.
141    #[serde(default, skip_serializing_if = "Option::is_none")]
142    pub org_settings: Option<HiveOrgSettingsV1>,
143}
144
145/// Organization-wide switches the lease carries (1.4). They only narrow:
146/// an engine uploads only what both its own `[hive]` setting and these
147/// allow, and receipts still need the `receipts.upload` right.
148#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
149pub struct HiveOrgSettingsV1 {
150    #[serde(default = "allowed")]
151    pub metrics_upload: bool,
152    #[serde(default = "allowed")]
153    pub receipts_upload: bool,
154}
155
156const fn allowed() -> bool {
157    true
158}
159
160/// Where a lease stands at a given (offset-corrected) time.
161#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
162#[serde(rename_all = "snake_case")]
163pub enum LeaseState {
164    Valid,
165    Grace,
166    Lapsed,
167}
168
169impl HiveLeaseV1 {
170    pub fn validate(&self) -> Result<(), ValidationError> {
171        require_schema(&self.schema, LEASE_SCHEMA)?;
172        validate_id(&self.lease_id, "lease_id")?;
173        validate_id(&self.org_id, "org_id")?;
174        validate_id(&self.instance_id, "instance_id")?;
175        if self.seats_limit == 0 {
176            return Err(ValidationError::new("seats_limit must be positive"));
177        }
178        if self.rights.len() > 64 {
179            return Err(ValidationError::new("lease lists are too long"));
180        }
181        let issued = parse_time(&self.issued_at)?;
182        let expires = parse_time(&self.expires_at)?;
183        let grace = parse_time(&self.grace_until)?;
184        parse_time(&self.server_time)?;
185        if expires <= issued || expires - issued > Duration::hours(MAX_LEASE_VALIDITY_HOURS) {
186            return Err(ValidationError::new(
187                "expires_at must be after issued_at and at most 24 h later",
188            ));
189        }
190        if grace < expires || grace - expires > Duration::days(MAX_LEASE_GRACE_DAYS) {
191            return Err(ValidationError::new(
192                "grace_until must be within 7 days after expires_at",
193            ));
194        }
195        Ok(())
196    }
197
198    /// Whether the lease grants `right`.
199    pub fn grants(&self, right: HiveRight) -> bool {
200        right != HiveRight::Unknown && self.rights.contains(&right)
201    }
202
203    /// Whether the organization allows metrics uploads (absent settings allow).
204    pub fn org_allows_metrics_upload(&self) -> bool {
205        self.org_settings
206            .is_none_or(|settings| settings.metrics_upload)
207    }
208
209    /// Whether the organization allows receipt uploads (absent settings allow).
210    pub fn org_allows_receipts_upload(&self) -> bool {
211        self.org_settings
212            .is_none_or(|settings| settings.receipts_upload)
213    }
214
215    /// State at `now` (service time: local clock plus the stored offset).
216    /// A lease issued more than 15 minutes after `now` counts as `Lapsed`.
217    pub fn state_at(&self, now: DateTime<FixedOffset>) -> Result<LeaseState, ValidationError> {
218        let issued = parse_time(&self.issued_at)?;
219        if issued - now > Duration::minutes(MAX_LEASE_FUTURE_SKEW_MINUTES) {
220            return Ok(LeaseState::Lapsed);
221        }
222        Ok(if now < parse_time(&self.expires_at)? {
223            LeaseState::Valid
224        } else if now < parse_time(&self.grace_until)? {
225            LeaseState::Grace
226        } else {
227            LeaseState::Lapsed
228        })
229    }
230
231    /// Whether the engine should renew now.
232    pub fn renew_due(&self, now: DateTime<FixedOffset>) -> Result<bool, ValidationError> {
233        Ok(parse_time(&self.expires_at)? - now < Duration::hours(LEASE_RENEW_BEFORE_HOURS))
234    }
235}
236
237/// Lease as it travels: the raw lease object plus its signature.
238///
239/// `lease` stays raw JSON so the signature covers exactly what the service
240/// signed, including fields this engine does not know.
241#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
242pub struct HiveLeaseEnvelopeV1 {
243    pub schema: String,
244    pub lease: Value,
245    /// Key id within [`HiveKeySetV1`].
246    pub kid: String,
247    /// Ed25519 signature (base64) over [`HiveLeaseEnvelopeV1::signing_input`].
248    pub signature: String,
249}
250
251impl HiveLeaseEnvelopeV1 {
252    /// Envelope fields only; call [`Self::lease`] after verifying the signature.
253    pub fn validate_shape(&self) -> Result<(), ValidationError> {
254        require_schema(&self.schema, LEASE_ENVELOPE_SCHEMA)?;
255        validate_id(&self.kid, "kid")?;
256        validate_b64_len(&self.signature, 64, "signature")?;
257        if !self.lease.is_object() {
258            return Err(ValidationError::new("lease must be a JSON object"));
259        }
260        Ok(())
261    }
262
263    /// `"leanctx.hive.lease.v1\n" || canonical_json(lease)`.
264    pub fn signing_input(&self) -> Result<Vec<u8>, ValidationError> {
265        signing_input(LEASE_SIGNATURE_DOMAIN, &self.lease)
266    }
267
268    /// Signing input for a lease the service is about to sign.
269    pub fn signing_input_for(lease: &HiveLeaseV1) -> Result<Vec<u8>, ValidationError> {
270        lease.validate()?;
271        signing_input(LEASE_SIGNATURE_DOMAIN, &lease_value(lease)?)
272    }
273
274    /// Build the envelope for a signed lease.
275    pub fn seal(
276        lease: &HiveLeaseV1,
277        kid: impl Into<String>,
278        signature: impl Into<String>,
279    ) -> Result<Self, ValidationError> {
280        lease.validate()?;
281        let envelope = Self {
282            schema: LEASE_ENVELOPE_SCHEMA.into(),
283            lease: lease_value(lease)?,
284            kid: kid.into(),
285            signature: signature.into(),
286        };
287        envelope.validate_shape()?;
288        Ok(envelope)
289    }
290
291    /// The typed, validated lease.
292    pub fn lease(&self) -> Result<HiveLeaseV1, ValidationError> {
293        let lease: HiveLeaseV1 = serde_json::from_value(self.lease.clone())
294            .map_err(|error| ValidationError::new(format!("lease: {error}")))?;
295        lease.validate()?;
296        Ok(lease)
297    }
298}
299
300fn lease_value(lease: &HiveLeaseV1) -> Result<Value, ValidationError> {
301    serde_json::to_value(lease).map_err(|error| ValidationError::new(format!("lease: {error}")))
302}
303
304/// One Hive signing key.
305#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
306pub struct HiveKeyV1 {
307    pub kid: String,
308    /// Ed25519 public key, 32 bytes base64.
309    pub ed25519_pub: String,
310    /// The key signs nothing after this time; signatures made before stay valid
311    /// until the signed object itself expires.
312    pub not_after: UtcTimestamp,
313}
314
315/// `GET /v1/keys`. The signature covers the object without `signature`.
316/// Engines keep the raw JSON (`keys.json`) and verify it with
317/// [`HiveKeySetV1::signing_input_raw`].
318#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
319pub struct HiveKeySetV1 {
320    pub schema: String,
321    pub keys: Vec<HiveKeyV1>,
322    /// Ed25519 signature (base64) of the Hive root key.
323    pub signature: String,
324}
325
326impl HiveKeySetV1 {
327    pub fn validate(&self) -> Result<(), ValidationError> {
328        require_schema(&self.schema, KEYSET_SCHEMA)?;
329        if self.keys.is_empty() || self.keys.len() > 16 {
330            return Err(ValidationError::new("keys must list 1-16 keys"));
331        }
332        let mut seen = std::collections::BTreeSet::new();
333        for key in &self.keys {
334            validate_id(&key.kid, "kid")?;
335            validate_b64_len(&key.ed25519_pub, 32, "ed25519_pub")?;
336            parse_time(&key.not_after)?;
337            if !seen.insert(key.kid.as_str()) {
338                return Err(ValidationError::new("kid repeats in key set"));
339            }
340        }
341        validate_b64_len(&self.signature, 64, "signature")
342    }
343
344    /// Signing input of a key set as received.
345    pub fn signing_input_raw(raw: &Value) -> Result<Vec<u8>, ValidationError> {
346        signing_input_without_signature(KEYSET_SIGNATURE_DOMAIN, raw)
347    }
348
349    /// Signing input of a key set the service is about to sign (`signature` ignored).
350    pub fn signing_input(&self) -> Result<Vec<u8>, ValidationError> {
351        let value = serde_json::to_value(self)
352            .map_err(|error| ValidationError::new(format!("keyset: {error}")))?;
353        Self::signing_input_raw(&value)
354    }
355
356    /// Key `kid`, if listed.
357    pub fn key(&self, kid: &str) -> Option<&HiveKeyV1> {
358        self.keys.iter().find(|key| key.kid == kid)
359    }
360}
361
362/// One key of a key set v3. Purposes stay strings here: the set's root
363/// signature covers them, and the engine checks each use against them.
364#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
365pub struct HiveKeyV3 {
366    /// `hex(blake3(public key))[..16]`.
367    pub key_id: String,
368    /// base64url (no padding) of the raw 32-byte Ed25519 key.
369    pub public_key: String,
370    pub purposes: Vec<String>,
371    /// Unix milliseconds.
372    pub created_at: u64,
373    /// Unix milliseconds; `None` while the key is in use.
374    pub revoked_at: Option<u64>,
375}
376
377/// One root signature of a key set v3.
378#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
379pub struct HiveRootSignatureV3 {
380    pub key_id: String,
381    /// hex Ed25519 over `"leanctx.hive.keyset.v3\n" ‖ canonical_json({schema, keys})`.
382    pub signature: String,
383}
384
385/// Key set v3 as an enrollment of Hive-Protocol 2.1+ carries it. The
386/// engine verifies `signatures` against its trusted roots; the legacy
387/// single `signature` is for pre-3.12 engines.
388#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
389pub struct HiveKeySetV3 {
390    pub schema: String,
391    pub keys: Vec<HiveKeyV3>,
392    pub signatures: Vec<HiveRootSignatureV3>,
393    pub signature: String,
394}
395
396fn lower_hex(value: &str, len: usize) -> bool {
397    value.len() == len
398        && value
399            .bytes()
400            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
401}
402
403impl HiveKeySetV3 {
404    pub fn validate(&self) -> Result<(), ValidationError> {
405        require_schema(&self.schema, KEYSET_V3_SCHEMA)?;
406        if self.keys.is_empty() || self.keys.len() > 64 {
407            return Err(ValidationError::new("keys must list 1-64 keys"));
408        }
409        let mut seen = std::collections::BTreeSet::new();
410        for key in &self.keys {
411            if !lower_hex(&key.key_id, 16) || !seen.insert(key.key_id.as_str()) {
412                return Err(ValidationError::new(
413                    "key_id must be 16 lowercase hex characters, once per set",
414                ));
415            }
416            if key.public_key.len() != 43
417                || !key
418                    .public_key
419                    .bytes()
420                    .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_'))
421            {
422                return Err(ValidationError::new(
423                    "public_key must be base64url of 32 bytes",
424                ));
425            }
426            let mut purposes = std::collections::BTreeSet::new();
427            if key.purposes.is_empty() || !key.purposes.iter().all(|p| purposes.insert(p)) {
428                return Err(ValidationError::new("purposes must list each purpose once"));
429            }
430            if key.revoked_at.is_some_and(|at| at <= key.created_at) {
431                return Err(ValidationError::new("revoked_at must follow created_at"));
432            }
433        }
434        if self.signatures.is_empty() || self.signatures.len() > 2 {
435            return Err(ValidationError::new(
436                "signatures must list 1-2 root signatures",
437            ));
438        }
439        if !self
440            .signatures
441            .iter()
442            .all(|s| lower_hex(&s.key_id, 16) && lower_hex(&s.signature, 128))
443        {
444            return Err(ValidationError::new(
445                "a root signature is a 16-hex key_id and a 128-hex signature",
446            ));
447        }
448        validate_b64_len(&self.signature, 64, "signature")
449    }
450
451    /// The key that may sign a lease named `kid`: listed with purpose
452    /// [`LEASE_KEY_PURPOSE`].
453    pub fn lease_key(&self, kid: &str) -> Option<&HiveKeyV3> {
454        self.keys
455            .iter()
456            .find(|key| key.key_id == kid && key.purposes.iter().any(|p| p == LEASE_KEY_PURPOSE))
457    }
458}
459
460/// The key set of an enrollment: v1 for an engine below Hive-Protocol 2.1,
461/// v3 from 2.1 (told apart by `schema`). Either way the lease `kid` names a
462/// key of this set, and the engine verifies the set as it verifies that
463/// version everywhere else.
464#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
465#[serde(untagged)]
466pub enum EnrollmentKeySet {
467    V1(HiveKeySetV1),
468    V3(HiveKeySetV3),
469}
470
471impl<'de> Deserialize<'de> for EnrollmentKeySet {
472    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
473        use serde::de::Error as _;
474        let raw = Value::deserialize(deserializer)?;
475        if raw["schema"] == KEYSET_V3_SCHEMA {
476            serde_json::from_value(raw)
477                .map(Self::V3)
478                .map_err(D::Error::custom)
479        } else {
480            serde_json::from_value(raw)
481                .map(Self::V1)
482                .map_err(D::Error::custom)
483        }
484    }
485}
486
487impl EnrollmentKeySet {
488    pub fn validate(&self) -> Result<(), ValidationError> {
489        match self {
490            Self::V1(set) => set.validate(),
491            Self::V3(set) => set.validate(),
492        }
493    }
494
495    /// Whether the set lists a key that may sign a lease named `kid`.
496    pub fn signs_leases_as(&self, kid: &str) -> bool {
497        match self {
498            Self::V1(set) => set.key(kid).is_some(),
499            Self::V3(set) => set.lease_key(kid).is_some(),
500        }
501    }
502}
503
504#[cfg(test)]
505mod tests {
506    use super::*;
507
508    #[test]
509    fn product_names_are_personal_team_enterprise() {
510        let names: Vec<&str> = [
511            HivePlan::NoPlan,
512            HivePlan::Personal,
513            HivePlan::Team,
514            HivePlan::Enterprise,
515        ]
516        .into_iter()
517        .map(HivePlan::product_name)
518        .collect();
519        assert_eq!(names, ["No plan", "Personal", "Team", "Enterprise"]);
520        // the wire name stays
521        assert_eq!(
522            serde_json::to_value(HivePlan::Enterprise).unwrap(),
523            serde_json::json!("enterprise")
524        );
525    }
526
527    fn lease() -> HiveLeaseV1 {
528        HiveLeaseV1 {
529            schema: LEASE_SCHEMA.into(),
530            lease_id: "lse_1".into(),
531            org_id: "org_1".into(),
532            instance_id: "inst_1".into(),
533            plan: HivePlan::Team,
534            seats_limit: 25,
535            rights: vec![HiveRight::KnowledgeRead],
536            issued_at: UtcTimestamp::new("2026-10-20T12:00:00Z").unwrap(),
537            expires_at: UtcTimestamp::new("2026-10-21T12:00:00Z").unwrap(),
538            grace_until: UtcTimestamp::new("2026-10-28T12:00:00Z").unwrap(),
539            server_time: UtcTimestamp::new("2026-10-20T12:00:00Z").unwrap(),
540            org_settings: None,
541        }
542    }
543
544    fn at(value: &str) -> DateTime<FixedOffset> {
545        DateTime::parse_from_rfc3339(value).unwrap()
546    }
547
548    /// Dogfood 25.10.: a personal workspace (plan `none`) showed "unknown
549    /// plan" at connect.
550    #[test]
551    fn plan_wire_ids_are_none_personal_team_enterprise() {
552        let plan = |s: &str| serde_json::from_value::<HivePlan>(serde_json::json!(s)).unwrap();
553        assert_eq!(plan("none"), HivePlan::NoPlan);
554        assert_eq!(plan("personal"), HivePlan::Personal);
555        assert_eq!(plan("none").display_name(), "No plan");
556        assert_eq!(plan("team").display_name(), "Team");
557        assert_eq!(plan("enterprise").display_name(), "Enterprise");
558        // Other ids are not aliases.
559        assert_eq!(plan("pro"), HivePlan::Unknown);
560        assert_eq!(plan("business"), HivePlan::Unknown);
561        assert_eq!(plan("community"), HivePlan::Unknown);
562        assert_eq!(
563            plan("galaxy"),
564            HivePlan::Unknown,
565            "new plans stay tolerated"
566        );
567        assert_eq!(serde_json::to_value(HivePlan::NoPlan).unwrap(), "none");
568        assert_eq!(
569            serde_json::to_value(HivePlan::Personal).unwrap(),
570            "personal"
571        );
572    }
573
574    #[test]
575    fn lease_moves_from_valid_to_grace_to_lapsed() {
576        let lease = lease();
577        assert_eq!(
578            lease.state_at(at("2026-10-21T11:59:59Z")).unwrap(),
579            LeaseState::Valid
580        );
581        assert_eq!(
582            lease.state_at(at("2026-10-21T12:00:00Z")).unwrap(),
583            LeaseState::Grace
584        );
585        assert_eq!(
586            lease.state_at(at("2026-10-28T12:00:00Z")).unwrap(),
587            LeaseState::Lapsed
588        );
589        assert_eq!(
590            lease.state_at(at("2026-10-20T11:44:59Z")).unwrap(),
591            LeaseState::Lapsed
592        );
593        assert!(lease.renew_due(at("2026-10-21T06:00:01Z")).unwrap());
594        assert!(!lease.renew_due(at("2026-10-21T05:59:59Z")).unwrap());
595    }
596
597    #[test]
598    fn lease_windows_are_bounded() {
599        let mut long = lease();
600        long.expires_at = UtcTimestamp::new("2026-10-21T12:00:01Z").unwrap();
601        assert!(long.validate().is_err());
602        let mut grace = lease();
603        grace.grace_until = UtcTimestamp::new("2026-10-28T12:00:01Z").unwrap();
604        assert!(grace.validate().is_err());
605        assert!(lease().validate().is_ok());
606    }
607
608    #[test]
609    fn signature_covers_unknown_lease_fields() {
610        let mut envelope =
611            HiveLeaseEnvelopeV1::seal(&lease(), "k1", "A".repeat(86) + "==").unwrap();
612        let before = envelope.signing_input().unwrap();
613        envelope.lease["future_field"] = Value::from(1);
614        assert_ne!(before, envelope.signing_input().unwrap());
615        assert!(envelope.lease().is_ok());
616    }
617
618    #[test]
619    fn unknown_rights_grant_nothing() {
620        let mut lease = lease();
621        lease.rights.push(HiveRight::Unknown);
622        assert!(!lease.grants(HiveRight::Unknown));
623        assert!(lease.grants(HiveRight::KnowledgeRead));
624        assert!(!lease.grants(HiveRight::KnowledgeMerge));
625    }
626}