Skip to main content

gent_daemon/store/
peer_configuration.rs

1//! Durable endpoint state for the ordered configuration log. Network I/O must
2//! happen outside the Store lock; each method commits its local work first.
3use super::*;
4use gent_crypto::{
5    configuration_log::{self as crypto, WriteCapability},
6    peer::{NodeSigner, envelope},
7};
8use gent_protocol::configuration_log::{Bootstrap, Commit, Head, Header, Receipt};
9use zeroize::Zeroizing;
10mod enrollment;
11pub(crate) use enrollment::install_checkpoint;
12mod decisions;
13mod maintenance;
14mod migration;
15mod proposals;
16#[cfg(test)]
17mod tests;
18
19struct SavedProposal {
20    salt: Zeroizing<Vec<u8>>,
21    intent: Vec<u8>,
22    candidate: Option<Vec<u8>>,
23}
24
25#[derive(Clone)]
26pub(crate) struct Queued {
27    pub origin: String,
28    pub id: String,
29    pub operation: String,
30}
31
32pub(super) fn schema(db: &Connection) -> Result<()> {
33    db.execute_batch(
34        "CREATE TABLE IF NOT EXISTS peer_configuration (
35        singleton INTEGER PRIMARY KEY CHECK(singleton=1),bootstrap BLOB NOT NULL,
36        head BLOB NOT NULL,capability BLOB CHECK(capability IS NULL OR length(capability)=32),
37        migration BLOB,active INTEGER NOT NULL CHECK(active IN (0,1)));
38        CREATE TABLE IF NOT EXISTS peer_configuration_requests (
39        origin TEXT NOT NULL,id TEXT NOT NULL,salt BLOB NOT NULL CHECK(length(salt)=32),
40        intent BLOB NOT NULL CHECK(length(intent)=32),candidate BLOB,
41        PRIMARY KEY(origin,id),FOREIGN KEY(origin,id) REFERENCES configuration_edits(origin,id));
42        CREATE TABLE IF NOT EXISTS peer_configuration_history (
43        sequence INTEGER PRIMARY KEY,receipt BLOB NOT NULL,body BLOB NOT NULL);
44        CREATE TABLE IF NOT EXISTS peer_configuration_decisions (
45        origin TEXT NOT NULL,id TEXT NOT NULL,fingerprint TEXT NOT NULL,result BLOB NOT NULL,
46        PRIMARY KEY(origin,id));
47        CREATE TABLE IF NOT EXISTS peer_configuration_routes (
48        origin TEXT NOT NULL,id TEXT NOT NULL,writer TEXT NOT NULL,event TEXT NOT NULL,PRIMARY KEY(origin,id,writer));",
49    )?;
50    Ok(())
51}
52
53pub(super) fn check_state(db: &Connection, state: &VerifiedState) -> Result<()> {
54    if state.state().peer.is_none() {
55        return Ok(());
56    }
57    let head: Vec<u8> = db
58        .query_row(
59            "SELECT head FROM peer_configuration WHERE singleton=1 AND active=1",
60            [],
61            |r| r.get(0),
62        )
63        .optional()?
64        .context("peer configuration checkpoint is missing; restore this node's state")?;
65    let head: Head = serde_json::from_slice(&head)?;
66    let receipt: Vec<u8> = db.query_row(
67        "SELECT receipt FROM peer_configuration_history WHERE sequence=?1",
68        [head.sequence],
69        |r| r.get(0),
70    )?;
71    ensure!(
72        head.sequence == state.checkpoint().revision
73            && serde_json::from_slice::<Receipt>(&receipt)?.head == head,
74        "peer configuration checkpoint mismatch"
75    );
76    Ok(())
77}
78
79fn random_salt() -> [u8; 32] {
80    Sha256::digest(config::secret().as_bytes()).into()
81}
82
83fn header(
84    state: &VerifiedState,
85    head: Head,
86    node: &str,
87    operation: &str,
88    intent: [u8; 32],
89    next: &WriteCapability,
90) -> Header {
91    Header {
92        version: 1,
93        cluster: state.anchor().cluster_id.clone(),
94        origin: node.into(),
95        operation: operation.into(),
96        intent,
97        previous: head,
98        next_write_key: next.public_key(),
99    }
100}
101
102impl Store {
103    pub(crate) fn configuration_proposals(&self) -> Result<Vec<Queued>> {
104        let state = self.identity.state(&self.db)?;
105        let administrator = self.identity.can_administer(&state);
106        let rows = self.db.prepare("SELECT e.origin,e.id,p.body FROM configuration_edits e JOIN configuration_pending p USING(origin,id) WHERE e.result IS NULL ORDER BY e.rowid")?
107            .query_map([], |r| Ok((r.get::<_,String>(0)?,r.get::<_,String>(1)?,r.get::<_,Vec<u8>>(2)?)))?.collect::<rusqlite::Result<Vec<_>>>()?;
108        let mut result = Vec::new();
109        for (origin, id, body) in rows {
110            if !administrator
111                && (origin != self.identity.node.id()
112                    || administration::edit_identity(&serde_json::from_slice(&body)?).is_some())
113            {
114                continue;
115            }
116            let operation = if origin == self.identity.node.id() {
117                id.clone()
118            } else {
119                gent_crypto::scoped_id(
120                    b"gent/delegated-configuration/v1\0",
121                    &[origin.as_bytes(), id.as_bytes()],
122                )
123                .to_string()
124            };
125            result.push(Queued {
126                origin,
127                id,
128                operation,
129            });
130            if result.len() == 8 {
131                break;
132            }
133        }
134        Ok(result)
135    }
136    pub(crate) fn begin_configuration_discovery(&mut self) {
137        if self.config.service.is_some() {
138            self.configuration_discovery(false);
139        }
140    }
141    pub(crate) fn configuration_discovery(&mut self, legacy_allowed: bool) {
142        self.identity.legacy_service_checked = legacy_allowed;
143    }
144    pub fn pending_configuration_proposals(&self) -> Result<Vec<String>> {
145        Ok(self.db.prepare("SELECT e.id FROM configuration_edits e JOIN configuration_pending p USING(origin,id) WHERE e.origin=?1 AND e.result IS NULL ORDER BY e.rowid LIMIT 8")?
146            .query_map([self.identity.node.id()], |r| r.get(0))?
147            .collect::<rusqlite::Result<Vec<_>>>()?)
148    }
149
150    pub fn configuration_proposal_intent(&self, id: &str) -> Result<Option<[u8; 32]>> {
151        self.configuration_intent_for(self.identity.node.id(), id)
152    }
153    pub(crate) fn configuration_intent_for(
154        &self,
155        origin: &str,
156        id: &str,
157    ) -> Result<Option<[u8; 32]>> {
158        let value: Option<Vec<u8>> = self
159            .db
160            .query_row(
161                "SELECT intent FROM peer_configuration_requests WHERE origin=?1 AND id=?2",
162                params![origin, id],
163                |r| r.get(0),
164            )
165            .optional()?;
166        value
167            .map(|value| value.as_slice().try_into().map_err(Into::into))
168            .transpose()
169    }
170
171    /// Trusted local administration, not an MCP operation. The runtime must
172    /// finish migration acceptance before exposing this through the CLI.
173    pub fn prepare_configuration_log(&mut self, credential: &str) -> Result<Bootstrap> {
174        ensure!(hash(credential) == self.owner_hash, "unauthorized");
175        if let Some(bytes) = self
176            .db
177            .query_row(
178                "SELECT bootstrap FROM peer_configuration WHERE singleton=1",
179                [],
180                |r| r.get::<_, Vec<u8>>(0),
181            )
182            .optional()?
183        {
184            self.sync_wakeup.notify_one();
185            return Ok(serde_json::from_slice(&bytes)?);
186        }
187        let state = self.identity.state(&self.db)?;
188        let key = self.identity.migration_owner(&self.db)?;
189        let admission = WriteCapability::generate()?;
190        let next = WriteCapability::generate()?;
191        let bootstrap = Bootstrap {
192            cluster: state.anchor().cluster_id.clone(),
193            head: Head {
194                sequence: state.checkpoint().revision,
195                digest: state.checkpoint().state_hash,
196                write_key: admission.public_key(),
197            },
198        };
199        let archive = migration::Archive::capture(&self.db, &state)?;
200        let salt = random_salt();
201        let proposal = header(
202            &state,
203            bootstrap.head.clone(),
204            self.identity.node.id(),
205            &uuid::Uuid::new_v4().to_string(),
206            crypto::intent(&salt, &archive),
207            &next,
208        );
209        let candidate = state.migrate_to_peers(
210            &key,
211            &self.identity.node,
212            proposal.clone(),
213            (now() as u64).max(state.state().issued_at),
214        )?;
215        let commit = admission.seal(
216            proposal,
217            &envelope::seal_migration(&candidate, &next, salt, &archive)?,
218        )?;
219        drop(key);
220        self.identity.fence_peer_authority()?;
221        let tx = self
222            .db
223            .transaction_with_behavior(TransactionBehavior::Immediate)?;
224        ensure!(
225            self.identity.state(&tx)?.checkpoint() == state.checkpoint(),
226            "migration checkpoint changed"
227        );
228        tx.execute(
229            "INSERT INTO peer_configuration VALUES(1,?1,?2,NULL,?3,0)",
230            params![
231                serde_json::to_vec(&bootstrap)?,
232                serde_json::to_vec(&bootstrap.head)?,
233                serde_json::to_vec(&commit)?
234            ],
235        )?;
236        tx.commit()?;
237        self.sync_wakeup.notify_one();
238        Ok(bootstrap)
239    }
240
241    pub fn configuration_log_head(&self) -> Result<Option<Head>> {
242        let bytes: Option<Vec<u8>> = self
243            .db
244            .query_row(
245                "SELECT head FROM peer_configuration WHERE singleton=1",
246                [],
247                |r| r.get(0),
248            )
249            .optional()?;
250        bytes
251            .map(|bytes| serde_json::from_slice(&bytes).map_err(Into::into))
252            .transpose()
253    }
254
255    pub fn configuration_log_migration(&self) -> Result<Option<Commit>> {
256        let bytes: Option<Vec<u8>> = self
257            .db
258            .query_row(
259                "SELECT migration FROM peer_configuration WHERE singleton=1 AND active=0",
260                [],
261                |r| r.get(0),
262            )
263            .optional()?
264            .flatten();
265        bytes
266            .map(|bytes| serde_json::from_slice(&bytes).map_err(Into::into))
267            .transpose()
268    }
269
270    /// Called with bytes fetched from the authenticated ordering service. A
271    /// locally prepared proposal is never passed here before service commitment.
272    pub fn accept_configuration_commit(&mut self, commit: &Commit) -> Result<Receipt> {
273        let receipt = crypto::verify(commit)?;
274        let previous = self
275            .db
276            .query_row(
277                "SELECT receipt FROM peer_configuration_history WHERE sequence=?1",
278                [receipt.head.sequence],
279                |r| r.get::<_, Vec<u8>>(0),
280            )
281            .optional()?;
282        if let Some(previous) = previous {
283            ensure!(
284                serde_json::from_slice::<Receipt>(&previous)? == receipt,
285                "configuration history fork"
286            );
287            return Ok(receipt);
288        }
289        let original = self.identity.state(&self.db)?;
290        let decrypted = envelope::decrypt(&self.identity.node, commit)?;
291        let archive = decrypted
292            .migration
293            .as_ref()
294            .map(|m| -> Result<migration::Archive> {
295                Ok(serde_json::from_slice(&STANDARD.decode(&m.archive)?)?)
296            })
297            .transpose()?;
298        let state = if original.state().peer.is_none() {
299            archive
300                .as_ref()
301                .context("migration archive is missing")?
302                .verify_history(&original)?
303        } else {
304            ensure!(archive.is_none(), "migration archive after activation");
305            original.clone()
306        };
307        let saved = self.configuration_log_head()?;
308        ensure!(
309            saved.is_some() || state.state().peer.is_none(),
310            "peer configuration checkpoint is missing"
311        );
312        let head = saved.unwrap_or_else(|| commit.header.previous.clone());
313        if state.state().peer.is_none() {
314            ensure!(
315                head.sequence == state.checkpoint().revision
316                    && head.digest == state.checkpoint().state_hash,
317                "migration bootstrap does not match pinned authority"
318            );
319        }
320        let mut updated = state.clone();
321        let updated_head = updated.advance_committed(decrypted.state, commit, &head)?;
322        self.identity.fence_peer_authority()?;
323        let tx = self
324            .db
325            .transaction_with_behavior(TransactionBehavior::Immediate)?;
326        ensure!(
327            self.identity.state(&tx)?.checkpoint() == original.checkpoint(),
328            "local configuration changed"
329        );
330        let mut history = archive
331            .as_ref()
332            .map(|a| {
333                a.history
334                    .iter()
335                    .filter(|s| s.state.revision > original.checkpoint().revision)
336                    .cloned()
337                    .collect::<Vec<_>>()
338            })
339            .unwrap_or_default();
340        history.push(updated.signed().clone());
341        encrypted::persist_authority(&tx, &self.identity.node, &updated, &history)?;
342        if let Some(archive) = &archive {
343            archive.adopt(&tx)?;
344            tx.execute("INSERT INTO peer_configuration_decisions(origin,id,fingerprint,result) SELECT origin,id,fingerprint,result FROM configuration_edits WHERE result IS NOT NULL ON CONFLICT DO NOTHING", [])?;
345        }
346        // Every surviving administrator retains service cleanup intent. The
347        // creating node is not needed to revoke a retired transport identity.
348        let session = StoreSession {
349            db: &tx,
350            home: &self.home,
351            config: self.config.clone(),
352            identity: &self.identity,
353            state: updated.clone(),
354            timestamp: now(),
355        };
356        for (id, member) in &state.state().nodes {
357            if !updated.state().nodes.contains_key(id) {
358                let known: bool = tx.query_row(
359                    "SELECT EXISTS(SELECT 1 FROM node_removals WHERE node=?1)",
360                    [id],
361                    |r| r.get(0),
362                )?;
363                if !known {
364                    session.record_removal(id, &member.signing_key, None)?;
365                }
366            }
367        }
368        let capability = decrypted.capability.as_ref().map(WriteCapability::secret);
369        let bootstrap = Bootstrap {
370            cluster: state.anchor().cluster_id.clone(),
371            head,
372        };
373        tx.execute("INSERT INTO peer_configuration VALUES(1,?1,?2,?3,NULL,1) ON CONFLICT(singleton) DO UPDATE SET head=excluded.head,capability=excluded.capability,migration=NULL,active=1", params![serde_json::to_vec(&bootstrap)?, serde_json::to_vec(&updated_head)?, capability.as_ref().map(|v| v.as_slice())])?;
374        tx.execute(
375            "INSERT INTO peer_configuration_history VALUES(?1,?2,?3)",
376            params![
377                receipt.head.sequence,
378                serde_json::to_vec(&receipt)?,
379                serde_json::to_vec(commit)?
380            ],
381        )?;
382        decisions::accept(&tx, &updated)?;
383        tx.commit()?;
384        let _ = self.project_config();
385        self.sync_wakeup.notify_one();
386        Ok(receipt)
387    }
388}