Skip to main content

coven_sync/
admin_steps.rs

1//! Administrative changes as steps of the app's write (§4, §11.1): the
2//! write checks the change against the state this device has applied and
3//! journals it, with or without storage. Making a circle is one too. A pass then catches up, validates
4//! it again against everything it read, and claims its slot; one the
5//! caught-up state refuses is undone and rejected (§11.2).
6
7use crate::sequence_sync::sequence_operations::SequenceOperation;
8use crate::sequence_sync::{next_slot, registered};
9use crate::{effects, OperationRejection, OperationSteps, SequenceState, SyncError};
10use coven_crypto::MemberIdentity;
11use coven_database::{Journal, OperationId, SqlContext, StoreState};
12use coven_format::{admin::StoreChange, sequence::SlotHeader};
13use coven_foundation::id_source::{CircleId, DeviceId, KeyId, MemberId};
14use std::sync::Arc;
15
16impl OperationSteps {
17    /// Journal an administrative change as a step of a write: renaming the
18    /// store, changing a role, removing a member or a device, and renaming,
19    /// deleting or changing the members of a circle. `None` when the applied
20    /// state already has what it asks for: nothing is journaled. A change the
21    /// applied state refuses fails the step with `Rejected`. Once the write
22    /// commits, a pass is asked for, which runs the operation as soon as
23    /// storage is connected.
24    pub fn administer(
25        &self,
26        sql: &SqlContext<'_, '_>,
27        change: StoreChange,
28    ) -> Result<Option<OperationId>, SyncError> {
29        journal_change(sql, self.device, &self.held()?, self.state.clone(), |_, _| Ok(change))
30    }
31
32    /// Journal the replacement of another member's public pair with `keys`, as
33    /// a step of a write, expecting the pair the applied state binds to them now
34    /// (§10.1, §12.3). A target that is this device's own member fails with
35    /// `Rejected(NotAllowed)`: replacing one's own pair is
36    /// `replace_member_keys`. A removed or unknown member fails with
37    /// `Rejected(TargetGone)`.
38    pub fn replace_member_keys_for(
39        &self,
40        sql: &SqlContext<'_, '_>,
41        member: MemberId,
42        keys: coven_crypto::MemberPublicKeys,
43    ) -> Result<Option<OperationId>, SyncError> {
44        journal_change(sql, self.device, &self.held()?, self.state.clone(), |applied, author| {
45            if member == author {
46                return Err(SyncError::Rejected(OperationRejection::NotAllowed));
47            }
48            let expected = applied
49                .active_member(&member)
50                .ok_or(SyncError::Rejected(OperationRejection::TargetGone(
51                    crate::EntryTarget::Member(member),
52                )))?
53                .keys;
54            Ok(StoreChange::ReplaceMemberKeys { member, expected, keys })
55        })
56    }
57
58    /// Journal removing `member` from `circle` as a step of a write, with the
59    /// circle's replacement key: the pass keeps the key in custody, claims a
60    /// copy of it for each member who stays, then claims the removal, whose
61    /// entry introduces it (§15.8). `None` when the applied state has the
62    /// member out of the circle already; a removal it refuses fails the step
63    /// with `Rejected`.
64    pub fn remove_circle_member(
65        &self,
66        sql: &SqlContext<'_, '_>,
67        circle: CircleId,
68        member: MemberId,
69    ) -> Result<Option<OperationId>, SyncError> {
70        let key = KeyId(self.ids.new_id());
71        let held = self.held()?;
72        let journaled = sql.journal_step(|journal| {
73            let applied = journal.store_state()?;
74            let author = registered(&applied, self.device, &held)?;
75            // The applied state judges who may remove whom; the key's
76            // commitment is made once the key is in custody, and no rule
77            // reads it.
78            let asked = StoreChange::RemoveCircleMember { circle, member, key, key_hash: [0; 32] };
79            if !changes(journal, &applied, self.device, author, &asked)? {
80                return Ok(None);
81            }
82            SequenceOperation::circle_removal(circle, member, key)
83                .start(journal, "operation")
84                .map(Some)
85        })?;
86        if journaled.is_some() {
87            let state = self.state.clone();
88            sql.after_commit(move || state.request_pass());
89        }
90        Ok(journaled)
91    }
92
93    /// Journal making a circle, with this device's member as its first member,
94    /// as a step of a write, and return the new circle's id with the
95    /// operation's (§15.5). Any active member of the store may make one; the
96    /// pass keeps the circle's first key in custody, then claims its copy and
97    /// its introduction. The app can write rows into the circle once its slot
98    /// applies. A name that isn't a valid name fails with `Format`.
99    pub fn create_circle(
100        &self,
101        sql: &SqlContext<'_, '_>,
102        name: String,
103    ) -> Result<(CircleId, OperationId), SyncError> {
104        coven_format::value::name(&name)?;
105        let circle = CircleId(self.ids.new_id());
106        let key = KeyId(self.ids.new_id());
107        let held = self.held()?;
108        let operation = sql.journal_step(|journal| {
109            registered(&journal.store_state()?, self.device, &held)?;
110            SequenceOperation::circle(circle, name, key).start(journal, "key")
111        })?;
112        let state = self.state.clone();
113        sql.after_commit(move || state.request_pass());
114        Ok((circle, operation))
115    }
116}
117
118/// Build the change from the applied state and this device's member, check
119/// it there, and journal it in the write.
120fn journal_change(
121    sql: &SqlContext<'_, '_>,
122    device: DeviceId,
123    held: &MemberIdentity,
124    state: Arc<SequenceState>,
125    change: impl FnOnce(&StoreState, MemberId) -> Result<StoreChange, SyncError>,
126) -> Result<Option<OperationId>, SyncError> {
127    let journaled = sql.journal_step(|journal| {
128        let applied = journal.store_state()?;
129        let author = registered(&applied, device, held)?;
130        let change = change(&applied, author)?;
131        if !changes(journal, &applied, device, author, &change)? {
132            return Ok(None);
133        }
134        SequenceOperation::change(change).start(journal, "operation").map(Some)
135    })?;
136    if journaled.is_some() {
137        sql.after_commit(move || state.request_pass());
138    }
139    Ok(journaled)
140}
141
142/// Whether the change would still change the applied state, as its next
143/// slot's entry by this device's member: what that state refuses fails
144/// with `Rejected`. Only the slots this device has applied are read; the
145/// pass validates again after catching up (§11.1). A target those slots
146/// don't name yet, such as a device registered since, isn't gone: the
147/// change is journaled, and the pass decides once it has read on. One they
148/// name as removed or deleted is refused at once.
149pub(crate) fn changes(
150    journal: &Journal<'_>,
151    applied: &StoreState,
152    device: DeviceId,
153    author: MemberId,
154    change: &StoreChange,
155) -> Result<bool, SyncError> {
156    let through = journal.applied_slot()?;
157    let header = SlotHeader { device, claim: 1, author, after: through };
158    let next = next_slot(through)?;
159    match effects::checked_change(applied, &header, next, change, &Default::default(), &[]) {
160        Err(OperationRejection::TargetGone(target)) if unseen(applied, &target) => Ok(true),
161        checked => Ok(checked?.is_some()),
162    }
163}
164
165/// Whether the applied state has never named `target`: not even as removed
166/// or deleted.
167fn unseen(applied: &StoreState, target: &crate::EntryTarget) -> bool {
168    match target {
169        crate::EntryTarget::Member(member) => !applied.members.contains_key(member),
170        crate::EntryTarget::Device(device) => !applied.devices.contains_key(device),
171        crate::EntryTarget::Circle(circle) => {
172            !applied.circles.contains_key(circle) && !applied.circle_deletions.contains_key(circle)
173        }
174    }
175}