Skip to main content

gent_daemon/store/
handoff.rs

1//! Owner-authenticated preparation and local successor activation.
2//! Private successor keys stay on their node. Issuing authority durably fences
3//! the source before any signature is returned. Preparation can exchange its
4//! artifacts over encrypted node links; issuing and activating remain explicit.
5use super::*;
6use gent_crypto::{
7    OwnerKey, SignedState,
8    succession::{MAX_CANDIDATE_BYTES, SignedOwnerCandidate, SignedOwnerTransition},
9};
10use std::{
11    fs,
12    io::{Read, Write},
13    os::unix::fs::{MetadataExt, PermissionsExt},
14};
15use uuid::Uuid;
16use zeroize::Zeroizing;
17
18const LIMIT: usize = 64;
19const MAGIC: &[u8] = b"GENTOWN1";
20mod activation;
21mod coordination;
22pub(crate) mod journal;
23mod readiness;
24mod streams;
25mod transfer;
26pub(crate) use activation::{active_key, admit_epochs, check_epochs};
27
28pub(crate) fn schema(db: &Connection, previous: i64) -> Result<()> {
29    let count: usize = db.query_row("SELECT COUNT(*) FROM sqlite_schema WHERE type='table' AND name IN ('owner_handoff_control','owner_handoffs','owner_candidates')", [], |r| r.get(0))?;
30    if previous < 18 && count == 0 {
31        db.execute_batch("CREATE TABLE owner_handoffs(id TEXT PRIMARY KEY CHECK(length(id)=36),baseline BLOB NOT NULL CHECK(length(baseline)<=2097152),candidate BLOB NOT NULL CHECK(length(candidate)<=8192),authorization BLOB NOT NULL CHECK(length(authorization)<=4096));
32        CREATE TABLE owner_handoff_control(singleton INTEGER PRIMARY KEY CHECK(singleton=1),issued TEXT REFERENCES owner_handoffs(id));
33        INSERT INTO owner_handoff_control VALUES(1,NULL);
34        CREATE TABLE owner_candidates(id TEXT PRIMARY KEY CHECK(length(id)=36),baseline BLOB NOT NULL CHECK(length(baseline)<=2097152),candidate BLOB NOT NULL CHECK(length(candidate)<=8192),completed BLOB CHECK(length(completed)<=2097152));")?;
35    } else {
36        ensure!(
37            count == 3,
38            "owner handoff journal is missing; do not resume signing"
39        );
40        db.prepare("SELECT id,baseline,candidate,authorization FROM owner_handoffs LIMIT 0")?;
41        db.prepare("SELECT id,baseline,candidate,completed FROM owner_candidates LIMIT 0")?;
42        ensure!(
43            db.query_row(
44                "SELECT COUNT(*) FROM owner_handoff_control WHERE singleton=1",
45                [],
46                |r| r.get::<_, usize>(0)
47            )? == 1,
48            "owner handoff fence is missing; do not resume signing"
49        );
50    }
51    journal::schema(db, previous)?;
52    activation::schema(db, previous)?;
53    readiness::schema(db, previous)?;
54    coordination::schema(db, previous)?;
55    transfer::schema(db, previous)
56}
57
58fn restore(candidate: &SignedOwnerCandidate, baseline: &[u8]) -> Result<VerifiedState> {
59    VerifiedState::restore(
60        candidate.candidate.anchor.clone(),
61        candidate.candidate.base.clone(),
62        SignedState::decode(baseline)?,
63    )
64}
65
66pub(crate) struct Issued {
67    pub(crate) base: VerifiedState,
68    pub(crate) candidate: SignedOwnerCandidate,
69    pub(crate) authorization: SignedOwnerTransition,
70}
71
72fn issued(db: &Connection) -> Result<Option<Issued>> {
73    let id: Option<String> = db.query_row(
74        "SELECT issued FROM owner_handoff_control WHERE singleton=1",
75        [],
76        |r| r.get(0),
77    )?;
78    let count: usize = db.query_row("SELECT COUNT(*) FROM owner_handoffs", [], |r| r.get(0))?;
79    let Some(id) = id else {
80        ensure!(count == 0, "owner handoff fence lost its record pin");
81        return Ok(None);
82    };
83    ensure!(
84        (1..=LIMIT).contains(&count),
85        "owner handoff history is missing or exceeds capacity"
86    );
87    issued_for(db, &id).map(Some)
88}
89
90pub(crate) fn issued_for(db: &Connection, id: &str) -> Result<Issued> {
91    let (baseline, candidate, authorization): (Vec<u8>, Vec<u8>, Vec<u8>) = db.query_row(
92        "SELECT baseline,candidate,authorization FROM owner_handoffs WHERE id=?1",
93        [&id],
94        |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
95    )?;
96    let candidate = SignedOwnerCandidate::decode(&candidate)?;
97    ensure!(
98        candidate.candidate.id == id,
99        "owner handoff request changed"
100    );
101    let base = restore(&candidate, &baseline)?;
102    let authorization = SignedOwnerTransition::decode(&authorization)?;
103    base.verify_owner_authorization(&candidate, &authorization)?;
104    journal::check_source(db, &base, &candidate, &authorization)?;
105    Ok(Issued {
106        base,
107        candidate,
108        authorization,
109    })
110}
111
112pub(crate) fn frozen(db: &Connection, state: &VerifiedState) -> Result<bool> {
113    let Some(record) = issued(db)? else {
114        return Ok(false);
115    };
116    ensure!(
117        state.anchor() == record.base.anchor(),
118        "owner handoff belongs to another cluster"
119    );
120    let mut archived =
121        db.prepare("SELECT id,candidate,authorization FROM owner_handoffs WHERE id!=?1")?;
122    for row in archived.query_map([&record.candidate.candidate.id], |r| {
123        Ok((
124            r.get::<_, String>(0)?,
125            r.get::<_, Vec<u8>>(1)?,
126            r.get::<_, Vec<u8>>(2)?,
127        ))
128    })? {
129        let (id, candidate, authorization) = row?;
130        let candidate = SignedOwnerCandidate::decode(&candidate)?;
131        let authorization = SignedOwnerTransition::decode(&authorization)?;
132        ensure!(
133            authorization.transition.epoch > 0
134                && authorization.transition.epoch <= record.base.owner_epoch()
135                && candidate.candidate.id == id
136                && authorization
137                    .transition
138                    .successor
139                    .as_ref()
140                    .is_some_and(|s| candidate.digest().is_ok_and(|d| d == s.candidate))
141                && state
142                    .state()
143                    .owner_transitions
144                    .get(authorization.transition.epoch as usize - 1)
145                    == Some(&authorization),
146            "archived signing stop conflicts with accepted owner history"
147        );
148    }
149    if state.owner_epoch() == record.base.owner_epoch() {
150        ensure!(
151            state.checkpoint() == record.base.checkpoint(),
152            "owner signing advanced after handoff was issued"
153        );
154        return Ok(true);
155    }
156    ensure!(
157        state.owner_epoch() > record.base.owner_epoch()
158            && state
159                .state()
160                .owner_transitions
161                .get(record.base.owner_epoch() as usize)
162                == Some(&record.authorization),
163        "accepted owner epoch conflicts with the issued handoff"
164    );
165    Ok(false)
166}
167
168pub(crate) fn check_state(db: &Connection, state: &VerifiedState) -> Result<()> {
169    frozen(db, state)?;
170    Ok(())
171}
172
173pub(super) fn status(db: &Connection, state: &VerifiedState) -> Result<Value> {
174    let blocked = frozen(db, state)?;
175    let issued = issued(db)?;
176    let (stream_records, stream_bytes) = encrypted::ordered::configuration::standby::usage(db)?;
177    let (candidates, completed): (u64, u64) = db.query_row(
178        "SELECT COUNT(*),COUNT(completed) FROM owner_candidates",
179        [],
180        |r| Ok((r.get(0)?, r.get(1)?)),
181    )?;
182    ensure!(
183        candidates <= LIMIT as u64,
184        "owner candidate capacity exceeded"
185    );
186    Ok(
187        json!({"owner_epoch":state.owner_epoch(),"signing_frozen":blocked,
188        "issued_request":issued.as_ref().map(|r| &r.candidate.candidate.id),
189        "successor_node":issued.as_ref().map(|r| &r.candidate.candidate.node.id),
190        "prepared_candidates":candidates,"completed_candidates":completed,
191        "journal_transfer":journal::usage(db)?,
192        "configuration_preparation":{"records":stream_records,"stored_bytes":stream_bytes},
193        "readiness":readiness::usage(db)?,
194        "preparation_exchange":coordination::usage(db)?,
195        "transfer":transfer::usage(db)?,
196        "delivery":encrypted::ordered::configuration::handoff::usage(db)?,
197        "activation_supported":true}),
198    )
199}
200
201fn candidate_path(home: &Path, id: &str) -> Result<PathBuf> {
202    ensure!(
203        Uuid::parse_str(id).is_ok_and(|u| !u.is_nil() && u.to_string() == id),
204        "invalid owner candidate ID"
205    );
206    Ok(home.join("owner-candidates").join(format!("{id}.key")))
207}
208
209fn read_key(path: &Path) -> Result<(OwnerKey, SignedOwnerCandidate)> {
210    let parent = fs::symlink_metadata(path.parent().context("candidate parent missing")?)?;
211    ensure!(
212        parent.is_dir()
213            && parent.uid() == rustix::process::geteuid().as_raw()
214            && parent.mode() & 0o077 == 0,
215        "owner candidate directory must be private, owned and without symlinks"
216    );
217    let before = fs::symlink_metadata(path)?;
218    ensure!(
219        before.is_file()
220            && before.nlink() == 1
221            && before.uid() == rustix::process::geteuid().as_raw()
222            && before.mode() & 0o077 == 0,
223        "owner candidate key must be a private owned file without links"
224    );
225    let file = fs::File::open(path)?;
226    let stamp = |m: &fs::Metadata| {
227        (
228            m.dev(),
229            m.ino(),
230            m.len(),
231            m.mode(),
232            m.mtime(),
233            m.mtime_nsec(),
234            m.ctime(),
235            m.ctime_nsec(),
236        )
237    };
238    ensure!(
239        stamp(&before) == stamp(&file.metadata()?),
240        "owner candidate key changed while opening"
241    );
242    let mut bytes = Zeroizing::new(Vec::new());
243    (&file)
244        .take((MAX_CANDIDATE_BYTES + 41) as u64)
245        .read_to_end(&mut bytes)?;
246    ensure!(
247        stamp(&before) == stamp(&file.metadata()?)
248            && bytes.len() > 40
249            && bytes.len() <= MAX_CANDIDATE_BYTES + 40
250            && &bytes[..8] == MAGIC,
251        "invalid or changed owner candidate key file"
252    );
253    let key = OwnerKey::from_secret_bytes(bytes[8..40].try_into()?);
254    let candidate = SignedOwnerCandidate::decode(&bytes[40..])?;
255    ensure!(
256        key.public_key() == candidate.candidate.owner_key,
257        "owner candidate signing key mismatch"
258    );
259    Ok((key, candidate))
260}
261
262fn save_key(path: &Path, key: &OwnerKey, candidate: &SignedOwnerCandidate) -> Result<()> {
263    let parent = path.parent().context("candidate parent missing")?;
264    config::private_dir(parent)?;
265    let meta = fs::symlink_metadata(parent)?;
266    ensure!(
267        meta.is_dir() && meta.uid() == rustix::process::geteuid().as_raw(),
268        "owner candidate directory must be owned by this user"
269    );
270    ensure!(
271        fs::read_dir(parent)?
272            .take(LIMIT + 1)
273            .collect::<std::io::Result<Vec<_>>>()?
274            .len()
275            < LIMIT,
276        "owner candidate key capacity reached"
277    );
278    let mut file = tempfile::NamedTempFile::new_in(parent)?;
279    file.as_file()
280        .set_permissions(fs::Permissions::from_mode(0o600))?;
281    file.write_all(MAGIC)?;
282    file.write_all(key.expose_secret().as_ref())?;
283    file.write_all(&candidate.encode()?)?;
284    file.as_file().sync_all()?;
285    file.persist_noclobber(path).map_err(|e| e.error)?;
286    fs::File::open(parent)?.sync_all()?;
287    Ok(())
288}
289
290impl Store {
291    /// Local-owner preparation API for the future handoff coordinator. No MCP
292    /// operation invokes it, and it changes no active signing authority.
293    pub fn prepare_owner_handoff(
294        &mut self,
295        credential: &str,
296        id: &str,
297    ) -> Result<SignedOwnerCandidate> {
298        ensure!(hash(credential) == self.owner_hash, "unauthorized");
299        let path = candidate_path(&self.home, id)?;
300        let _lock = config::state_lock(&self.home, "owner-handoff.lock")?;
301        let tx = self
302            .db
303            .transaction_with_behavior(TransactionBehavior::Immediate)?;
304        let state = self.identity.state(&tx)?;
305        ensure!(
306            !self.identity.is_current_owner(&state),
307            "prepare the successor on a different enrolled node"
308        );
309        let previous: Option<(Vec<u8>, Vec<u8>)> = tx
310            .query_row(
311                "SELECT baseline,candidate FROM owner_candidates WHERE id=?1",
312                [id],
313                |r| Ok((r.get(0)?, r.get(1)?)),
314            )
315            .optional()?;
316        if let Some((baseline, wire)) = previous {
317            let (key, candidate) = read_key(&path)?;
318            ensure!(
319                candidate.encode()? == wire
320                    && candidate.candidate.node.id == self.identity.node.id()
321                    && candidate.candidate.node.signing_key == self.identity.node.public_key(),
322                "owner candidate identity changed"
323            );
324            let pinned = restore(&candidate, &baseline)?;
325            candidate.verify(&pinned, candidate.candidate.issued_at)?;
326            ensure!(
327                pinned.anchor() == state.anchor()
328                    && key.public_key() == candidate.candidate.owner_key,
329                "candidate cluster changed"
330            );
331            return Ok(candidate);
332        }
333        ensure!(
334            tx.query_row("SELECT COUNT(*) FROM owner_candidates", [], |r| r
335                .get::<_, usize>(0))?
336                < LIMIT,
337            "owner candidate capacity reached"
338        );
339        let timestamp = requests::clock(&tx, now())? as u64;
340        let candidate = match fs::symlink_metadata(&path) {
341            Ok(_) => read_key(&path)?.1,
342            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
343                let key = OwnerKey::generate()?;
344                let candidate = self
345                    .identity
346                    .node
347                    .prepare_owner_candidate(&state, &key, id, timestamp)?;
348                save_key(&path, &key, &candidate)?;
349                candidate
350            }
351            Err(e) => return Err(e.into()),
352        };
353        ensure!(
354            candidate.candidate.id == id
355                && candidate.candidate.node.id == self.identity.node.id()
356                && candidate.candidate.node.signing_key == self.identity.node.public_key(),
357            "owner candidate file belongs to another request or node"
358        );
359        candidate.verify(&state, timestamp)?;
360        tx.execute(
361            "INSERT INTO owner_candidates VALUES(?1,?2,?3,NULL)",
362            params![id, state.signed().encode()?, candidate.encode()?],
363        )?;
364        tx.commit()?;
365        Ok(candidate)
366    }
367
368    /// Irrevocable once returned or committed: no timeout clears this fence.
369    /// The coordinator must finish activation, never resume the old writer.
370    pub fn authorize_owner_handoff(
371        &mut self,
372        credential: &str,
373        candidate: &SignedOwnerCandidate,
374    ) -> Result<SignedOwnerTransition> {
375        self.issue_owner_handoff(credential, candidate, false)
376    }
377
378    fn issue_owner_handoff(
379        &mut self,
380        credential: &str,
381        candidate: &SignedOwnerCandidate,
382        coordinated: bool,
383    ) -> Result<SignedOwnerTransition> {
384        ensure!(hash(credential) == self.owner_hash, "unauthorized");
385        let _lock = config::state_lock(&self.home, "owner-handoff.lock")?;
386        let tx = self
387            .db
388            .transaction_with_behavior(TransactionBehavior::Immediate)?;
389        let state = self.identity.state(&tx)?;
390        let previous: bool = tx.query_row(
391            "SELECT EXISTS(SELECT 1 FROM owner_handoffs WHERE id=?1)",
392            [&candidate.candidate.id],
393            |r| r.get(0),
394        )?;
395        if previous {
396            let previous = issued_for(&tx, &candidate.candidate.id)?;
397            ensure!(
398                previous.candidate == *candidate,
399                "a different owner handoff is already issued"
400            );
401            if coordinated {
402                transfer::arm_source(&tx, &self.identity.node, &state, candidate, false)?;
403                tx.commit()?;
404            }
405            return Ok(previous.authorization);
406        }
407        ensure!(
408            tx.query_row("SELECT COUNT(*) FROM owner_handoffs", [], |r| r
409                .get::<_, usize>(0))?
410                < LIMIT,
411            "owner handoff history is full"
412        );
413        ensure!(
414            candidate.candidate.node.id != self.identity.node.id(),
415            "owner handoff requires another node"
416        );
417        let owner = &*self.identity.signing_owner(&tx)?;
418        let timestamp = requests::clock(&tx, now())? as u64;
419        readiness::require(&tx, &state, candidate, timestamp)?;
420        let (manifest, body) = journal::capture(&tx, &state, candidate)?;
421        let authorization = state.authorize_owner_candidate_with_journal(
422            owner,
423            candidate,
424            manifest.digest()?,
425            timestamp,
426        )?;
427        tx.execute(
428            "INSERT INTO owner_handoffs VALUES(?1,?2,?3,?4)",
429            params![
430                candidate.candidate.id,
431                state.signed().encode()?,
432                candidate.encode()?,
433                authorization.encode()?
434            ],
435        )?;
436        tx.execute(
437            "UPDATE owner_handoff_control SET issued=?1 WHERE singleton=1",
438            [&candidate.candidate.id],
439        )?;
440        journal::save_source(&tx, candidate, &authorization, &manifest, &body)?;
441        if coordinated {
442            transfer::arm_source(&tx, &self.identity.node, &state, candidate, true)?;
443        }
444        tx.commit()?;
445        Ok(authorization)
446    }
447
448    /// Save the successor's signature without installing its key or activating
449    /// the state. Retries preserve the same result, including after expiry.
450    pub fn accept_owner_handoff(
451        &mut self,
452        credential: &str,
453        id: &str,
454        authorization: &SignedOwnerTransition,
455    ) -> Result<SignedState> {
456        ensure!(hash(credential) == self.owner_hash, "unauthorized");
457        let path = candidate_path(&self.home, id)?;
458        let _lock = config::state_lock(&self.home, "owner-handoff.lock")?;
459        let tx = self
460            .db
461            .transaction_with_behavior(TransactionBehavior::Immediate)?;
462        let state = self.identity.state(&tx)?;
463        let (baseline, wire, completed): (Vec<u8>, Vec<u8>, Option<Vec<u8>>) = tx.query_row(
464            "SELECT baseline,candidate,completed FROM owner_candidates WHERE id=?1",
465            [id],
466            |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
467        )?;
468        let (key, candidate) = read_key(&path)?;
469        ensure!(
470            candidate.encode()? == wire
471                && candidate.candidate.id == id
472                && candidate.candidate.node.id == self.identity.node.id()
473                && candidate.candidate.node.signing_key == self.identity.node.public_key(),
474            "owner candidate changed"
475        );
476        let pinned = restore(&candidate, &baseline)?;
477        pinned.verify_owner_authorization(&candidate, authorization)?;
478        if let Some(previous) = &completed
479            && state.owner_epoch() >= authorization.transition.epoch
480        {
481            ensure!(
482                state
483                    .state()
484                    .owner_transitions
485                    .get(authorization.transition.epoch as usize - 1)
486                    == Some(authorization),
487                "another owner handoff was accepted"
488            );
489            let result =
490                pinned.accept_owner_authorization(&key, &candidate, authorization, now() as u64)?;
491            ensure!(
492                *previous == result.encode()?,
493                "owner authorization changed after completion"
494            );
495            return Ok(result);
496        }
497        ensure!(
498            state.anchor() == pinned.anchor() && state.checkpoint() == pinned.checkpoint(),
499            "local state changed since owner preparation"
500        );
501        let timestamp = requests::clock(&tx, now())? as u64;
502        if authorization
503            .transition
504            .successor
505            .as_ref()
506            .is_some_and(|s| s.journal.is_some())
507        {
508            journal::require_complete(&tx, &pinned, &candidate, authorization)?;
509        }
510        let result =
511            pinned.accept_owner_authorization(&key, &candidate, authorization, timestamp)?;
512        if let Some(previous) = completed {
513            ensure!(
514                previous == result.encode()?,
515                "owner authorization changed after completion"
516            );
517            return Ok(result);
518        }
519        tx.execute(
520            "UPDATE owner_candidates SET completed=?1 WHERE id=?2",
521            params![result.encode()?, id],
522        )?;
523        tx.commit()?;
524        Ok(result)
525    }
526}
527
528impl Store {
529    /// Trusted local owner API; no remote request can initiate a signing stop.
530    pub fn queue_owner_handoff_delivery(
531        &self,
532        credential: &str,
533        id: &str,
534    ) -> Result<serde_json::Value> {
535        ensure!(hash(credential) == self.owner_hash, "unauthorized");
536        let result =
537            encrypted::ordered::OrderedEndpoint::open_runtime(&self.home, &self.identity.node)?
538                .queue_owner_handoff(id, now() as u64)?;
539        self.sync_wakeup.notify_one();
540        Ok(result)
541    }
542}