gent-crypto 0.1.6

Cryptographic primitives, invitations and signatures for the Gent protocol.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
//! Protected invitation files and an owner-authenticated bootstrap channel.
//!
//! Files must arrive through an independently trusted channel. Their embedded
//! signature does not authenticate an anchor downloaded from Gent's service.
//! This module has no storage or membership side effects. The owner must durably
//! claim an invitation and restrict pairing operations before releasing state.
use super::*;
use uuid::Uuid;
use zeroize::Zeroize;

pub mod channel;

pub const OFFER_LIFETIME: u64 = gent_protocol::service::invitations::LIFETIME_SECONDS;
pub const MAX_INVITATION_BYTES: usize = MAX_OWNER_CHAIN_BYTES + 16 * 1024;
const OFFER_DOMAIN: &[u8] = b"gent/invitation-offer/v1\0";
const CLAIM_DOMAIN: &[u8] = b"gent/invitation-claim/v1\0";
const MAX_OFFER_BYTES: usize = MAX_OWNER_CHAIN_BYTES + 8192;

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ServiceBinding {
    pub account_id: String,
    pub account_origin: String,
    pub relay_origin: String,
}

impl ServiceBinding {
    pub fn validate(&self) -> Result<()> {
        id(&self.account_id)?;
        fn origin(value: &str) -> Result<url::Url> {
            ensure!(value.len() <= 2048, "invitation origin too long");
            let url = url::Url::parse(value).context("invalid invitation origin")?;
            ensure!(
                url.username().is_empty()
                    && url.password().is_none()
                    && url.query().is_none()
                    && url.fragment().is_none()
                    && url.path() == "/"
                    && url.origin().ascii_serialization() == value
                    && (url.scheme() == "https"
                        || (url.scheme() == "http"
                            && matches!(url.host_str(), Some("127.0.0.1" | "[::1]")))),
                "invitation requires a canonical HTTPS origin or explicit loopback"
            );
            Ok(url)
        }
        let account = origin(&self.account_origin)?;
        let relay = origin(&self.relay_origin)?;
        ensure!(
            account.scheme() != "https" || relay.scheme() == "https",
            "HTTPS account service cannot select an insecure relay"
        );
        Ok(())
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ClaimedNode {
    pub id: String,
    pub key: PublicKey,
    pub name: String,
}
impl ClaimedNode {
    fn validate(&self, offer: &Offer) -> Result<()> {
        id(&self.id)?;
        public_key(&self.key)?;
        label(&self.name)?;
        if let Purpose::NamedNode { name, .. } = &offer.purpose {
            ensure!(
                &self.name == name,
                "invitation requires its assigned node name"
            );
        }
        ensure!(
            self.id != offer.issuer_id
                && self.key != offer.issuer_key
                && self.key != offer.anchor.owner_key,
            "invitation requires a separate joining identity"
        );
        ensure!(
            offer
                .owner_transitions
                .iter()
                .all(|t| t.transition.owner_key != self.key),
            "joining node cannot reuse an owner signing key"
        );
        if let Some(target) = &offer.replaces {
            ensure!(
                self.id != target.id && self.key != target.signing_key,
                "replacement invitation requires a fresh identity and key"
            );
        }
        Ok(())
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum Purpose {
    NewNode,
    NamedNode {
        name: String,
        inviter: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        continuation: Option<ClaimedNode>,
    },
    Continue {
        node: ClaimedNode,
    },
}

impl Purpose {
    pub fn continuation(&self) -> Option<&ClaimedNode> {
        match self {
            Self::Continue { node } => Some(node),
            Self::NamedNode { continuation, .. } => continuation.as_ref(),
            Self::NewNode => None,
        }
    }
}

pub struct Options {
    pub service: ServiceBinding,
    pub purpose: Purpose,
    pub can_configure: bool,
    pub replaces: Option<ReplacedNode>,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Offer {
    pub version: u8,
    pub id: String,
    pub anchor: TrustAnchor,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub owner_transitions: Vec<SignedOwnerTransition>,
    pub issuer_id: String,
    pub issuer_key: PublicKey,
    pub service: ServiceBinding,
    pub responder_key: [u8; 32],
    pub routing_digest: Digest,
    pub purpose: Purpose,
    pub can_configure: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub replaces: Option<ReplacedNode>,
    pub issued_at: u64,
    pub expires_at: u64,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SignedOffer {
    pub offer: Offer,
    pub signature: Vec<u8>,
}
impl SignedOffer {
    pub fn encode(&self) -> Result<Vec<u8>> {
        encode(self, MAX_OFFER_BYTES)
    }
    pub fn decode(bytes: &[u8]) -> Result<Self> {
        decode(bytes, MAX_OFFER_BYTES)
    }
    pub fn fingerprint(&self) -> Result<Digest> {
        self.verify_signature()?;
        digest(OFFER_DOMAIN, self, MAX_OFFER_BYTES)
    }
    fn verify_signature(&self) -> Result<()> {
        let offer = &self.offer;
        ensure!(
            matches!(offer.version, 1 | 2),
            "unsupported invitation version"
        );
        id(&offer.id)?;
        ensure!(
            gent_protocol::service::invitations::issued_at(&offer.id) == Some(offer.issued_at),
            "invitation ID does not match issue time"
        );
        id(&offer.anchor.cluster_id)?;
        id(&offer.issuer_id)?;
        public_key(&offer.anchor.owner_key)?;
        public_key(&offer.issuer_key)?;
        let owner = verify_lineage(&offer.anchor, &offer.owner_transitions)?;
        ensure!(
            offer
                .owner_transitions
                .last()
                .is_none_or(|t| t.transition.issued_at <= offer.issued_at),
            "invitation precedes owner activation"
        );
        ensure!(
            offer.issuer_key != offer.anchor.owner_key
                && !succession::owner_keys(&offer.owner_transitions, owner)
                    .contains(&offer.issuer_key)
                && offer.anchor.genesis_hash != [0; 32]
                && offer.routing_digest != [0; 32]
                && offer.issued_at > 0,
            "invalid invitation authority or binding"
        );
        channel::validate_public_key(&offer.responder_key)?;
        offer.service.validate()?;
        if let Some(target) = &offer.replaces {
            id(&target.id)?;
            public_key(&target.signing_key)?;
            ensure!(
                target.id != offer.issuer_id
                    && target.signing_key != offer.issuer_key
                    && target.signing_key != offer.anchor.owner_key,
                "invitation cannot replace the signing owner"
            );
        }
        if let Some(node) = offer.purpose.continuation() {
            node.validate(offer)?;
        }
        if let Purpose::NamedNode { name, inviter, .. } = &offer.purpose {
            label(name)?;
            id(inviter)?;
            ensure!(
                offer.replaces.is_none(),
                "named invitation cannot replace a node"
            );
        }
        lifetime(offer.issued_at, offer.expires_at, OFFER_LIFETIME)?;
        verify(
            if offer.version == 1 {
                &owner
            } else {
                &offer.issuer_key
            },
            OFFER_DOMAIN,
            offer,
            &self.signature,
            MAX_OFFER_BYTES,
        )
    }
    /// Authenticate the offer and its deadline. Admission must also compare the
    /// current owner epoch through verify_current and check service revocation.
    pub fn verify(&self, anchor: &TrustAnchor, now: u64) -> Result<()> {
        ensure!(&self.offer.anchor == anchor, "invitation authority changed");
        self.verify_signature()?;
        fresh(self.offer.issued_at, self.offer.expires_at, now)
    }

    pub fn verify_current(&self, state: &VerifiedState, now: u64) -> Result<()> {
        self.verify(state.anchor(), now)?;
        if self.offer.version == 2 || state.state().peer.is_some() {
            ensure!(
                state.state().peer.is_some()
                    && state
                        .state()
                        .nodes
                        .get(&self.offer.issuer_id)
                        .is_some_and(|n| n.can_configure),
                "invitation issuer cannot administer this cluster"
            );
        }
        ensure!(
            self.offer.owner_transitions == state.state().owner_transitions,
            "invitation is from another owner epoch"
        );
        state.authorize_node(&self.offer.issuer_id, &self.offer.issuer_key, now)?;
        if let Purpose::NamedNode { inviter, .. } = &self.offer.purpose {
            let node = state
                .state()
                .nodes
                .get(inviter)
                .context("inviting node is no longer enrolled")?;
            state.authorize_node(inviter, &node.signing_key, now)?;
            ensure!(
                inviter == &self.offer.issuer_id || node.can_configure,
                "inviting node no longer has configuration authority"
            );
        }
        Ok(())
    }
}

/// Deliberately no Debug, Clone, or Serialize. Export only to a protected file.
pub struct Invitation {
    offer: SignedOffer,
    psk: Zeroizing<[u8; 32]>,
    routing: Zeroizing<[u8; 32]>,
}
impl Invitation {
    pub fn offer(&self) -> &SignedOffer {
        &self.offer
    }
    pub fn expose_routing_secret(&self) -> Zeroizing<[u8; 32]> {
        Zeroizing::new(*self.routing)
    }
    pub fn encode(&self) -> Result<Zeroizing<Vec<u8>>> {
        secret_encode(&self.wire())
    }
    /// Checks the signed offer and routing binding. Protected delivery supplies
    /// provenance; the handshake separately checks the PSK and current expiry.
    pub fn decode(bytes: &[u8]) -> Result<Self> {
        let wire: WireInvitation = secret_decode(bytes)?;
        Self::from_wire(&wire)
    }
    fn from_wire(wire: &WireInvitation) -> Result<Self> {
        wire.offer.verify_signature()?;
        ensure!(
            <[u8; 32]>::from(Sha256::digest(wire.routing)) == wire.offer.offer.routing_digest,
            "invitation routing secret does not match offer"
        );
        Ok(Self {
            offer: wire.offer.clone(),
            psk: Zeroizing::new(wire.psk),
            routing: Zeroizing::new(wire.routing),
        })
    }
    fn wire(&self) -> WireInvitation {
        WireInvitation {
            offer: self.offer.clone(),
            psk: *self.psk,
            routing: *self.routing,
        }
    }
}

/// Persist locally before publishing the offer. Never export this owner record
/// as the joining file; only `invitation().encode()` belongs on the new machine.
pub struct OwnerInvitation {
    invitation: Invitation,
    private: Zeroizing<[u8; 32]>,
}
impl OwnerInvitation {
    pub fn issue(
        owner: &OwnerKey,
        state: &VerifiedState,
        issuer: &NodeIdentity,
        options: Options,
        now: u64,
    ) -> Result<Self> {
        ensure!(
            owner.public_key() == state.state().owner_key,
            "wrong invitation owner"
        );
        ensure!(
            state.state().peer.is_none(),
            "legacy invitation signing is fenced"
        );
        Self::issue_with(&owner.0, 1, state, issuer, options, now)
    }

    pub fn issue_peer(
        state: &VerifiedState,
        issuer: &NodeIdentity,
        options: Options,
        now: u64,
    ) -> Result<Self> {
        ensure!(
            state.state().peer.is_some()
                && state
                    .state()
                    .nodes
                    .get(issuer.id())
                    .is_some_and(|n| n.can_configure),
            "node cannot issue invitations"
        );
        Self::issue_with(&issuer.key, 2, state, issuer, options, now)
    }

    fn issue_with(
        key: &SigningKey,
        version: u8,
        state: &VerifiedState,
        issuer: &NodeIdentity,
        options: Options,
        now: u64,
    ) -> Result<Self> {
        state.authorize_node(issuer.id(), &issuer.public_key(), now)?;
        if let Some(node) = options.purpose.continuation() {
            state.authorize_node(&node.id, &node.key, now)?;
            let member = &state.state().nodes[&node.id];
            ensure!(
                node.name == member.name && options.can_configure == member.can_configure,
                "continuation must preserve the existing node and privileges"
            );
        }
        if let Some(target) = &options.replaces {
            match options.purpose.continuation() {
                None => {
                    let member = state
                        .state()
                        .nodes
                        .get(&target.id)
                        .context("replacement target is unavailable")?;
                    ensure!(
                        member.signing_key == target.signing_key
                            && (!options.can_configure || member.can_configure),
                        "replacement target key or configuration privileges changed"
                    );
                }
                Some(_) => ensure!(
                    !state.state().nodes.contains_key(&target.id)
                        && state.state().retired_nodes.contains(&target.id)
                        && state.state().retired_keys.contains(&target.signing_key),
                    "replacement continuation requires signed retirement"
                ),
            }
        }
        let private = random_secret()?;
        let routing = random_secret()?;
        let psk = random_secret()?;
        let offer = Offer {
            version,
            id: Uuid::new_v7(uuid::Timestamp::from_unix(uuid::NoContext, now, 0)).to_string(),
            anchor: state.anchor().clone(),
            owner_transitions: state.state().owner_transitions.clone(),
            issuer_id: issuer.id().into(),
            issuer_key: issuer.public_key(),
            service: options.service,
            responder_key: channel::public_key(&private),
            routing_digest: Sha256::digest(routing.as_ref()).into(),
            purpose: options.purpose,
            can_configure: options.can_configure,
            replaces: options.replaces,
            issued_at: now,
            expires_at: now
                .checked_add(OFFER_LIFETIME)
                .context("invitation timestamp overflow")?,
        };
        let signature = key
            .sign(&signing_input(OFFER_DOMAIN, &offer, MAX_OFFER_BYTES)?)
            .to_bytes()
            .to_vec();
        let signed = SignedOffer { offer, signature };
        signed.verify(state.anchor(), now)?;
        Ok(Self {
            invitation: Invitation {
                offer: signed,
                psk,
                routing,
            },
            private,
        })
    }
    pub fn invitation(&self) -> &Invitation {
        &self.invitation
    }
    pub fn encode(&self) -> Result<Zeroizing<Vec<u8>>> {
        secret_encode(&WireOwner {
            invitation: self.invitation.wire(),
            private: *self.private,
        })
    }
    pub fn decode(bytes: &[u8]) -> Result<Self> {
        let wire: WireOwner = secret_decode(bytes)?;
        let invitation = Invitation::from_wire(&wire.invitation)?;
        ensure!(
            channel::public_key(&wire.private) == invitation.offer.offer.responder_key,
            "owner invitation key does not match offer"
        );
        Ok(Self {
            invitation,
            private: Zeroizing::new(wire.private),
        })
    }
}

fn random_secret() -> Result<Zeroizing<[u8; 32]>> {
    let mut secret = Zeroizing::new([0; 32]);
    getrandom::fill(secret.as_mut())?;
    Ok(secret)
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct WireInvitation {
    offer: SignedOffer,
    psk: [u8; 32],
    routing: [u8; 32],
}
impl Drop for WireInvitation {
    fn drop(&mut self) {
        self.psk.zeroize();
        self.routing.zeroize();
    }
}
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct WireOwner {
    invitation: WireInvitation,
    private: [u8; 32],
}
impl Drop for WireOwner {
    fn drop(&mut self) {
        self.private.zeroize();
    }
}
fn secret_encode(value: &impl Serialize) -> Result<Zeroizing<Vec<u8>>> {
    let bytes = Zeroizing::new(serde_jcs::to_vec(value)?);
    ensure!(
        bytes.len() <= MAX_INVITATION_BYTES,
        "invitation file too large"
    );
    Ok(bytes)
}
fn secret_decode<T: Serialize + DeserializeOwned>(bytes: &[u8]) -> Result<T> {
    ensure!(
        bytes.len() <= MAX_INVITATION_BYTES,
        "invitation file too large"
    );
    let value: T =
        serde_json::from_slice(bytes).map_err(|_| anyhow::anyhow!("invalid invitation file"))?;
    ensure!(
        *secret_encode(&value)? == bytes,
        "invitation file must use canonical JSON"
    );
    Ok(value)
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Claim {
    version: u8,
    invitation: String,
    offer: Digest,
    handshake: Digest,
    node: ClaimedNode,
    issued_at: u64,
    expires_at: u64,
}
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct SignedClaim {
    claim: Claim,
    signature: Vec<u8>,
}
impl SignedClaim {
    fn create(
        offer: &SignedOffer,
        handshake: Digest,
        node: &NodeIdentity,
        name: &str,
        now: u64,
    ) -> Result<Self> {
        let claim = Claim {
            version: 1,
            invitation: offer.offer.id.clone(),
            offer: offer.fingerprint()?,
            handshake,
            node: ClaimedNode {
                id: node.id().into(),
                key: node.public_key(),
                name: name.into(),
            },
            issued_at: now,
            expires_at: now
                .checked_add(60)
                .context("claim timestamp overflow")?
                .min(offer.offer.expires_at),
        };
        let signature = node
            .key
            .sign(&signing_input(CLAIM_DOMAIN, &claim, MAX_REQUEST_BYTES)?)
            .to_bytes()
            .to_vec();
        let signed = Self { claim, signature };
        signed.verify(offer, handshake, now)?;
        Ok(signed)
    }
    fn verify(&self, offer: &SignedOffer, handshake: Digest, now: u64) -> Result<()> {
        offer.verify(&offer.offer.anchor, now)?;
        let claim = &self.claim;
        ensure!(
            claim.version == 1
                && claim.invitation == offer.offer.id
                && claim.offer == offer.fingerprint()?
                && claim.handshake == handshake
                && claim.issued_at >= offer.offer.issued_at
                && claim.expires_at <= offer.offer.expires_at,
            "invitation claim binding mismatch"
        );
        claim.node.validate(&offer.offer)?;
        if let Some(node) = offer.offer.purpose.continuation() {
            ensure!(
                &claim.node == node,
                "continuation requires the original node"
            );
        }
        lifetime(claim.issued_at, claim.expires_at, 60)?;
        fresh(claim.issued_at, claim.expires_at, now)?;
        verify(
            &claim.node.key,
            CLAIM_DOMAIN,
            claim,
            &self.signature,
            MAX_REQUEST_BYTES,
        )
    }
}