Skip to main content

coven_sync/
sequence_invite_steps.rs

1//! The app's decisions about an invite as steps of its write (§4, §13.2):
2//! each reads the invite in the write's transaction and decides it there,
3//! with or without storage; a pass does the storage work after. The store's
4//! `OperationSteps` run them and wake that pass.
5
6use super::*;
7
8/// Whom an invite admits.
9enum Admits {
10    /// A new person, with this role.
11    Person(MemberRole),
12    /// This member's new keys, after they lost every device.
13    MemberKeys(MemberId),
14}
15
16/// What the app asks an invite for: whom it admits, how they reach storage,
17/// and how long it stays open (§13.2).
18pub struct NewInvite {
19    admits: Admits,
20    access: InviteAccess,
21    lifetime: InviteLifetime,
22    inviter: String,
23}
24
25impl NewInvite {
26    /// An invite for a new person, added with `role`. `access` is the
27    /// provider account to share with or the S3 key made for them; the invite
28    /// expires `lifetime` after it is made; `inviter` is the inviting admin's
29    /// name, a format `name`, which the invite carries for the joining
30    /// person's screens (§13.2).
31    pub fn person(
32        role: MemberRole,
33        access: InviteAccess,
34        lifetime: InviteLifetime,
35        inviter: String,
36    ) -> Self {
37        Self { admits: Admits::Person(role), access, lifetime, inviter }
38    }
39
40    /// An invite for `member`'s new keys: the member lost every device, and
41    /// approval binds the requester's new keys to their id, keeping its
42    /// role, circles and devices. The other fields are those of `person`.
43    pub fn member_keys(
44        member: MemberId,
45        access: InviteAccess,
46        lifetime: InviteLifetime,
47        inviter: String,
48    ) -> Self {
49        Self { admits: Admits::MemberKeys(member), access, lifetime, inviter }
50    }
51}
52
53/// Make an invite, as a step of a write (§13.2), and return its id, the
54/// member id it fixes and its operation. The write checks the invite against
55/// the slots this device has applied, then journals it, with or without
56/// storage; the invite is listed in `coven_invites` from its commit, without
57/// a code. Once the write commits, a pass is asked for, which checks the
58/// invite again against the history it catches up with, grants its storage
59/// access and fixes its code. A check that fails there, or a failed grant,
60/// is the invite's pending record in `coven_pending`, under its operation;
61/// the app cancels the invite to end it. The invite expires after its
62/// lifetime by this device's clock, from `now`.
63///
64/// Made by a device that isn't a registered admin, the step fails with
65/// `Rejected(NotAllowed)`; for a replacement of a member who isn't active,
66/// with `Rejected(TargetGone)`, and of this device's own member, with
67/// `Rejected(NotAllowed)`. Access that doesn't fit `location` fails with its
68/// storage failure.
69pub(crate) fn make_invite(
70    sql: &SqlContext<'_, '_>,
71    device: DeviceId,
72    held: &MemberIdentity,
73    ids: &dyn IdSource,
74    now: SystemTime,
75    location: &coven_storage::StorageConfig,
76    custody: &crate::DeviceCredentials,
77    invite: NewInvite,
78) -> Result<(InviteId, MemberId, OperationId), SyncError> {
79    let NewInvite { admits, access, lifetime, inviter } = invite;
80    coven_format::value::name(&inviter)?;
81    if matches!(
82        location,
83        coven_storage::StorageConfig::Dropbox {
84            location: coven_storage::DropboxLocation::AppFolder,
85            ..
86        }
87    ) {
88        return Err(StorageFailure::DropboxAppFolderNotShareable.into());
89    }
90    let grant = invite_grant(access, location.provider(), custody)?;
91    let secret = InviteSecret::generate()?;
92    let secret = SecretText::new(serde_json::to_string(secret.to_secret_bytes().as_bytes())?);
93    let expires_at = now.checked_add(lifetime.duration()).ok_or(
94        StorageFailure::InvalidConfiguration
95            .with_source("the clock cannot represent the invite's expiry"),
96    )?;
97    let id = InviteId(ids.new_id());
98    let started_by = match admits {
99        Admits::Person(_) => "create_invite",
100        Admits::MemberKeys(_) => "add_device_for",
101    };
102    let made = sql.journal_step(|journal| {
103        let applied = journal.store_state()?;
104        let me = crate::sequence_sync::registered(&applied, device, held)?;
105        if !applied.active_admin(&me) {
106            return Err(SyncError::Rejected(OperationRejection::NotAllowed));
107        }
108        let (member, binding) = match admits {
109            Admits::Person(role) => (MemberId(ids.new_id()), InviteBinding::Add { role }),
110            Admits::MemberKeys(target) => {
111                let Some(existing) = applied.active_member(&target) else {
112                    return Err(SyncError::Rejected(OperationRejection::TargetGone(
113                        crate::EntryTarget::Member(target),
114                    )));
115                };
116                // Replacing this installation's own pair stops the device that
117                // must finish the invite; members replace their own keys directly.
118                if target == me {
119                    return Err(SyncError::Rejected(OperationRejection::NotAllowed));
120                }
121                if let InviteGrant::Account { email } = &grant {
122                    let account = MemberAccess::ProviderAccount(email.clone());
123                    if !existing.access.as_ref().is_some_and(|held| held.same_credential(&account))
124                    {
125                        return Err(StorageFailure::InvalidConfiguration
126                            .with_source(
127                                "a replacement invite shares the member's recorded account",
128                            )
129                            .into());
130                    }
131                }
132                (target, InviteBinding::Replace { expected: existing.keys })
133            }
134        };
135        let work = InviteWork {
136            id,
137            device,
138            member,
139            inviter,
140            binding,
141            access: grant,
142            secret,
143            expires_at,
144            state: InviteState::Requested,
145        };
146        let operation = journal.start_operation(&NewOperation {
147            kind: operation_kind::INVITE.into(),
148            data: serde_json::to_vec(&work)?,
149            started_by: started_by.into(),
150            pauses_writes: false,
151        })?;
152        Ok((id, member, operation))
153    })?;
154    Ok(made)
155}
156
157/// The storage access an invite grants, as the location allows it: a
158/// provider account to share with, or on S3 a key the person made for the
159/// invitee or the one this device connects with, read from `custody`.
160fn invite_grant(
161    access: InviteAccess,
162    provider: CloudProvider,
163    custody: &crate::DeviceCredentials,
164) -> Result<InviteGrant, SyncError> {
165    match access {
166        InviteAccess::ProviderAccount { email } => {
167            let email = MemberAccess::normalized_account(&email);
168            if email.is_empty() {
169                return Err(StorageFailure::InvalidConfiguration
170                    .with_source("invite account is empty")
171                    .into());
172            }
173            if provider == CloudProvider::S3 {
174                return Err(StorageFailure::InvalidConfiguration
175                    .with_source("an S3 invitation needs its own access key")
176                    .into());
177            }
178            Ok(InviteGrant::Account { email })
179        }
180        InviteAccess::S3AccessKey { .. } | InviteAccess::HeldS3AccessKey
181            if provider != CloudProvider::S3 =>
182        {
183            Err(StorageFailure::InvalidConfiguration
184                .with_source("an access-key invitation requires S3")
185                .into())
186        }
187        InviteAccess::S3AccessKey { access_key_id, secret_access_key } => {
188            let credentials = S3Credentials { access_key_id, secret_access_key };
189            credentials.validate()?;
190            Ok(InviteGrant::S3Key(credentials))
191        }
192        InviteAccess::HeldS3AccessKey => match custody.connection()? {
193            Some(coven_storage::ConnectionCredentials {
194                credentials: coven_storage::StorageCredentials::S3(key),
195                ..
196            }) => Ok(InviteGrant::S3Key(key)),
197            Some(_) | None => Err(StorageFailure::InvalidConfiguration
198                .with_source("this device holds no S3 key to give")
199                .into()),
200        },
201    }
202}
203
204/// Approve exactly this checked request, as a step of a write (§13.2), and
205/// return the operation that binds its pair: the write journals it, and the
206/// invite's approval begins, with or without storage. Once the write commits, a
207/// pass is asked for, which catches up and claims one admission: the entry
208/// admitting the member with the request's pair, or rebinding their pair, and
209/// registering the request's device, carrying copies of every store key and
210/// the held circle keys for that pair; once begun, approval finishes. The
211/// operation's outcome is listed in `coven_operations`: a rejection ends the
212/// invite as a decline does. The step doesn't check the approval against the
213/// applied state, so the app is never refused an approval it was shown as
214/// waiting: one the history refuses, as when this admin was demoted, is refused
215/// by the pass, as its binding's outcome. A request the invite no longer shows,
216/// and an invite whose lifetime ended by `now`, fail the step with
217/// `InvitationChanged`.
218pub(crate) fn approve_request(
219    sql: &SqlContext<'_, '_>,
220    now: SystemTime,
221    request: &JoinRequest,
222) -> Result<(OperationId, OperationId), SyncError> {
223    sql.journal_step(|journal| {
224        let (record, mut work) = invite_record(journal, request.invite)?;
225        if work.expired(now) {
226            return Err(SyncError::InvitationChanged);
227        }
228        let InviteState::Waiting { code, request: Some(stored) } = &work.state else {
229            return Err(SyncError::InvitationChanged);
230        };
231        let (code, stored) = (code.clone(), stored.clone());
232        if work.present_request(&stored)? != *request {
233            return Err(SyncError::InvitationChanged);
234        }
235        let admission = work.binding_admission(&stored)?;
236        let binding =
237            SequenceOperation::admission(admission).start(journal, operation_kind::INVITE)?;
238        work.state = InviteState::Approving { code, request: stored, binding };
239        journal.advance_operation(&work.update(&record)?)?;
240        Ok((record.id, binding))
241    })
242}
243
244/// End the invite in the write, for a decline of `request` or a cancel.
245/// Reading the invite and ending it share the write's transaction, so no
246/// expiry comes between. An invite whose lifetime ended is left to its
247/// expiry, a write of its own that the handle makes at that time.
248pub(crate) fn end_invite(
249    sql: &SqlContext<'_, '_>,
250    now: SystemTime,
251    invite: InviteId,
252    request: Option<&JoinRequest>,
253) -> Result<OperationId, SyncError> {
254    sql.journal_step(|journal| {
255        let (record, mut work) = invite_record(journal, invite)?;
256        if work.expired(now) {
257            return Err(SyncError::InvitationChanged);
258        }
259        match (&work.state, request) {
260            (InviteState::Waiting { request: Some(stored), .. }, Some(request)) => {
261                if work.present_request(stored)? != *request {
262                    return Err(SyncError::InvitationChanged);
263                }
264            }
265            (
266                InviteState::Requested
267                | InviteState::Sharing { .. }
268                | InviteState::Grant
269                | InviteState::Waiting { .. },
270                None,
271            ) => {}
272            _ => return Err(SyncError::InvitationChanged),
273        }
274        work.end();
275        journal.advance_operation(&work.update(&record)?)?;
276        Ok(record.id)
277    })
278}
279
280/// The invite's journal row and its state, as the write sees them; a
281/// finished or unknown invite fails with `InvitationChanged`.
282fn invite_record(
283    journal: &Journal<'_>,
284    invite: InviteId,
285) -> Result<(OperationRecord, InviteWork), SyncError> {
286    for record in journal.operations(operation_kind::INVITE)? {
287        let work = InviteWork::read(&record)?;
288        if work.id == invite {
289            return Ok((record, work));
290        }
291    }
292    Err(SyncError::InvitationChanged)
293}
294
295#[cfg(test)]
296#[path = "sequence_invite_steps_tests.rs"]
297mod tests;
298
299/// An invite a test records outside a store, as `make_invite` journals one
300/// and later steps advance it (api.md E4): its id, the member it fixes, and
301/// its stage.
302#[cfg(any(test, feature = "test-utils"))]
303pub struct RecordedInvite {
304    /// The invite's id.
305    pub id: InviteId,
306    /// The member id the invite fixes, which its request repeats.
307    pub member: MemberId,
308    /// Where the invite is, with the request it holds.
309    pub stage: RecordedInviteStage,
310}
311
312/// Where an invite a test records is, as `coven_invites.stage` names it.
313#[cfg(any(test, feature = "test-utils"))]
314pub enum RecordedInviteStage {
315    /// coven checks the invite and grants its access before its code shows.
316    Granting,
317    /// Its code shows, and the request that arrived, if any, waits for the
318    /// app.
319    Waiting {
320        /// Who asks, once a request arrived.
321        joiner: Option<RecordedJoiner>,
322    },
323    /// The app approved the request, and `binding` is the operation that
324    /// claims its admission.
325    Approving {
326        /// Who asks.
327        joiner: RecordedJoiner,
328        /// The operation that claims the request's admission.
329        binding: OperationId,
330    },
331}
332
333/// Who asks in the request of an invite a test records.
334#[cfg(any(test, feature = "test-utils"))]
335pub enum RecordedJoiner {
336    /// A new person, with the name they typed; the invite adds a member.
337    NewPerson(String),
338    /// A member recovering after losing every device; the request carries
339    /// no name, and the invite binds the member's new keys.
340    Recovering,
341}
342
343/// The journal row of `invite`, as `make_invite` journals an invite and
344/// later steps record its state: the invite made by device 1 for an
345/// account, with a fixed secret and an expiry in 2096, and the request as
346/// coven-format's fixture request with `invite`'s id, member and joiner
347/// (api.md E4).
348#[cfg(any(test, feature = "test-utils"))]
349pub fn invite_operation(invite: RecordedInvite) -> Result<NewOperation, SyncError> {
350    let request = |joiner: &RecordedJoiner| -> Result<Vec<u8>, SyncError> {
351        let mut request = coven_format::test_utils::join_request();
352        request.invite = invite.id;
353        request.member = invite.member;
354        if let RecordedJoiner::NewPerson(name) = joiner {
355            request.joiner = coven_format::objects::Joiner::NewPerson {
356                name: name.clone(),
357                circle: coven_format::objects::JoiningCircle {
358                    circle: coven_format::test_utils::recovered_circle(),
359                    copy: coven_format::test_utils::recovered_circle_copy(),
360                },
361            };
362        }
363        Ok(Object::JoinRequest(request).encode()?)
364    };
365    let binding = |joiner: Option<&RecordedJoiner>| match joiner {
366        Some(RecordedJoiner::Recovering) => {
367            InviteBinding::Replace { expected: coven_format::test_utils::replacement() }
368        }
369        Some(RecordedJoiner::NewPerson(_)) | None => {
370            InviteBinding::Add { role: MemberRole::Member }
371        }
372    };
373    let code = || SecretText::new("code".into());
374    let (binding, state) = match &invite.stage {
375        RecordedInviteStage::Granting => (binding(None), InviteState::Requested),
376        RecordedInviteStage::Waiting { joiner } => (
377            binding(joiner.as_ref()),
378            InviteState::Waiting {
379                code: code(),
380                request: joiner.as_ref().map(request).transpose()?,
381            },
382        ),
383        RecordedInviteStage::Approving { joiner, binding: claim } => (
384            binding(Some(joiner)),
385            InviteState::Approving { code: code(), request: request(joiner)?, binding: *claim },
386        ),
387    };
388    let work = InviteWork {
389        id: invite.id,
390        device: DeviceId(1),
391        member: invite.member,
392        inviter: "Ana".into(),
393        binding,
394        access: InviteGrant::Account { email: "invited@example.com".into() },
395        secret: SecretText::new(serde_json::to_string(&[7_u8; 32])?),
396        expires_at: std::time::UNIX_EPOCH + std::time::Duration::from_secs(4_000_000_000),
397        state,
398    };
399    Ok(NewOperation {
400        kind: operation_kind::INVITE.into(),
401        data: serde_json::to_vec(&work)?,
402        started_by: "record_invite".into(),
403        pauses_writes: false,
404    })
405}