gent-daemon 0.1.3

Local daemon, storage and synchronization for Gent chat clusters.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
//! Owner-authenticated preparation and local successor activation.
//! Private successor keys stay on their node. Issuing authority durably fences
//! the source before any signature is returned. Preparation can exchange its
//! artifacts over encrypted node links; issuing and activating remain explicit.
use super::*;
use gent_crypto::{
    OwnerKey, SignedState,
    succession::{MAX_CANDIDATE_BYTES, SignedOwnerCandidate, SignedOwnerTransition},
};
use std::{
    fs,
    io::{Read, Write},
    os::unix::fs::{MetadataExt, PermissionsExt},
};
use uuid::Uuid;
use zeroize::Zeroizing;

const LIMIT: usize = 64;
const MAGIC: &[u8] = b"GENTOWN1";
mod activation;
mod coordination;
pub(crate) mod journal;
mod readiness;
mod streams;
mod transfer;
pub(crate) use activation::{active_key, admit_epochs, check_epochs};

pub(crate) fn schema(db: &Connection, previous: i64) -> Result<()> {
    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))?;
    if previous < 18 && count == 0 {
        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));
        CREATE TABLE owner_handoff_control(singleton INTEGER PRIMARY KEY CHECK(singleton=1),issued TEXT REFERENCES owner_handoffs(id));
        INSERT INTO owner_handoff_control VALUES(1,NULL);
        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));")?;
    } else {
        ensure!(
            count == 3,
            "owner handoff journal is missing; do not resume signing"
        );
        db.prepare("SELECT id,baseline,candidate,authorization FROM owner_handoffs LIMIT 0")?;
        db.prepare("SELECT id,baseline,candidate,completed FROM owner_candidates LIMIT 0")?;
        ensure!(
            db.query_row(
                "SELECT COUNT(*) FROM owner_handoff_control WHERE singleton=1",
                [],
                |r| r.get::<_, usize>(0)
            )? == 1,
            "owner handoff fence is missing; do not resume signing"
        );
    }
    journal::schema(db, previous)?;
    activation::schema(db, previous)?;
    readiness::schema(db, previous)?;
    coordination::schema(db, previous)?;
    transfer::schema(db, previous)
}

fn restore(candidate: &SignedOwnerCandidate, baseline: &[u8]) -> Result<VerifiedState> {
    VerifiedState::restore(
        candidate.candidate.anchor.clone(),
        candidate.candidate.base.clone(),
        SignedState::decode(baseline)?,
    )
}

pub(crate) struct Issued {
    pub(crate) base: VerifiedState,
    pub(crate) candidate: SignedOwnerCandidate,
    pub(crate) authorization: SignedOwnerTransition,
}

fn issued(db: &Connection) -> Result<Option<Issued>> {
    let id: Option<String> = db.query_row(
        "SELECT issued FROM owner_handoff_control WHERE singleton=1",
        [],
        |r| r.get(0),
    )?;
    let count: usize = db.query_row("SELECT COUNT(*) FROM owner_handoffs", [], |r| r.get(0))?;
    let Some(id) = id else {
        ensure!(count == 0, "owner handoff fence lost its record pin");
        return Ok(None);
    };
    ensure!(
        (1..=LIMIT).contains(&count),
        "owner handoff history is missing or exceeds capacity"
    );
    issued_for(db, &id).map(Some)
}

pub(crate) fn issued_for(db: &Connection, id: &str) -> Result<Issued> {
    let (baseline, candidate, authorization): (Vec<u8>, Vec<u8>, Vec<u8>) = db.query_row(
        "SELECT baseline,candidate,authorization FROM owner_handoffs WHERE id=?1",
        [&id],
        |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
    )?;
    let candidate = SignedOwnerCandidate::decode(&candidate)?;
    ensure!(
        candidate.candidate.id == id,
        "owner handoff request changed"
    );
    let base = restore(&candidate, &baseline)?;
    let authorization = SignedOwnerTransition::decode(&authorization)?;
    base.verify_owner_authorization(&candidate, &authorization)?;
    journal::check_source(db, &base, &candidate, &authorization)?;
    Ok(Issued {
        base,
        candidate,
        authorization,
    })
}

pub(crate) fn frozen(db: &Connection, state: &VerifiedState) -> Result<bool> {
    let Some(record) = issued(db)? else {
        return Ok(false);
    };
    ensure!(
        state.anchor() == record.base.anchor(),
        "owner handoff belongs to another cluster"
    );
    let mut archived =
        db.prepare("SELECT id,candidate,authorization FROM owner_handoffs WHERE id!=?1")?;
    for row in archived.query_map([&record.candidate.candidate.id], |r| {
        Ok((
            r.get::<_, String>(0)?,
            r.get::<_, Vec<u8>>(1)?,
            r.get::<_, Vec<u8>>(2)?,
        ))
    })? {
        let (id, candidate, authorization) = row?;
        let candidate = SignedOwnerCandidate::decode(&candidate)?;
        let authorization = SignedOwnerTransition::decode(&authorization)?;
        ensure!(
            authorization.transition.epoch > 0
                && authorization.transition.epoch <= record.base.owner_epoch()
                && candidate.candidate.id == id
                && authorization
                    .transition
                    .successor
                    .as_ref()
                    .is_some_and(|s| candidate.digest().is_ok_and(|d| d == s.candidate))
                && state
                    .state()
                    .owner_transitions
                    .get(authorization.transition.epoch as usize - 1)
                    == Some(&authorization),
            "archived signing stop conflicts with accepted owner history"
        );
    }
    if state.owner_epoch() == record.base.owner_epoch() {
        ensure!(
            state.checkpoint() == record.base.checkpoint(),
            "owner signing advanced after handoff was issued"
        );
        return Ok(true);
    }
    ensure!(
        state.owner_epoch() > record.base.owner_epoch()
            && state
                .state()
                .owner_transitions
                .get(record.base.owner_epoch() as usize)
                == Some(&record.authorization),
        "accepted owner epoch conflicts with the issued handoff"
    );
    Ok(false)
}

pub(crate) fn check_state(db: &Connection, state: &VerifiedState) -> Result<()> {
    frozen(db, state)?;
    Ok(())
}

pub(super) fn status(db: &Connection, state: &VerifiedState) -> Result<Value> {
    let blocked = frozen(db, state)?;
    let issued = issued(db)?;
    let (stream_records, stream_bytes) = encrypted::ordered::configuration::standby::usage(db)?;
    let (candidates, completed): (u64, u64) = db.query_row(
        "SELECT COUNT(*),COUNT(completed) FROM owner_candidates",
        [],
        |r| Ok((r.get(0)?, r.get(1)?)),
    )?;
    ensure!(
        candidates <= LIMIT as u64,
        "owner candidate capacity exceeded"
    );
    Ok(
        json!({"owner_epoch":state.owner_epoch(),"signing_frozen":blocked,
        "issued_request":issued.as_ref().map(|r| &r.candidate.candidate.id),
        "successor_node":issued.as_ref().map(|r| &r.candidate.candidate.node.id),
        "prepared_candidates":candidates,"completed_candidates":completed,
        "journal_transfer":journal::usage(db)?,
        "configuration_preparation":{"records":stream_records,"stored_bytes":stream_bytes},
        "readiness":readiness::usage(db)?,
        "preparation_exchange":coordination::usage(db)?,
        "transfer":transfer::usage(db)?,
        "delivery":encrypted::ordered::configuration::handoff::usage(db)?,
        "activation_supported":true}),
    )
}

fn candidate_path(home: &Path, id: &str) -> Result<PathBuf> {
    ensure!(
        Uuid::parse_str(id).is_ok_and(|u| !u.is_nil() && u.to_string() == id),
        "invalid owner candidate ID"
    );
    Ok(home.join("owner-candidates").join(format!("{id}.key")))
}

fn read_key(path: &Path) -> Result<(OwnerKey, SignedOwnerCandidate)> {
    let parent = fs::symlink_metadata(path.parent().context("candidate parent missing")?)?;
    ensure!(
        parent.is_dir()
            && parent.uid() == rustix::process::geteuid().as_raw()
            && parent.mode() & 0o077 == 0,
        "owner candidate directory must be private, owned and without symlinks"
    );
    let before = fs::symlink_metadata(path)?;
    ensure!(
        before.is_file()
            && before.nlink() == 1
            && before.uid() == rustix::process::geteuid().as_raw()
            && before.mode() & 0o077 == 0,
        "owner candidate key must be a private owned file without links"
    );
    let file = fs::File::open(path)?;
    let stamp = |m: &fs::Metadata| {
        (
            m.dev(),
            m.ino(),
            m.len(),
            m.mode(),
            m.mtime(),
            m.mtime_nsec(),
            m.ctime(),
            m.ctime_nsec(),
        )
    };
    ensure!(
        stamp(&before) == stamp(&file.metadata()?),
        "owner candidate key changed while opening"
    );
    let mut bytes = Zeroizing::new(Vec::new());
    (&file)
        .take((MAX_CANDIDATE_BYTES + 41) as u64)
        .read_to_end(&mut bytes)?;
    ensure!(
        stamp(&before) == stamp(&file.metadata()?)
            && bytes.len() > 40
            && bytes.len() <= MAX_CANDIDATE_BYTES + 40
            && &bytes[..8] == MAGIC,
        "invalid or changed owner candidate key file"
    );
    let key = OwnerKey::from_secret_bytes(bytes[8..40].try_into()?);
    let candidate = SignedOwnerCandidate::decode(&bytes[40..])?;
    ensure!(
        key.public_key() == candidate.candidate.owner_key,
        "owner candidate signing key mismatch"
    );
    Ok((key, candidate))
}

fn save_key(path: &Path, key: &OwnerKey, candidate: &SignedOwnerCandidate) -> Result<()> {
    let parent = path.parent().context("candidate parent missing")?;
    config::private_dir(parent)?;
    let meta = fs::symlink_metadata(parent)?;
    ensure!(
        meta.is_dir() && meta.uid() == rustix::process::geteuid().as_raw(),
        "owner candidate directory must be owned by this user"
    );
    ensure!(
        fs::read_dir(parent)?
            .take(LIMIT + 1)
            .collect::<std::io::Result<Vec<_>>>()?
            .len()
            < LIMIT,
        "owner candidate key capacity reached"
    );
    let mut file = tempfile::NamedTempFile::new_in(parent)?;
    file.as_file()
        .set_permissions(fs::Permissions::from_mode(0o600))?;
    file.write_all(MAGIC)?;
    file.write_all(key.expose_secret().as_ref())?;
    file.write_all(&candidate.encode()?)?;
    file.as_file().sync_all()?;
    file.persist_noclobber(path).map_err(|e| e.error)?;
    fs::File::open(parent)?.sync_all()?;
    Ok(())
}

impl Store {
    /// Local-owner preparation API for the future handoff coordinator. No MCP
    /// operation invokes it, and it changes no active signing authority.
    pub fn prepare_owner_handoff(
        &mut self,
        credential: &str,
        id: &str,
    ) -> Result<SignedOwnerCandidate> {
        ensure!(hash(credential) == self.owner_hash, "unauthorized");
        let path = candidate_path(&self.home, id)?;
        let _lock = config::state_lock(&self.home, "owner-handoff.lock")?;
        let tx = self
            .db
            .transaction_with_behavior(TransactionBehavior::Immediate)?;
        let state = self.identity.state(&tx)?;
        ensure!(
            !self.identity.is_current_owner(&state),
            "prepare the successor on a different enrolled node"
        );
        let previous: Option<(Vec<u8>, Vec<u8>)> = tx
            .query_row(
                "SELECT baseline,candidate FROM owner_candidates WHERE id=?1",
                [id],
                |r| Ok((r.get(0)?, r.get(1)?)),
            )
            .optional()?;
        if let Some((baseline, wire)) = previous {
            let (key, candidate) = read_key(&path)?;
            ensure!(
                candidate.encode()? == wire
                    && candidate.candidate.node.id == self.identity.node.id()
                    && candidate.candidate.node.signing_key == self.identity.node.public_key(),
                "owner candidate identity changed"
            );
            let pinned = restore(&candidate, &baseline)?;
            candidate.verify(&pinned, candidate.candidate.issued_at)?;
            ensure!(
                pinned.anchor() == state.anchor()
                    && key.public_key() == candidate.candidate.owner_key,
                "candidate cluster changed"
            );
            return Ok(candidate);
        }
        ensure!(
            tx.query_row("SELECT COUNT(*) FROM owner_candidates", [], |r| r
                .get::<_, usize>(0))?
                < LIMIT,
            "owner candidate capacity reached"
        );
        let timestamp = requests::clock(&tx, now())? as u64;
        let candidate = match fs::symlink_metadata(&path) {
            Ok(_) => read_key(&path)?.1,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                let key = OwnerKey::generate()?;
                let candidate = self
                    .identity
                    .node
                    .prepare_owner_candidate(&state, &key, id, timestamp)?;
                save_key(&path, &key, &candidate)?;
                candidate
            }
            Err(e) => return Err(e.into()),
        };
        ensure!(
            candidate.candidate.id == id
                && candidate.candidate.node.id == self.identity.node.id()
                && candidate.candidate.node.signing_key == self.identity.node.public_key(),
            "owner candidate file belongs to another request or node"
        );
        candidate.verify(&state, timestamp)?;
        tx.execute(
            "INSERT INTO owner_candidates VALUES(?1,?2,?3,NULL)",
            params![id, state.signed().encode()?, candidate.encode()?],
        )?;
        tx.commit()?;
        Ok(candidate)
    }

    /// Irrevocable once returned or committed: no timeout clears this fence.
    /// The coordinator must finish activation, never resume the old writer.
    pub fn authorize_owner_handoff(
        &mut self,
        credential: &str,
        candidate: &SignedOwnerCandidate,
    ) -> Result<SignedOwnerTransition> {
        self.issue_owner_handoff(credential, candidate, false)
    }

    fn issue_owner_handoff(
        &mut self,
        credential: &str,
        candidate: &SignedOwnerCandidate,
        coordinated: bool,
    ) -> Result<SignedOwnerTransition> {
        ensure!(hash(credential) == self.owner_hash, "unauthorized");
        let _lock = config::state_lock(&self.home, "owner-handoff.lock")?;
        let tx = self
            .db
            .transaction_with_behavior(TransactionBehavior::Immediate)?;
        let state = self.identity.state(&tx)?;
        let previous: bool = tx.query_row(
            "SELECT EXISTS(SELECT 1 FROM owner_handoffs WHERE id=?1)",
            [&candidate.candidate.id],
            |r| r.get(0),
        )?;
        if previous {
            let previous = issued_for(&tx, &candidate.candidate.id)?;
            ensure!(
                previous.candidate == *candidate,
                "a different owner handoff is already issued"
            );
            if coordinated {
                transfer::arm_source(&tx, &self.identity.node, &state, candidate, false)?;
                tx.commit()?;
            }
            return Ok(previous.authorization);
        }
        ensure!(
            tx.query_row("SELECT COUNT(*) FROM owner_handoffs", [], |r| r
                .get::<_, usize>(0))?
                < LIMIT,
            "owner handoff history is full"
        );
        ensure!(
            candidate.candidate.node.id != self.identity.node.id(),
            "owner handoff requires another node"
        );
        let owner = &*self.identity.signing_owner(&tx)?;
        let timestamp = requests::clock(&tx, now())? as u64;
        readiness::require(&tx, &state, candidate, timestamp)?;
        let (manifest, body) = journal::capture(&tx, &state, candidate)?;
        let authorization = state.authorize_owner_candidate_with_journal(
            owner,
            candidate,
            manifest.digest()?,
            timestamp,
        )?;
        tx.execute(
            "INSERT INTO owner_handoffs VALUES(?1,?2,?3,?4)",
            params![
                candidate.candidate.id,
                state.signed().encode()?,
                candidate.encode()?,
                authorization.encode()?
            ],
        )?;
        tx.execute(
            "UPDATE owner_handoff_control SET issued=?1 WHERE singleton=1",
            [&candidate.candidate.id],
        )?;
        journal::save_source(&tx, candidate, &authorization, &manifest, &body)?;
        if coordinated {
            transfer::arm_source(&tx, &self.identity.node, &state, candidate, true)?;
        }
        tx.commit()?;
        Ok(authorization)
    }

    /// Save the successor's signature without installing its key or activating
    /// the state. Retries preserve the same result, including after expiry.
    pub fn accept_owner_handoff(
        &mut self,
        credential: &str,
        id: &str,
        authorization: &SignedOwnerTransition,
    ) -> Result<SignedState> {
        ensure!(hash(credential) == self.owner_hash, "unauthorized");
        let path = candidate_path(&self.home, id)?;
        let _lock = config::state_lock(&self.home, "owner-handoff.lock")?;
        let tx = self
            .db
            .transaction_with_behavior(TransactionBehavior::Immediate)?;
        let state = self.identity.state(&tx)?;
        let (baseline, wire, completed): (Vec<u8>, Vec<u8>, Option<Vec<u8>>) = tx.query_row(
            "SELECT baseline,candidate,completed FROM owner_candidates WHERE id=?1",
            [id],
            |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
        )?;
        let (key, candidate) = read_key(&path)?;
        ensure!(
            candidate.encode()? == wire
                && candidate.candidate.id == id
                && candidate.candidate.node.id == self.identity.node.id()
                && candidate.candidate.node.signing_key == self.identity.node.public_key(),
            "owner candidate changed"
        );
        let pinned = restore(&candidate, &baseline)?;
        pinned.verify_owner_authorization(&candidate, authorization)?;
        if let Some(previous) = &completed
            && state.owner_epoch() >= authorization.transition.epoch
        {
            ensure!(
                state
                    .state()
                    .owner_transitions
                    .get(authorization.transition.epoch as usize - 1)
                    == Some(authorization),
                "another owner handoff was accepted"
            );
            let result =
                pinned.accept_owner_authorization(&key, &candidate, authorization, now() as u64)?;
            ensure!(
                *previous == result.encode()?,
                "owner authorization changed after completion"
            );
            return Ok(result);
        }
        ensure!(
            state.anchor() == pinned.anchor() && state.checkpoint() == pinned.checkpoint(),
            "local state changed since owner preparation"
        );
        let timestamp = requests::clock(&tx, now())? as u64;
        if authorization
            .transition
            .successor
            .as_ref()
            .is_some_and(|s| s.journal.is_some())
        {
            journal::require_complete(&tx, &pinned, &candidate, authorization)?;
        }
        let result =
            pinned.accept_owner_authorization(&key, &candidate, authorization, timestamp)?;
        if let Some(previous) = completed {
            ensure!(
                previous == result.encode()?,
                "owner authorization changed after completion"
            );
            return Ok(result);
        }
        tx.execute(
            "UPDATE owner_candidates SET completed=?1 WHERE id=?2",
            params![result.encode()?, id],
        )?;
        tx.commit()?;
        Ok(result)
    }
}

impl Store {
    /// Trusted local owner API; no remote request can initiate a signing stop.
    pub fn queue_owner_handoff_delivery(
        &self,
        credential: &str,
        id: &str,
    ) -> Result<serde_json::Value> {
        ensure!(hash(credential) == self.owner_hash, "unauthorized");
        let result =
            encrypted::ordered::OrderedEndpoint::open_runtime(&self.home, &self.identity.node)?
                .queue_owner_handoff(id, now() as u64)?;
        self.sync_wakeup.notify_one();
        Ok(result)
    }
}