Skip to main content

khive_db/stores/note/
node_pins.rs

1//! Durable history of confirmed node public keys.
2//!
3//! Rows are keyed by the full peer identity plus key epoch. A retained pin is
4//! never overwritten or deleted, so an old epoch stays readable after a newer
5//! one is retained. Public keys are not secret.
6use super::{map_err, SqlNoteStore};
7use crate::pool::ConnectionPool;
8use khive_storage::{StorageCapability, StorageError, StorageResult};
9use rusqlite::types::Type;
10use rusqlite::{params, OptionalExtension};
11use std::sync::Arc;
12use uuid::Uuid;
13
14/// Identity of one confirmed key: peer address parts, device, and key epoch.
15#[derive(Clone, Debug, PartialEq, Eq)]
16pub struct NodePinKey {
17    pub namespace: String,
18    pub slug: String,
19    pub realm: String,
20    pub agent_id: Uuid,
21    pub device_id: Uuid,
22    pub key_epoch: u64,
23}
24
25/// A confirmed public-key triple for one identity.
26#[derive(Clone, Debug, PartialEq, Eq)]
27pub struct NodePinRecord {
28    pub key: NodePinKey,
29    pub kem_public_key: [u8; 32],
30    pub signing_public_key: [u8; 32],
31    pub fingerprint: [u8; 32],
32}
33
34const CONFLICT: &str = "node pin identity already has different confirmed keys";
35
36fn invalid(message: &str) -> StorageError {
37    StorageError::InvalidInput {
38        capability: StorageCapability::Notes,
39        operation: "node_pins".into(),
40        message: message.into(),
41    }
42}
43
44/// Epochs are stored as SQLite integers and must fit 1..=u32::MAX.
45fn epoch_to_sql(epoch: u64) -> StorageResult<i64> {
46    match u32::try_from(epoch) {
47        Ok(e) if e >= 1 => Ok(i64::from(e)),
48        _ => Err(invalid(
49            "node pin key epoch must be between 1 and 4294967295",
50        )),
51    }
52}
53
54const COLUMNS: &str = concat!(
55    "namespace, slug, realm, agent_id, device_id, key_epoch, kem_public_key, ",
56    "signing_public_key, fingerprint",
57);
58
59const LOAD_SQL: &str = concat!(
60    "SELECT namespace, slug, realm, agent_id, device_id, key_epoch, kem_public_key, ",
61    "signing_public_key, fingerprint FROM comm_node_confirmed_pin WHERE namespace = ?1 ",
62    "AND slug = ?2 AND realm = ?3 AND agent_id = ?4 ",
63    "AND device_id = ?5 ",
64    "AND key_epoch = ?6",
65);
66
67fn conversion_error(
68    index: usize,
69    ty: Type,
70    error: Box<dyn std::error::Error + Send + Sync>,
71) -> rusqlite::Error {
72    rusqlite::Error::FromSqlConversionFailure(index, ty, error)
73}
74
75fn blob32(row: &rusqlite::Row<'_>, index: usize) -> rusqlite::Result<[u8; 32]> {
76    let bytes: Vec<u8> = row.get(index)?;
77    let len = bytes.len();
78    bytes.try_into().map_err(|_| {
79        conversion_error(
80            index,
81            Type::Blob,
82            format!("expected 32 bytes, found {len}").into(),
83        )
84    })
85}
86
87fn uuid_col(row: &rusqlite::Row<'_>, index: usize) -> rusqlite::Result<Uuid> {
88    let text: String = row.get(index)?;
89    Uuid::parse_str(&text).map_err(|e| conversion_error(index, Type::Text, Box::new(e)))
90}
91
92fn read_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<NodePinRecord> {
93    let epoch: i64 = row.get(5)?;
94    let key_epoch =
95        u64::try_from(epoch).map_err(|e| conversion_error(5, Type::Integer, Box::new(e)))?;
96    Ok(NodePinRecord {
97        key: NodePinKey {
98            namespace: row.get(0)?,
99            slug: row.get(1)?,
100            realm: row.get(2)?,
101            agent_id: uuid_col(row, 3)?,
102            device_id: uuid_col(row, 4)?,
103            key_epoch,
104        },
105        kem_public_key: blob32(row, 6)?,
106        signing_public_key: blob32(row, 7)?,
107        fingerprint: blob32(row, 8)?,
108    })
109}
110
111fn load(
112    conn: &rusqlite::Connection,
113    key: &NodePinKey,
114    epoch: i64,
115) -> rusqlite::Result<Option<NodePinRecord>> {
116    conn.query_row(
117        LOAD_SQL,
118        params![
119            key.namespace,
120            key.slug,
121            key.realm,
122            key.agent_id.to_string(),
123            key.device_id.to_string(),
124            epoch
125        ],
126        read_row,
127    )
128    .optional()
129}
130
131/// Store uses the note writer's transaction routing and bounded pooled readers.
132pub struct NodePinStore {
133    notes: SqlNoteStore,
134}
135
136impl NodePinStore {
137    pub fn new(pool: Arc<ConnectionPool>) -> Self {
138        Self {
139            notes: SqlNoteStore::new(pool, false),
140        }
141    }
142
143    /// Retain confirmed pins in one transaction. An exact existing payload is a
144    /// no-op. Different bytes at an existing identity refuse the whole call and
145    /// leave every entry of it unwritten. Nothing is overwritten or deleted.
146    pub async fn retain(&self, pins: Vec<NodePinRecord>) -> StorageResult<()> {
147        let epochs = pins
148            .iter()
149            .map(|pin| epoch_to_sql(pin.key.key_epoch))
150            .collect::<StorageResult<Vec<_>>>()?;
151        if pins.is_empty() {
152            return Ok(());
153        }
154        self.notes
155            .with_writer_tx_storage("node_pins_retain", move |conn| {
156                let op = "node_pins_retain";
157                for (record, epoch) in pins.iter().zip(epochs) {
158                    match load(conn, &record.key, epoch).map_err(|e| map_err(e, op))? {
159                        Some(existing) if existing == *record => {}
160                        Some(_) => return Err(invalid(CONFLICT)),
161                        None => {
162                            conn.execute(
163                                &format!(
164                                    "INSERT INTO comm_node_confirmed_pin({COLUMNS}) \
165                                     VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)"
166                                ),
167                                params![
168                                    record.key.namespace,
169                                    record.key.slug,
170                                    record.key.realm,
171                                    record.key.agent_id.to_string(),
172                                    record.key.device_id.to_string(),
173                                    epoch,
174                                    record.kem_public_key.as_slice(),
175                                    record.signing_public_key.as_slice(),
176                                    record.fingerprint.as_slice()
177                                ],
178                            )
179                            .map_err(|e| map_err(e, op))?;
180                        }
181                    }
182                }
183                // Every entry matched an existing row or was inserted.
184                Ok(())
185            })
186            .await
187    }
188
189    /// Look up one exact identity. An epoch outside 1..=u32::MAX cannot exist,
190    /// so it reads as absent.
191    pub async fn get(&self, key: NodePinKey) -> StorageResult<Option<NodePinRecord>> {
192        let Ok(epoch) = epoch_to_sql(key.key_epoch) else {
193            return Ok(None);
194        };
195        self.notes
196            .with_reader("node_pins_get", move |conn| load(conn, &key, epoch))
197            .await
198    }
199}
200
201#[cfg(test)]
202#[path = "node_pins_tests.rs"]
203mod tests;