Skip to main content

gent_crypto/authority/
succession.rs

1//! Authenticated signer succession, separate from daemon activation and key recovery.
2use super::*;
3
4pub const MAX_OWNER_TRANSITIONS: usize = 64;
5pub const MAX_OWNER_CHAIN_BYTES: usize = 128 * 1024;
6pub const MAX_OWNER_TRANSITION_BYTES: usize = 4096;
7const DOMAIN: &[u8] = b"gent/owner-succession/v1\0";
8const RECORD_DOMAIN: &[u8] = b"gent/owner-succession-record/v1\0";
9mod candidate;
10pub use candidate::*;
11pub mod journal;
12pub mod readiness;
13
14#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
15#[serde(deny_unknown_fields)]
16pub struct OwnerTransition {
17    pub version: u32,
18    pub anchor: TrustAnchor,
19    pub epoch: u32,
20    pub previous: Digest,
21    pub base: Checkpoint,
22    pub owner_key: PublicKey,
23    #[serde(default, skip_serializing_if = "Option::is_none")]
24    pub successor: Option<OwnerSuccessor>,
25    pub issued_at: u64,
26}
27
28#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
29#[serde(deny_unknown_fields)]
30pub struct SignedOwnerTransition {
31    pub transition: OwnerTransition,
32    pub signature: Vec<u8>,
33}
34
35impl SignedOwnerTransition {
36    pub fn encode(&self) -> Result<Vec<u8>> {
37        encode(self, MAX_OWNER_TRANSITION_BYTES)
38    }
39    pub fn decode(bytes: &[u8]) -> Result<Self> {
40        decode(bytes, MAX_OWNER_TRANSITION_BYTES)
41    }
42    pub fn digest(&self) -> Result<Digest> {
43        digest(RECORD_DOMAIN, self, MAX_OWNER_TRANSITION_BYTES)
44    }
45}
46
47pub(super) fn owner_keys(
48    chain: &[SignedOwnerTransition],
49    current: PublicKey,
50) -> BTreeSet<PublicKey> {
51    let mut keys = BTreeSet::from([current]);
52    for link in chain {
53        keys.insert(link.transition.anchor.owner_key);
54        keys.insert(link.transition.owner_key);
55    }
56    keys
57}
58
59/// Authenticates a historical delegation chain. It does not select an active
60/// chain or prove that the predecessor has stopped. Accepted state does that
61/// selection through exact checkpoints and append-only epoch history.
62pub(super) fn verify_lineage(
63    anchor: &TrustAnchor,
64    chain: &[SignedOwnerTransition],
65) -> Result<PublicKey> {
66    id(&anchor.cluster_id)?;
67    public_key(&anchor.owner_key)?;
68    ensure!(anchor.genesis_hash != [0; 32], "invalid genesis hash");
69    ensure!(
70        chain.len() <= MAX_OWNER_TRANSITIONS,
71        "owner succession history is full"
72    );
73    encode(&chain, MAX_OWNER_CHAIN_BYTES)?;
74    let mut owner = anchor.owner_key;
75    let mut previous = anchor.genesis_hash;
76    let mut seen = BTreeSet::from([owner]);
77    let mut last: Option<&OwnerTransition> = None;
78    for (index, signed) in chain.iter().enumerate() {
79        let record = &signed.transition;
80        ensure!(
81            record.version == 1
82                && &record.anchor == anchor
83                && record.epoch as usize == index + 1
84                && record.previous == previous,
85            "owner succession chain mismatch"
86        );
87        public_key(&record.owner_key)?;
88        ensure!(
89            seen.insert(record.owner_key),
90            "owner signing key cannot be reused"
91        );
92        if let Some(successor) = &record.successor {
93            id(&successor.node.id)?;
94            public_key(&successor.node.signing_key)?;
95            ensure!(
96                !seen.contains(&successor.node.signing_key)
97                    && successor.candidate != [0; 32]
98                    && successor.journal.is_none_or(|digest| digest != [0; 32]),
99                "invalid successor node binding"
100            );
101        }
102        ensure!(
103            record.base.revision < MAX_SAFE_INTEGER
104                && record.base.state_hash != [0; 32]
105                && record.issued_at > 0
106                && record.issued_at <= MAX_SAFE_INTEGER,
107            "invalid owner succession checkpoint or time"
108        );
109        if record.base.revision == 0 {
110            ensure!(
111                record.base.state_hash == anchor.genesis_hash,
112                "owner succession genesis mismatch"
113            );
114        }
115        if let Some(last) = last {
116            ensure!(
117                record.base.revision > last.base.revision && record.issued_at >= last.issued_at,
118                "owner succession moved backwards"
119            );
120        }
121        verify(
122            &owner,
123            DOMAIN,
124            record,
125            &signed.signature,
126            MAX_OWNER_TRANSITION_BYTES,
127        )?;
128        previous = signed.digest()?;
129        owner = record.owner_key;
130        last = Some(record);
131    }
132    Ok(owner)
133}
134
135pub(super) fn verify_step(previous: &VerifiedState, update: &SignedState) -> Result<()> {
136    let old = &previous.state().owner_transitions;
137    let new = &update.state.owner_transitions;
138    if old == new {
139        return Ok(());
140    }
141    ensure!(
142        new.len() == old.len() + 1 && new.starts_with(old),
143        "owner succession cannot be removed, replaced or skipped"
144    );
145    let transition = &new.last().context("missing owner transition")?.transition;
146    if let Some(successor) = &transition.successor {
147        ensure!(
148            previous
149                .state()
150                .nodes
151                .get(&successor.node.id)
152                .is_some_and(|n| n.signing_key == successor.node.signing_key),
153            "successor node is not enrolled at the handoff checkpoint"
154        );
155    }
156    ensure!(
157        &transition.base == previous.checkpoint() && transition.issued_at == update.state.issued_at,
158        "owner succession requires the exact accepted checkpoint and activation time"
159    );
160    // The handoff changes only signing authority. Policy and membership changes
161    // require a subsequent ordinary revision signed by the successor.
162    let mut expected = previous.state().clone();
163    expected.version = 2;
164    expected.owner_key = transition.owner_key;
165    expected.owner_transitions = new.clone();
166    expected.revision = update.state.revision;
167    expected.previous = update.state.previous;
168    expected.issued_at = update.state.issued_at;
169    expected.expires_at = update.state.expires_at;
170    ensure!(
171        encode(&expected, MAX_STATE_BYTES)? == encode(&update.state, MAX_STATE_BYTES)?,
172        "owner handoff cannot change membership or policy"
173    );
174    ensure!(
175        !previous
176            .state()
177            .retired_keys
178            .contains(&transition.owner_key),
179        "retired node key cannot become an owner key"
180    );
181    Ok(())
182}
183
184impl VerifiedState {
185    pub fn owner_epoch(&self) -> u32 {
186        self.state().owner_transitions.len() as u32
187    }
188
189    /// Requires possession of both the current signer and a fresh successor.
190    /// This creates a record only; persistence, fencing and recovery approval
191    /// belong to the caller. An expired lease does not invalidate the signer.
192    pub fn transfer_owner(
193        &self,
194        owner: &OwnerKey,
195        successor: &OwnerKey,
196        now: u64,
197    ) -> Result<SignedState> {
198        ensure!(
199            owner.public_key() == self.state().owner_key,
200            "wrong current owner authority"
201        );
202        ensure!(
203            self.state().owner_transitions.len() < MAX_OWNER_TRANSITIONS,
204            "owner succession history is full"
205        );
206        ensure!(
207            now >= self.state().issued_at && now > 0,
208            "owner succession clock moved backwards"
209        );
210        let key = successor.public_key();
211        ensure!(
212            !owner_keys(&self.state().owner_transitions, owner.public_key()).contains(&key)
213                && !self.state().retired_keys.contains(&key)
214                && self
215                    .state()
216                    .nodes
217                    .values()
218                    .all(|node| node.signing_key != key),
219            "owner succession requires a fresh separate signing key"
220        );
221        let previous = self
222            .state()
223            .owner_transitions
224            .last()
225            .map(SignedOwnerTransition::digest)
226            .transpose()?
227            .unwrap_or(self.anchor().genesis_hash);
228        let transition = OwnerTransition {
229            version: 1,
230            anchor: self.anchor().clone(),
231            epoch: self.owner_epoch() + 1,
232            previous,
233            base: self.checkpoint().clone(),
234            owner_key: key,
235            successor: None,
236            issued_at: now,
237        };
238        let signature = owner
239            .0
240            .sign(&signing_input(
241                DOMAIN,
242                &transition,
243                MAX_OWNER_TRANSITION_BYTES,
244            )?)
245            .to_bytes()
246            .to_vec();
247        self.sign_owner_transition(
248            successor,
249            SignedOwnerTransition {
250                transition,
251                signature,
252            },
253        )
254    }
255
256    fn sign_owner_transition(
257        &self,
258        successor: &OwnerKey,
259        transition: SignedOwnerTransition,
260    ) -> Result<SignedState> {
261        let now = transition.transition.issued_at;
262        ensure!(
263            transition.transition.owner_key == successor.public_key(),
264            "wrong successor signing key"
265        );
266        let mut state = self.state().clone();
267        state.version = 2;
268        state.owner_key = successor.public_key();
269        state.owner_transitions.push(transition);
270        state.revision = state.revision.checked_add(1).context("revision overflow")?;
271        state.previous = Some(self.checkpoint().state_hash);
272        state.issued_at = now;
273        state.expires_at = now
274            .checked_add(MAX_STATE_LIFETIME)
275            .context("timestamp overflow")?;
276        let update = successor.sign(state)?;
277        self.verify_chain(std::slice::from_ref(&update))?;
278        Ok(update)
279    }
280}