Skip to main content

coven_sync/
sequence_keys.rs

1//! Fresh audience keys enter custody only after their operation records them.
2use crate::sequence_sync::OperationState;
3use crate::{
4    sequence_sync::sequence_operations::{
5        OperationProgress, OperationStep, Request, SequenceOperation,
6    },
7    sequence_sync::{next_slot, SequenceSync, Session},
8    SyncError,
9};
10use coven_crypto::{MemberIdentity, StoreKeyring};
11use coven_database::OperationRecord;
12use coven_format::admin::StoreChange;
13use coven_foundation::id_source::{CircleId, KeyId, MemberId};
14use coven_merge::Audience;
15use serde::{Deserialize, Serialize};
16use std::sync::Arc;
17
18/// The journal names material in custody; it never carries the material (§12.4).
19#[derive(Clone, Serialize, Deserialize)]
20pub(crate) enum KeyPreparation {
21    Circle {
22        circle: CircleId,
23        name: String,
24        key: KeyId,
25    },
26    Rotation {
27        #[serde(with = "crate::pending_encoding::audience")]
28        audience: Audience,
29        key: KeyId,
30    },
31    /// Removing `member` from `circle` with the circle's replacement key
32    /// (§15.8): the removal entry introduces it.
33    CircleRemoval {
34        circle: CircleId,
35        member: MemberId,
36        key: KeyId,
37    },
38}
39
40impl KeyPreparation {
41    pub(crate) fn kind(&self) -> crate::OperationKind {
42        match self {
43            Self::Circle { .. } => crate::OperationKind::CreateCircle,
44            Self::Rotation { .. } => crate::OperationKind::RotateKey,
45            Self::CircleRemoval { .. } => crate::OperationKind::RemoveCircleMember,
46        }
47    }
48}
49
50impl SequenceOperation {
51    /// Making a circle with its first key, before its first step: the pass
52    /// keeps the key in custody, then claims its copy and its introduction.
53    pub(crate) fn circle(circle: CircleId, name: String, key: KeyId) -> Self {
54        Self {
55            request: Request::Key(KeyPreparation::Circle { circle, name, key }),
56            progress: OperationProgress::Running(OperationStep::Preparing),
57        }
58    }
59}
60
61impl SequenceOperation {
62    /// Removing a circle member with the circle's new key, before its first
63    /// step: the pass keeps the key in custody, then claims its copies for the
64    /// members who stay and the removal that introduces it.
65    pub(crate) fn circle_removal(circle: CircleId, member: MemberId, key: KeyId) -> Self {
66        Self {
67            request: Request::Key(KeyPreparation::CircleRemoval { circle, member, key }),
68            progress: OperationProgress::Running(OperationStep::Preparing),
69        }
70    }
71}
72
73impl SequenceSync {
74    /// Replace an audience key through the administrative journal.
75    pub async fn rotate_key(self: &Arc<Self>, audience: Audience) -> Result<(), SyncError> {
76        let key = KeyId(self.ids.new_id());
77        self.run_key(KeyPreparation::Rotation { audience, key }).await
78    }
79
80    /// Remove `member` from `circle`, replacing the circle's key in the same
81    /// entry (§15.8), through the administrative journal.
82    pub async fn remove_circle_member(
83        self: &Arc<Self>,
84        circle: CircleId,
85        member: MemberId,
86    ) -> Result<(), SyncError> {
87        let key = KeyId(self.ids.new_id());
88        self.run_key(KeyPreparation::CircleRemoval { circle, member, key }).await
89    }
90
91    async fn run_key(self: &Arc<Self>, target: KeyPreparation) -> Result<(), SyncError> {
92        let owner = self.clone();
93        // The owned task survives cancellation of the app's waiter, as an
94        // operation's submission does.
95        let rotating = async move {
96            let mut session = owner.session.lock().await;
97            let member =
98                owner.member.read()?.ok_or(coven_storage::StorageFailure::MemberKeysMissing)?;
99            let mut ring = owner.ring(&mut session, &member).await?;
100            owner.read_forward(&mut session, &mut ring, &member).await?;
101            owner.settle_open(&mut session, &mut ring, &member).await?;
102            owner.resume_administration(&mut session, &mut ring, &member).await?;
103            owner.install_key(&mut session, &mut ring, &member, target).await
104        };
105        coven_foundation::task::spawn_completing(
106            "replace a key",
107            self.database.bugs().clone(),
108            rotating,
109        )
110        .await?
111    }
112    async fn install_key(
113        &self,
114        session: &mut Session,
115        ring: &mut StoreKeyring,
116        member: &MemberIdentity,
117        target: KeyPreparation,
118    ) -> Result<(), SyncError> {
119        let id = self.start_request_row(Request::Key(target), "key").await?;
120        self.run_administration(session, ring, member, id).await?.into_slot().map(drop)
121    }
122
123    pub(crate) async fn prepare_audience_key(
124        &self,
125        session: &Session,
126        ring: &mut StoreKeyring,
127        member: &MemberIdentity,
128        record: &OperationRecord,
129        target: KeyPreparation,
130    ) -> Result<(), SyncError> {
131        let (audience, key) = match &target {
132            KeyPreparation::Circle { circle, key, .. } => (Audience::Circle(*circle), *key),
133            KeyPreparation::Rotation { audience, key } => (audience.clone(), *key),
134            KeyPreparation::CircleRemoval { circle, key, .. } => (Audience::Circle(*circle), *key),
135        };
136        let mut prepared = ring.clone();
137        // A crash after custody committed but before the journal advanced
138        // reuses that exact key. Before custody committed, nothing used it (§12.4).
139        let hash = match audience {
140            Audience::Store => {
141                if !prepared.store_key_ids().any(|id| id == key) {
142                    prepared.insert_store_key(coven_crypto::StoreKey::generate(key)?)?;
143                }
144                prepared.store_key(key)?.hash()
145            }
146            Audience::Circle(circle) => {
147                if !prepared.circle_key_ids(circle).any(|id| id == key) {
148                    prepared.insert_circle_key(coven_crypto::CircleKey::generate(circle, key)?)?;
149                }
150                prepared.circle_key(circle, key)?.hash()
151            }
152        };
153        let change = match target {
154            // The circle starts at the version this app's newest breaking
155            // migration reached, its base (§15.5).
156            KeyPreparation::Circle { circle, name, key } => StoreChange::CreateCircle {
157                circle,
158                name,
159                key,
160                key_hash: hash,
161                breaking_version: self.database.breaking_version().await?,
162            },
163            KeyPreparation::Rotation { audience, key } => {
164                StoreChange::RotateKey { audience, key, key_hash: hash }
165            }
166            KeyPreparation::CircleRemoval { circle, member, key } => {
167                StoreChange::RemoveCircleMember { circle, member, key, key_hash: hash }
168            }
169        };
170        let progress = match session.history.validate(
171            &coven_format::sequence::SlotHeader {
172                device: self.device,
173                claim: 1,
174                author: member.member(),
175                after: session.through,
176            },
177            next_slot(session.through)?,
178            &change,
179        ) {
180            Ok(_) => {
181                self.keys.persist(&prepared)?;
182                *ring = prepared;
183                OperationProgress::Running(OperationStep::Preparing)
184            }
185            Err(reason) => OperationProgress::Undo { step: OperationStep::Preparing, reason },
186        };
187        self.database
188            .advance_operation(
189                SequenceOperation { request: Request::Change(change), progress }.update(record)?,
190            )
191            .await?;
192        Ok(())
193    }
194    pub(crate) async fn rotate_exposed(
195        &self,
196        session: &mut Session,
197        ring: &mut StoreKeyring,
198        member: &MemberIdentity,
199    ) -> Result<(), SyncError> {
200        for audience in session.history.introduced_audiences() {
201            if crate::effects::belongs(&session.history.state, &audience, &member.member())
202                && session
203                    .history
204                    .introductions
205                    .iter()
206                    .rev()
207                    .find(|intro| intro.audience == audience)
208                    .is_some_and(|intro| session.history.exposed(&audience, intro.key))
209            {
210                let rotates = |request: &Request| {
211                    matches!(request,
212                    Request::Change(StoreChange::RotateKey { audience: rotated, .. })
213                    | Request::Key(KeyPreparation::Rotation { audience: rotated, .. })
214                    if *rotated == audience)
215                };
216                // A journaled rotation resumes under its own backoff.
217                if self.journaled(rotates).await?.is_some() {
218                    continue;
219                }
220                let key = KeyId(self.ids.new_id());
221                let target = KeyPreparation::Rotation { audience: audience.clone(), key };
222                let result = self.install_key(session, ring, member, target).await;
223                self.own_work(result, rotates).await?;
224            }
225        }
226        Ok(())
227    }
228}
229
230#[cfg(test)]
231#[path = "sequence_keys_tests.rs"]
232mod tests;