Skip to main content

gent_daemon/encrypted/ordered/
configuration.rs

1//! Owner-authorized configuration recovery and committed handoff journals.
2//! Application messages never gain an expired-lease exemption.
3use super::*;
4use gent_crypto::{MAX_STATE_BYTES, OwnerKey, SignedConfigurationGrant};
5pub(crate) mod handoff;
6pub mod standby;
7
8pub const MAX_FRAGMENT_BYTES: usize = 256 * 1024;
9pub const MAX_PENDING_CONFIGURATION_BYTES: usize = 8 * 1024 * 1024;
10const MAX_REASSEMBLY_BYTES: usize = 8 * 1024 * 1024;
11
12/// Contains private identity metadata. Exchange through protected pairing only.
13#[derive(Clone)]
14pub struct ConfigurationInvitation {
15    pub packet: Packet,
16    pub grant: SignedConfigurationGrant,
17}
18
19#[derive(Serialize, Deserialize)]
20#[serde(deny_unknown_fields)]
21struct Fragment {
22    version: u8,
23    revision: u64,
24    digest: Digest,
25    total: usize,
26    offset: usize,
27    data: String,
28}
29
30#[derive(Deserialize)]
31#[serde(untagged)]
32enum ConfigurationRecord {
33    State(Fragment),
34    Handoff(handoff::Record),
35}
36
37pub(super) struct Progress {
38    pub(super) grant: SignedConfigurationGrant,
39    revision: u64,
40    hash: Digest,
41    offset: usize,
42}
43
44#[derive(Clone)]
45pub struct ConfigurationStream {
46    pub group: Vec<u8>,
47    pub outgoing: bool,
48}
49
50/// A replacement stream carries the next owner's activation. Older streams
51/// finish their accepted epoch without racing that separately prepared route.
52pub(crate) fn publication_limit(
53    signed: &SignedConfigurationGrant,
54    state: &VerifiedState,
55) -> Option<u64> {
56    let epoch =
57        signed.grant.owner_transitions.len() + usize::from(signed.grant.owner_candidate.is_some());
58    state
59        .state()
60        .owner_transitions
61        .get(epoch)
62        .map(|signed| signed.transition.base.revision)
63}
64
65impl OrderedEndpoint<'_> {
66    /// Only established, still-authorized configuration streams are eligible.
67    /// Expiry alone does not hide the recovery route; known revocation does.
68    pub fn configuration_streams(&mut self, now: u64) -> Result<Vec<ConfigurationStream>> {
69        self.inner.transact_mode(now, true, |session| {
70            let mut query = session.db.prepare(
71                "SELECT group_id FROM configuration_streams ORDER BY group_id LIMIT 4097",
72            )?;
73            let groups = query
74                .query_map([], |r| r.get::<_, Vec<u8>>(0))?
75                .collect::<rusqlite::Result<Vec<_>>>()?;
76            ensure!(groups.len() <= 4096, "too many configuration streams");
77            let mut streams = Vec::new();
78            for group in groups {
79                if let Ok(stream) = checked_stream(session, &group, Purpose::Configuration) {
80                    if stream.writer == session.signer.id()
81                        && !progress(session.db, &group)?
82                            .grant
83                            .can_publish(&session.state)?
84                    {
85                        continue;
86                    }
87                    streams.push(ConfigurationStream {
88                        group,
89                        outgoing: stream.writer == session.signer.id(),
90                    });
91                }
92            }
93            Ok(streams)
94        })
95    }
96
97    pub fn authority_state(&self) -> Result<VerifiedState> {
98        self.inner.authority_state()
99    }
100
101    /// Grants full configuration access to one trusted daemon. Both node keys
102    /// and the exact initial checkpoint are signed by the separate owner key.
103    pub fn create_configuration(
104        &mut self,
105        owner: &OwnerKey,
106        request: Uuid,
107        peer: (&str, &[u8]),
108        now: u64,
109    ) -> Result<ConfigurationInvitation> {
110        self.inner.transact(now, |session| {
111            ensure!(
112                owner.public_key() == session.state.state().owner_key,
113                "wrong owner authority"
114            );
115            let raw_exists: bool = session.db.query_row(
116                "SELECT EXISTS(SELECT 1 FROM outbox WHERE id=?1)",
117                [request.to_string()],
118                |row| row.get(0),
119            )?;
120            let saved = outgoing_request(session.db, request)?;
121            ensure!(
122                !raw_exists || saved.is_some(),
123                "cannot adopt a raw MLS operation"
124            );
125            if saved.is_none() {
126                ensure!(
127                    !crate::store::handoff::frozen(session.db, &session.state)?,
128                    "owner handoff is issued; configuration grants are frozen"
129                );
130            }
131            let welcome = session.create_group(request, &[peer])?;
132            if let Some(packet) = saved {
133                checked_stream(session, packet.group(), Purpose::Configuration)?;
134                return Ok(ConfigurationInvitation {
135                    grant: progress(session.db, packet.group())?.grant,
136                    packet,
137                });
138            }
139            let packet =
140                session
141                    .signer
142                    .sign_stream_packet(&welcome.group_id, 0, [0; 32], &welcome.bytes)?;
143            let grant = owner.authorize_configuration_stream(
144                &session.state,
145                packet.group(),
146                packet.digest()?,
147                (session.signer.id(), peer.0),
148                now,
149            )?;
150            initialize_stream(
151                session,
152                &packet,
153                session.signer.id(),
154                session.signer.public_key(),
155                roster_hash(&[session.signer.id(), peer.0])?,
156            )?;
157            initialize_configuration(session.db, &grant)?;
158            save_outgoing(session.db, request, &packet)?;
159            Ok(ConfigurationInvitation { packet, grant })
160        })
161    }
162
163    pub fn join_configuration(
164        &mut self,
165        invitation: &ConfigurationInvitation,
166        now: u64,
167    ) -> Result<()> {
168        let packet = &invitation.packet;
169        let signed = &invitation.grant;
170        self.inner.transact_mode(now, true, |session| {
171            signed.verify(session.state.anchor())?;
172            let grant = &signed.grant;
173            ensure!(
174                grant.reader == session.signer.id()
175                    && grant.reader_key == session.signer.public_key(),
176                "configuration grant belongs to another reader"
177            );
178            ensure!(
179                packet.sequence() == 0
180                    && packet.group() == grant.group
181                    && packet.digest()? == grant.origin,
182                "configuration grant does not match Welcome"
183            );
184            packet.verify(&grant.writer_key)?;
185            if let Some(saved) = stream(session.db, packet.group())? {
186                authorize(session, packet.group(), &saved)?;
187                ensure!(
188                    progress(session.db, packet.group())?.grant == *signed,
189                    "conflicting configuration grant"
190                );
191                return Ok(());
192            }
193            signed.verify_initial(&session.state, now)?;
194            let raw = Outgoing {
195                id: Uuid::nil(),
196                group_id: packet.group().into(),
197                bytes: packet.ciphertext().into(),
198            };
199            session.join(&raw, &[&grant.writer, &grant.reader], Some(&grant.writer))?;
200            initialize_stream(
201                session,
202                packet,
203                &grant.writer,
204                grant.writer_key,
205                roster_hash(&[&grant.writer, &grant.reader])?,
206            )?;
207            initialize_configuration(session.db, signed)
208        })
209    }
210
211    /// Publish the next bounded fragment of already accepted owner history.
212    /// Applying a new local signed revision and its history is a separate owner
213    /// transaction; this outbox then catches every configured peer up to it.
214    pub fn next_configuration(
215        &mut self,
216        group: &[u8],
217        request: Uuid,
218        now: u64,
219    ) -> Result<Option<Packet>> {
220        ensure!(!request.is_nil(), "nil request ID");
221        self.prepare_configuration(group, Some(request), now)
222    }
223
224    /// Daemon publication commits its allocated ID with the fragment and cursor.
225    pub(crate) fn prepare_configuration(
226        &mut self,
227        group: &[u8],
228        request: Option<Uuid>,
229        now: u64,
230    ) -> Result<Option<Packet>> {
231        // Already accepted signed history must remain publishable after lease
232        // expiry, including when its quota is preventing an owner renewal.
233        // The recovery grant and current saved node/key membership still apply.
234        self.inner.transact_mode(now, true, |session| {
235            let saved = checked_stream(session, group, Purpose::Configuration)?;
236            ensure!(saved.writer == session.signer.id(), "only the configuration writer can publish");
237            if let Some(request) = request {
238                let prior: Option<Vec<u8>> = session.db.query_row("SELECT group_id FROM configuration_requests WHERE id=?1", [request.to_string()], |row| row.get(0)).optional()?;
239                if let Some(prior) = prior {
240                    ensure!(prior == group, "conflicting configuration request ID");
241                    return Ok(Some(outgoing_request(session.db, request)?.context("missing configuration packet")?));
242                }
243                ensure!(!requests::managed(request), "transport request is unallocated or retired; it cannot publish configuration");
244            }
245            let cursor = progress(session.db, group)?;
246            ensure!(cursor.grant.can_publish(&session.state)?, "standby configuration candidate is not active");
247            let revision = cursor.revision.checked_add(1).context("revision overflow")?;
248            if publication_limit(&cursor.grant, &session.state).is_some_and(|last| revision > last) {
249                return Ok(None);
250            }
251            let Some(record) = history(session.db, revision)? else { return Ok(None); };
252            let checkpoint = record.verified_checkpoint(session.state.anchor())?;
253            ensure!(record.state.previous == Some(cursor.hash), "configuration publication history fork");
254            let wire = record.encode()?;
255            ensure!(cursor.offset < wire.len(), "invalid configuration cursor");
256            let end = (cursor.offset + MAX_FRAGMENT_BYTES).min(wire.len());
257            let fragment = Fragment { version:1, revision, digest:Sha256::digest(&wire).into(), total:wire.len(), offset:cursor.offset, data:STANDARD.encode(&wire[cursor.offset..end]) };
258            let body = serde_json::to_vec(&fragment)?;
259            let request = match request {
260                Some(request) => request,
261                None => requests::allocate(session.db, group, &body, None)?,
262            };
263            let packet = publish_in(session, group, Purpose::Configuration, |session| session.send(group, request, &body))?;
264            let (revision,hash,offset) = if end == wire.len() { (revision, checkpoint.state_hash,0) } else { (cursor.revision,cursor.hash,end) };
265            session.db.execute("UPDATE configuration_streams SET revision=?1,state_hash=?2,offset=?3 WHERE group_id=?4", params![revision,hash.as_slice(),offset,group])?;
266            session.db.execute("INSERT INTO configuration_requests VALUES(?1,?2)", params![request.to_string(),group])?;
267            Ok(Some(packet))
268        })
269    }
270
271    pub fn rotate_configuration(
272        &mut self,
273        group: &[u8],
274        request: Uuid,
275        now: u64,
276    ) -> Result<Packet> {
277        self.inner.transact(now, |session| {
278            ensure!(
279                progress(session.db, group)?
280                    .grant
281                    .can_publish(&session.state)?,
282                "standby configuration candidate is not active"
283            );
284            publish_in(session, group, Purpose::Configuration, |session| {
285                session.rotate(group, request)
286            })
287        })
288    }
289
290    pub fn stage_configuration(&mut self, packet: &Packet, now: u64) -> Result<Staged> {
291        self.inner.transact_mode(now, true, |session| {
292            stage_in(session, packet, Purpose::Configuration)
293        })
294    }
295    pub fn drain_configuration(
296        &mut self,
297        group: &[u8],
298        limit: usize,
299        now: u64,
300    ) -> Result<Vec<Received>> {
301        self.drain_mode(group, limit, now, Purpose::Configuration)
302    }
303    pub fn configuration_status(&mut self, group: &[u8], now: u64) -> Result<StreamStatus> {
304        self.status_mode(group, now, Purpose::Configuration)
305    }
306    pub fn configuration_outbox(
307        &mut self,
308        group: &[u8],
309        after: Option<u64>,
310        limit: usize,
311        now: u64,
312    ) -> Result<Vec<Packet>> {
313        self.outbox_mode(group, after, limit, now, Purpose::Configuration)
314    }
315}
316
317fn initialize_configuration(db: &Connection, signed: &SignedConfigurationGrant) -> Result<()> {
318    let grant = &signed.grant;
319    ensure!(
320        db.query_row("SELECT COUNT(*) FROM configuration_streams", [], |r| r
321            .get::<_, usize>(0))?
322            < 4096,
323        "configuration stream capacity reached"
324    );
325    db.execute(
326        "UPDATE streams SET purpose='configuration' WHERE group_id=?1",
327        [&grant.group],
328    )?;
329    db.execute(
330        "INSERT INTO configuration_streams VALUES(?1,?2,?3,?4,0)",
331        params![
332            grant.group,
333            signed.encode()?,
334            grant.base.revision,
335            grant.base.state_hash.as_slice()
336        ],
337    )?;
338    Ok(())
339}
340
341pub(super) fn progress(db: &Connection, group: &[u8]) -> Result<Progress> {
342    let (grant, revision, hash, offset): (Vec<u8>, u64, Digest, usize) = db.query_row(
343        "SELECT grant,revision,state_hash,offset FROM configuration_streams WHERE group_id=?1",
344        [group],
345        |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
346    )?;
347    Ok(Progress {
348        grant: SignedConfigurationGrant::decode(&grant)?,
349        revision,
350        hash,
351        offset,
352    })
353}
354
355pub(super) fn authorize(session: &Session<'_>, group: &[u8], stream: &Stream) -> Result<()> {
356    ensure!(
357        stream.purpose == Purpose::Configuration.name(),
358        "wrong stream purpose"
359    );
360    let signed = progress(session.db, group)?.grant;
361    signed.verify(session.state.anchor())?;
362    let grant = &signed.grant;
363    ensure!(
364        grant.group == group
365            && grant.origin == stream.origin
366            && grant.writer == stream.writer
367            && grant.writer_key == stream.key,
368        "configuration stream pin mismatch"
369    );
370    ensure!(
371        (session.signer.id() == grant.writer && session.signer.public_key() == grant.writer_key)
372            || (session.signer.id() == grant.reader
373                && session.signer.public_key() == grant.reader_key),
374        "configuration grant belongs to other endpoints"
375    );
376    authorize_saved_node(&session.state, &grant.writer, &grant.writer_key)?;
377    authorize_saved_node(&session.state, &grant.reader, &grant.reader_key)?;
378    Ok(())
379}
380
381fn history(db: &Connection, revision: u64) -> Result<Option<SignedState>> {
382    let wire: Option<Vec<u8>> = db
383        .query_row(
384            "SELECT state FROM authority_history WHERE revision=?1",
385            [revision],
386            |row| row.get(0),
387        )
388        .optional()?;
389    wire.map(|wire| SignedState::decode(&wire)).transpose()
390}
391
392pub(super) fn receive(
393    session: &Session<'_>,
394    group: &[u8],
395    wire: &[u8],
396    writer: &str,
397) -> Result<Received> {
398    session.receive_with(
399        group,
400        wire,
401        Some(writer),
402        |_, _, body| match serde_json::from_slice::<ConfigurationRecord>(&body)? {
403            ConfigurationRecord::State(part) => receive_fragment(session, group, part),
404            ConfigurationRecord::Handoff(record) => handoff::receive(session, group, record),
405        },
406    )
407}
408
409fn receive_fragment(session: &Session<'_>, group: &[u8], part: Fragment) -> Result<Received> {
410    let cursor = progress(session.db, group)?;
411    ensure!(
412        part.version == 1
413            && part.revision == cursor.revision + 1
414            && part.total > 0
415            && part.total <= MAX_STATE_BYTES
416            && part.offset < part.total,
417        "invalid configuration fragment"
418    );
419    let bytes = STANDARD.decode(&part.data)?;
420    ensure!(
421        bytes.len() == (part.total - part.offset).min(MAX_FRAGMENT_BYTES),
422        "invalid configuration fragment length"
423    );
424    let saved: Option<(u64, Digest, usize, Vec<u8>)> = session
425        .db
426        .query_row(
427            "SELECT revision,digest,total,bytes FROM configuration_fragments WHERE group_id=?1",
428            [group],
429            |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
430        )
431        .optional()?;
432    let mut wire = if let Some((revision, digest, total, wire)) = saved {
433        ensure!(
434            revision == part.revision
435                && digest == part.digest
436                && total == part.total
437                && wire.len() == part.offset,
438            "configuration fragment conflict or gap"
439        );
440        wire
441    } else {
442        ensure!(part.offset == 0, "missing configuration prefix");
443        // Reserve the complete record up front. Already admitted partial records
444        // must always have enough space to finish and release their reservation.
445        if bytes.len() < part.total {
446            let reserved: usize = session.db.query_row(
447                "SELECT COALESCE(SUM(total),0) FROM configuration_fragments",
448                [],
449                |row| row.get(0),
450            )?;
451            ensure!(
452                reserved + part.total <= MAX_REASSEMBLY_BYTES,
453                "configuration reassembly limit reached"
454            );
455        }
456        Vec::new()
457    };
458    wire.extend_from_slice(&bytes);
459    if wire.len() < part.total {
460        session.db.execute("INSERT INTO configuration_fragments VALUES(?1,?2,?3,?4,?5) ON CONFLICT(group_id) DO UPDATE SET bytes=excluded.bytes", params![group,part.revision,part.digest.as_slice(),part.total,wire])?;
461        return Ok(Received::ConfigurationPart {
462            revision: part.revision,
463            complete: false,
464        });
465    }
466    ensure!(
467        Sha256::digest(&wire).as_slice() == part.digest,
468        "configuration fragment digest mismatch"
469    );
470    let update = SignedState::decode(&wire)?;
471    let checkpoint = update.verified_checkpoint(session.state.anchor())?;
472    if cursor.grant.grant.owner_candidate.is_some() {
473        let publication = VerifiedState::restore(
474            session.state.anchor().clone(),
475            checkpoint.clone(),
476            update.clone(),
477        )?;
478        ensure!(
479            cursor.grant.can_publish(&publication)?,
480            "configuration update does not activate its standby candidate"
481        );
482    }
483    ensure!(
484        checkpoint.revision == part.revision && update.state.previous == Some(cursor.hash),
485        "configuration history fork or gap"
486    );
487    if checkpoint.revision <= session.state.checkpoint().revision {
488        let accepted = super::super::history::checkpoint(
489            session.db,
490            checkpoint.revision,
491            session.state.anchor(),
492        )?;
493        ensure!(
494            accepted == checkpoint,
495            "conflicting accepted authority history"
496        );
497    } else {
498        let mut next = session.state.clone();
499        next.advance_history(std::slice::from_ref(&update))?;
500        crate::store::handoff::admit_epochs(
501            session.db,
502            session.signer,
503            &next,
504            false,
505            Some(&cursor.grant),
506        )?;
507        persist_authority(session.db, session.signer, &next, &[update])?;
508    }
509    session.db.execute(
510        "UPDATE configuration_streams SET revision=?1,state_hash=?2 WHERE group_id=?3",
511        params![checkpoint.revision, checkpoint.state_hash.as_slice(), group],
512    )?;
513    session.db.execute(
514        "DELETE FROM configuration_fragments WHERE group_id=?1",
515        [group],
516    )?;
517    Ok(Received::ConfigurationPart {
518        revision: checkpoint.revision,
519        complete: true,
520    })
521}