Skip to main content

coven_sync/
sequence_copies.rs

1//! Key copies sent beside an operation's entry, in an admission's slot and on
2//! their own (§12.1, §13.2).
3
4use crate::{
5    history::History,
6    sequence_sync::sequence_operations::Request,
7    sequence_sync::{SequenceSync, Session},
8    OperationRejection, SyncError,
9};
10use coven_crypto::{MemberIdentity, StoreKeyring};
11use coven_format::{
12    admin::StoreChange,
13    sealed_key::{CopyBox, KeyCopyPrefix},
14    sealed_slot::{BoxPlace, SlotKind, SlotObjectPrefix},
15};
16use coven_merge::Audience;
17use serde::{Deserialize, Serialize};
18
19/// An approved join request's admission, as its operation journals it: the
20/// entry, and the member's own copy of the circle key it introduces, exactly
21/// as the request carried it, so the one claim, and every retry of it, sends
22/// the bytes the request held (§13.2). The approving device never holds that
23/// key.
24#[derive(Clone, Serialize, Deserialize)]
25pub(crate) struct ApprovedAdmission {
26    #[serde(with = "change")]
27    pub(crate) change: StoreChange,
28    #[serde(with = "route")]
29    own_routing: KeyCopyPrefix,
30    own_sealed: Vec<u8>,
31}
32
33impl ApprovedAdmission {
34    pub(crate) fn new(change: StoreChange, own: CopyBox) -> Self {
35        Self { change, own_routing: own.routing, own_sealed: own.sealed }
36    }
37
38    /// The member's own circle box.
39    fn own(&self) -> CopyBox {
40        CopyBox { routing: self.own_routing.clone(), sealed: self.own_sealed.clone() }
41    }
42}
43
44/// The copies `change` sends before its entry, when `author`'s device
45/// holding `ring` makes it. An admission carries its own in its slot, each
46/// key once, in `(audience, key)` order (format.md D9).
47pub(crate) fn required_copies(
48    history: &History,
49    ring: &StoreKeyring,
50    change: &StoreChange,
51    author: coven_foundation::id_source::MemberId,
52) -> Vec<KeyCopyPrefix> {
53    match change {
54        StoreChange::RotateKey { audience, key, .. } => history.routes(audience, *key),
55        // The key replaces the one the removed member holds: it goes to the
56        // members who stay, never to the one removed (§15.8).
57        StoreChange::RemoveCircleMember { circle, member, key, .. } => history
58            .routes(&Audience::Circle(*circle), *key)
59            .into_iter()
60            .filter(|route| route.member != *member)
61            .collect(),
62        // Store creation carries the creator's copy of the first store key
63        // and of each circle's first key, her private circle's among them
64        // (§10.3).
65        StoreChange::CreateStore { key, admin, .. } => {
66            let mut copies = vec![KeyCopyPrefix {
67                audience: Audience::Store,
68                key: *key,
69                member: author,
70                sealing: admin.sealing,
71            }];
72            copies.extend(change.created_circles().map(|circle| KeyCopyPrefix {
73                audience: Audience::Circle(circle.circle),
74                key: circle.key,
75                member: author,
76                sealing: admin.sealing,
77            }));
78            copies.sort_by(|a, b| (&a.audience, a.key).cmp(&(&b.audience, b.key)));
79            copies
80        }
81        StoreChange::CreateCircle { circle, key, .. } => vec![KeyCopyPrefix {
82            audience: Audience::Circle(*circle),
83            key: *key,
84            member: author,
85            sealing: history.state.members[&author].keys.sealing,
86        }],
87        StoreChange::AddCircleMember { circle, member } => history
88            .introductions
89            .iter()
90            .filter(|intro| intro.audience == Audience::Circle(*circle))
91            .map(|intro| KeyCopyPrefix {
92                audience: intro.audience.clone(),
93                key: intro.key,
94                member: *member,
95                sealing: history.state.members[member].keys.sealing,
96            })
97            .collect(),
98        StoreChange::AdmitMember { member, keys, .. }
99        | StoreChange::RecoverMember { member, keys, .. }
100        | StoreChange::ReplaceMemberKeys { member, keys, .. } => history
101            .introductions
102            .iter()
103            .filter(|intro| {
104                intro.audience == Audience::Store
105                    || (crate::effects::belongs(&history.state, &intro.audience, member)
106                        && history.accepted(ring, &intro.audience, intro.key))
107            })
108            .map(|intro| ((intro.audience.clone(), intro.key), keys.sealing))
109            .collect::<std::collections::BTreeMap<_, _>>()
110            .into_iter()
111            .map(|((audience, key), sealing)| KeyCopyPrefix {
112                audience,
113                key,
114                member: *member,
115                sealing,
116            })
117            .collect(),
118        _ => Vec::new(),
119    }
120}
121
122/// An admission's clear prefix: each of `copies`, in order, sealed for its
123/// box at its index in the slot at `path` whose body `store_key` seals, then
124/// an admitted member's own box as the request carried it (a creation has
125/// none). A claim that loses its slot
126/// seals the copies again (D11). A store key `ring` lacks
127/// fails here, before anything is claimed: the approval waits for it (§13.2).
128/// An admission whose slot, with `plaintext` bytes of body, would exceed a
129/// slot's size is refused with `AdmissionTooLarge`, also before anything is
130/// claimed (format.md D2).
131pub(crate) fn admission_prefix(
132    ring: &StoreKeyring,
133    path: &coven_storage::ObjectPath,
134    store_key: coven_foundation::id_source::KeyId,
135    copies: Vec<KeyCopyPrefix>,
136    admission: Option<&ApprovedAdmission>,
137    plaintext: usize,
138) -> Result<Result<SlotObjectPrefix, OperationRejection>, SyncError> {
139    let boxes = copies
140        .into_iter()
141        .enumerate()
142        .map(|(index, route)| {
143            seal_copy(ring, path, store_key, BoxPlace::Admission(index as u32), route)
144        })
145        .collect::<Result<Vec<_>, _>>()?;
146    let prefix = SlotObjectPrefix {
147        format: coven_format::FormatVersion::CURRENT,
148        key: store_key,
149        kind: SlotKind::Admission { copies: boxes, own: admission.map(ApprovedAdmission::own) },
150    };
151    Ok(if prefix.fits(plaintext)? {
152        Ok(prefix)
153    } else {
154        Err(OperationRejection::AdmissionTooLarge)
155    })
156}
157
158/// `route`'s key from `ring`, sealed to its recipient for the box at `place`
159/// in the slot at `path` whose body `store_key` seals (D11).
160pub(super) fn seal_copy(
161    ring: &StoreKeyring,
162    path: &coven_storage::ObjectPath,
163    store_key: coven_foundation::id_source::KeyId,
164    place: BoxPlace,
165    route: KeyCopyPrefix,
166) -> Result<CopyBox, SyncError> {
167    let context = SlotObjectPrefix::copy_context(
168        coven_format::FormatVersion::CURRENT,
169        store_key,
170        place,
171        &route,
172    )?;
173    let sealed = match route.audience {
174        Audience::Store => coven_crypto::seal_store_key(
175            ring.store_key(route.key)?,
176            &route.sealing,
177            path.as_str(),
178            &context,
179        )?,
180        Audience::Circle(circle) => coven_crypto::seal_circle_key(
181            ring.circle_key(circle, route.key)?,
182            &route.sealing,
183            path.as_str(),
184            &context,
185        )?,
186    };
187    Ok(CopyBox { routing: route, sealed })
188}
189
190pub(super) mod change {
191    use super::*;
192    pub(crate) fn serialize<S: serde::Serializer>(
193        value: &StoreChange,
194        output: S,
195    ) -> Result<S::Ok, S::Error> {
196        value.encode().map_err(serde::ser::Error::custom)?.serialize(output)
197    }
198    pub(crate) fn deserialize<'de, D: serde::Deserializer<'de>>(
199        input: D,
200    ) -> Result<StoreChange, D::Error> {
201        StoreChange::decode(&Vec::<u8>::deserialize(input)?).map_err(serde::de::Error::custom)
202    }
203}
204
205pub(super) mod route {
206    use super::*;
207    pub(crate) fn serialize<S: serde::Serializer>(
208        value: &KeyCopyPrefix,
209        output: S,
210    ) -> Result<S::Ok, S::Error> {
211        (&value.audience.to_string(), value.key, value.member, value.sealing.as_bytes())
212            .serialize(output)
213    }
214    pub(crate) fn deserialize<'de, D: serde::Deserializer<'de>>(
215        input: D,
216    ) -> Result<KeyCopyPrefix, D::Error> {
217        let (audience, key, member, sealing): (String, _, _, [u8; 32]) =
218            Deserialize::deserialize(input)?;
219        let audience: Audience = audience.parse().map_err(serde::de::Error::custom)?;
220        Ok(KeyCopyPrefix {
221            audience,
222            key,
223            member,
224            sealing: coven_crypto::SealingKey::from_bytes(sealing),
225        })
226    }
227}
228
229impl SequenceSync {
230    /// Admit a member as an approved join request does, with the member's
231    /// own copy of the circle key the entry introduces, for a test that
232    /// admits without a join: the pair `admitting` returns.
233    #[cfg(any(test, feature = "test-utils"))]
234    pub async fn administer_admission(
235        self: &std::sync::Arc<Self>,
236        (change, own): (StoreChange, CopyBox),
237    ) -> Result<(), SyncError> {
238        self.submit(crate::sequence_sync::sequence_operations::Request::Admission(
239            ApprovedAdmission::new(change, own),
240        ))
241        .await
242        .map(drop)
243    }
244
245    /// Send the older keys this device's member holds to the current members
246    /// of those keys' audiences whose current sealing key has no copy of
247    /// them, each as an operation of its own (§12.1). Another member's device
248    /// may send the same copy meanwhile; two copies of one key to one member
249    /// are harmless, so no device waits for another.
250    pub(crate) async fn send_owed_copies(
251        &self,
252        session: &mut Session,
253        ring: &mut StoreKeyring,
254        member: &MemberIdentity,
255    ) -> Result<(), SyncError> {
256        for route in session.history.owed_copies(ring, member.member()) {
257            let sends =
258                |request: &Request| matches!(request, Request::Copy(owed) if *owed == route);
259            // A journaled copy resumes under its own backoff.
260            if self.journaled(&sends).await?.is_some() {
261                continue;
262            }
263            let result = self
264                .start_request(session, ring, member, Request::Copy(route.clone()), "key copy")
265                .await
266                .map(drop);
267            self.own_work(result, &sends).await?;
268        }
269        Ok(())
270    }
271}
272
273#[cfg(test)]
274#[path = "sequence_copies_tests.rs"]
275mod tests;