Skip to main content

kernable_core/
signing.rs

1//! Signed messages and the event hash chain, as specified in `proto/SIGNING.md`.
2//!
3//! A key ID is the hex-encoded Ed25519 public key, so any signature can be checked
4//! without a key registry; *authorization* of a key is up to the kernel.
5
6use std::{fmt, fs, io, path::Path};
7
8use ed25519_dalek::{Signature as Ed25519Signature, Signer, SigningKey, VerifyingKey};
9use sha2::{Digest, Sha256};
10use zeroize::Zeroizing;
11
12use crate::proto::{
13    CacheRequest, CancelRequest, Command, DataRequest, Event, Grant, Membership, NewEvent,
14    Permission, QueryRequest, Rejected, RequestContext, Requirement, Signature, UniqueKey,
15    WitnessGeneration,
16};
17
18/// Hash that precedes the first event of the chain.
19pub const GENESIS: [u8; 32] = [0; 32];
20
21#[derive(Debug, PartialEq)]
22pub enum SignError {
23    InvalidKey,
24    InvalidSignature,
25}
26
27impl fmt::Display for SignError {
28    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29        match self {
30            SignError::InvalidKey => write!(f, "invalid key"),
31            SignError::InvalidSignature => write!(f, "invalid signature"),
32        }
33    }
34}
35
36impl std::error::Error for SignError {}
37
38/// Length-prefixed message builder: every field is `u32 BE length || bytes`, integers are 8 bytes BE.
39struct Msg(Vec<u8>);
40
41impl Msg {
42    fn new(tag: &str) -> Self {
43        Msg(Vec::new()).str(tag)
44    }
45
46    fn bytes(mut self, b: &[u8]) -> Self {
47        self.0.extend((b.len() as u32).to_be_bytes());
48        self.0.extend(b);
49        self
50    }
51
52    fn str(self, s: &str) -> Self {
53        self.bytes(s.as_bytes())
54    }
55
56    fn u64(mut self, v: u64) -> Self {
57        self.0.extend(v.to_be_bytes());
58        self
59    }
60
61    fn i64(mut self, v: i64) -> Self {
62        self.0.extend(v.to_be_bytes());
63        self
64    }
65
66    /// A request context; an absent one encodes like an empty one.
67    fn context(self, c: Option<&RequestContext>) -> Self {
68        let default = RequestContext::default();
69        let c = c.unwrap_or(&default);
70        let mut m = self
71            .str(&c.sender_tenant)
72            .str(&c.sender_identity)
73            .str(&c.sender_account)
74            .str(&c.sender_session)
75            .str(&c.on_behalf_of);
76        m = match c.expected_version {
77            Some(v) => m.u64(1).u64(v),
78            None => m.u64(0),
79        };
80        m = m
81            .str(&c.correlation_id)
82            .str(&c.causation_id)
83            .str(&c.trace_id)
84            .u64(c.bypass_authorization as u64)
85            .u64(c.attributes.len() as u64);
86        for a in &c.attributes {
87            m = m.str(&a.key).str(&a.value);
88        }
89        m
90    }
91
92    /// Vault references, appended only when there are any.
93    fn refs(self, refs: &[String]) -> Self {
94        if refs.is_empty() {
95            return self;
96        }
97        let mut m = self.u64(refs.len() as u64);
98        for r in refs {
99            m = m.str(r);
100        }
101        m
102    }
103}
104
105/// The reference of a value kept in the vault: it commits to the value, its subject and kind,
106/// and a random salt, so it reveals nothing about an erased value.
107pub fn vault_ref(salt: &[u8], subject: &str, secret: bool, value: &[u8]) -> String {
108    let msg = Msg::new("kernable.v1.vault")
109        .bytes(salt)
110        .str(subject)
111        .u64(secret as u64)
112        .bytes(value);
113    hex::encode(Sha256::digest(msg.0))
114}
115
116/// What a client signs when submitting a command.
117pub fn command_message(cmd: &Command) -> Vec<u8> {
118    let m = Msg::new("kernable.v1.command")
119        .str(&cmd.command_id)
120        .str(&cmd.tenant_id)
121        .str(&cmd.domain)
122        .str(&cmd.aggregate_type)
123        .str(&cmd.aggregate_id)
124        .str(&cmd.command_type)
125        .bytes(&cmd.payload)
126        .context(cmd.context.as_ref())
127        .refs(&cmd.vault_refs);
128    // Optional fields: each is appended only when set, after its name.
129    let m = if cmd.deliver_at != 0 {
130        m.str("deliver_at").i64(cmd.deliver_at)
131    } else {
132        m
133    };
134    let m = if cmd.deliver_until != 0 {
135        m.str("deliver_until").i64(cmd.deliver_until)
136    } else {
137        m
138    };
139    m.0
140}
141
142/// What a client signs when cancelling a scheduled command.
143pub fn cancel_message(c: &CancelRequest) -> Vec<u8> {
144    Msg::new("kernable.v1.cancel")
145        .str(&c.command_id)
146        .str(&c.tenant_id)
147        .context(c.context.as_ref())
148        .i64(c.issued_at)
149        .0
150}
151
152/// What a client signs when asking a query.
153pub fn query_message(q: &QueryRequest) -> Vec<u8> {
154    let m = Msg::new("kernable.v1.query")
155        .str(&q.query_id)
156        .str(&q.tenant_id)
157        .str(&q.domain)
158        .str(&q.query_type)
159        .bytes(&q.payload)
160        .context(q.context.as_ref())
161        .u64(q.min_position)
162        .i64(q.issued_at);
163    // Optional fields: each is appended only when set, after its name.
164    let m = if q.wait_only { m.str("wait_only") } else { m };
165    match &q.target {
166        Some(t) => {
167            m.str("target")
168                .str(&t.aggregate_type)
169                .str(&t.aggregate_id)
170                .0
171        }
172        None => m.0,
173    }
174}
175
176/// What a worker signs when returning events for `cmd` based on `expected_version`.
177pub fn result_message(cmd: &Command, expected_version: u64, events: &[NewEvent]) -> Vec<u8> {
178    let mut m = Msg::new("kernable.v1.result")
179        .str(&cmd.command_id)
180        .str(&cmd.tenant_id)
181        .str(&cmd.domain)
182        .str(&cmd.aggregate_type)
183        .str(&cmd.aggregate_id)
184        .u64(expected_version)
185        .u64(events.len() as u64);
186    for e in events {
187        m = m.str(&e.event_type).u64(e.schema.into()).bytes(&e.payload);
188    }
189    // Vault fields, appended only when an event has any (see `Msg::refs`).
190    if events
191        .iter()
192        .any(|e| !e.vault_refs.is_empty() || !e.erases.is_empty())
193    {
194        for e in events {
195            m = m.u64(e.vault_refs.len() as u64);
196            for r in &e.vault_refs {
197                m = m.str(r);
198            }
199            m = m.str(&e.erases);
200        }
201    }
202    m.0
203}
204
205/// What a worker signs for the unique keys, facts and requirements of its result for `cmd`
206/// based on `expected_version`. A message of its own, not part of [`result_message`]: every
207/// event stores the result signature, and `kernable verify` checks it against the stored events
208/// alone, which never hold value hashes or requirements.
209pub fn index_message(
210    cmd: &Command,
211    expected_version: u64,
212    keys: &[UniqueKey],
213    facts: &[String],
214    requires: &[Requirement],
215) -> Vec<u8> {
216    let mut m = Msg::new("kernable.v1.index")
217        .str(&cmd.command_id)
218        .str(&cmd.tenant_id)
219        .str(&cmd.domain)
220        .str(&cmd.aggregate_type)
221        .str(&cmd.aggregate_id)
222        .u64(expected_version)
223        .u64(keys.len() as u64);
224    for k in keys {
225        m = m
226            .str(&k.name)
227            .u64(k.global as u64)
228            .bytes(&k.value_hash)
229            .str(&k.subject);
230    }
231    m = m.u64(facts.len() as u64);
232    for f in facts {
233        m = m.str(f);
234    }
235    m = m.u64(requires.len() as u64);
236    for r in requires {
237        m = m
238            .str(&r.domain)
239            .str(&r.aggregate_type)
240            .str(&r.aggregate_id)
241            .str(&r.fact)
242            .str(&r.key)
243            .bytes(&r.value_hash)
244            .u64(u64::from(r.absent));
245    }
246    m.0
247}
248
249/// The identity of a unique key in the kernel's index. The kernel computes it from the
250/// command's own tenant (none for a global key), domain and aggregate type, so a worker cannot
251/// place a key in another domain's namespace.
252pub fn unique_key_id(cmd: &Command, key: &UniqueKey) -> [u8; 32] {
253    let tenant = if key.global { "" } else { &cmd.tenant_id };
254    unique_key_id_of(
255        tenant,
256        &cmd.domain,
257        &cmd.aggregate_type,
258        &key.name,
259        &key.value_hash,
260    )
261}
262
263/// The identity of the unique key `name` with the value hash `value_hash` of aggregates of
264/// `domain` and `aggregate_type`, in `tenant` (empty for a global key); see [`unique_key_id`].
265pub fn unique_key_id_of(
266    tenant: &str,
267    domain: &str,
268    aggregate_type: &str,
269    name: &str,
270    value_hash: &[u8],
271) -> [u8; 32] {
272    let msg = Msg::new("kernable.v1.key")
273        .str(tenant)
274        .str(domain)
275        .str(aggregate_type)
276        .str(name)
277        .bytes(value_hash);
278    Sha256::digest(msg.0).into()
279}
280
281/// What a worker signs for a snapshot of `stream`'s aggregate (the stream fields of a command:
282/// tenant, domain, aggregate type and ID).
283pub fn snapshot_message(stream: &Command, version: u64, schema: &str, state: &[u8]) -> Vec<u8> {
284    Msg::new("kernable.v1.snapshot")
285        .str(&stream.tenant_id)
286        .str(&stream.domain)
287        .str(&stream.aggregate_type)
288        .str(&stream.aggregate_id)
289        .u64(version)
290        .str(schema)
291        .bytes(state)
292        .0
293}
294
295/// What a worker signs when rejecting a command.
296pub fn rejection_message(command_id: &str, reason: &Rejected) -> Vec<u8> {
297    Msg::new("kernable.v1.rejection")
298        .str(command_id)
299        .str(&reason.code)
300        .str(&reason.message)
301        .0
302}
303
304/// What a worker signs to prove it holds its key when registering.
305pub fn challenge_message(nonce: &[u8]) -> Vec<u8> {
306    Msg::new("kernable.v1.challenge").bytes(nonce).0
307}
308
309/// What a subscriber signs to open an event stream.
310pub fn subscribe_message(after_position: u64, event_types: &[String], issued_at: i64) -> Vec<u8> {
311    let mut m = Msg::new("kernable.v1.subscribe")
312        .u64(after_position)
313        .i64(issued_at)
314        .u64(event_types.len() as u64);
315    for t in event_types {
316        m = m.str(t);
317    }
318    m.0
319}
320
321/// What a client signs to put, get or delete a file (`op`: `put`, `get`, `delete`). The data is
322/// signed by its SHA-256 hash; get and delete sign the hash of nothing.
323pub fn data_message(op: &str, r: &DataRequest) -> Vec<u8> {
324    let msg = Msg::new(&format!("kernable.v1.data.{op}"))
325        .str(&r.tenant_id)
326        .str(&r.domain)
327        .str(&r.key)
328        .str(&r.content_type)
329        .bytes(&Sha256::digest(&r.data))
330        .i64(r.issued_at)
331        .context(r.context.as_ref());
332    // A listing's page, after the context.
333    if op == "list" {
334        msg.str(&r.after).0
335    } else {
336        msg.0
337    }
338}
339
340/// What a client signs to set, get or delete a cache value (`op`: `set`, `get`, `delete`), with
341/// the value's SHA-256 hash as for data.
342pub fn cache_message(op: &str, r: &CacheRequest) -> Vec<u8> {
343    Msg::new(&format!("kernable.v1.cache.{op}"))
344        .str(&r.tenant_id)
345        .str(&r.domain)
346        .str(&r.key)
347        .bytes(&Sha256::digest(&r.value))
348        .u64(r.ttl_ms)
349        .i64(r.issued_at)
350        .context(r.context.as_ref())
351        .0
352}
353
354/// What the kernel signs to revoke `key_id` from `since` on (both ms since epoch).
355pub fn revocation_message(key_id: &str, since: i64, created_at: i64) -> Vec<u8> {
356    Msg::new("kernable.v1.revocation")
357        .str(key_id)
358        .i64(since)
359        .i64(created_at)
360        .0
361}
362
363/// What a root key signs to grant `grant.key_id` its permissions.
364pub fn grant_message(grant: &Grant) -> Vec<u8> {
365    let mut m = Msg::new("kernable.v1.grant")
366        .str(&grant.key_id)
367        .str(&grant.succeeds)
368        .i64(grant.issued_at)
369        .u64(grant.permissions.len() as u64);
370    for p in &grant.permissions {
371        m = m.str(&p.action).u64(p.types.len() as u64);
372        for t in &p.types {
373            m = m.str(t);
374        }
375    }
376    m.0
377}
378
379/// A grant for `key_id`, signed by `root`.
380pub fn grant(
381    root: &SigningKey,
382    key_id: &str,
383    permissions: Vec<Permission>,
384    succeeds: &str,
385    issued_at: i64,
386) -> Grant {
387    let mut grant = Grant {
388        key_id: key_id.to_owned(),
389        permissions,
390        succeeds: succeeds.to_owned(),
391        issued_at,
392        root_sig: None,
393        issuer: None,
394    };
395    grant.root_sig = Some(sign(root, &grant_message(&grant)));
396    grant
397}
398
399/// A delegated grant for `key_id`, signed by `delegate`, whose own grant `issuer` (signed by a
400/// root key) lets it grant these permissions' actions; it carries `issuer`.
401pub fn delegated_grant(
402    delegate: &SigningKey,
403    issuer: Grant,
404    key_id: &str,
405    permissions: Vec<Permission>,
406    issued_at: i64,
407) -> Grant {
408    let mut grant = Grant {
409        key_id: key_id.to_owned(),
410        permissions,
411        succeeds: String::new(),
412        issued_at,
413        root_sig: None,
414        issuer: Some(Box::new(issuer)),
415    };
416    grant.root_sig = Some(sign(delegate, &grant_message(&grant)));
417    grant
418}
419
420/// What a key granted `manage` signs to apply a service's membership.
421pub fn membership_message(m: &Membership) -> Vec<u8> {
422    let mut msg = Msg::new("kernable.v1.membership").str(&m.service);
423    for list in [&m.workers, &m.listeners, &m.middlewares] {
424        msg = msg.u64(list.len() as u64);
425        for entry in list {
426            msg = msg.str(entry);
427        }
428    }
429    msg = msg.u64(m.metadata.len() as u64);
430    for a in &m.metadata {
431        msg = msg.str(&a.key).str(&a.value);
432    }
433    msg = msg.i64(m.issued_at);
434    // Processes: appended only when there are any, after their name.
435    if !m.processes.is_empty() {
436        msg = msg.str("processes").u64(m.processes.len() as u64);
437        for p in &m.processes {
438            msg = msg.str(p);
439        }
440    }
441    // The deployment that serves the service: appended only when set, after its name.
442    if !m.deployment.is_empty() {
443        msg = msg.str("deployment").str(&m.deployment);
444    }
445    msg.0
446}
447
448/// What a key granted `process` signs to register a process model (its JSON as sent).
449pub fn process_message(model: &[u8], issued_at: i64) -> Vec<u8> {
450    Msg::new("kernable.v1.process")
451        .bytes(model)
452        .i64(issued_at)
453        .0
454}
455
456/// What a key granted `process` signs to set as whom a process acts (`ProcessService.Act`).
457pub fn process_act_message(
458    name: &str,
459    context: Option<&RequestContext>,
460    issued_at: i64,
461) -> Vec<u8> {
462    Msg::new("kernable.v1.process_act")
463        .str(name)
464        .context(context)
465        .i64(issued_at)
466        .0
467}
468
469/// What a key granted `process` signs to resolve a case's incident (`ProcessService.Resolve`).
470pub fn process_resolve_message(
471    process: &str,
472    case_id: &str,
473    tenant_id: &str,
474    action: &str,
475    issued_at: i64,
476) -> Vec<u8> {
477    Msg::new("kernable.v1.process_resolve")
478        .str(process)
479        .str(case_id)
480        .str(tenant_id)
481        .str(action)
482        .i64(issued_at)
483        .0
484}
485
486/// What a key granted `process` signs to remove a process (`ProcessService.Remove`).
487pub fn process_remove_message(name: &str, issued_at: i64) -> Vec<u8> {
488    Msg::new("kernable.v1.process_remove")
489        .str(name)
490        .i64(issued_at)
491        .0
492}
493
494/// What a key granted `manage` signs to deliver a listener's parked events again, or dismiss
495/// them; no `positions` means all of them.
496pub fn retry_message(listener: &str, positions: &[u64], dismiss: bool, issued_at: i64) -> Vec<u8> {
497    let mut msg = Msg::new("kernable.v1.retry")
498        .str(listener)
499        .u64(positions.len() as u64);
500    for p in positions {
501        msg = msg.u64(*p);
502    }
503    msg.u64(u64::from(dismiss)).i64(issued_at).0
504}
505
506/// What a root key signs to revoke `key_id` from `since` on (both ms since epoch).
507pub fn revoke_message(key_id: &str, since: i64, issued_at: i64) -> Vec<u8> {
508    Msg::new("kernable.v1.revoke")
509        .str(key_id)
510        .i64(since)
511        .i64(issued_at)
512        .0
513}
514
515/// What a key granted `manage` for `*` signs to apply a partition map.
516pub fn partitions_message(map: &crate::proto::PartitionMap) -> Vec<u8> {
517    let mut msg = Msg::new("kernable.v1.partitions")
518        .u64(map.epoch)
519        .u64(map.partitions.len() as u64);
520    for p in &map.partitions {
521        msg = msg.str(&p.name).u64(p.addresses.len() as u64);
522        for a in &p.addresses {
523            msg = msg.str(a);
524        }
525    }
526    msg = msg.u64(map.tenants.len() as u64);
527    for t in &map.tenants {
528        msg = msg.str(&t.tenant).str(&t.partition);
529    }
530    msg = msg.str(&map.default).str(&map.control).i64(map.issued_at);
531    // Moves: appended only when there are any.
532    if !map.moving.is_empty() || !map.moved.is_empty() {
533        for list in [&map.moving, &map.moved] {
534            msg = msg.u64(list.len() as u64);
535            for m in list {
536                msg = msg
537                    .str(&m.tenant)
538                    .str(&m.from)
539                    .str(&m.to)
540                    .u64(m.source_head)
541                    .u64(m.target_after)
542                    .u64(m.epoch);
543            }
544        }
545    }
546    // Copies while the tenant runs, appended only when there are any, under their own tag.
547    if !map.copying.is_empty() {
548        msg = msg.str("copying").u64(map.copying.len() as u64);
549        for m in &map.copying {
550            msg = msg.str(&m.tenant).str(&m.from).str(&m.to).u64(m.epoch);
551        }
552    }
553    msg.0
554}
555
556/// What a partition's node key signs to export a moving tenant, or to report it moved; `after`
557/// (an export after a precopy) is appended only when set.
558pub fn move_message(
559    op: &str,
560    tenant: &str,
561    from: &str,
562    to: &str,
563    after: u64,
564    issued_at: i64,
565) -> Vec<u8> {
566    let msg = Msg::new("kernable.v1.move")
567        .str(op)
568        .str(tenant)
569        .str(from)
570        .str(to)
571        .i64(issued_at);
572    if after > 0 { msg.u64(after).0 } else { msg.0 }
573}
574
575/// What a partition's node key signs to reserve global keys, or to ask whether it holds them.
576pub fn global_keys_message(op: &str, keys: &[Vec<u8>], partition: &str, issued_at: i64) -> Vec<u8> {
577    let mut msg = Msg::new("kernable.v1.global-keys")
578        .str(op)
579        .u64(keys.len() as u64);
580    for k in keys {
581        msg = msg.bytes(k);
582    }
583    msg.str(partition).i64(issued_at).0
584}
585
586/// What a partition's node key signs to take the trust records from the control partition.
587pub fn trust_sync_message(issued_at: i64) -> Vec<u8> {
588    Msg::new("kernable.v1.trust-sync").i64(issued_at).0
589}
590
591/// What an operator's key signs to export a running kernel (`kernable export`).
592pub fn export_message(issued_at: i64) -> Vec<u8> {
593    Msg::new("kernable.v1.export").i64(issued_at).0
594}
595
596/// What an operator's key signs to promote a standby to the primary (`kernable promote`).
597pub fn promote_message(issued_at: i64) -> Vec<u8> {
598    Msg::new("kernable.v1.promote").i64(issued_at).0
599}
600
601/// What a reader of a relay's copy signs to send a write through the relay: the copy, the
602/// call's ID, the SHA-256 of the sealed call and when.
603pub fn relay_call_message(copy: &str, id: u64, sealed: &[u8], issued_at: i64) -> Vec<u8> {
604    use sha2::Digest;
605    Msg::new("kernable.v1.relay-call")
606        .str(copy)
607        .u64(id)
608        .bytes(&sha2::Sha256::digest(sealed))
609        .i64(issued_at)
610        .0
611}
612
613/// What a pusher or a reader signs into the request that opens a stream at a relay (`push`,
614/// `calls`, `follow`), so the relay knows the key before it reads a single message.
615pub fn relay_stream_message(rpc: &str, copy: &str, key_id: &str, issued_at: i64) -> Vec<u8> {
616    Msg::new("kernable.v1.relay-stream")
617        .str(rpc)
618        .str(copy)
619        .str(key_id)
620        .i64(issued_at)
621        .0
622}
623
624/// The request headers of a stream at a relay: the key, the copy, when (ms), the signature
625/// over [`relay_stream_message`] (hex).
626pub const RELAY_KEY_HEADER: &str = "kernable-relay-key";
627pub const RELAY_COPY_HEADER: &str = "kernable-relay-copy";
628pub const RELAY_AT_HEADER: &str = "kernable-relay-at";
629pub const RELAY_SIG_HEADER: &str = "kernable-relay-sig";
630
631/// What a new reader of a relay's copy signs to ask for the copy key.
632pub fn copy_key_message(copy: &str, key_id: &str, id: u64, issued_at: i64) -> Vec<u8> {
633    Msg::new("kernable.v1.copy-key")
634        .str(copy)
635        .str(key_id)
636        .u64(id)
637        .i64(issued_at)
638        .0
639}
640
641/// What an operator's key signs to hand a pair's primary role over (`kernable switchover`).
642pub fn switchover_message(issued_at: i64) -> Vec<u8> {
643    Msg::new("kernable.v1.switchover").i64(issued_at).0
644}
645
646/// What a backup follower (or `kernable backup list`, `check`, `plan`, `restore`) signs to ask
647/// a backup signer for a presigned request: `op` (`put`, `get`, `list` or `delete`) on the
648/// object `name` under `prefix` in `bucket` (for `list`: the names starting with `name`, from
649/// `continuation` on), with the SHA-256 and length of the body it will send (`put`; others the
650/// hash of nothing and 0).
651#[allow(clippy::too_many_arguments)]
652pub fn backup_object_message(
653    op: &str,
654    bucket: &str,
655    prefix: &str,
656    name: &str,
657    continuation: &str,
658    sha256: &[u8],
659    length: u64,
660    issued_at: i64,
661) -> Vec<u8> {
662    Msg::new("kernable.v1.backup-object")
663        .str(op)
664        .str(bucket)
665        .str(prefix)
666        .str(name)
667        .str(continuation)
668        .bytes(sha256)
669        .u64(length)
670        .i64(issued_at)
671        .0
672}
673
674/// What a kernel of a pair signs to ask the witness (`WitnessRequest`).
675pub fn witness_message(
676    op: i32,
677    term: u64,
678    address: &str,
679    standby: &str,
680    issued_at: i64,
681) -> Vec<u8> {
682    Msg::new("kernable.v1.witness")
683        .u64(op as u64)
684        .u64(term)
685        .str(address)
686        .str(standby)
687        .i64(issued_at)
688        .0
689}
690
691/// What a root key signs to name the current witness of a pair: its `generation` and its
692/// address as the kernels name it (`--witness`).
693pub fn witness_generation_message(generation: u64, witness: &str, issued_at: i64) -> Vec<u8> {
694    Msg::new("kernable.v1.witness-generation")
695        .u64(generation)
696        .str(witness)
697        .i64(issued_at)
698        .0
699}
700
701/// Witness generation `generation` for the witness at `witness`, signed by `root`.
702pub fn witness_generation(
703    root: &SigningKey,
704    generation: u64,
705    witness: &str,
706    issued_at: i64,
707) -> WitnessGeneration {
708    WitnessGeneration {
709        generation,
710        witness: witness.to_owned(),
711        issued_at,
712        root_sig: Some(sign(
713            root,
714            &witness_generation_message(generation, witness, issued_at),
715        )),
716    }
717}
718
719/// What the kernel signs to anchor the chain at `global_position`.
720pub fn checkpoint_message(global_position: u64, chain_hash: &[u8], created_at: i64) -> Vec<u8> {
721    Msg::new("kernable.v1.checkpoint")
722        .u64(global_position)
723        .bytes(chain_hash)
724        .i64(created_at)
725        .0
726}
727
728/// The `n`-th ID a command handler derives while handling `command_id` (`ctx.id()` in the
729/// SDKs): a UUID (version 8) from SHA-256 over a tagged message, so it is the same in every
730/// language and every time the command runs again.
731pub fn derived_id(command_id: &str, n: u64) -> String {
732    let digest = Sha256::digest(Msg::new("kernable.v1.id").str(command_id).u64(n).0);
733    let mut b: [u8; 16] = digest[..16].try_into().expect("32-byte digest");
734    b[6] = (b[6] & 0x0f) | 0x80; // version 8
735    b[8] = (b[8] & 0x3f) | 0x80; // RFC 9562 variant
736    let h = hex::encode(b);
737    format!(
738        "{}-{}-{}-{}-{}",
739        &h[..8],
740        &h[8..12],
741        &h[12..16],
742        &h[16..20],
743        &h[20..]
744    )
745}
746
747/// Chain hash of `event`, linked to the hash of the previous event (`GENESIS` for the first).
748pub fn event_hash(prev: &[u8], event: &Event) -> [u8; 32] {
749    let sig = event.producer_sig.clone().unwrap_or_default();
750    let msg = Msg::new("kernable.v1.event")
751        .bytes(prev)
752        .u64(event.global_position)
753        .str(&event.tenant_id)
754        .str(&event.domain)
755        .str(&event.aggregate_type)
756        .str(&event.aggregate_id)
757        .u64(event.version)
758        .str(&event.event_type)
759        .u64(event.schema.into())
760        .bytes(&event.payload)
761        .str(&event.command_id)
762        .i64(event.created_at)
763        .str(&sig.key_id)
764        .bytes(&sig.sig)
765        .context(event.context.as_ref());
766    // Vault fields, appended only when set (see `Msg::refs`).
767    let msg = if event.vault_refs.is_empty() && event.erases.is_empty() {
768        msg
769    } else {
770        let mut m = msg.u64(event.vault_refs.len() as u64);
771        for r in &event.vault_refs {
772            m = m.str(r);
773        }
774        m.str(&event.erases)
775    };
776    // Where a moved event was first committed, appended only when set.
777    let msg = if event.origin_partition.is_empty() {
778        msg
779    } else {
780        msg.str(&event.origin_partition).u64(event.origin_position)
781    };
782    // The producer's deployment, appended only when set, after its name.
783    let msg = if event.deployment.is_empty() {
784        msg
785    } else {
786        msg.str("deployment").str(&event.deployment)
787    };
788    Sha256::digest(msg.0).into()
789}
790
791pub fn key_id(key: &VerifyingKey) -> String {
792    hex::encode(key.as_bytes())
793}
794
795/// The ID of a vault key: the key ID of the public half `kernable keys new` writes beside it
796/// (the key read as a signing key's seed). It names the key without revealing it: a backup
797/// generation says by it which vault key its values are sealed with.
798pub fn vault_key_id(key: &[u8; 32]) -> String {
799    key_id(&SigningKey::from_bytes(key).verifying_key())
800}
801
802pub fn generate_key() -> SigningKey {
803    let mut seed = Zeroizing::new([0u8; 32]);
804    getrandom::fill(seed.as_mut()).expect("OS randomness unavailable");
805    SigningKey::from_bytes(&seed)
806}
807
808pub fn sign(key: &SigningKey, msg: &[u8]) -> Signature {
809    Signature {
810        key_id: key_id(&key.verifying_key()),
811        sig: key.sign(msg).to_bytes().to_vec(),
812    }
813}
814
815pub fn verify(sig: &Signature, msg: &[u8]) -> Result<(), SignError> {
816    let key = verifying_key_from_hex(&sig.key_id)?;
817    let sig = Ed25519Signature::from_slice(&sig.sig).map_err(|_| SignError::InvalidSignature)?;
818    key.verify_strict(msg, &sig)
819        .map_err(|_| SignError::InvalidSignature)
820}
821
822pub fn verifying_key_from_hex(s: &str) -> Result<VerifyingKey, SignError> {
823    let bytes: [u8; 32] = hex::decode(s.trim())
824        .ok()
825        .and_then(|b| b.try_into().ok())
826        .ok_or(SignError::InvalidKey)?;
827    VerifyingKey::from_bytes(&bytes).map_err(|_| SignError::InvalidKey)
828}
829
830pub fn signing_key_from_hex(s: &str) -> Result<SigningKey, SignError> {
831    let seed = secret_from_hex(s)?;
832    Ok(SigningKey::from_bytes(&seed))
833}
834
835/// 32 secret bytes from hex, decoded in place: no copy of the secret is left behind.
836fn secret_from_hex(s: &str) -> Result<Zeroizing<[u8; 32]>, SignError> {
837    let mut secret = Zeroizing::new([0u8; 32]);
838    hex::decode_to_slice(s.trim(), secret.as_mut()).map_err(|_| SignError::InvalidKey)?;
839    Ok(secret)
840}
841
842/// Reads a file of 32 secret bytes in hex, such as a `.key` file or a vault key. The secret
843/// and the text it was read from are wiped from memory when dropped.
844pub fn read_secret(path: impl AsRef<Path>) -> io::Result<Zeroizing<[u8; 32]>> {
845    secret_from_hex(&Zeroizing::new(fs::read_to_string(path)?)).map_err(invalid_data)
846}
847
848/// Reads a `.key` file (hex-encoded 32-byte seed).
849pub fn read_signing_key(path: impl AsRef<Path>) -> io::Result<SigningKey> {
850    let seed = read_secret(path)?;
851    Ok(SigningKey::from_bytes(&seed))
852}
853
854/// Reads a `.pub` file (hex-encoded public key, i.e. the key ID).
855pub fn read_verifying_key(path: impl AsRef<Path>) -> io::Result<VerifyingKey> {
856    verifying_key_from_hex(&fs::read_to_string(path)?).map_err(invalid_data)
857}
858
859fn invalid_data(e: SignError) -> io::Error {
860    io::Error::new(io::ErrorKind::InvalidData, e)
861}
862
863#[cfg(test)]
864mod tests {
865    use super::*;
866
867    #[test]
868    fn secret_keys_are_wiped_when_dropped() {
869        fn wiped<T: zeroize::ZeroizeOnDrop>() {}
870        wiped::<SigningKey>();
871        wiped::<Zeroizing<[u8; 32]>>();
872    }
873
874    #[test]
875    fn key_files_read_back_as_written() {
876        let key = generate_key();
877        let dir = std::env::temp_dir().join(format!("kernable-keys-{}", std::process::id()));
878        fs::create_dir_all(&dir).unwrap();
879        fs::write(dir.join("k.key"), hex::encode(key.as_bytes())).unwrap();
880        fs::write(
881            dir.join("k.pub"),
882            format!("{}\n", key_id(&key.verifying_key())),
883        )
884        .unwrap();
885        assert_eq!(
886            read_signing_key(dir.join("k.key")).unwrap().as_bytes(),
887            key.as_bytes()
888        );
889        assert_eq!(
890            read_verifying_key(dir.join("k.pub")).unwrap(),
891            key.verifying_key()
892        );
893        fs::remove_dir_all(&dir).unwrap();
894    }
895
896    #[test]
897    fn a_secret_key_is_exactly_32_bytes_in_hex() {
898        let hex = "11".repeat(32);
899        let key = signing_key_from_hex(&format!("  {hex}\n")).unwrap();
900        assert_eq!(key.as_bytes(), &[0x11; 32]);
901        for bad in [
902            &hex[..62],
903            &format!("{hex}11"),
904            &format!("{}x", &hex[..63]),
905            "",
906        ] {
907            assert_eq!(
908                signing_key_from_hex(bad).err(),
909                Some(SignError::InvalidKey),
910                "{bad}"
911            );
912        }
913    }
914}