Skip to main content

gent_crypto/authority/
recovery.rs

1//! Signed observations for owner recovery review. These never freeze a writer,
2//! grant ownership, choose a winning fork, or reactivate archived state.
3use super::*;
4
5pub const MAX_CHALLENGE_BYTES: usize = 4096;
6pub const MAX_OBSERVATION_BYTES: usize = MAX_STATE_BYTES + 8192;
7pub const OBSERVATION_LIFETIME: u64 = 15 * 60;
8const DOMAIN: &[u8] = b"gent/recovery-observation/v1\0";
9
10#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
11#[serde(deny_unknown_fields)]
12pub struct RecoveryChallenge {
13    pub version: u32,
14    pub id: String,
15    pub anchor: TrustAnchor,
16    pub base: Checkpoint,
17    pub issued_at: u64,
18    pub expires_at: u64,
19}
20
21impl RecoveryChallenge {
22    pub fn encode(&self) -> Result<Vec<u8>> {
23        encode(self, MAX_CHALLENGE_BYTES)
24    }
25    pub fn decode(bytes: &[u8]) -> Result<Self> {
26        decode(bytes, MAX_CHALLENGE_BYTES)
27    }
28    pub fn validate(&self, now: u64) -> Result<()> {
29        ensure!(self.version == 1, "unsupported recovery challenge");
30        id(&self.id)?;
31        id(&self.anchor.cluster_id)?;
32        public_key(&self.anchor.owner_key)?;
33        ensure!(
34            self.anchor.genesis_hash != [0; 32]
35                && self.base.state_hash != [0; 32]
36                && self.base.revision <= MAX_SAFE_INTEGER,
37            "invalid recovery checkpoint"
38        );
39        lifetime(self.issued_at, self.expires_at, OBSERVATION_LIFETIME)?;
40        fresh(self.issued_at, self.expires_at, now)?;
41        self.encode()?;
42        Ok(())
43    }
44}
45
46/// Obtain this file from the intended, independently trusted local node.
47/// The self-contained owner signature does not select the user's trust anchor.
48#[derive(Clone, Debug, Serialize, Deserialize)]
49#[serde(deny_unknown_fields)]
50pub struct RecoveryBaseline {
51    pub challenge: RecoveryChallenge,
52    pub state: SignedState,
53}
54
55impl RecoveryBaseline {
56    pub fn new(state: &VerifiedState, now: u64) -> Result<Self> {
57        ensure!(
58            now >= state.state().issued_at,
59            "recovery clock precedes saved state"
60        );
61        let baseline = Self {
62            challenge: RecoveryChallenge {
63                version: 1,
64                id: uuid::Uuid::new_v4().to_string(),
65                anchor: state.anchor().clone(),
66                base: state.checkpoint().clone(),
67                issued_at: now,
68                expires_at: now
69                    .checked_add(OBSERVATION_LIFETIME)
70                    .context("timestamp overflow")?,
71            },
72            state: state.signed().clone(),
73        };
74        baseline.verify(now)?;
75        Ok(baseline)
76    }
77    pub fn encode(&self) -> Result<Vec<u8>> {
78        encode(self, MAX_OBSERVATION_BYTES)
79    }
80    pub fn decode(bytes: &[u8]) -> Result<Self> {
81        decode(bytes, MAX_OBSERVATION_BYTES)
82    }
83    pub fn verify(&self, now: u64) -> Result<VerifiedState> {
84        self.challenge.validate(now)?;
85        ensure!(
86            self.state.state.issued_at <= self.challenge.issued_at,
87            "baseline state is from the future"
88        );
89        self.encode()?;
90        VerifiedState::restore(
91            self.challenge.anchor.clone(),
92            self.challenge.base.clone(),
93            self.state.clone(),
94        )
95    }
96}
97
98#[derive(Clone, Debug, Serialize, Deserialize)]
99#[serde(deny_unknown_fields)]
100pub struct RecoveryObservationBody {
101    pub version: u32,
102    pub challenge: RecoveryChallenge,
103    pub observer: String,
104    pub observer_key: PublicKey,
105    pub observed_at: u64,
106    pub state: SignedState,
107}
108
109#[derive(Clone, Debug, Serialize, Deserialize)]
110#[serde(deny_unknown_fields)]
111pub struct SignedRecoveryObservation {
112    pub observation: RecoveryObservationBody,
113    pub signature: Vec<u8>,
114}
115
116impl NodeIdentity {
117    /// May report an expired configuration, but never grants new authority.
118    pub fn observe_recovery(
119        &self,
120        state: &VerifiedState,
121        challenge: &RecoveryChallenge,
122        now: u64,
123    ) -> Result<SignedRecoveryObservation> {
124        challenge.validate(now)?;
125        ensure!(
126            state.anchor() == &challenge.anchor,
127            "recovery challenge belongs to another cluster"
128        );
129        ensure!(
130            state.state().issued_at <= now,
131            "observed state is from the future"
132        );
133        ensure!(
134            state
135                .state()
136                .nodes
137                .get(self.id())
138                .is_some_and(|n| n.signing_key == self.public_key()),
139            "observer is not a member of its reported state"
140        );
141        let observation = RecoveryObservationBody {
142            version: 1,
143            challenge: challenge.clone(),
144            observer: self.id().into(),
145            observer_key: self.public_key(),
146            observed_at: now,
147            state: state.signed().clone(),
148        };
149        let signature = self
150            .key
151            .sign(&signing_input(DOMAIN, &observation, MAX_OBSERVATION_BYTES)?)
152            .to_bytes()
153            .to_vec();
154        let report = SignedRecoveryObservation {
155            observation,
156            signature,
157        };
158        report.encode()?;
159        Ok(report)
160    }
161}
162
163impl SignedRecoveryObservation {
164    pub fn encode(&self) -> Result<Vec<u8>> {
165        encode(self, MAX_OBSERVATION_BYTES)
166    }
167    pub fn decode(bytes: &[u8]) -> Result<Self> {
168        decode(bytes, MAX_OBSERVATION_BYTES)
169    }
170    /// This authenticates a statement, not the completeness of the node's
171    /// knowledge or the absence of a later/competing owner revision.
172    pub fn verify(&self, challenge: &RecoveryChallenge, now: u64) -> Result<Checkpoint> {
173        challenge.validate(now)?;
174        let body = &self.observation;
175        ensure!(
176            body.version == 1 && &body.challenge == challenge,
177            "wrong recovery challenge"
178        );
179        id(&body.observer)?;
180        ensure!(
181            body.observed_at >= challenge.issued_at
182                && body.observed_at <= now
183                && body.observed_at < challenge.expires_at
184                && body.state.state.issued_at <= body.observed_at,
185            "invalid recovery observation time"
186        );
187        let checkpoint = body.state.verified_checkpoint(&challenge.anchor)?;
188        ensure!(
189            checkpoint.revision != 0 || checkpoint.state_hash == challenge.anchor.genesis_hash,
190            "observed genesis does not match the pinned cluster"
191        );
192        ensure!(
193            body.state
194                .state
195                .nodes
196                .get(&body.observer)
197                .is_some_and(|n| n.signing_key == body.observer_key),
198            "observer is not a member of its reported state"
199        );
200        verify(
201            &body.observer_key,
202            DOMAIN,
203            body,
204            &self.signature,
205            MAX_OBSERVATION_BYTES,
206        )?;
207        self.encode()?;
208        Ok(checkpoint)
209    }
210}
211
212#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
213#[serde(rename_all = "snake_case")]
214pub enum CheckpointRelation {
215    Matches,
216    Behind,
217    Ahead,
218    Conflict,
219}
220
221#[derive(Clone, Debug, Serialize)]
222pub struct ObservationSummary {
223    pub node: String,
224    pub checkpoint: Checkpoint,
225    pub observed_at: u64,
226    pub relation: CheckpointRelation,
227    pub state_expires_at: u64,
228    pub state_expired: bool,
229}
230
231#[derive(Debug, Serialize)]
232pub struct RecoveryReview {
233    pub challenge: String,
234    pub base: Checkpoint,
235    pub valid_until: u64,
236    pub observations: Vec<ObservationSummary>,
237    pub missing_nodes: Vec<String>,
238    pub conflicting_revisions: Vec<u64>,
239    pub all_match_baseline: bool,
240    pub authorizes_owner_change: bool,
241    pub proves_writer_stopped: bool,
242    pub proves_global_freshness: bool,
243}
244
245/// Stream reports one at a time, retaining only small verified summaries.
246pub struct RecoveryReviewer {
247    baseline: RecoveryBaseline,
248    reports: BTreeMap<String, ObservationSummary>,
249    hashes: BTreeMap<u64, BTreeSet<Digest>>,
250}
251
252impl RecoveryReviewer {
253    pub fn new(baseline: RecoveryBaseline, now: u64) -> Result<Self> {
254        baseline.verify(now)?;
255        let hashes = BTreeMap::from([(
256            baseline.challenge.base.revision,
257            BTreeSet::from([baseline.challenge.base.state_hash]),
258        )]);
259        Ok(Self {
260            baseline,
261            reports: BTreeMap::new(),
262            hashes,
263        })
264    }
265
266    pub fn observe(&mut self, report: &SignedRecoveryObservation, now: u64) -> Result<()> {
267        let checkpoint = report.verify(&self.baseline.challenge, now)?;
268        let body = &report.observation;
269        ensure!(
270            self.baseline
271                .state
272                .state
273                .nodes
274                .get(&body.observer)
275                .is_some_and(|n| n.signing_key == body.observer_key),
276            "observer is not the node key pinned by the baseline; obtain a current trusted baseline"
277        );
278        ensure!(
279            !self.reports.contains_key(&body.observer),
280            "duplicate observer report"
281        );
282        let base = &self.baseline.challenge.base;
283        let relation = if checkpoint.revision < base.revision {
284            CheckpointRelation::Behind
285        } else if checkpoint.revision > base.revision {
286            CheckpointRelation::Ahead
287        } else if checkpoint.state_hash == base.state_hash {
288            CheckpointRelation::Matches
289        } else {
290            CheckpointRelation::Conflict
291        };
292        self.hashes
293            .entry(checkpoint.revision)
294            .or_default()
295            .insert(checkpoint.state_hash);
296        self.reports.insert(
297            body.observer.clone(),
298            ObservationSummary {
299                node: body.observer.clone(),
300                checkpoint,
301                observed_at: body.observed_at,
302                relation,
303                state_expires_at: body.state.state.expires_at,
304                state_expired: body.state.state.expires_at <= now,
305            },
306        );
307        Ok(())
308    }
309
310    pub fn finish(self, now: u64) -> Result<RecoveryReview> {
311        self.baseline.challenge.validate(now)?;
312        ensure!(
313            self.reports.values().all(|r| r.observed_at <= now),
314            "review clock moved backwards"
315        );
316        let missing_nodes: Vec<_> = self
317            .baseline
318            .state
319            .state
320            .nodes
321            .keys()
322            .filter(|id| !self.reports.contains_key(*id))
323            .cloned()
324            .collect();
325        let conflicting_revisions: Vec<_> = self
326            .hashes
327            .iter()
328            .filter_map(|(revision, hashes)| (hashes.len() > 1).then_some(*revision))
329            .collect();
330        let all_match_baseline = missing_nodes.is_empty()
331            && conflicting_revisions.is_empty()
332            && self
333                .reports
334                .values()
335                .all(|r| r.relation == CheckpointRelation::Matches);
336        Ok(RecoveryReview {
337            challenge: self.baseline.challenge.id,
338            base: self.baseline.challenge.base,
339            valid_until: self.baseline.challenge.expires_at,
340            observations: self
341                .reports
342                .into_values()
343                .map(|mut summary| {
344                    summary.state_expired = summary.state_expires_at <= now;
345                    summary
346                })
347                .collect(),
348            missing_nodes,
349            conflicting_revisions,
350            all_match_baseline,
351            authorizes_owner_change: false,
352            proves_writer_stopped: false,
353            proves_global_freshness: false,
354        })
355    }
356}