Skip to main content

khive_capability/durable/
envelope.rs

1use super::codec::{decode, encode, encoded_len};
2use super::keys::KeyRef;
3use super::permission::*;
4use super::{
5    bound, nonempty, ClosedCatalog, EnvelopeError, EnvelopeResult, SuppliedKeys, ALIAS_END,
6    ALIAS_START, CARRIER_VERSION, MAX_RECORD_BYTES,
7};
8use hmac::{Hmac, Mac};
9use khive_types::Timestamp;
10use lion_core::{Capability, Kernel, Rights, SealedTag, SecurityLevel};
11use sha2::Sha256;
12use uuid::Uuid;
13
14pub(super) const MAGIC: &[u8; 6] = b"KHAE\0\x01";
15pub(super) const DOMAIN: &[u8] = b"khive.authority.grant-envelope\0";
16const OUTPUT_END: u128 = 1_u128 << 126;
17const PRIVATE_ANCHOR: u128 = u128::MAX - 1;
18const RECORD_OVERHEAD: usize = 6 + 4 + 32;
19
20#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
21pub enum IssuanceAssurance {
22    ConfiguredLocal,
23}
24#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
25pub enum CreationOperation {
26    Grant,
27    Import,
28}
29
30#[derive(Clone, Debug, PartialEq, Eq)]
31pub struct EnvelopeDraft {
32    pub id: Uuid,
33    pub store_id: Uuid,
34    pub epoch_id: Uuid,
35    pub root_anchor_id: Uuid,
36    pub issuer: Principal,
37    pub grantee: Principal,
38    pub namespace: String,
39    pub rights: Vec<RightSpec>,
40    pub validity: Validity,
41    pub created_at: Timestamp,
42    pub assurance: IssuanceAssurance,
43    pub operation: CreationOperation,
44    pub action_id: Uuid,
45    pub configuration_source: Option<String>,
46    pub issuance_id: Uuid,
47    pub key: KeyRef,
48}
49#[derive(Clone, Debug, PartialEq, Eq)]
50pub struct NativeCapability {
51    pub id: u128,
52    pub holder: u128,
53    pub target: u128,
54    pub rights: u16,
55    pub parent: Option<u128>,
56    pub epoch: u64,
57    pub signature: [u8; 32],
58}
59impl NativeCapability {
60    fn from_core(cap: &Capability) -> Self {
61        let mut signature = [0; 32];
62        signature.copy_from_slice(cap.signature().as_bytes());
63        Self {
64            id: cap.id(),
65            holder: cap.holder(),
66            target: cap.target(),
67            rights: cap.rights().to_bits(),
68            parent: cap.parent(),
69            epoch: cap.epoch(),
70            signature,
71        }
72    }
73    fn to_core(&self, id: u128) -> EnvelopeResult<Capability> {
74        if self.parent == Some(u128::MAX) || self.rights & !Rights::all().to_bits() != 0 {
75            return Err(EnvelopeError::Reject(
76                "invalid native parent or rights bits",
77            ));
78        }
79        Capability::new(
80            id,
81            self.holder,
82            self.target,
83            Rights::from_bits(self.rights),
84            self.parent,
85            self.epoch,
86            SealedTag::from_bytes(self.signature),
87        )
88        .map_err(|_| EnvelopeError::Reject("invalid native capability"))
89    }
90    pub fn canonical_digest(&self) -> EnvelopeResult<ContractDigest> {
91        Ok(ContractDigest::blake3(&encode(self)?))
92    }
93}
94#[derive(Clone, Debug, PartialEq, Eq)]
95pub enum ParentBinding {
96    Grant {
97        grant_id: Uuid,
98        issuance_id: Uuid,
99        original_local_id: u128,
100        alias_id: u128,
101        native_digest: ContractDigest,
102    },
103    BootstrapSlot {
104        slot: String,
105        manifest_digest: ContractDigest,
106        anchor_local_id: u128,
107    },
108}
109#[derive(Clone, Debug, PartialEq, Eq)]
110pub struct IssuanceContext {
111    pub id: Uuid,
112    pub holder: u128,
113    pub holder_principal: Principal,
114    pub target: u128,
115    pub namespace: String,
116}
117#[derive(Clone, Debug, PartialEq, Eq)]
118pub struct GrantBody {
119    pub schema_version: u16,
120    pub profile_version: u16,
121    pub carrier_version: u16,
122    pub grant: EnvelopeDraft,
123    pub parent: ParentBinding,
124    pub context: IssuanceContext,
125    pub native: NativeCapability,
126}
127
128/// A cryptographically authenticated immutable record, not effective authority.
129/// The store's current terminal state, full UUID ancestry and root anchor still
130/// have to be checked in the transaction that commits a protected operation.
131#[derive(Clone, Debug, PartialEq, Eq)]
132pub struct AuthenticatedEnvelope {
133    body: GrantBody,
134    bytes: Vec<u8>,
135}
136impl AuthenticatedEnvelope {
137    pub fn body(&self) -> &GrantBody {
138        &self.body
139    }
140    pub fn as_bytes(&self) -> &[u8] {
141        &self.bytes
142    }
143}
144
145/// Finite composition-root source; this is not a persisted unsealed capability.
146/// The service may use it only after checking its immutable initialized manifest
147/// and live epoch/root anchor in its active writer transaction.
148#[derive(Clone, Debug)]
149pub struct BootstrapSource {
150    pub store_id: Uuid,
151    pub epoch_id: Uuid,
152    pub root_anchor_id: Uuid,
153    pub owner: Principal,
154    pub namespace: String,
155    pub slot: String,
156    pub manifest_digest: ContractDigest,
157    pub rights: Vec<RightSpec>,
158    pub validity: Validity,
159}
160
161pub struct EnvelopeVerifier<'a> {
162    keys: &'a SuppliedKeys,
163    catalog: &'a ClosedCatalog,
164}
165impl<'a> EnvelopeVerifier<'a> {
166    pub fn new(keys: &'a SuppliedKeys, catalog: &'a ClosedCatalog) -> Self {
167        Self { keys, catalog }
168    }
169    pub fn verify(
170        &self,
171        bytes: &[u8],
172        store_id: Uuid,
173        epoch_id: Uuid,
174    ) -> EnvelopeResult<AuthenticatedEnvelope> {
175        bound("canonical record", bytes.len(), MAX_RECORD_BYTES)?;
176        if bytes.len() < RECORD_OVERHEAD || bytes.get(..6) != Some(MAGIC.as_slice()) {
177            return Err(EnvelopeError::Reject("unknown envelope header"));
178        }
179        let length = u32::from_be_bytes(
180            bytes[6..10]
181                .try_into()
182                .map_err(|_| EnvelopeError::Reject("invalid envelope length"))?,
183        ) as usize;
184        if length.checked_add(RECORD_OVERHEAD) != Some(bytes.len()) {
185            return Err(EnvelopeError::Reject(
186                "record length or trailing bytes mismatch",
187            ));
188        }
189        let encoded = &bytes[10..10 + length];
190        let body: GrantBody = decode(encoded)?;
191        let mac = envelope_mac(self.keys.extension(&body.grant.key)?, encoded)?;
192        mac.verify_slice(&bytes[10 + length..])
193            .map_err(|_| EnvelopeError::Reject("extension MAC mismatch"))?;
194        self.validate_body(&body, store_id, epoch_id)?;
195        let native = body.native.to_core(body.native.id)?;
196        let kernel = Kernel::with_key(self.keys.native(&body.grant.key)?)
197            .map_err(|_| EnvelopeError::Unavailable("native key unavailable"))?;
198        if !kernel.state().kernel().verify_cap_seal(&native) {
199            return Err(EnvelopeError::Reject("native seal mismatch"));
200        }
201        Ok(AuthenticatedEnvelope {
202            body,
203            bytes: bytes.to_vec(),
204        })
205    }
206
207    /// Verify one immutable UUID lineage link. This does not check live DB state.
208    pub fn verify_delegation_link(
209        &self,
210        child: &AuthenticatedEnvelope,
211        parent: &AuthenticatedEnvelope,
212    ) -> EnvelopeResult<()> {
213        let c = self.verify(
214            child.as_bytes(),
215            child.body.grant.store_id,
216            child.body.grant.epoch_id,
217        )?;
218        let p = self.verify(
219            parent.as_bytes(),
220            c.body.grant.store_id,
221            c.body.grant.epoch_id,
222        )?;
223        let ParentBinding::Grant {
224            grant_id,
225            issuance_id,
226            original_local_id,
227            alias_id,
228            native_digest,
229        } = &c.body.parent
230        else {
231            return Err(EnvelopeError::Reject("child does not name a grant parent"));
232        };
233        if *grant_id != p.body.grant.id
234            || *issuance_id != p.body.grant.issuance_id
235            || *original_local_id != p.body.native.id
236            || *native_digest != p.body.native.canonical_digest()?
237            || c.body.native.parent != Some(*alias_id)
238            || c.body.native.target != p.body.native.target
239        {
240            return Err(EnvelopeError::Reject(
241                "authenticated parent alias does not match durable parent",
242            ));
243        }
244        self.check_parent_scope(&p.body.grant, &c.body.grant)
245    }
246    fn check_parent_scope(
247        &self,
248        parent: &EnvelopeDraft,
249        child: &EnvelopeDraft,
250    ) -> EnvelopeResult<()> {
251        if parent.id == child.id
252            || parent.issuance_id == child.issuance_id
253            || parent.store_id != child.store_id
254            || parent.epoch_id != child.epoch_id
255            || parent.root_anchor_id != child.root_anchor_id
256            || parent.namespace != child.namespace
257            || parent.grantee != child.issuer
258            || !parent.validity.covers(&child.validity)
259            || !self.catalog.covers_rights(&parent.rights, &child.rights)
260        {
261            return Err(EnvelopeError::Reject(
262                "parent holder, scope or interval does not cover child",
263            ));
264        }
265        Ok(())
266    }
267    fn validate_body(&self, body: &GrantBody, store: Uuid, epoch: Uuid) -> EnvelopeResult<()> {
268        if body.schema_version != 1
269            || body.profile_version != 1
270            || body.carrier_version != CARRIER_VERSION
271        {
272            return Err(EnvelopeError::Reject(
273                "unsupported envelope or carrier version",
274            ));
275        }
276        validate_draft(self.catalog, &body.grant)?;
277        if body.grant.store_id != store
278            || body.grant.epoch_id != epoch
279            || body.grant.id == body.grant.root_anchor_id
280        {
281            return Err(EnvelopeError::Reject(
282                "store, epoch or record role mismatch",
283            ));
284        }
285        let carriers = self.catalog.validate_rights(
286            &body.grant.rights,
287            &body.grant.namespace,
288            &body.grant.grantee,
289        )?;
290        if body.native.epoch != 0
291            || body.native.id >= OUTPUT_END
292            || body.native.rights != carriers.to_bits()
293            || body.native.holder != 1
294            || body.native.target != 1
295            || body.context.id != body.grant.issuance_id
296            || body.context.holder != body.native.holder
297            || body.context.target != body.native.target
298            || body.context.holder_principal != body.grant.grantee
299            || body.context.namespace != body.grant.namespace
300        {
301            return Err(EnvelopeError::Reject(
302                "native capability or local interpretation mismatch",
303            ));
304        }
305        match &body.parent {
306            ParentBinding::Grant {
307                grant_id,
308                issuance_id,
309                original_local_id,
310                alias_id,
311                ..
312            } => {
313                check_alias(*alias_id)?;
314                if *grant_id == body.grant.id
315                    || *issuance_id == body.grant.issuance_id
316                    || *original_local_id >= OUTPUT_END
317                    || body.native.parent != Some(*alias_id)
318                {
319                    return Err(EnvelopeError::Reject("invalid durable parent binding"));
320                }
321            }
322            ParentBinding::BootstrapSlot {
323                slot,
324                anchor_local_id,
325                ..
326            } => {
327                nonempty(slot)?;
328                if !(ALIAS_END..u128::MAX).contains(anchor_local_id)
329                    || body.native.parent != Some(*anchor_local_id)
330                {
331                    return Err(EnvelopeError::Reject(
332                        "invalid private bootstrap parent binding",
333                    ));
334                }
335            }
336        }
337        Ok(())
338    }
339}
340
341/// Trusted issuance helper, not a caller-facing authorization decision.
342/// The service must validate live durable ancestry, current administration and
343/// its configured policy inside its writer before calling this helper. The
344/// helper enforces cryptography, structural holder and immutable attenuation;
345/// each private scratch Kernel is discarded before returning.
346pub struct EnvelopeIssuer<'a> {
347    verifier: EnvelopeVerifier<'a>,
348}
349impl<'a> EnvelopeIssuer<'a> {
350    pub fn new(keys: &'a SuppliedKeys, catalog: &'a ClosedCatalog) -> Self {
351        Self {
352            verifier: EnvelopeVerifier::new(keys, catalog),
353        }
354    }
355    pub fn issue_from_bootstrap(
356        &self,
357        source: &BootstrapSource,
358        grant: EnvelopeDraft,
359    ) -> EnvelopeResult<AuthenticatedEnvelope> {
360        bound("unsigned grant", encoded_len(&grant)?, MAX_RECORD_BYTES)?;
361        validate_draft(self.verifier.catalog, &grant)?;
362        source.owner.validate()?;
363        source.validity.validate()?;
364        nonempty(&source.slot)?;
365        let source_carriers = self.verifier.catalog.validate_source_rights(
366            &source.rights,
367            &source.namespace,
368            &source.owner,
369        )?;
370        if source.owner.leg.is_some()
371            || source.owner != grant.issuer
372            || source.store_id != grant.store_id
373            || source.epoch_id != grant.epoch_id
374            || source.root_anchor_id != grant.root_anchor_id
375            || source.namespace != grant.namespace
376            || !source.validity.covers(&grant.validity)
377            || !self
378                .verifier
379                .catalog
380                .covers_rights(&source.rights, &grant.rights)
381        {
382            return Err(EnvelopeError::Reject(
383                "bootstrap source does not cover issued record",
384            ));
385        }
386        let parent = ParentBinding::BootstrapSlot {
387            slot: source.slot.clone(),
388            manifest_digest: source.manifest_digest,
389            anchor_local_id: PRIVATE_ANCHOR,
390        };
391        let mut kernel = self.kernel(&grant)?;
392        let anchor = Capability::new(
393            PRIVATE_ANCHOR,
394            1,
395            1,
396            source_carriers,
397            None,
398            0,
399            SealedTag::from_bytes([0; 32]),
400        )
401        .map_err(|e| EnvelopeError::Native(e.to_string()))?;
402        kernel
403            .insert_cap_raw(anchor, 1)
404            .map_err(|e| EnvelopeError::Native(e.to_string()))?;
405        self.delegate_and_seal(kernel, PRIVATE_ANCHOR, grant, parent)
406    }
407    pub fn delegate(
408        &self,
409        parent: &AuthenticatedEnvelope,
410        grant: EnvelopeDraft,
411    ) -> EnvelopeResult<AuthenticatedEnvelope> {
412        bound("unsigned grant", encoded_len(&grant)?, MAX_RECORD_BYTES)?;
413        validate_draft(self.verifier.catalog, &grant)?;
414        let alias = issuance_alias(grant.issuance_id);
415        check_alias(alias)?;
416        let parent = self
417            .verifier
418            .verify(parent.as_bytes(), grant.store_id, grant.epoch_id)?;
419        self.verifier
420            .check_parent_scope(&parent.body.grant, &grant)?;
421        let binding = ParentBinding::Grant {
422            grant_id: parent.body.grant.id,
423            issuance_id: parent.body.grant.issuance_id,
424            original_local_id: parent.body.native.id,
425            alias_id: alias,
426            native_digest: parent.body.native.canonical_digest()?,
427        };
428        let mut kernel = self.kernel(&grant)?;
429        let reconstructed = parent.body.native.to_core(alias)?;
430        kernel
431            .insert_cap_raw(reconstructed, parent.body.native.holder)
432            .map_err(|e| EnvelopeError::Native(e.to_string()))?;
433        let child = self.delegate_and_seal(kernel, alias, grant, binding)?;
434        self.verifier.verify_delegation_link(&child, &parent)?;
435        Ok(child)
436    }
437    fn kernel(&self, grant: &EnvelopeDraft) -> EnvelopeResult<Kernel> {
438        let mut kernel = Kernel::with_key(self.verifier.keys.native(&grant.key)?)
439            .map_err(|_| EnvelopeError::Unavailable("native key unavailable"))?;
440        kernel
441            .register_plugin(1, SecurityLevel::BOT, 0)
442            .map_err(|e| EnvelopeError::Native(e.to_string()))?;
443        Ok(kernel)
444    }
445    fn delegate_and_seal(
446        &self,
447        mut kernel: Kernel,
448        parent_id: u128,
449        grant: EnvelopeDraft,
450        parent: ParentBinding,
451    ) -> EnvelopeResult<AuthenticatedEnvelope> {
452        check_output_capacity(kernel.state().kernel().next_cap_id())?;
453        let rights = self.verifier.catalog.validate_rights(
454            &grant.rights,
455            &grant.namespace,
456            &grant.grantee,
457        )?;
458        // The same shape is sized before minting; native ids/signatures have fixed width.
459        let mut body = GrantBody {
460            schema_version: 1,
461            profile_version: 1,
462            carrier_version: CARRIER_VERSION,
463            context: IssuanceContext {
464                id: grant.issuance_id,
465                holder: 1,
466                holder_principal: grant.grantee.clone(),
467                target: 1,
468                namespace: grant.namespace.clone(),
469            },
470            grant,
471            parent,
472            native: NativeCapability {
473                id: 0,
474                holder: 1,
475                target: 1,
476                rights: rights.to_bits(),
477                parent: Some(parent_id),
478                epoch: 0,
479                signature: [0; 32],
480            },
481        };
482        check_record_size(encoded_len(&body)?)?;
483        let id = kernel
484            .delegate_cap(parent_id, 1, rights)
485            .map_err(|e| EnvelopeError::Native(e.to_string()))?;
486        let cap = kernel
487            .get_cap(id)
488            .ok_or(EnvelopeError::Reject("native delegate returned no record"))?;
489        if *cap.rights() != rights {
490            return Err(EnvelopeError::Reject(
491                "native intersection narrowed requested authority",
492            ));
493        }
494        body.native = NativeCapability::from_core(cap);
495        let bytes = seal_body(&body, self.verifier.keys)?;
496        self.verifier
497            .verify(&bytes, body.grant.store_id, body.grant.epoch_id)
498    }
499}
500fn validate_draft(catalog: &ClosedCatalog, grant: &EnvelopeDraft) -> EnvelopeResult<()> {
501    grant.issuer.validate()?;
502    grant.grantee.validate()?;
503    grant.validity.validate()?;
504    nonempty(&grant.namespace)?;
505    nonempty(&grant.key.id)?;
506    if grant.issuer.leg.is_some() {
507        return Err(EnvelopeError::Reject("subactor cannot issue grants"));
508    }
509    if grant.grantee.leg.is_some() && grant.grantee.parent() != grant.issuer {
510        return Err(EnvelopeError::Reject("only parent can grant to its leg"));
511    }
512    match (&grant.operation, &grant.configuration_source) {
513        (CreationOperation::Import, Some(source)) => nonempty(source)?,
514        (CreationOperation::Grant, None) => {}
515        _ => {
516            return Err(EnvelopeError::InvalidInput(
517                "creation provenance does not match operation",
518            ))
519        }
520    }
521    let _ = catalog.validate_rights(&grant.rights, &grant.namespace, &grant.grantee)?;
522    Ok(())
523}
524pub(super) fn issuance_alias(id: Uuid) -> u128 {
525    ALIAS_START | (id.as_u128() & ((1_u128 << 126) - 1))
526}
527pub(super) fn check_alias(alias: u128) -> EnvelopeResult<()> {
528    if !(ALIAS_START..ALIAS_END).contains(&alias) {
529        return Err(EnvelopeError::IdSpaceExhausted);
530    }
531    Ok(())
532}
533pub(super) fn check_output_capacity(next: u128) -> EnvelopeResult<()> {
534    if next >= OUTPUT_END {
535        return Err(EnvelopeError::IdSpaceExhausted);
536    }
537    Ok(())
538}
539fn check_record_size(body_length: usize) -> EnvelopeResult<usize> {
540    let length = body_length
541        .checked_add(RECORD_OVERHEAD)
542        .ok_or(EnvelopeError::OverLimit {
543            field: "canonical record",
544            measured: usize::MAX,
545            bound: MAX_RECORD_BYTES,
546        })?;
547    bound("canonical record", length, MAX_RECORD_BYTES)?;
548    Ok(length)
549}
550pub(super) fn envelope_mac(key: &[u8; 32], body: &[u8]) -> EnvelopeResult<Hmac<Sha256>> {
551    let length = u32::try_from(body.len())
552        .map_err(|_| EnvelopeError::InvalidInput("body length exceeds u32"))?;
553    let mut mac = Hmac::<Sha256>::new_from_slice(key)
554        .map_err(|_| EnvelopeError::Unavailable("extension key unavailable"))?;
555    mac.update(DOMAIN);
556    mac.update(&1_u16.to_be_bytes());
557    mac.update(&length.to_be_bytes());
558    mac.update(body);
559    Ok(mac)
560}
561pub(super) fn seal_body(body: &GrantBody, keys: &SuppliedKeys) -> EnvelopeResult<Vec<u8>> {
562    let capacity = check_record_size(encoded_len(body)?)?;
563    let encoded = encode(body)?;
564    let tag = envelope_mac(keys.extension(&body.grant.key)?, &encoded)?
565        .finalize()
566        .into_bytes();
567    let mut bytes = Vec::with_capacity(capacity);
568    bytes.extend_from_slice(MAGIC);
569    bytes.extend_from_slice(&(encoded.len() as u32).to_be_bytes());
570    bytes.extend_from_slice(&encoded);
571    bytes.extend_from_slice(&tag);
572    Ok(bytes)
573}