Skip to main content

gent_crypto/
authority.rs

1use anyhow::{Context, Result, ensure};
2use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
3use gent_protocol::administration::MAX_ADMIN_GRANT_LIFETIME;
4use gent_protocol::{MAX_RELAY_GRANT_LIFETIME, Policy, Selector};
5use serde::{Deserialize, Serialize, de::DeserializeOwned};
6use sha2::{Digest as _, Sha256};
7use std::collections::{BTreeMap, BTreeSet};
8use zeroize::Zeroizing;
9mod agents;
10mod helper;
11mod hosting;
12#[cfg(feature = "invitation")]
13mod noise;
14pub mod peer;
15pub use agents::*;
16pub use helper::verify_helper_channel;
17#[cfg(feature = "invitation")]
18pub mod invitation;
19pub mod recovery;
20pub mod succession;
21use succession::{MAX_OWNER_CHAIN_BYTES, SignedOwnerTransition, verify_lineage};
22
23pub type Digest = [u8; 32];
24pub type PublicKey = [u8; 32];
25pub const MAX_STATE_BYTES: usize = 2 * 1024 * 1024;
26pub const MAX_REQUEST_BYTES: usize = 4096;
27pub const MAX_STATE_LIFETIME: u64 = 24 * 60 * 60;
28pub const REQUEST_LIFETIME: u64 = 15 * 60;
29pub const MAX_CHAIN_LENGTH: usize = 1024;
30pub const MAX_CHAIN_BYTES: usize = 16 * 1024 * 1024;
31const MAX_SAFE_INTEGER: u64 = (1 << 53) - 1;
32const STATE_DOMAIN: &[u8] = b"gent/cluster-state/v1\0";
33const REQUEST_DOMAIN: &[u8] = b"gent/enrollment-request/v1\0";
34const CONFIGURATION_DOMAIN: &[u8] = b"gent/configuration-grant/v1\0";
35const MAX_CONFIGURATION_GRANT_BYTES: usize = MAX_OWNER_CHAIN_BYTES + 8192;
36
37/// Owner signing authority, distinct from the local owner RPC credential and node keys.
38/// Deliberately has no Debug or Serialize implementation.
39pub struct OwnerKey(SigningKey);
40
41/// A node's signing identity. Encryption keys will belong to the selected session protocol.
42/// Deliberately has no Debug or Serialize implementation.
43pub struct NodeIdentity {
44    id: String,
45    key: SigningKey,
46}
47
48// MLS supplies its standard domain-separated signing inputs. Keep the secret
49// inside the identity instead of exporting another copy to an MLS credential.
50#[cfg(feature = "mls")]
51impl openmls_traits::signatures::Signer for NodeIdentity {
52    fn sign(&self, payload: &[u8]) -> Result<Vec<u8>, openmls_traits::signatures::SignerError> {
53        Ok(self.key.sign(payload).to_bytes().to_vec())
54    }
55
56    fn signature_scheme(&self) -> openmls_traits::types::SignatureScheme {
57        openmls_traits::types::SignatureScheme::ED25519
58    }
59}
60
61#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
62#[serde(deny_unknown_fields)]
63pub struct NodeMember {
64    pub name: String,
65    pub signing_key: PublicKey,
66    /// Owner-approved configuration editing, independent of node membership.
67    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
68    pub can_configure: bool,
69    /// Signed delegation of chat transport only; configuration authority is unchanged.
70    #[serde(default, skip_serializing_if = "Option::is_none")]
71    pub hosted_by: Option<String>,
72}
73
74#[derive(Clone, Debug, Serialize, Deserialize)]
75#[serde(deny_unknown_fields)]
76pub struct ClusterState {
77    pub version: u32,
78    #[serde(default, skip_serializing_if = "Option::is_none")]
79    pub peer: Option<peer::Authority>,
80    pub cluster_id: String,
81    pub name: String,
82    pub owner_key: PublicKey,
83    #[serde(default, skip_serializing_if = "Vec::is_empty")]
84    pub owner_transitions: Vec<SignedOwnerTransition>,
85    pub revision: u64,
86    pub previous: Option<Digest>,
87    pub issued_at: u64,
88    pub expires_at: u64,
89    pub nodes: BTreeMap<String, NodeMember>,
90    pub retired_nodes: BTreeSet<String>,
91    pub retired_keys: BTreeSet<PublicKey>,
92    #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
93    pub retired_relay_grants: BTreeSet<String>,
94    #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
95    pub retired_admin_grants: BTreeSet<String>,
96    /// Omit stable to preserve pre-channel signatures and checkpoint digests.
97    #[serde(
98        default,
99        skip_serializing_if = "gent_protocol::ReleaseChannel::is_stable"
100    )]
101    pub release_channel: gent_protocol::ReleaseChannel,
102    pub policy: Policy,
103}
104
105#[derive(Clone, Debug, Serialize, Deserialize)]
106#[serde(deny_unknown_fields)]
107pub struct SignedState {
108    pub state: ClusterState,
109    pub signature: Vec<u8>,
110}
111
112/// Pin this through an already trusted endpoint, never from an unverified directory.
113#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
114#[serde(deny_unknown_fields)]
115pub struct TrustAnchor {
116    pub cluster_id: String,
117    pub owner_key: PublicKey,
118    pub genesis_hash: Digest,
119}
120
121/// Persist with the accepted signed state before exposing any new authorization.
122#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
123#[serde(deny_unknown_fields)]
124pub struct Checkpoint {
125    pub revision: u64,
126    pub state_hash: Digest,
127}
128
129#[derive(Clone, Debug, Serialize, Deserialize)]
130#[serde(deny_unknown_fields)]
131pub struct EnrollmentRequest {
132    pub version: u32,
133    pub anchor: TrustAnchor,
134    pub base: Checkpoint,
135    pub node_id: String,
136    pub member: NodeMember,
137    #[serde(default, skip_serializing_if = "Option::is_none")]
138    pub replaces: Option<ReplacedNode>,
139    pub nonce: String,
140    pub issued_at: u64,
141    pub expires_at: u64,
142}
143
144/// Public identity of a lost joined node, pinned through the owner channel.
145#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
146#[serde(deny_unknown_fields)]
147pub struct ReplacedNode {
148    pub id: String,
149    pub signing_key: PublicKey,
150}
151
152#[derive(Clone, Debug, Serialize, Deserialize)]
153#[serde(deny_unknown_fields)]
154pub struct SignedEnrollment {
155    pub request: EnrollmentRequest,
156    pub signature: Vec<u8>,
157}
158
159/// Owner authorization for a private, two-node configuration distribution stream.
160/// The grant itself contains private metadata and needs protected pairing transport.
161#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
162#[serde(deny_unknown_fields)]
163pub struct ConfigurationGrant {
164    pub version: u32,
165    pub anchor: TrustAnchor,
166    #[serde(default, skip_serializing_if = "Vec::is_empty")]
167    pub owner_transitions: Vec<SignedOwnerTransition>,
168    pub base: Checkpoint,
169    pub group: Vec<u8>,
170    pub origin: Digest,
171    pub writer: String,
172    pub writer_key: PublicKey,
173    pub reader: String,
174    pub reader_key: PublicKey,
175    /// A prepared successor stream may publish only after this exact candidate
176    /// is selected at `base`. Absent on ordinary, immediately usable streams.
177    #[serde(default, skip_serializing_if = "Option::is_none")]
178    pub owner_candidate: Option<Digest>,
179}
180
181#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
182#[serde(deny_unknown_fields)]
183pub struct SignedConfigurationGrant {
184    pub grant: ConfigurationGrant,
185    pub signature: Vec<u8>,
186}
187
188impl SignedConfigurationGrant {
189    pub fn encode(&self) -> Result<Vec<u8>> {
190        encode(self, MAX_CONFIGURATION_GRANT_BYTES)
191    }
192    pub fn decode(bytes: &[u8]) -> Result<Self> {
193        decode(bytes, MAX_CONFIGURATION_GRANT_BYTES)
194    }
195
196    /// Does not grant messaging authority or require an unexpired lease. The
197    /// receiver must also enforce the grant's saved stream and node-key bindings.
198    pub fn verify(&self, anchor: &TrustAnchor) -> Result<()> {
199        let grant = &self.grant;
200        let owner = verify_lineage(anchor, &grant.owner_transitions)?;
201        ensure!(
202            grant.version == 1 && &grant.anchor == anchor,
203            "wrong configuration grant authority"
204        );
205        id(&grant.writer)?;
206        id(&grant.reader)?;
207        public_key(&grant.writer_key)?;
208        public_key(&grant.reader_key)?;
209        ensure!(
210            grant.writer != grant.reader
211                && grant.writer_key != grant.reader_key
212                && grant.writer_key != anchor.owner_key
213                && grant.reader_key != anchor.owner_key
214                && grant.writer_key != owner
215                && grant.reader_key != owner,
216            "configuration grant requires two distinct node identities"
217        );
218        ensure!(
219            !grant.group.is_empty()
220                && grant.group.len() <= 256
221                && grant.origin != [0; 32]
222                && grant.owner_candidate != Some([0; 32])
223                && grant.base.revision <= MAX_SAFE_INTEGER,
224            "invalid configuration stream binding"
225        );
226        ensure!(
227            grant
228                .owner_transitions
229                .last()
230                .is_none_or(|t| t.transition.base.revision < grant.base.revision),
231            "configuration grant precedes owner activation"
232        );
233        verify(
234            &owner,
235            CONFIGURATION_DOMAIN,
236            grant,
237            &self.signature,
238            MAX_CONFIGURATION_GRANT_BYTES,
239        )
240    }
241
242    /// Enrollment of this exception requires the exact fresh approved checkpoint.
243    pub fn verify_initial(&self, state: &VerifiedState, now: u64) -> Result<()> {
244        self.verify(state.anchor())?;
245        ensure!(
246            self.grant.owner_transitions == state.state().owner_transitions,
247            "configuration grant is from another owner epoch"
248        );
249        ensure!(
250            &self.grant.base == state.checkpoint(),
251            "configuration grant has a stale base"
252        );
253        state.authorize_node(&self.grant.writer, &self.grant.writer_key, now)?;
254        state.authorize_node(&self.grant.reader, &self.grant.reader_key, now)?;
255        Ok(())
256    }
257
258    /// Check the pins of a candidate already verified against its initial state.
259    /// This alone does not authorize a new candidate or activate an owner.
260    pub fn verify_owner_candidate(
261        &self,
262        candidate: &succession::SignedOwnerCandidate,
263    ) -> Result<()> {
264        self.verify(&candidate.candidate.anchor)?;
265        ensure!(
266            self.grant.owner_candidate == Some(candidate.digest()?)
267                && self.grant.base == candidate.candidate.base
268                && self.grant.writer == candidate.candidate.node.id
269                && self.grant.writer_key == candidate.candidate.node.signing_key,
270            "configuration grant belongs to another owner candidate"
271        );
272        Ok(())
273    }
274
275    /// Standby streams wait for their exact handoff. Later accepted epochs may
276    /// still distribute retained history through an established stream.
277    pub fn can_publish(&self, state: &VerifiedState) -> Result<bool> {
278        self.verify(state.anchor())?;
279        let Some(candidate) = self.grant.owner_candidate else {
280            return Ok(true);
281        };
282        let chain = &state.state().owner_transitions;
283        let preceding = &self.grant.owner_transitions;
284        Ok(chain.starts_with(preceding)
285            && chain.get(preceding.len()).is_some_and(|signed| {
286                let transition = &signed.transition;
287                transition.base == self.grant.base
288                    && transition.successor.as_ref().is_some_and(|s| {
289                        s.candidate == candidate
290                            && s.node.id == self.grant.writer
291                            && s.node.signing_key == self.grant.writer_key
292                    })
293            }))
294    }
295}
296
297/// A verified history prefix. Its fields cannot be mutated without validation.
298#[derive(Clone)]
299pub struct VerifiedState {
300    anchor: TrustAnchor,
301    signed: SignedState,
302    checkpoint: Checkpoint,
303}
304
305fn signing_key() -> Result<SigningKey> {
306    let mut secret = Zeroizing::new([0; 32]);
307    getrandom::fill(secret.as_mut())?;
308    Ok(SigningKey::from_bytes(&secret))
309}
310
311fn id(value: &str) -> Result<()> {
312    let parsed = uuid::Uuid::parse_str(value).context("invalid identity")?;
313    ensure!(
314        !parsed.is_nil() && parsed.to_string() == value,
315        "identity must be a canonical nonzero UUID"
316    );
317    Ok(())
318}
319
320fn label(value: &str) -> Result<()> {
321    ensure!(
322        !value.trim().is_empty() && value.len() <= 128 && !value.chars().any(char::is_control),
323        "invalid display label"
324    );
325    Ok(())
326}
327
328fn public_key(bytes: &PublicKey) -> Result<VerifyingKey> {
329    let key = VerifyingKey::from_bytes(bytes).context("invalid public key")?;
330    ensure!(!key.is_weak(), "weak public key");
331    Ok(key)
332}
333
334fn lifetime(issued: u64, expires: u64, maximum: u64) -> Result<()> {
335    ensure!(
336        expires <= MAX_SAFE_INTEGER && expires > issued && expires - issued <= maximum,
337        "invalid validity period"
338    );
339    Ok(())
340}
341
342fn fresh(issued: u64, expires: u64, now: u64) -> Result<()> {
343    ensure!(
344        issued <= now && now < expires,
345        "authorization is expired or not yet valid"
346    );
347    Ok(())
348}
349
350fn signing_input(domain: &[u8], value: &impl Serialize, limit: usize) -> Result<Vec<u8>> {
351    let canonical = serde_jcs::to_vec(value)?;
352    ensure!(canonical.len() <= limit, "signed record exceeds size limit");
353    let mut bytes = Vec::with_capacity(domain.len() + canonical.len());
354    bytes.extend_from_slice(domain);
355    bytes.extend_from_slice(&canonical);
356    Ok(bytes)
357}
358
359fn digest(domain: &[u8], value: &impl Serialize, limit: usize) -> Result<Digest> {
360    Ok(Sha256::digest(signing_input(domain, value, limit)?).into())
361}
362
363fn verify(
364    key: &PublicKey,
365    domain: &[u8],
366    value: &impl Serialize,
367    signature: &[u8],
368    limit: usize,
369) -> Result<()> {
370    public_key(key)?
371        .verify_strict(
372            &signing_input(domain, value, limit)?,
373            &Signature::try_from(signature)?,
374        )
375        .context("invalid signature")
376}
377
378fn encode(value: &impl Serialize, limit: usize) -> Result<Vec<u8>> {
379    let bytes = serde_jcs::to_vec(value)?;
380    ensure!(bytes.len() <= limit, "record exceeds size limit");
381    Ok(bytes)
382}
383
384fn decode<T: Serialize + DeserializeOwned>(bytes: &[u8], limit: usize) -> Result<T> {
385    ensure!(bytes.len() <= limit, "record exceeds size limit");
386    let value: T = serde_json::from_slice(bytes)?;
387    // Requiring canonical wire bytes also rejects duplicate map keys and ambiguous encodings.
388    ensure!(
389        serde_jcs::to_vec(&value)? == bytes,
390        "record must use canonical JSON"
391    );
392    Ok(value)
393}
394
395/// Shared validation for TOML proposals and owner-signed policy records.
396pub fn validate_policy(policy: &Policy) -> Result<()> {
397    ensure!(
398        policy.rules.len() <= 4096
399            && policy.groups.len() <= 256
400            && policy.relay_grants.len() <= 1024
401            && policy.admin_grants.len() + policy.group_admin_grants.len() <= 1024,
402        "policy exceeds limits"
403    );
404    for (name, members) in &policy.groups {
405        label(name)?;
406        ensure!(members.len() <= 4096, "group exceeds limits");
407        let mut distinct = BTreeSet::new();
408        for member in members {
409            id(member)?;
410            ensure!(distinct.insert(member), "duplicate group member");
411        }
412    }
413    for selector in policy
414        .rules
415        .iter()
416        .flat_map(|r| [&r.actor, &r.peer])
417        .chain(
418            policy
419                .admin_grants
420                .values()
421                .flat_map(|g| [&g.actor, &g.peer]),
422        )
423        .chain(policy.group_admin_grants.values().map(|g| &g.members))
424    {
425        match selector {
426            Selector::Agent(value) | Selector::Node(value) => id(value)?,
427            Selector::Group(name) => {
428                label(name)?;
429                ensure!(policy.groups.contains_key(name), "unknown policy group");
430            }
431            Selector::All | Selector::SameNode => {}
432        }
433    }
434    for (grant_id, grant) in &policy.relay_grants {
435        id(grant_id)?;
436        id(&grant.intermediary)?;
437        id(&grant.target)?;
438        ensure!(
439            grant.intermediary != grant.target,
440            "relay endpoints must differ"
441        );
442        lifetime(grant.issued_at, grant.expires_at, MAX_RELAY_GRANT_LIFETIME)?;
443    }
444    for (grant_id, grant) in &policy.admin_grants {
445        id(grant_id)?;
446        id(&grant.administrator)?;
447        ensure!(
448            !grant.permissions.is_empty() && grant.permissions.len() <= 3,
449            "invalid administration permissions"
450        );
451        for (i, permission) in grant.permissions.iter().enumerate() {
452            ensure!(
453                !grant.permissions[..i].contains(permission),
454                "duplicate administration permission"
455            );
456        }
457        lifetime(grant.issued_at, grant.expires_at, MAX_ADMIN_GRANT_LIFETIME)?;
458    }
459    for (grant_id, grant) in &policy.group_admin_grants {
460        id(grant_id)?;
461        id(&grant.administrator)?;
462        label(&grant.group)?;
463        ensure!(
464            !policy.admin_grants.contains_key(grant_id),
465            "duplicate administration grant ID"
466        );
467        ensure!(
468            policy.groups.contains_key(&grant.group),
469            "unknown administration group"
470        );
471        ensure!(
472            !grant.actions.is_empty() && grant.actions.len() <= 2,
473            "invalid group administration actions"
474        );
475        for (i, action) in grant.actions.iter().enumerate() {
476            ensure!(
477                !grant.actions[..i].contains(action),
478                "duplicate group administration action"
479            );
480        }
481        lifetime(grant.issued_at, grant.expires_at, MAX_ADMIN_GRANT_LIFETIME)?;
482    }
483    Ok(())
484}
485
486impl ClusterState {
487    fn validate(&self) -> Result<()> {
488        ensure!(
489            (self.version == 1 && self.owner_transitions.is_empty() && self.peer.is_none())
490                || (self.version == 2 && !self.owner_transitions.is_empty() && self.peer.is_none())
491                || (self.version == 3 && self.peer.is_some()),
492            "unsupported state version"
493        );
494        id(&self.cluster_id)?;
495        label(&self.name)?;
496        public_key(&self.owner_key)?;
497        if let Some(authority) = &self.peer {
498            authority.validate(self)?;
499        }
500        if let Some(successor) = self
501            .owner_transitions
502            .last()
503            .and_then(|t| t.transition.successor.as_ref())
504            .filter(|_| self.peer.is_none())
505        {
506            ensure!(
507                self.nodes.get(&successor.node.id).is_some_and(|n| {
508                    n.signing_key == successor.node.signing_key && n.hosted_by.is_none()
509                }),
510                "active owner node must remain enrolled and native until another handoff"
511            );
512        }
513        ensure!(
514            self.revision <= MAX_SAFE_INTEGER && (self.revision == 0) == self.previous.is_none(),
515            "invalid revision"
516        );
517        lifetime(self.issued_at, self.expires_at, MAX_STATE_LIFETIME)?;
518        ensure!(
519            !self.nodes.is_empty() && self.nodes.len() <= 1024,
520            "invalid node count"
521        );
522        ensure!(
523            self.retired_nodes.len() <= 8192
524                && self.retired_keys.len() <= 8192
525                && self.retired_relay_grants.len() <= 8192
526                && self.retired_admin_grants.len() <= 8192,
527            "retirement history exceeds limits"
528        );
529        let mut keys = BTreeSet::new();
530        let owner_keys = succession::owner_keys(&self.owner_transitions, self.owner_key);
531        ensure!(
532            owner_keys.is_disjoint(&self.retired_keys),
533            "retired node keys cannot be owner signing keys"
534        );
535        for (node_id, member) in &self.nodes {
536            id(node_id)?;
537            self.transport_host(node_id)?;
538            label(&member.name)?;
539            public_key(&member.signing_key)?;
540            ensure!(
541                !owner_keys.contains(&member.signing_key) && keys.insert(member.signing_key),
542                "node keys must be distinct from each other and owner authority"
543            );
544            ensure!(
545                !self.retired_nodes.contains(node_id)
546                    && !self.retired_keys.contains(&member.signing_key),
547                "retired identity cannot be reenrolled"
548            );
549        }
550        for retired in &self.retired_nodes {
551            id(retired)?;
552        }
553        for retired in &self.retired_keys {
554            public_key(retired)?;
555        }
556        for retired in &self.retired_relay_grants {
557            id(retired)?;
558            ensure!(
559                !self.policy.relay_grants.contains_key(retired),
560                "retired relay grant cannot be restored"
561            );
562        }
563        for grant in self.policy.relay_grants.values() {
564            ensure!(
565                grant.issued_at <= self.issued_at,
566                "relay grant issued after its configuration"
567            );
568        }
569        for retired in &self.retired_admin_grants {
570            id(retired)?;
571            ensure!(
572                !self.policy.admin_grants.contains_key(retired)
573                    && !self.policy.group_admin_grants.contains_key(retired),
574                "retired administration grant cannot be restored"
575            );
576        }
577        for grant in self.policy.admin_grants.values() {
578            ensure!(
579                grant.issued_at <= self.issued_at,
580                "administration grant issued after its configuration"
581            );
582        }
583        for grant in self.policy.group_admin_grants.values() {
584            ensure!(
585                grant.issued_at <= self.issued_at,
586                "administration grant issued after its configuration"
587            );
588        }
589        validate_policy(&self.policy)
590    }
591}
592
593impl OwnerKey {
594    pub fn authorize_configuration_stream(
595        &self,
596        state: &VerifiedState,
597        group: &[u8],
598        origin: Digest,
599        endpoints: (&str, &str),
600        now: u64,
601    ) -> Result<SignedConfigurationGrant> {
602        self.configuration_grant(state, group, origin, endpoints, None, now)
603    }
604
605    pub fn authorize_standby_configuration_stream(
606        &self,
607        state: &VerifiedState,
608        candidate: &succession::SignedOwnerCandidate,
609        group: &[u8],
610        origin: Digest,
611        reader: &str,
612        now: u64,
613    ) -> Result<SignedConfigurationGrant> {
614        candidate.verify(state, now)?;
615        self.configuration_grant(
616            state,
617            group,
618            origin,
619            (&candidate.candidate.node.id, reader),
620            Some(candidate.digest()?),
621            now,
622        )
623    }
624
625    fn configuration_grant(
626        &self,
627        state: &VerifiedState,
628        group: &[u8],
629        origin: Digest,
630        endpoints: (&str, &str),
631        owner_candidate: Option<Digest>,
632        now: u64,
633    ) -> Result<SignedConfigurationGrant> {
634        ensure!(
635            self.public_key() == state.state().owner_key,
636            "wrong owner authority"
637        );
638        state.require_fresh(now)?;
639        let (writer, reader) = endpoints;
640        let grant = ConfigurationGrant {
641            version: 1,
642            anchor: state.anchor().clone(),
643            owner_transitions: state.state().owner_transitions.clone(),
644            base: state.checkpoint().clone(),
645            group: group.into(),
646            origin,
647            writer: writer.into(),
648            writer_key: state
649                .state()
650                .nodes
651                .get(writer)
652                .context("unknown configuration writer")?
653                .signing_key,
654            reader: reader.into(),
655            reader_key: state
656                .state()
657                .nodes
658                .get(reader)
659                .context("unknown configuration reader")?
660                .signing_key,
661            owner_candidate,
662        };
663        let signature = self
664            .0
665            .sign(&signing_input(
666                CONFIGURATION_DOMAIN,
667                &grant,
668                MAX_CONFIGURATION_GRANT_BYTES,
669            )?)
670            .to_bytes()
671            .to_vec();
672        let signed = SignedConfigurationGrant { grant, signature };
673        signed.verify_initial(state, now)?;
674        signed.encode()?;
675        Ok(signed)
676    }
677
678    pub fn generate() -> Result<Self> {
679        Ok(Self(signing_key()?))
680    }
681
682    pub fn from_secret_bytes(bytes: &[u8; 32]) -> Self {
683        Self(SigningKey::from_bytes(bytes))
684    }
685
686    /// For protected endpoint storage only. Never pass the result to a chat or relay.
687    pub fn expose_secret(&self) -> Zeroizing<[u8; 32]> {
688        Zeroizing::new(*self.0.as_bytes())
689    }
690
691    pub fn public_key(&self) -> PublicKey {
692        self.0.verifying_key().to_bytes()
693    }
694
695    pub fn create_cluster(
696        &self,
697        name: &str,
698        first: &NodeIdentity,
699        node_name: &str,
700        now: u64,
701    ) -> Result<VerifiedState> {
702        self.create_cluster_with_id(
703            (&uuid::Uuid::new_v4().to_string(), name),
704            first,
705            node_name,
706            Policy::cluster_default(),
707            now,
708        )
709    }
710
711    /// Bootstrap a locally owned cluster while preserving an existing local ID.
712    /// This does not authorize replacing any previously pinned trust anchor.
713    pub fn create_cluster_with_id(
714        &self,
715        cluster: (&str, &str),
716        first: &NodeIdentity,
717        node_name: &str,
718        policy: Policy,
719        now: u64,
720    ) -> Result<VerifiedState> {
721        let state = ClusterState {
722            version: 1,
723            peer: None,
724            release_channel: Default::default(),
725            cluster_id: cluster.0.into(),
726            name: cluster.1.into(),
727            owner_key: self.public_key(),
728            owner_transitions: Vec::new(),
729            revision: 0,
730            previous: None,
731            issued_at: now,
732            expires_at: now
733                .checked_add(MAX_STATE_LIFETIME)
734                .context("timestamp overflow")?,
735            nodes: BTreeMap::from([(first.id.clone(), first.member(node_name)?)]),
736            retired_nodes: BTreeSet::new(),
737            retired_keys: BTreeSet::new(),
738            retired_relay_grants: BTreeSet::new(),
739            retired_admin_grants: BTreeSet::new(),
740            policy,
741        };
742        let signed = self.sign(state)?;
743        let anchor = TrustAnchor {
744            cluster_id: signed.state.cluster_id.clone(),
745            owner_key: self.public_key(),
746            genesis_hash: signed.digest()?,
747        };
748        VerifiedState::bootstrap(anchor, signed)
749    }
750
751    fn sign(&self, state: ClusterState) -> Result<SignedState> {
752        state.validate()?;
753        ensure!(
754            state.peer.is_none(),
755            "legacy signing is fenced by peer authority"
756        );
757        ensure!(
758            state.owner_key == self.public_key(),
759            "wrong owner authority"
760        );
761        let signature = self
762            .0
763            .sign(&signing_input(STATE_DOMAIN, &state, MAX_STATE_BYTES)?)
764            .to_bytes()
765            .to_vec();
766        let signed = SignedState { state, signature };
767        signed.encode()?;
768        Ok(signed)
769    }
770}
771
772impl NodeIdentity {
773    pub fn sign_stream_receipt(
774        &self,
775        group: &[u8],
776        sequence: u64,
777        digest: Digest,
778    ) -> Result<crate::stream::Receipt> {
779        let mut receipt = crate::stream::Receipt::unsigned(group, sequence, digest);
780        receipt.signature = self.key.sign(&receipt.signing_input()?).to_bytes().to_vec();
781        Ok(receipt)
782    }
783    /// Authenticate an opaque packet and its position in a directional stream.
784    pub fn sign_stream_packet(
785        &self,
786        group: &[u8],
787        sequence: u64,
788        previous: Digest,
789        ciphertext: &[u8],
790    ) -> Result<crate::stream::Packet> {
791        let mut packet = crate::stream::Packet::unsigned(group, sequence, previous, ciphertext);
792        packet.signature = self.key.sign(&packet.signing_input()?).to_bytes().to_vec();
793        Ok(packet)
794    }
795
796    pub fn generate() -> Result<Self> {
797        Ok(Self {
798            id: uuid::Uuid::new_v4().to_string(),
799            key: signing_key()?,
800        })
801    }
802
803    pub fn from_secret_bytes(node_id: &str, bytes: &[u8; 32]) -> Result<Self> {
804        id(node_id)?;
805        Ok(Self {
806            id: node_id.into(),
807            key: SigningKey::from_bytes(bytes),
808        })
809    }
810
811    /// Generate replacement signing material while retaining the stable node ID.
812    pub fn replacement(&self) -> Result<Self> {
813        Ok(Self {
814            id: self.id.clone(),
815            key: signing_key()?,
816        })
817    }
818
819    /// For protected endpoint storage only. Never pass the result to a chat or relay.
820    pub fn expose_secret(&self) -> Zeroizing<[u8; 32]> {
821        Zeroizing::new(*self.key.as_bytes())
822    }
823
824    pub fn id(&self) -> &str {
825        &self.id
826    }
827
828    pub fn public_key(&self) -> PublicKey {
829        self.key.verifying_key().to_bytes()
830    }
831
832    fn member(&self, name: &str) -> Result<NodeMember> {
833        label(name)?;
834        Ok(NodeMember {
835            name: name.into(),
836            signing_key: self.public_key(),
837            can_configure: false,
838            hosted_by: None,
839        })
840    }
841
842    /// The anchor and checkpoint must be obtained through the trusted pairing flow.
843    pub fn request_enrollment(
844        &self,
845        anchor: &TrustAnchor,
846        base: &Checkpoint,
847        name: &str,
848        now: u64,
849    ) -> Result<SignedEnrollment> {
850        self.enrollment_request(anchor, base, name, None, now)
851    }
852
853    pub fn request_replacement(
854        &self,
855        anchor: &TrustAnchor,
856        base: &Checkpoint,
857        name: &str,
858        replaces: ReplacedNode,
859        now: u64,
860    ) -> Result<SignedEnrollment> {
861        self.enrollment_request(anchor, base, name, Some(replaces), now)
862    }
863
864    fn enrollment_request(
865        &self,
866        anchor: &TrustAnchor,
867        base: &Checkpoint,
868        name: &str,
869        replaces: Option<ReplacedNode>,
870        now: u64,
871    ) -> Result<SignedEnrollment> {
872        let request = EnrollmentRequest {
873            version: 1,
874            anchor: anchor.clone(),
875            base: base.clone(),
876            node_id: self.id.clone(),
877            member: self.member(name)?,
878            replaces,
879            nonce: uuid::Uuid::new_v4().to_string(),
880            issued_at: now,
881            expires_at: now
882                .checked_add(REQUEST_LIFETIME)
883                .context("timestamp overflow")?,
884        };
885        request.validate()?;
886        let signature = self
887            .key
888            .sign(&signing_input(REQUEST_DOMAIN, &request, MAX_REQUEST_BYTES)?)
889            .to_bytes()
890            .to_vec();
891        let signed = SignedEnrollment { request, signature };
892        signed.encode()?;
893        Ok(signed)
894    }
895}
896
897impl EnrollmentRequest {
898    fn validate(&self) -> Result<()> {
899        ensure!(self.version == 1, "unsupported request version");
900        id(&self.anchor.cluster_id)?;
901        id(&self.node_id)?;
902        id(&self.nonce)?;
903        label(&self.member.name)?;
904        ensure!(
905            !self.member.can_configure,
906            "enrollment cannot self-grant administration"
907        );
908        ensure!(
909            self.member.hosted_by.is_none(),
910            "hosting requires a separate configuration edit"
911        );
912        public_key(&self.anchor.owner_key)?;
913        public_key(&self.member.signing_key)?;
914        if let Some(replaces) = &self.replaces {
915            id(&replaces.id)?;
916            public_key(&replaces.signing_key)?;
917            ensure!(
918                replaces.id != self.node_id && replaces.signing_key != self.member.signing_key,
919                "replacement requires a fresh node identity and key"
920            );
921        }
922        ensure!(
923            self.member.signing_key != self.anchor.owner_key,
924            "node cannot use owner signing key"
925        );
926        ensure!(
927            self.base.revision <= MAX_SAFE_INTEGER,
928            "invalid base revision"
929        );
930        lifetime(self.issued_at, self.expires_at, REQUEST_LIFETIME)
931    }
932}
933
934impl SignedEnrollment {
935    pub fn encode(&self) -> Result<Vec<u8>> {
936        encode(self, MAX_REQUEST_BYTES)
937    }
938    pub fn decode(bytes: &[u8]) -> Result<Self> {
939        decode(bytes, MAX_REQUEST_BYTES)
940    }
941
942    /// Compare all 32 bytes via a channel independent of the untrusted relay.
943    pub fn fingerprint(&self) -> Result<Digest> {
944        self.request.validate()?;
945        verify(
946            &self.request.member.signing_key,
947            REQUEST_DOMAIN,
948            &self.request,
949            &self.signature,
950            MAX_REQUEST_BYTES,
951        )?;
952        digest(REQUEST_DOMAIN, &self.request, MAX_REQUEST_BYTES)
953    }
954}
955
956impl SignedState {
957    /// Verify one record, without authorizing it or establishing history continuity.
958    /// Apply through VerifiedState before changing live authority.
959    pub fn verified_checkpoint(&self, anchor: &TrustAnchor) -> Result<Checkpoint> {
960        self.verify(anchor)
961    }
962
963    pub fn encode(&self) -> Result<Vec<u8>> {
964        encode(self, MAX_STATE_BYTES)
965    }
966    pub fn decode(bytes: &[u8]) -> Result<Self> {
967        decode(bytes, MAX_STATE_BYTES)
968    }
969
970    fn digest(&self) -> Result<Digest> {
971        digest(STATE_DOMAIN, &self.state, MAX_STATE_BYTES)
972    }
973
974    fn verify(&self, anchor: &TrustAnchor) -> Result<Checkpoint> {
975        self.state.validate()?;
976        let owner = verify_lineage(anchor, &self.state.owner_transitions)?;
977        ensure!(
978            self.state.cluster_id == anchor.cluster_id && self.state.owner_key == owner,
979            "state does not match pinned authority"
980        );
981        if let Some(last) = self.state.owner_transitions.last() {
982            let transition = &last.transition;
983            ensure!(
984                transition.base.revision < self.state.revision
985                    && transition.issued_at <= self.state.issued_at,
986                "state precedes owner activation"
987            );
988            if self.state.revision == transition.base.revision + 1 {
989                ensure!(
990                    self.state.previous == Some(transition.base.state_hash),
991                    "owner activation checkpoint mismatch"
992                );
993            }
994        }
995        let signer = self.state.peer.as_ref().map_or(owner, |peer| {
996            if peer.migration { owner } else { peer.signer }
997        });
998        verify(
999            &signer,
1000            STATE_DOMAIN,
1001            &self.state,
1002            &self.signature,
1003            MAX_STATE_BYTES,
1004        )?;
1005        self.encode()?;
1006        Ok(Checkpoint {
1007            revision: self.state.revision,
1008            state_hash: self.digest()?,
1009        })
1010    }
1011}
1012
1013impl VerifiedState {
1014    /// Bootstrap from the genesis whose digest and owner key were pinned independently.
1015    /// Expired state can be loaded for synchronization, but cannot authorize operations.
1016    pub fn bootstrap(anchor: TrustAnchor, genesis: SignedState) -> Result<Self> {
1017        let checkpoint = genesis.verify(&anchor)?;
1018        ensure!(
1019            checkpoint.revision == 0 && checkpoint.state_hash == anchor.genesis_hash,
1020            "genesis does not match trust anchor"
1021        );
1022        Ok(Self {
1023            anchor,
1024            signed: genesis,
1025            checkpoint,
1026        })
1027    }
1028
1029    /// Restore only the exact checkpoint held in trusted endpoint storage.
1030    pub fn restore(
1031        anchor: TrustAnchor,
1032        checkpoint: Checkpoint,
1033        signed: SignedState,
1034    ) -> Result<Self> {
1035        let actual = signed.verify(&anchor)?;
1036        ensure!(
1037            actual == checkpoint,
1038            "state does not match saved checkpoint"
1039        );
1040        if actual.revision == 0 {
1041            ensure!(actual.state_hash == anchor.genesis_hash, "genesis mismatch");
1042        }
1043        Ok(Self {
1044            anchor,
1045            signed,
1046            checkpoint,
1047        })
1048    }
1049
1050    pub fn anchor(&self) -> &TrustAnchor {
1051        &self.anchor
1052    }
1053    pub fn checkpoint(&self) -> &Checkpoint {
1054        &self.checkpoint
1055    }
1056    pub fn signed(&self) -> &SignedState {
1057        &self.signed
1058    }
1059    pub fn state(&self) -> &ClusterState {
1060        &self.signed.state
1061    }
1062
1063    pub fn require_fresh(&self, now: u64) -> Result<()> {
1064        fresh(self.state().issued_at, self.state().expires_at, now)
1065    }
1066
1067    /// Authorizes a node key, not chat discovery or messaging. Check chat policy separately.
1068    pub fn authorize_node(
1069        &self,
1070        node_id: &str,
1071        signing_key: &PublicKey,
1072        now: u64,
1073    ) -> Result<&NodeMember> {
1074        self.require_fresh(now)?;
1075        let member = self
1076            .state()
1077            .nodes
1078            .get(node_id)
1079            .context("node unavailable")?;
1080        ensure!(&member.signing_key == signing_key, "node unavailable");
1081        Ok(member)
1082    }
1083
1084    /// Validate a full contiguous update chain before changing any in-memory authority.
1085    /// Historical intermediate records may be expired; the final record must be fresh.
1086    pub fn apply_chain(&mut self, updates: &[SignedState], now: u64) -> Result<()> {
1087        ensure!(
1088            updates.iter().all(|s| s.state.peer.is_none()),
1089            "peer authority requires the committed configuration log"
1090        );
1091        let next = self.verify_chain(updates)?;
1092        next.require_fresh(now)?;
1093        *self = next;
1094        Ok(())
1095    }
1096
1097    /// Advance verified history in bounded batches while offline or catching up.
1098    /// This may leave expired state; authorize_node still requires fresh authority.
1099    pub fn advance_history(&mut self, updates: &[SignedState]) -> Result<()> {
1100        ensure!(
1101            updates.iter().all(|s| s.state.peer.is_none()),
1102            "peer authority requires the committed configuration log"
1103        );
1104        *self = self.verify_chain(updates)?;
1105        Ok(())
1106    }
1107
1108    fn verify_chain(&self, updates: &[SignedState]) -> Result<Self> {
1109        ensure!(
1110            !updates.is_empty() && updates.len() <= MAX_CHAIN_LENGTH,
1111            "invalid update chain length"
1112        );
1113        let mut next = self.clone();
1114        let mut total_bytes = 0;
1115        for update in updates {
1116            total_bytes += update.encode()?.len();
1117            ensure!(
1118                total_bytes <= MAX_CHAIN_BYTES,
1119                "update chain exceeds size limit"
1120            );
1121            let checkpoint = update.verify(&self.anchor)?;
1122            let previous = next.state();
1123            peer::verify_step(&next, update)?;
1124            succession::verify_step(&next, update)?;
1125            hosting::verify_step(previous, &update.state)?;
1126            ensure!(
1127                checkpoint.revision == next.checkpoint.revision + 1
1128                    && update.state.previous == Some(next.checkpoint.state_hash),
1129                "revision rollback, gap, or conflict"
1130            );
1131            ensure!(
1132                update.state.issued_at >= previous.issued_at,
1133                "revision time moved backwards"
1134            );
1135            ensure!(
1136                previous.retired_keys.is_subset(&update.state.retired_keys)
1137                    && previous
1138                        .retired_nodes
1139                        .is_subset(&update.state.retired_nodes)
1140                    && previous
1141                        .retired_relay_grants
1142                        .is_subset(&update.state.retired_relay_grants)
1143                    && previous
1144                        .retired_admin_grants
1145                        .is_subset(&update.state.retired_admin_grants),
1146                "retirement history cannot be removed"
1147            );
1148            for (node_id, member) in &previous.nodes {
1149                match update.state.nodes.get(node_id) {
1150                    None => ensure!(
1151                        update.state.retired_nodes.contains(node_id)
1152                            && update.state.retired_keys.contains(&member.signing_key),
1153                        "removed node requires retirement"
1154                    ),
1155                    Some(replacement) if replacement.signing_key != member.signing_key => ensure!(
1156                        update.state.retired_keys.contains(&member.signing_key),
1157                        "replaced key requires retirement"
1158                    ),
1159                    _ => {}
1160                }
1161            }
1162            for (id, grant) in &previous.policy.relay_grants {
1163                match update.state.policy.relay_grants.get(id) {
1164                    Some(next) => ensure!(next == grant, "relay grant identity is immutable"),
1165                    None => ensure!(
1166                        update.state.retired_relay_grants.contains(id),
1167                        "removed relay grant requires retirement"
1168                    ),
1169                }
1170            }
1171            for (id, grant) in &previous.policy.admin_grants {
1172                match update.state.policy.admin_grants.get(id) {
1173                    Some(next) => {
1174                        ensure!(next == grant, "administration grant identity is immutable")
1175                    }
1176                    None => ensure!(
1177                        update.state.retired_admin_grants.contains(id),
1178                        "removed administration grant requires retirement"
1179                    ),
1180                }
1181            }
1182            for (id, grant) in &previous.policy.group_admin_grants {
1183                match update.state.policy.group_admin_grants.get(id) {
1184                    Some(next) => ensure!(
1185                        next == grant,
1186                        "group administration grant identity is immutable"
1187                    ),
1188                    None => ensure!(
1189                        update.state.retired_admin_grants.contains(id),
1190                        "removed administration grant requires retirement"
1191                    ),
1192                }
1193            }
1194            next.signed = update.clone();
1195            next.checkpoint = checkpoint;
1196        }
1197        Ok(next)
1198    }
1199
1200    fn revise(
1201        &self,
1202        owner: &(impl peer::ConfigurationSigner + ?Sized),
1203        now: u64,
1204        edit: impl FnOnce(&mut ClusterState) -> Result<()>,
1205    ) -> Result<SignedState> {
1206        ensure!(
1207            now >= self.state().issued_at,
1208            "revision time moved backwards"
1209        );
1210        let mut state = self.state().clone();
1211        state.revision = state.revision.checked_add(1).context("revision overflow")?;
1212        state.previous = Some(self.checkpoint.state_hash);
1213        state.issued_at = now;
1214        state.expires_at = now
1215            .checked_add(MAX_STATE_LIFETIME)
1216            .context("timestamp overflow")?;
1217        edit(&mut state)?;
1218        for (id, grant) in &self.state().policy.relay_grants {
1219            match state.policy.relay_grants.get(id) {
1220                Some(next) => ensure!(next == grant, "relay grant identity is immutable"),
1221                None => {
1222                    state.retired_relay_grants.insert(id.clone());
1223                }
1224            }
1225        }
1226        for (id, grant) in &self.state().policy.admin_grants {
1227            match state.policy.admin_grants.get(id) {
1228                Some(next) => ensure!(next == grant, "administration grant identity is immutable"),
1229                None => {
1230                    state.retired_admin_grants.insert(id.clone());
1231                }
1232            }
1233        }
1234        for (id, grant) in &self.state().policy.group_admin_grants {
1235            match state.policy.group_admin_grants.get(id) {
1236                Some(next) => ensure!(
1237                    next == grant,
1238                    "group administration grant identity is immutable"
1239                ),
1240                None => {
1241                    state.retired_admin_grants.insert(id.clone());
1242                }
1243            }
1244        }
1245        owner.sign_revision(self, state)
1246    }
1247
1248    /// Renewal may repair an expired configuration using endpoint-held owner authority.
1249    pub fn renew(
1250        &self,
1251        owner: &(impl peer::ConfigurationSigner + ?Sized),
1252        now: u64,
1253    ) -> Result<SignedState> {
1254        self.revise(owner, now, |_| Ok(()))
1255    }
1256
1257    pub fn set_release_channel(
1258        &self,
1259        signer: &(impl peer::ConfigurationSigner + ?Sized),
1260        channel: gent_protocol::ReleaseChannel,
1261        now: u64,
1262    ) -> Result<SignedState> {
1263        self.revise(signer, now, |state| {
1264            state.release_channel = channel;
1265            Ok(())
1266        })
1267    }
1268
1269    pub fn set_policy(
1270        &self,
1271        owner: &(impl peer::ConfigurationSigner + ?Sized),
1272        policy: Policy,
1273        now: u64,
1274    ) -> Result<SignedState> {
1275        self.revise(owner, now, |state| {
1276            state.policy = policy;
1277            Ok(())
1278        })
1279    }
1280
1281    /// Apply an owner-authorized TOML edit as one ordered cluster revision.
1282    pub fn configure(
1283        &self,
1284        owner: &(impl peer::ConfigurationSigner + ?Sized),
1285        name: &str,
1286        node: (&str, &str),
1287        policy: Policy,
1288        now: u64,
1289    ) -> Result<SignedState> {
1290        self.revise(owner, now, |state| {
1291            state.name = name.into();
1292            state.nodes.get_mut(node.0).context("unknown node")?.name = node.1.into();
1293            state.policy = policy;
1294            Ok(())
1295        })
1296    }
1297
1298    pub fn rename_node(
1299        &self,
1300        signer: &(impl peer::ConfigurationSigner + ?Sized),
1301        node_id: &str,
1302        name: &str,
1303        now: u64,
1304    ) -> Result<SignedState> {
1305        self.revise(signer, now, |state| {
1306            state.nodes.get_mut(node_id).context("unknown node")?.name = name.into();
1307            Ok(())
1308        })
1309    }
1310
1311    /// `approved_fingerprint` must be independently confirmed by the owner; merely
1312    /// echoing a fingerprint supplied by the relay does not authenticate enrollment.
1313    pub fn enroll(
1314        &self,
1315        owner: &(impl peer::ConfigurationSigner + ?Sized),
1316        request: &SignedEnrollment,
1317        approved_fingerprint: Digest,
1318        now: u64,
1319    ) -> Result<SignedState> {
1320        self.accept_request(owner, request, approved_fingerprint, now, false, false)
1321    }
1322
1323    /// Explicit owner approval for a machine used to manage cluster configuration.
1324    pub fn enroll_configurator(
1325        &self,
1326        owner: &(impl peer::ConfigurationSigner + ?Sized),
1327        request: &SignedEnrollment,
1328        approved: Digest,
1329        now: u64,
1330    ) -> Result<SignedState> {
1331        self.accept_request(owner, request, approved, now, false, true)
1332    }
1333
1334    pub fn delegate_configuration(
1335        &self,
1336        owner: &(impl peer::ConfigurationSigner + ?Sized),
1337        node: &str,
1338        allow: bool,
1339        now: u64,
1340    ) -> Result<SignedState> {
1341        self.revise(owner, now, |state| {
1342            state
1343                .nodes
1344                .get_mut(node)
1345                .context("unknown node")?
1346                .can_configure = allow;
1347            Ok(())
1348        })
1349    }
1350
1351    pub fn rotate_node_key(
1352        &self,
1353        owner: &(impl peer::ConfigurationSigner + ?Sized),
1354        request: &SignedEnrollment,
1355        approved_fingerprint: Digest,
1356        now: u64,
1357    ) -> Result<SignedState> {
1358        self.accept_request(owner, request, approved_fingerprint, now, true, false)
1359    }
1360
1361    fn accept_request(
1362        &self,
1363        owner: &(impl peer::ConfigurationSigner + ?Sized),
1364        signed: &SignedEnrollment,
1365        approved: Digest,
1366        now: u64,
1367        rotation: bool,
1368        can_configure: bool,
1369    ) -> Result<SignedState> {
1370        ensure!(
1371            signed.request.replaces.is_none(),
1372            "replacement requires explicit owner approval"
1373        );
1374        self.require_fresh(now)?;
1375        ensure!(
1376            signed.fingerprint()? == approved,
1377            "enrollment fingerprint does not match owner approval"
1378        );
1379        let request = &signed.request;
1380        fresh(request.issued_at, request.expires_at, now)?;
1381        ensure!(
1382            request.anchor == self.anchor && request.base == self.checkpoint,
1383            "enrollment targets another cluster or stale revision"
1384        );
1385        self.revise(owner, now, |state| {
1386            match (rotation, state.nodes.get(&request.node_id)) {
1387                (true, Some(previous)) => {
1388                    ensure!(
1389                        previous.signing_key != request.member.signing_key,
1390                        "replacement key is unchanged"
1391                    );
1392                    state.retired_keys.insert(previous.signing_key);
1393                }
1394                (false, None) => {}
1395                _ => anyhow::bail!("node enrollment mode does not match membership"),
1396            }
1397            let mut member = request.member.clone();
1398            member.can_configure = if rotation {
1399                state.nodes[&request.node_id].can_configure
1400            } else {
1401                can_configure
1402            };
1403            if rotation {
1404                member
1405                    .hosted_by
1406                    .clone_from(&state.nodes[&request.node_id].hosted_by);
1407            }
1408            state.nodes.insert(request.node_id.clone(), member);
1409            Ok(())
1410        })
1411    }
1412
1413    pub fn revoke_node(
1414        &self,
1415        owner: &(impl peer::ConfigurationSigner + ?Sized),
1416        node_id: &str,
1417        now: u64,
1418    ) -> Result<SignedState> {
1419        self.revise(owner, now, |state| {
1420            state.require_no_hosted_children(node_id)?;
1421            let member = state.nodes.remove(node_id).context("node unavailable")?;
1422            state.retired_nodes.insert(node_id.into());
1423            state.retired_keys.insert(member.signing_key);
1424            Ok(())
1425        })
1426    }
1427
1428    /// Retire the pinned old identity and admit a fresh identity atomically.
1429    /// Endpoint code separately refuses replacing the active signing owner.
1430    pub fn replace_node(
1431        &self,
1432        owner: &(impl peer::ConfigurationSigner + ?Sized),
1433        signed: &SignedEnrollment,
1434        approved: Digest,
1435        can_configure: bool,
1436        now: u64,
1437    ) -> Result<SignedState> {
1438        self.require_fresh(now)?;
1439        ensure!(
1440            signed.fingerprint()? == approved,
1441            "replacement fingerprint does not match owner approval"
1442        );
1443        let request = &signed.request;
1444        fresh(request.issued_at, request.expires_at, now)?;
1445        ensure!(
1446            request.anchor == self.anchor && request.base == self.checkpoint,
1447            "replacement targets another cluster or stale revision"
1448        );
1449        let replaces = request
1450            .replaces
1451            .as_ref()
1452            .context("replacement target is missing")?;
1453        let previous = self
1454            .state()
1455            .nodes
1456            .get(&replaces.id)
1457            .context("replacement target is unavailable")?;
1458        ensure!(
1459            previous.signing_key == replaces.signing_key,
1460            "replacement target key changed"
1461        );
1462        ensure!(
1463            !self.state().nodes.contains_key(&request.node_id),
1464            "replacement identity is already enrolled"
1465        );
1466        let mut member = request.member.clone();
1467        member.can_configure = previous.can_configure && can_configure;
1468        member.hosted_by.clone_from(&previous.hosted_by);
1469        self.revise(owner, now, |state| {
1470            state.require_no_hosted_children(&replaces.id)?;
1471            state.nodes.remove(&replaces.id);
1472            state.retired_nodes.insert(replaces.id.clone());
1473            state.retired_keys.insert(replaces.signing_key);
1474            state.nodes.insert(request.node_id.clone(), member);
1475            Ok(())
1476        })
1477    }
1478}