1use super::*;
3use gent_crypto::{NodeIdentity, SignedConfigurationGrant, stream::Receipt};
4
5pub(super) fn schema(db: &Connection, previous: i64) -> Result<()> {
6 let exists: bool = db.query_row(
7 "SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='owner_epochs')",
8 [],
9 |r| r.get(0),
10 )?;
11 if !exists {
12 ensure!(previous < 22, "accepted owner epoch storage is missing");
13 db.execute_batch("CREATE TABLE owner_epochs(epoch INTEGER PRIMARY KEY CHECK(epoch BETWEEN 1 AND 64),transition BLOB NOT NULL CHECK(length(transition)<=4096),local_candidate TEXT REFERENCES owner_candidates(id));")?;
14 } else {
15 db.prepare("SELECT epoch,transition,local_candidate FROM owner_epochs LIMIT 0")?;
16 }
17 Ok(())
18}
19
20fn local(signed: &SignedOwnerTransition, node: &NodeIdentity) -> Result<bool> {
21 let successor = signed.transition.successor.as_ref().context(
22 "owner succession requires coordinated daemon activation with a node-bound candidate",
23 )?;
24 ensure!(
25 successor.journal.is_some(),
26 "owner succession requires coordinated daemon activation with a decision journal"
27 );
28 Ok(successor.node.id == node.id() && successor.node.signing_key == node.public_key())
29}
30
31pub(crate) fn check_epochs(
32 db: &Connection,
33 node: &NodeIdentity,
34 state: &VerifiedState,
35) -> Result<()> {
36 for signed in &state.state().owner_transitions {
37 let own = local(signed, node)?;
38 let (wire, id): (Vec<u8>, Option<String>) = db.query_row(
39 "SELECT transition,local_candidate FROM owner_epochs WHERE epoch=?1",
40 [signed.transition.epoch],
41 |r| Ok((r.get(0)?, r.get(1)?)),
42 )?;
43 ensure!(
44 wire == signed.encode()? && own == id.is_some(),
45 "accepted owner epoch or local signer reference changed"
46 );
47 if let Some(id) = id {
48 let wire: Vec<u8> = db.query_row(
49 "SELECT candidate FROM owner_candidates WHERE id=?1",
50 [&id],
51 |r| r.get(0),
52 )?;
53 let candidate = SignedOwnerCandidate::decode(&wire)?;
54 ensure!(
55 candidate.candidate.id == id
56 && candidate.digest()?
57 == signed.transition.successor.as_ref().unwrap().candidate
58 && candidate.candidate.owner_key == signed.transition.owner_key,
59 "active owner candidate changed"
60 );
61 }
62 }
63 Ok(())
64}
65
66pub(crate) fn admit_epochs(
70 db: &Connection,
71 node: &NodeIdentity,
72 state: &VerifiedState,
73 initial: bool,
74 channel: Option<&SignedConfigurationGrant>,
75) -> Result<()> {
76 for signed in &state.state().owner_transitions {
77 let exists: bool = db.query_row(
78 "SELECT EXISTS(SELECT 1 FROM owner_epochs WHERE epoch=?1)",
79 [signed.transition.epoch],
80 |r| r.get(0),
81 )?;
82 let own = local(signed, node)?;
83 if exists {
84 continue;
85 }
86 ensure!(
87 !own,
88 "local owner succession requires coordinated activation"
89 );
90 if !initial {
91 let channel = channel
92 .context("owner succession must arrive through its prepared successor stream")?;
93 let mut ready = false;
94 let mut query = db.prepare("SELECT c.grant,s.writer,s.writer_key,s.origin_hash,c.group_id FROM configuration_streams c JOIN streams s USING(group_id) WHERE s.purpose='configuration'")?;
95 for row in query.query_map([], |r| {
96 Ok((
97 r.get::<_, Vec<u8>>(0)?,
98 r.get::<_, String>(1)?,
99 r.get::<_, gent_crypto::PublicKey>(2)?,
100 r.get::<_, gent_crypto::Digest>(3)?,
101 r.get::<_, Vec<u8>>(4)?,
102 ))
103 })? {
104 let (wire, writer, key, origin, group) = row?;
105 let grant = SignedConfigurationGrant::decode(&wire)?;
106 let g = &grant.grant;
107 if grant == *channel
108 && g.group == group
109 && g.owner_candidate
110 == Some(signed.transition.successor.as_ref().unwrap().candidate)
111 && g.reader == node.id()
112 && g.reader_key == node.public_key()
113 && g.writer == writer
114 && g.writer_key == key
115 && g.origin == origin
116 && g.base == signed.transition.base
117 && grant.can_publish(state)?
118 {
119 ready = true;
120 }
121 }
122 ensure!(
123 ready,
124 "owner succession requires a prepared incoming configuration stream"
125 );
126 }
127 db.execute(
128 "INSERT INTO owner_epochs VALUES(?1,?2,NULL)",
129 params![signed.transition.epoch, signed.encode()?],
130 )?;
131 }
132 check_epochs(db, node, state)
133}
134
135pub(crate) fn active_key(
136 home: &Path,
137 db: &Connection,
138 state: &VerifiedState,
139 node: &NodeIdentity,
140) -> Result<OwnerKey> {
141 check_epochs(db, node, state)?;
142 let id: String = db.query_row(
143 "SELECT local_candidate FROM owner_epochs WHERE epoch=?1",
144 [state.owner_epoch()],
145 |r| r.get(0),
146 )?;
147 let (key, candidate) = read_key(&candidate_path(home, &id)?)?;
148 let signed = state
149 .state()
150 .owner_transitions
151 .last()
152 .context("missing successor epoch")?;
153 ensure!(
154 key.public_key() == state.state().owner_key
155 && candidate.candidate.id == id
156 && candidate.digest()?
157 == signed
158 .transition
159 .successor
160 .as_ref()
161 .context("missing successor")?
162 .candidate
163 && candidate.candidate.node.id == node.id()
164 && candidate.candidate.node.signing_key == node.public_key(),
165 "active successor key changed"
166 );
167 Ok(key)
168}
169
170pub(super) fn readiness(
171 db: &Connection,
172 node: &NodeIdentity,
173 baseline: &VerifiedState,
174 candidate: &SignedOwnerCandidate,
175) -> Result<Vec<(SignedConfigurationGrant, Receipt)>> {
176 let digest = candidate.digest()?;
177 let mut ready = std::collections::BTreeMap::new();
178 let mut query = db.prepare("SELECT c.grant,c.group_id,s.writer,s.writer_key,s.origin_hash,s.head FROM configuration_streams c JOIN streams s USING(group_id) WHERE s.purpose='configuration' ORDER BY c.group_id")?;
179 for row in query.query_map([], |r| {
180 Ok((
181 r.get::<_, Vec<u8>>(0)?,
182 r.get::<_, Vec<u8>>(1)?,
183 r.get::<_, String>(2)?,
184 r.get::<_, gent_crypto::PublicKey>(3)?,
185 r.get::<_, gent_crypto::Digest>(4)?,
186 r.get::<_, u64>(5)?,
187 ))
188 })? {
189 let (wire, group, writer, key, origin, head) = row?;
190 let grant = SignedConfigurationGrant::decode(&wire)?;
191 if grant.grant.owner_candidate != Some(digest) {
192 continue;
193 }
194 grant.verify_owner_candidate(candidate)?;
195 grant.verify_initial(baseline, candidate.candidate.issued_at)?;
196 let g = &grant.grant;
197 ensure!(
198 writer == node.id()
199 && key == node.public_key()
200 && group == g.group
201 && origin == g.origin
202 && head == 0,
203 "standby stream changed before activation"
204 );
205 let (reader, reader_key, sequence, saved_digest, receipt): (String,gent_crypto::PublicKey,u64,gent_crypto::Digest,Vec<u8>) = db.query_row("SELECT reader,reader_key,sequence,digest,receipt FROM stream_confirmed WHERE group_id=?1", [&group], |r| Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?)))?;
206 let receipt = Receipt::decode(&receipt)?;
207 receipt.verify(&g.reader_key)?;
208 ensure!(
209 reader == g.reader
210 && reader_key == g.reader_key
211 && sequence == 0
212 && saved_digest == origin
213 && receipt.group() == group
214 && receipt.sequence() == 0
215 && receipt.digest() == origin,
216 "standby reader readiness changed"
217 );
218 let data: bool = db.query_row("SELECT EXISTS(SELECT 1 FROM network_links l JOIN streams o ON o.group_id=l.outgoing JOIN streams i ON i.group_id=l.incoming
219 WHERE l.peer=?1 AND l.peer_key=?2 AND o.purpose='data' AND i.purpose='data' AND o.writer=?3 AND o.writer_key=?4 AND i.writer=?1 AND i.writer_key=?2)",
220 params![reader,reader_key.as_slice(),node.id(),node.public_key().as_slice()], |r| r.get(0))?;
221 ensure!(
222 data,
223 "successor needs an established data link to each peer"
224 );
225 ready.insert(reader, (grant, receipt));
226 }
227 ensure!(
228 baseline
229 .state()
230 .nodes
231 .keys()
232 .filter(|id| id.as_str() != node.id())
233 .all(|id| ready.contains_key(id)),
234 "successor configuration streams are not ready for every enrolled peer"
235 );
236 Ok(ready.into_values().collect())
237}
238
239impl Store {
240 pub fn activate_owner_handoff(&mut self, credential: &str, id: &str) -> Result<SignedState> {
243 ensure!(hash(credential) == self.owner_hash, "unauthorized");
244 let _lock = config::state_lock(&self.home, "owner-handoff.lock")?;
245 let (key, candidate) = read_key(&candidate_path(&self.home, id)?)?;
246 let tx = self
247 .db
248 .transaction_with_behavior(TransactionBehavior::Immediate)?;
249 let (baseline, wire, completed): (Vec<u8>, Vec<u8>, Option<Vec<u8>>) = tx.query_row(
250 "SELECT baseline,candidate,completed FROM owner_candidates WHERE id=?1",
251 [id],
252 |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
253 )?;
254 ensure!(
255 wire == candidate.encode()?
256 && candidate.candidate.node.id == self.identity.node.id()
257 && candidate.candidate.node.signing_key == self.identity.node.public_key(),
258 "activation belongs to another candidate or node"
259 );
260 let pinned = restore(&candidate, &baseline)?;
261 let completed = SignedState::decode(&completed.context("owner handoff is not completed")?)?;
262 let authorization = completed
263 .state
264 .owner_transitions
265 .last()
266 .context("missing handoff authorization")?;
267 pinned.verify_owner_authorization(&candidate, authorization)?;
268 ensure!(
269 pinned
270 .accept_owner_authorization(&key, &candidate, authorization, now() as u64)?
271 .encode()?
272 == completed.encode()?,
273 "completed owner handoff changed"
274 );
275 let state = self.identity.state(&tx)?;
276 if state.owner_epoch() >= authorization.transition.epoch {
277 ensure!(
278 state
279 .state()
280 .owner_transitions
281 .get(authorization.transition.epoch as usize - 1)
282 == Some(authorization),
283 "another owner handoff was accepted"
284 );
285 check_epochs(&tx, &self.identity.node, &state)?;
286 } else {
287 ensure!(
288 state.checkpoint() == pinned.checkpoint(),
289 "authority changed since handoff preparation"
290 );
291 readiness(&tx, &self.identity.node, &pinned, &candidate)?;
292 let (entries, body) =
293 journal::require_complete(&tx, &pinned, &candidate, authorization)?;
294 configuration::storage::handoff::adopt(&tx, pinned.checkpoint(), entries, &body)?;
295 tx.execute(
296 "INSERT INTO owner_epochs VALUES(?1,?2,?3)",
297 params![authorization.transition.epoch, authorization.encode()?, id],
298 )?;
299 let accepted = self.identity.apply(&tx, completed.clone())?;
300 let timestamp = requests::clock(&tx, now())? as u64;
301 if accepted.state().expires_at.saturating_sub(timestamp) <= 6 * 60 * 60 {
302 self.identity.apply(&tx, accepted.renew(&key, timestamp)?)?;
303 }
304 }
305 tx.commit()?;
306 self.sync_wakeup.notify_one();
307 self.project_config()?;
308 self.reconcile_configuration()?;
309 Ok(completed)
310 }
311}