Skip to main content

gent_crypto/authority/
peer.rs

1//! Versioned transition from owner-signed state to node-signed, ordered state.
2use super::*;
3use gent_protocol::configuration_log::{Commit, Head, Header};
4#[cfg(feature = "invitation")]
5pub mod direct;
6#[cfg(feature = "invitation")]
7pub mod envelope;
8
9#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
10#[serde(deny_unknown_fields)]
11pub struct Authority {
12    pub header: Header,
13    pub signer: PublicKey,
14    /// The one transition record is signed by the previously pinned owner.
15    /// Every subsequent record is signed by an authorized member node.
16    pub migration: bool,
17    #[serde(default, skip_serializing_if = "Option::is_none")]
18    pub request: Option<Request>,
19}
20
21/// Logical request identity, encrypted with configuration. Delegated requests
22/// keep this identity when a different administrator publishes their result.
23#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
24#[serde(deny_unknown_fields)]
25pub struct Request {
26    pub origin: String,
27    pub id: String,
28    pub fingerprint: String,
29    #[serde(default, skip_serializing_if = "Option::is_none")]
30    pub rejection: Option<String>,
31}
32
33impl Request {
34    fn validate(&self) -> Result<()> {
35        id(&self.origin)?;
36        id(&self.id)?;
37        ensure!(
38            self.rejection.as_ref().is_none_or(|r| r.len() <= 1024),
39            "configuration rejection exceeds limit"
40        );
41        ensure!(
42            self.fingerprint.len() == 64
43                && self
44                    .fingerprint
45                    .bytes()
46                    .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)),
47            "invalid logical configuration request"
48        );
49        Ok(())
50    }
51}
52
53impl Authority {
54    pub(super) fn validate(&self, state: &ClusterState) -> Result<()> {
55        ensure!(self.header.valid(), "invalid peer ordering header");
56        public_key(&self.signer)?;
57        if let Some(request) = &self.request {
58            ensure!(!self.migration, "migration cannot decide a new edit");
59            request.validate()?;
60        }
61        ensure!(
62            self.header.cluster == state.cluster_id
63                && self.header.previous.sequence + 1 == state.revision,
64            "peer authority does not match configuration sequence"
65        );
66        ensure!(
67            state
68                .nodes
69                .values()
70                .any(|n| n.can_configure && n.hosted_by.is_none()),
71            "cluster requires a native configuration administrator"
72        );
73        Ok(())
74    }
75}
76
77/// Signing a candidate does not apply it. Only the committed encrypted log can
78/// advance a peer-authority checkpoint.
79pub trait ConfigurationSigner {
80    fn sign_revision(&self, previous: &VerifiedState, state: ClusterState) -> Result<SignedState>;
81}
82
83impl ConfigurationSigner for OwnerKey {
84    fn sign_revision(&self, previous: &VerifiedState, state: ClusterState) -> Result<SignedState> {
85        ensure!(
86            previous.state().peer.is_none(),
87            "legacy signing is fenced by peer authority"
88        );
89        ensure!(
90            self.public_key() == previous.state().owner_key,
91            "wrong owner authority"
92        );
93        self.sign(state)
94    }
95}
96
97pub struct NodeSigner<'a> {
98    node: &'a NodeIdentity,
99    header: Header,
100    request: Option<Request>,
101}
102
103impl<'a> NodeSigner<'a> {
104    pub fn new(node: &'a NodeIdentity, header: Header) -> Result<Self> {
105        ensure!(
106            header.valid() && header.origin == node.id(),
107            "wrong proposal identity"
108        );
109        Ok(Self {
110            node,
111            header,
112            request: None,
113        })
114    }
115
116    pub fn with_request(mut self, request: Request) -> Result<Self> {
117        request.validate()?;
118        self.request = Some(request);
119        Ok(self)
120    }
121}
122
123impl ConfigurationSigner for NodeSigner<'_> {
124    fn sign_revision(
125        &self,
126        previous: &VerifiedState,
127        mut state: ClusterState,
128    ) -> Result<SignedState> {
129        ensure!(
130            previous.state().peer.is_some(),
131            "peer authority is not active"
132        );
133        let member = previous
134            .state()
135            .nodes
136            .get(self.node.id())
137            .context("node unavailable")?;
138        ensure!(
139            member.signing_key == self.node.public_key() && member.can_configure,
140            "node cannot administer configuration"
141        );
142        ensure!(
143            self.header.previous.sequence == previous.checkpoint().revision,
144            "proposal requires current sequence"
145        );
146        state.version = 3;
147        state.peer = Some(Authority {
148            header: self.header.clone(),
149            signer: self.node.public_key(),
150            migration: false,
151            request: self.request.clone(),
152        });
153        state.validate()?;
154        let signature = self
155            .node
156            .key
157            .sign(&signing_input(STATE_DOMAIN, &state, MAX_STATE_BYTES)?)
158            .to_bytes()
159            .to_vec();
160        let signed = SignedState { state, signature };
161        // Check retirement continuity before any network publication.
162        previous.verify_chain(std::slice::from_ref(&signed))?;
163        Ok(signed)
164    }
165}
166
167impl VerifiedState {
168    /// Prepare the single owner-authenticated migration. The caller first
169    /// durably fences the legacy writer, then publishes this candidate through
170    /// the log. Existing restrictions and identities are preserved exactly.
171    pub fn migrate_to_peers(
172        &self,
173        owner: &OwnerKey,
174        node: &NodeIdentity,
175        header: Header,
176        now: u64,
177    ) -> Result<SignedState> {
178        ensure!(self.state().peer.is_none(), "peer authority already active");
179        ensure!(
180            owner.public_key() == self.state().owner_key,
181            "wrong migration authority"
182        );
183        ensure!(
184            header.origin == node.id() && header.previous.sequence == self.checkpoint().revision,
185            "wrong migration checkpoint"
186        );
187        let member = self
188            .state()
189            .nodes
190            .get(node.id())
191            .context("migration node unavailable")?;
192        ensure!(
193            member.signing_key == node.public_key(),
194            "migration node key mismatch"
195        );
196        let mut state = self.renew(owner, now)?.state;
197        // The legacy signing owner always had effective configuration access,
198        // even in older encodings that left its delegated-access flag false.
199        state.nodes.get_mut(node.id()).unwrap().can_configure = true;
200        state.version = 3;
201        state.peer = Some(Authority {
202            header,
203            signer: node.public_key(),
204            migration: true,
205            request: None,
206        });
207        state.validate()?;
208        let signature = owner
209            .0
210            .sign(&signing_input(STATE_DOMAIN, &state, MAX_STATE_BYTES)?)
211            .to_bytes()
212            .to_vec();
213        let signed = SignedState { state, signature };
214        self.verify_chain(std::slice::from_ref(&signed))?;
215        Ok(signed)
216    }
217
218    /// Called only after opening the committed ciphertext. `head` is the
219    /// durable local log checkpoint, never a value supplied by the proposal.
220    /// The runtime must persist the returned head and authority transactionally.
221    pub fn advance_committed(
222        &mut self,
223        update: SignedState,
224        commit: &Commit,
225        head: &Head,
226    ) -> Result<Head> {
227        ensure!(
228            &commit.header.previous == head && head.sequence == self.checkpoint().revision,
229            "configuration log rollback, gap, or fork"
230        );
231        let receipt = crate::configuration_log::verify(commit)?;
232        let peer = update
233            .state
234            .peer
235            .as_ref()
236            .context("committed state requires peer authority")?;
237        ensure!(
238            peer.header == commit.header,
239            "encrypted state does not match committed header"
240        );
241        let next = self.verify_chain(&[update])?;
242        *self = next;
243        Ok(receipt.head)
244    }
245}
246
247pub(super) fn verify_step(previous: &VerifiedState, update: &SignedState) -> Result<()> {
248    match (&previous.state().peer, &update.state.peer) {
249        (None, None) => Ok(()),
250        (Some(_), None) => anyhow::bail!("peer authority cannot return to legacy signing"),
251        (old, Some(peer)) => {
252            ensure!(
253                previous.state().owner_key == update.state.owner_key
254                    && previous.state().owner_transitions == update.state.owner_transitions,
255                "peer authority freezes legacy owner lineage"
256            );
257            ensure!(
258                peer.migration == old.is_none(),
259                "invalid peer migration transition"
260            );
261            let member = previous
262                .state()
263                .nodes
264                .get(&peer.header.origin)
265                .context("peer signer is not enrolled")?;
266            ensure!(
267                member.signing_key == peer.signer && (peer.migration || member.can_configure),
268                "peer signer is not authorized by prior state"
269            );
270            if peer.migration {
271                let mut expected = previous.state().clone();
272                expected.version = 3;
273                expected.peer = update.state.peer.clone();
274                expected.revision = update.state.revision;
275                expected.previous = update.state.previous;
276                expected.issued_at = update.state.issued_at;
277                expected.expires_at = update.state.expires_at;
278                expected
279                    .nodes
280                    .get_mut(&peer.header.origin)
281                    .unwrap()
282                    .can_configure = true;
283                ensure!(
284                    encode(&expected, MAX_STATE_BYTES)? == encode(&update.state, MAX_STATE_BYTES)?,
285                    "migration cannot change membership or policy"
286                );
287            }
288            Ok(())
289        }
290    }
291}