Skip to main content

gent_daemon/encrypted/ordered/configuration/
standby.rs

1//! Prepare the successor's MLS groups without sharing an owner signing key.
2//! Grants are installed before handoff; publication waits for the signed choice.
3use super::*;
4use gent_crypto::succession::SignedOwnerCandidate;
5
6const MAX_RECORDS: u64 = 4096;
7const MAX_BYTES: u64 = 64 * 1024 * 1024;
8
9/// Private pairing material for the current owner to authorize. The Welcome is
10/// signed by the candidate node; the eventual grant binds every field below.
11#[derive(Clone)]
12pub struct ConfigurationPreparation {
13    pub candidate: SignedOwnerCandidate,
14    pub reader: String,
15    pub reader_key: PublicKey,
16    pub packet: Packet,
17}
18
19impl ConfigurationPreparation {
20    pub fn verify_grant(&self, grant: &SignedConfigurationGrant) -> Result<()> {
21        grant.verify_owner_candidate(&self.candidate)?;
22        self.packet
23            .verify(&self.candidate.candidate.node.signing_key)?;
24        ensure!(
25            self.packet.sequence() == 0
26                && self.packet.group() == grant.grant.group
27                && self.packet.digest()? == grant.grant.origin
28                && self.reader == grant.grant.reader,
29            "standby configuration grant does not match preparation"
30        );
31        ensure!(
32            self.reader_key == grant.grant.reader_key,
33            "standby reader key changed"
34        );
35        Ok(())
36    }
37}
38
39pub(crate) fn schema(db: &Connection, previous: i64) -> Result<()> {
40    let count: usize = db.query_row("SELECT COUNT(*) FROM sqlite_schema WHERE type='table' AND name IN ('configuration_preparations','owner_configuration_grants')", [], |r| r.get(0))?;
41    if count == 0 && previous < 21 {
42        db.execute_batch("CREATE TABLE configuration_preparations(
43            id TEXT PRIMARY KEY CHECK(length(id)=36),candidate BLOB NOT NULL CHECK(length(candidate)<=8192),
44            reader TEXT NOT NULL,reader_key BLOB NOT NULL CHECK(length(reader_key)=32),package_hash BLOB NOT NULL CHECK(length(package_hash)=32),
45            group_id BLOB NOT NULL UNIQUE REFERENCES streams(group_id));
46            CREATE TABLE owner_configuration_grants(group_id BLOB PRIMARY KEY,
47            candidate BLOB NOT NULL CHECK(length(candidate)<=8192),grant BLOB NOT NULL CHECK(length(grant)<=139264));")?;
48    } else {
49        ensure!(count == 2, "standby configuration storage is missing");
50        db.prepare("SELECT id,candidate,reader,reader_key,package_hash,group_id FROM configuration_preparations LIMIT 0")?;
51        db.prepare("SELECT group_id,candidate,grant FROM owner_configuration_grants LIMIT 0")?;
52    }
53    Ok(())
54}
55
56pub(crate) fn usage(db: &Connection) -> Result<(u64, u64)> {
57    Ok(db.query_row("SELECT COUNT(*),COALESCE(SUM(bytes),0) FROM (
58        SELECT length(candidate)+length(reader)+length(reader_key)+length(package_hash)+length(group_id) AS bytes FROM configuration_preparations
59        UNION ALL SELECT length(candidate)+length(grant)+length(group_id) FROM owner_configuration_grants)", [], |r| Ok((r.get(0)?,r.get(1)?)))?)
60}
61
62pub(crate) fn capacity(db: &Connection, bytes: usize) -> Result<()> {
63    let (records, used) = usage(db)?;
64    ensure!(
65        records < MAX_RECORDS && used.saturating_add(bytes as u64) <= MAX_BYTES,
66        "standby configuration preparation quota exhausted"
67    );
68    Ok(())
69}
70
71fn saved(db: &Connection, request: Uuid) -> Result<Option<(ConfigurationPreparation, Digest)>> {
72    type PreparationRow = (Vec<u8>, String, PublicKey, Digest, Vec<u8>);
73    let row: Option<PreparationRow> = db.query_row(
74        "SELECT candidate,reader,reader_key,package_hash,group_id FROM configuration_preparations WHERE id=?1",
75        [request.to_string()], |r| Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?)),
76    ).optional()?;
77    row.map(|(candidate, reader, reader_key, hash, group)| {
78        let candidate = SignedOwnerCandidate::decode(&candidate)?;
79        let packet = outgoing_request(db, request)?.context("standby stream origin is missing")?;
80        packet.verify(&candidate.candidate.node.signing_key)?;
81        let stream = stream(db, &group)?.context("standby stream is missing")?;
82        ensure!(
83            packet.group() == group
84                && packet.sequence() == 0
85                && stream.purpose == Purpose::Configuration.name()
86                && stream.writer == candidate.candidate.node.id
87                && stream.key == candidate.candidate.node.signing_key
88                && stream.origin == packet.digest()?
89                && stream.roster == roster_hash(&[&stream.writer, &reader])?,
90            "standby stream pins changed"
91        );
92        Ok((
93            ConfigurationPreparation {
94                candidate,
95                reader,
96                reader_key,
97                packet,
98            },
99            hash,
100        ))
101    })
102    .transpose()
103}
104
105impl OrderedEndpoint<'_> {
106    /// Create only a configuration stream. Until its grant is installed it is
107    /// unavailable to the dispatcher and cannot send application traffic.
108    pub fn prepare_standby_configuration(
109        &mut self,
110        request: Uuid,
111        candidate: &SignedOwnerCandidate,
112        peer: (&str, &[u8]),
113        now: u64,
114    ) -> Result<ConfigurationPreparation> {
115        ensure!(!request.is_nil(), "nil request ID");
116        self.inner.transact_mode(now, true, |session| {
117            ensure!(
118                candidate.candidate.node.id == session.signer.id()
119                    && candidate.candidate.node.signing_key == session.signer.public_key()
120                    && &candidate.candidate.anchor == session.state.anchor(),
121                "standby stream belongs to another candidate node"
122            );
123            let package_hash: Digest = Sha256::digest(peer.1).into();
124            if let Some((previous, pinned_hash)) = saved(session.db, request)? {
125                ensure!(
126                    previous.candidate == *candidate
127                        && previous.reader == peer.0
128                        && package_hash == pinned_hash,
129                    "standby configuration request changed"
130                );
131                authorize_saved_node(&session.state, peer.0, &previous.reader_key)?;
132                return Ok(previous);
133            }
134            candidate.verify(&session.state, now)?;
135            let reader_key = session
136                .state
137                .state()
138                .nodes
139                .get(peer.0)
140                .context("unknown standby reader")?
141                .signing_key;
142            let exists: bool = session.db.query_row(
143                "SELECT EXISTS(SELECT 1 FROM outbox WHERE id=?1)",
144                [request.to_string()],
145                |r| r.get(0),
146            )?;
147            ensure!(
148                !exists,
149                "cannot adopt another MLS operation as a standby stream"
150            );
151            let welcome = session.create_group(request, &[peer])?;
152            let packet =
153                session
154                    .signer
155                    .sign_stream_packet(&welcome.group_id, 0, [0; 32], &welcome.bytes)?;
156            let wire = candidate.encode()?;
157            capacity(
158                session.db,
159                wire.len() + peer.0.len() + 64 + packet.group().len(),
160            )?;
161            initialize_stream(
162                session,
163                &packet,
164                session.signer.id(),
165                session.signer.public_key(),
166                roster_hash(&[session.signer.id(), peer.0])?,
167            )?;
168            session.db.execute(
169                "UPDATE streams SET purpose='configuration' WHERE group_id=?1",
170                [packet.group()],
171            )?;
172            save_outgoing(session.db, request, &packet)?;
173            session.db.execute(
174                "INSERT INTO configuration_preparations VALUES(?1,?2,?3,?4,?5,?6)",
175                params![
176                    request.to_string(),
177                    wire,
178                    peer.0,
179                    reader_key.as_slice(),
180                    package_hash.as_slice(),
181                    packet.group()
182                ],
183            )?;
184            Ok(ConfigurationPreparation {
185                candidate: candidate.clone(),
186                reader: peer.0.into(),
187                reader_key,
188                packet,
189            })
190        })
191    }
192
193    /// Install the old owner's authorization without activating the candidate.
194    /// Exact installed retries need neither a fresh candidate nor a fresh lease.
195    pub fn install_standby_configuration(
196        &mut self,
197        request: Uuid,
198        grant: &SignedConfigurationGrant,
199        now: u64,
200    ) -> Result<ConfigurationInvitation> {
201        self.inner.transact_mode(now, true, |session| {
202            let (preparation, _) =
203                saved(session.db, request)?.context("unknown standby preparation")?;
204            preparation.verify_grant(grant)?;
205            ensure!(
206                grant.grant.writer == session.signer.id()
207                    && grant.grant.writer_key == session.signer.public_key(),
208                "standby grant belongs to another writer"
209            );
210            let group = preparation.packet.group();
211            let installed: bool = session.db.query_row(
212                "SELECT EXISTS(SELECT 1 FROM configuration_streams WHERE group_id=?1)",
213                [group],
214                |r| r.get(0),
215            )?;
216            if installed {
217                checked_stream(session, group, Purpose::Configuration)?;
218                ensure!(
219                    progress(session.db, group)?.grant == *grant,
220                    "standby grant changed"
221                );
222            } else {
223                preparation.candidate.verify(&session.state, now)?;
224                grant.verify_initial(&session.state, now)?;
225                ensure!(
226                    stream(session.db, group)?
227                        .context("missing standby stream")?
228                        .head
229                        == 0,
230                    "standby stream advanced before installation"
231                );
232                initialize_configuration(session.db, grant)?;
233            }
234            Ok(ConfigurationInvitation {
235                packet: preparation.packet,
236                grant: grant.clone(),
237            })
238        })
239    }
240}