Skip to main content

coven_sync/
sequence_invites.rs

1//! The inviting device's one-time invitation, its join request and the
2//! approval that binds the request's exact pair (§13.2, §13.3).
3
4use super::sequence_copies::ApprovedAdmission;
5use super::{SequenceSync, Session};
6use crate::operation_outcome::EntryOutcome;
7use crate::sequence_sync::sequence_operations::SequenceOperation;
8use crate::sequence_sync::OperationState;
9use crate::{
10    Invite, InviteAccess, InviteLifetime, InviteOutcome, JoinRequest, OperationKind,
11    OperationRejection, PendingReason, PendingRecord, PendingSubject, ProviderAccessAction,
12    SyncError,
13};
14use approval::Child;
15use coven_crypto::{ConfirmationNumber, InviteSecret, MemberIdentity, SecretText, StoreKeyring};
16use coven_database::{
17    operation_kind, DbError, Journal, NewOperation, OperationId, OperationRecord, SqlContext,
18};
19use coven_format::{
20    admin::{MemberRole, StoreChange},
21    codes::InviteCode,
22    invite_end::InviteEnd,
23    MemberAccess, Object,
24};
25use coven_foundation::id_source::{DeviceId, IdSource, InviteId, MemberId};
26use coven_merge::Audience;
27use coven_storage::{
28    CloudProvider, InviteStorage, ObjectPath, S3Credentials, StorageFailure, StorageInvitation,
29};
30use serde::{Deserialize, Serialize};
31use std::{collections::BTreeSet, time::SystemTime};
32
33/// How an invited person reaches storage, as the invite's journal keeps it.
34#[derive(Serialize, Deserialize)]
35pub(crate) enum InviteGrant {
36    /// The provider shares the store with this account.
37    Account { email: String },
38    /// An S3 key the person made in the provider's console for this invite.
39    S3Key(S3Credentials),
40}
41
42impl InviteGrant {
43    fn member_access(&self) -> MemberAccess {
44        match self {
45            Self::Account { email } => MemberAccess::ProviderAccount(email.clone()),
46            Self::S3Key(key) => {
47                MemberAccess::S3AccessKey { access_key_id: key.access_key_id.clone() }
48            }
49        }
50    }
51}
52
53/// What approving the invite's request binds to its member id.
54#[derive(Clone, Copy, Serialize, Deserialize)]
55pub(crate) enum InviteBinding {
56    /// A fresh id with this role and the invite's access.
57    Add { role: MemberRole },
58    /// An existing active id keeps its role, circles, devices and recorded
59    /// access; only its pair changes.
60    Replace {
61        #[serde(with = "crate::pending_encoding::public_keys")]
62        expected: coven_crypto::MemberPublicKeys,
63    },
64}
65
66#[derive(Serialize, Deserialize)]
67pub(crate) enum InviteState {
68    /// The app's write made the invite. A pass checks it again against the
69    /// history it caught up with before granting anything.
70    Requested,
71    /// The invite's share is being recorded in history, before its grant:
72    /// `share` is the operation claiming it, journaled with this state.
73    Sharing { share: OperationId },
74    /// Storage access is being granted.
75    Grant,
76    /// The code is shown; the request, once read and checked, waits for the app.
77    Waiting {
78        /// The code as first shown, which every later showing repeats: the
79        /// joining device binds its saved request to the exact code (§13.2).
80        code: SecretText,
81        request: Option<Vec<u8>>,
82    },
83    /// This checked request is approved: `binding` is the operation that
84    /// claims its admission, journaled with this state.
85    Approving { code: SecretText, request: Vec<u8>, binding: OperationId },
86    /// The invite ended: put its marker in the request's place and settle
87    /// its account's sharing. `share` is the share's record the invite was
88    /// claiming when it ended, whose claim it settles without claiming again;
89    /// `end`, once journaled with this state, is the operation claiming the
90    /// share's end. Both end with the invite. An S3 key it carried is the
91    /// person's to delete in the provider's console; coven records nothing
92    /// about it (§14.3). `refusal`, when the invite ended because the provider
93    /// refused to share the store for a reason only a person can fix, is what
94    /// the invite's operation ends with, for the app to acknowledge (§13.2).
95    Settled {
96        share: Option<OperationId>,
97        end: Option<OperationId>,
98        refusal: Option<coven_foundation::sharing::SharingRefusal>,
99    },
100}
101
102#[derive(Serialize, Deserialize)]
103pub(crate) struct InviteWork {
104    id: InviteId,
105    /// The device that made the invite, under which its request lives. A
106    /// reset carries the invite to an installation with another id, which
107    /// ends the request where it is (§13.2, §19.3).
108    device: DeviceId,
109    member: MemberId,
110    /// The inviting admin's name, which the invite's code carries.
111    inviter: String,
112    binding: InviteBinding,
113    access: InviteGrant,
114    secret: SecretText,
115    expires_at: std::time::SystemTime,
116    state: InviteState,
117}
118
119impl OperationState for InviteWork {}
120
121impl InviteWork {
122    fn read(record: &OperationRecord) -> Result<Self, SyncError> {
123        Ok(serde_json::from_slice(&record.data)?)
124    }
125    /// The refusal that ended the invite, once it has settled.
126    fn refusal(&self) -> Option<coven_foundation::sharing::SharingRefusal> {
127        match &self.state {
128            InviteState::Settled { refusal, .. } => *refusal,
129            _ => None,
130        }
131    }
132    fn secret(&self) -> Result<InviteSecret, SyncError> {
133        Ok(InviteSecret::from_bytes(serde_json::from_str(self.secret.as_str())?))
134    }
135    /// Whether the invite admits a new person or a member's new keys: the
136    /// request it takes.
137    fn admits(&self) -> coven_format::codes::InviteAdmits {
138        match self.binding {
139            InviteBinding::Add { .. } => coven_format::codes::InviteAdmits::NewPerson,
140            InviteBinding::Replace { .. } => coven_format::codes::InviteAdmits::MemberKeys,
141        }
142    }
143    fn account(&self) -> Option<&str> {
144        match &self.access {
145            InviteGrant::Account { email } => Some(email),
146            _ => None,
147        }
148    }
149    /// Whether the invite ends at its expiry: it waits for its check, grants
150    /// access, or waits for its request or the app's decision. Approval,
151    /// once begun, finishes.
152    fn expires(&self) -> bool {
153        matches!(
154            self.state,
155            InviteState::Requested
156                | InviteState::Sharing { .. }
157                | InviteState::Grant
158                | InviteState::Waiting { .. }
159        )
160    }
161    fn expired(&self, now: std::time::SystemTime) -> bool {
162        self.expires() && now >= self.expires_at
163    }
164
165    /// End the invite, as expiry, a decline or a cancel does: its settled
166    /// step carries the share's record it was claiming, which ends with it.
167    fn end(&mut self) {
168        let share = match self.state {
169            InviteState::Sharing { share } => Some(share),
170            _ => None,
171        };
172        self.state = InviteState::Settled { share, end: None, refusal: None };
173    }
174
175    /// The invite's step from `record` to `state`, built from the id of the
176    /// operation it starts, which `state` names: the two commit together
177    /// (`start_child`).
178    fn naming(
179        record: &OperationRecord,
180        state: impl FnOnce(OperationId) -> InviteState + Send + 'static,
181    ) -> impl FnOnce(OperationId) -> Result<coven_database::OperationUpdate, SyncError> + Send + 'static
182    {
183        let record = record.clone();
184        move |child| {
185            let mut work = InviteWork::read(&record)?;
186            work.state = state(child);
187            work.update(&record)
188        }
189    }
190
191    /// The admission approving `request` claims: admitting the invite's
192    /// member with the request's pair, or recovering the member with it,
193    /// registering the device the request names and making the circle it
194    /// carries, with the request's copy of that circle's key (§13.2).
195    fn binding_admission(&self, request: &[u8]) -> Result<ApprovedAdmission, SyncError> {
196        let request = decode_request(request)?;
197        let (keys, device, device_name) = (request.keys, request.device, request.device_name);
198        let joining = request
199            .joiner
200            .circle()
201            .cloned()
202            .ok_or(coven_format::Error::UnknownTag { field: "invite joiner", tag: 2 })?;
203        let circle = joining.circle;
204        let change = match self.binding {
205            InviteBinding::Add { role } => StoreChange::AdmitMember {
206                member: self.member,
207                keys,
208                role,
209                access: self.access.member_access(),
210                device,
211                device_name,
212                person: request
213                    .joiner
214                    .person()
215                    .ok_or(coven_format::Error::UnknownTag { field: "invite joiner", tag: 0 })?
216                    .to_owned(),
217                circle,
218            },
219            // A recovery on S3 records the invite's new key as the member's
220            // access in the same entry; on another provider the member keeps
221            // the account they reach storage with (§13.2, §14.3).
222            InviteBinding::Replace { expected } => StoreChange::RecoverMember {
223                member: self.member,
224                expected,
225                keys,
226                access: match &self.access {
227                    InviteGrant::S3Key(_) => Some(self.access.member_access()),
228                    InviteGrant::Account { .. } => None,
229                },
230                device,
231                device_name,
232                circle,
233            },
234        };
235        Ok(ApprovedAdmission::new(change, joining.copy))
236    }
237
238    /// The invite as the app sees it, at `stage`, with the operation that
239    /// names it.
240    fn shown(&self, operation: OperationId, stage: crate::InviteStage) -> Invite {
241        Invite {
242            id: self.id,
243            operation,
244            member: self.member,
245            admits: self.admits(),
246            access: self.access.member_access(),
247            expires_at: self.expires_at,
248            stage,
249        }
250    }
251
252    fn present_request(&self, bytes: &[u8]) -> Result<JoinRequest, SyncError> {
253        let request = decode_request(bytes)?;
254        Ok(JoinRequest {
255            invite: request.invite,
256            member: request.member,
257            confirmation: ConfirmationNumber::of(request.invite, &request.keys),
258            keys: request.keys,
259            device_name: request.device_name,
260            joiner: request.joiner.try_into()?,
261            provider_account_email: self.account().map(str::to_owned),
262            record: bytes.to_vec(),
263        })
264    }
265}
266
267impl Invite {
268    /// Decode one invite from the `invite` and `operation` columns of a
269    /// `coven_invites` row. `Invite::list` decodes its rows with this.
270    pub fn from_columns(invite: &[u8], operation: OperationId) -> Result<Self, SyncError> {
271        let work: InviteWork = serde_json::from_slice(invite)?;
272        let shown = |code: &SecretText| code.as_str().to_owned();
273        let stage = match &work.state {
274            InviteState::Requested | InviteState::Sharing { .. } | InviteState::Grant => {
275                crate::InviteStage::Granting
276            }
277            InviteState::Waiting { code, request } => crate::InviteStage::Waiting {
278                code: shown(code),
279                request: request.as_deref().map(|bytes| work.present_request(bytes)).transpose()?,
280            },
281            InviteState::Approving { code, request, binding } => crate::InviteStage::Approving {
282                code: shown(code),
283                request: work.present_request(request)?,
284                binding: *binding,
285            },
286            InviteState::Settled { .. } => {
287                return Err(coven_database::DbError::Invariant {
288                    what: "coven_invites lists invites that haven't ended",
289                }
290                .into())
291            }
292        };
293        Ok(work.shown(operation, stage))
294    }
295
296    /// Read `coven_invites`, as an app's live query does:
297    /// `handle.subscribe(Invite::list)`. This device's invites that haven't
298    /// ended, in the order they were made (§13.2).
299    pub fn list(sql: coven_database::SqlReadContext<'_>) -> Result<Vec<Self>, DbError> {
300        Ok(sql.query(
301            "SELECT invite,operation FROM coven_invites ORDER BY operation",
302            [],
303            |row| {
304                let data: Vec<u8> = row.get(0)?;
305                Self::from_columns(&data, OperationId(row.get(1)?)).map_err(|error| {
306                    coven_database::SqliteError::FromSqlConversionFailure(
307                        0,
308                        coven_database::types::Type::Blob,
309                        Box::new(error),
310                    )
311                })
312            },
313        )?)
314    }
315
316    /// The code the invite shows.
317    #[cfg(any(test, feature = "test-utils"))]
318    pub fn shown_code(&self) -> &str {
319        match &self.stage {
320            crate::InviteStage::Granting => panic!("the invite shows no code before its grant"),
321            crate::InviteStage::Waiting { code, .. }
322            | crate::InviteStage::Approving { code, .. } => code,
323        }
324    }
325
326    /// The checked request, waiting for the app or being approved.
327    #[cfg(any(test, feature = "test-utils"))]
328    pub fn shown_request(&self) -> Option<&JoinRequest> {
329        match &self.stage {
330            crate::InviteStage::Granting => None,
331            crate::InviteStage::Waiting { request, .. } => request.as_ref(),
332            crate::InviteStage::Approving { request, .. } => Some(request),
333        }
334    }
335
336    /// Follow `coven_invites` with a live query, as an app does.
337    #[cfg(any(test, feature = "test-utils"))]
338    pub fn follow(
339        database: &coven_database::StoreDatabase,
340    ) -> coven_database::test_utils::Followed<Vec<Self>, DbError> {
341        coven_database::test_utils::Followed::new(database.subscribe(Self::list))
342    }
343}
344
345impl SequenceSync {
346    /// Make an invite for a new person as the app's write step does, then
347    /// run a pass, and return the invite once it shows its code, or its
348    /// pending record as the error.
349    #[cfg(test)]
350    pub(crate) async fn create_invite(
351        &self,
352        role: MemberRole,
353        access: InviteAccess,
354        lifetime: InviteLifetime,
355    ) -> Result<Invite, SyncError> {
356        self.made_invite(NewInvite::person(role, access, lifetime, "Ana".to_owned())).await
357    }
358
359    /// Make an invite for a member's new keys as `add_device_for` does, and
360    /// run it as `create_invite` does.
361    #[cfg(test)]
362    pub(crate) async fn add_device_for(
363        &self,
364        member: MemberId,
365        access: InviteAccess,
366        lifetime: InviteLifetime,
367    ) -> Result<Invite, SyncError> {
368        self.made_invite(NewInvite::member_keys(member, access, lifetime, "Ana".to_owned())).await
369    }
370
371    #[cfg(test)]
372    async fn made_invite(&self, made: NewInvite) -> Result<Invite, SyncError> {
373        let steps = self.operation_steps();
374        let location = self.storage.config().clone();
375        coven_storage::record_config(&self.directory, &location)?;
376        let (invite, _, operation) =
377            self.database.write_as(move |sql| steps.create_invite(&sql, made)).await?;
378        self.pass().await?;
379        let shown = self.database.read(Invite::list).await?.into_iter().find(|listed| {
380            listed.id == invite && !matches!(listed.stage, crate::InviteStage::Granting)
381        });
382        if let Some(shown) = shown {
383            return Ok(shown);
384        }
385        match self.database.operation_pending::<PendingRecord>(operation).await? {
386            Some(pending) => Err(SyncError::Pending(Box::new(pending))),
387            None => Err(SyncError::InvitationChanged),
388        }
389    }
390
391    /// Approve the request as the app's write step does, then run the pass
392    /// that binds it, returning its rejection as the error.
393    #[cfg(test)]
394    pub(crate) async fn approve_join_request(
395        &self,
396        request: &JoinRequest,
397    ) -> Result<(), SyncError> {
398        use crate::operation_outcome::SettledByPass as _;
399        let request = request.clone();
400        let steps = self.operation_steps();
401        let outcome: coven_database::ChangeOutcome = self
402            .journal_and_pass(move |sql| steps.approve_join_request(sql, &request).map(Some))
403            .await?
404            .expect("an approval always journals its binding");
405        outcome.settled()
406    }
407
408    /// Decline the request as the app's write step does, then run the pass
409    /// that deletes it.
410    #[cfg(test)]
411    pub(crate) async fn decline_join_request(
412        &self,
413        request: &JoinRequest,
414    ) -> Result<(), SyncError> {
415        let request = request.clone();
416        let steps = self.operation_steps();
417        self.settle_and_pass(move |sql| steps.decline_join_request(sql, &request)).await
418    }
419
420    /// Cancel the invite as the app's write step does, then run the pass
421    /// that deletes its request.
422    #[cfg(test)]
423    pub(crate) async fn cancel_invite(&self, invite: InviteId) -> Result<(), SyncError> {
424        let steps = self.operation_steps();
425        self.settle_and_pass(move |sql| steps.cancel_invite(sql, invite)).await
426    }
427
428    #[cfg(test)]
429    async fn settle_and_pass(
430        &self,
431        step: impl FnOnce(&SqlContext<'_, '_>) -> Result<(), SyncError> + Send + 'static,
432    ) -> Result<(), SyncError> {
433        self.database.write_as(move |sql| step(&sql)).await?;
434        self.pass().await.map(drop)
435    }
436
437    /// Advance this device's invites in a pass: grant, read the request
438    /// under backoff, revoke on expiry, and finish decided work.
439    pub(crate) async fn resume_invites(
440        &self,
441        session: &mut Session,
442        ring: &mut StoreKeyring,
443        member: &MemberIdentity,
444    ) -> Result<(), SyncError> {
445        for record in self.database.operations().await? {
446            if record.kind != operation_kind::INVITE {
447                continue;
448            }
449            // Expiry takes back the grant even while a request waits for the app.
450            let expired = InviteWork::read(&record)?.expired(self.clock.now());
451            if !expired && !self.operation_ready(&record, ring).await? {
452                continue;
453            }
454            if let Err(error) = self.run_invite(session, ring, member, record.id).await {
455                if self.database.operation(record.id).await?.is_none() {
456                    return Err(error);
457                }
458            }
459            self.state.check()?;
460        }
461        // Ended invites' markers, once no joining device can send a first
462        // request to their paths (`end_request`).
463        for path in self.database.due_object_removals(seconds(self.clock.now())?).await? {
464            let object = ObjectPath::parse(&path).map_err(|error| {
465                StorageFailure::Protocol.with_source(format!("a recorded removal's path: {error}"))
466            })?;
467            self.storage.delete_if_present(&object).await?;
468            self.database.object_removed(path).await?;
469        }
470        Ok(())
471    }
472
473    /// Advance the invite as far as it goes now. `step` follows the step
474    /// of the invite's row this attempt last read, which a failure belongs
475    /// to; `None` until it has read the row.
476    async fn advance_invite(
477        &self,
478        session: &mut Session,
479        ring: &mut StoreKeyring,
480        member: &MemberIdentity,
481        id: OperationId,
482        step: &mut Option<u32>,
483    ) -> Result<InviteProgress, SyncError> {
484        loop {
485            let record = self
486                .database
487                .operation(id)
488                .await?
489                .ok_or(coven_database::DbError::OperationChanged(id))?;
490            *step = Some(record.last_step);
491            let mut work = InviteWork::read(&record)?;
492            if work.expired(self.clock.now()) {
493                work.end();
494                self.database.advance_operation(work.update(&record)?).await?;
495                continue;
496            }
497            match &work.state {
498                InviteState::Requested => {
499                    // A refusal waits for the app to cancel the invite: it is
500                    // the invite's pending record, and fails no pass.
501                    if let Err(refusal) = self.check_invite(session, member, &work) {
502                        return Ok(InviteProgress::Waiting(self.error_reason(&refusal)));
503                    }
504                    // Recorded before the grant, so no share is ever left
505                    // that only this device knows of.
506                    if let Some(account) = work.account() {
507                        let started =
508                            self.start_invite_share(session, member, &record, &work, account);
509                        match started.await? {
510                            Child::Journaled(_) => continue,
511                            Child::Decided(EntryOutcome::Rejected(reason)) => {
512                                return Ok(InviteProgress::Waiting(
513                                    self.error_reason(&SyncError::Rejected(reason)),
514                                ))
515                            }
516                            Child::Decided(_) => (),
517                        }
518                    }
519                    self.grant(session, ring, member, &record, work, None, step).await?;
520                }
521                InviteState::Sharing { share } => {
522                    let share = *share;
523                    match self.run_administration(session, ring, member, share).await? {
524                        EntryOutcome::Landed(_) | EntryOutcome::Satisfied => {
525                            let shared = Some(share);
526                            self.grant(session, ring, member, &record, work, shared, step).await?;
527                        }
528                        // The invite checks again, and waits on the refusal.
529                        EntryOutcome::Rejected(_) => {
530                            work.state = InviteState::Requested;
531                            let update = work.update(&record)?;
532                            self.database.finish_operation_advancing(share, None, update).await?;
533                        }
534                    }
535                }
536                InviteState::Grant => {
537                    let invitation = match &work.access {
538                        InviteGrant::Account { email } => {
539                            let access = self
540                                .database
541                                .provider_access(email.clone())
542                                .await?
543                                .ok_or(coven_database::DbError::DamagedDatabase)?;
544                            if access.request.is_some() || access.granted != Some(true) {
545                                // A grant that failed keeps its cause in the
546                                // invite's pending record too.
547                                let failed = match &access.request {
548                                    Some(request) => {
549                                        self.database
550                                            .operation_pending::<PendingRecord>(request.operation)
551                                            .await?
552                                    }
553                                    None => None,
554                                };
555                                if let Some(PendingRecord {
556                                    reason:
557                                        PendingReason::Storage {
558                                            failure: StorageFailure::SharingRefused(refusal),
559                                            ..
560                                        },
561                                    ..
562                                }) = &failed
563                                {
564                                    let grant = access
565                                        .request
566                                        .as_ref()
567                                        .ok_or(coven_database::DbError::DamagedDatabase)?
568                                        .operation;
569                                    self.end_refused(id, grant, *refusal).await?;
570                                    continue;
571                                }
572                                return Ok(InviteProgress::Waiting(failed.map_or(
573                                    PendingReason::ProviderPending {
574                                        action: ProviderAccessAction::Grant,
575                                        account: email.clone(),
576                                    },
577                                    |failed| failed.reason,
578                                )));
579                            }
580                            StorageInvitation::decode(
581                                access
582                                    .invitation
583                                    .as_ref()
584                                    .ok_or(coven_database::DbError::DamagedDatabase)?
585                                    .as_bytes(),
586                            )?
587                        }
588                        InviteGrant::S3Key(_) => {
589                            StorageInvitation::for_account(self.storage.config())?
590                        }
591                    };
592                    let code = self.invite_code(session, &work, invitation)?;
593                    work.state = InviteState::Waiting { code, request: None };
594                    self.database.advance_operation(work.update(&record)?).await?;
595                    // The next pass looks for the request, then backs off.
596                    self.state.request_pass();
597                    return Ok(InviteProgress::Shown);
598                }
599                InviteState::Waiting { request: Some(_), .. } => {
600                    return Ok(InviteProgress::Waiting(PendingReason::Paused));
601                }
602                InviteState::Waiting { request: None, code } => {
603                    let path = ObjectPath::join_request(self.store(), work.device, work.id);
604                    let bytes = match self.storage.read(&path).await {
605                        Ok(bytes) => bytes,
606                        Err(error) if error.failure() == StorageFailure::NotFound => {
607                            return Ok(InviteProgress::Waiting(PendingReason::Missing { path }));
608                        }
609                        Err(error) => return Err(error.into()),
610                    };
611                    let request = match self.open_request(&work, &session.history.state, &bytes)? {
612                        Opened::Checked(request) => request,
613                        // No attempt can pass it, and no other request can
614                        // reach the invite's one path while it is there: the
615                        // invite ends, as a decline does (§13.2).
616                        Opened::Refused(refusal) => {
617                            tracing::warn!(?id, %refusal, "a join request failed its checks");
618                            work.end();
619                            self.database.advance_operation(work.update(&record)?).await?;
620                            continue;
621                        }
622                    };
623                    // A checked request waits for the app's decision: someone
624                    // who saw the code may have sent it first (§13.2).
625                    work.state =
626                        InviteState::Waiting { code: code.clone(), request: Some(request) };
627                    self.database.advance_operation(work.update(&record)?).await?;
628                    return Ok(InviteProgress::Waiting(PendingReason::Paused));
629                }
630                InviteState::Approving { binding, .. } => {
631                    let binding = *binding;
632                    // The binding ends in the transaction that moves the
633                    // invite on, so it is journaled while the invite approves.
634                    if self.database.operation(binding).await?.is_none() {
635                        return Err(coven_database::DbError::Invariant {
636                            what: "an approving invite's binding ends with its step",
637                        }
638                        .into());
639                    }
640                    let outcome = self.run_administration(session, ring, member, binding).await?;
641                    // Landed or refused, the invite ends. A refusal is the
642                    // binding's outcome, which `coven_operations` lists for the
643                    // app that approved it; the invite ends as a decline does.
644                    work.state = InviteState::Settled { share: None, end: None, refusal: None };
645                    let listed = OperationKind::ApproveJoin.listed_outcome(outcome)?;
646                    self.database
647                        .finish_operation_advancing(binding, listed, work.update(&record)?)
648                        .await?;
649                }
650                InviteState::Settled { share, end, refusal } => {
651                    let (share, end, refusal) = (*share, *end, *refusal);
652                    let kept_until = self.end_request(&work).await?;
653                    // The share's record the invite was claiming when it
654                    // ended: its claim may have landed, and is settled
655                    // before anything else claims (§5.1).
656                    if let Some(share) = share {
657                        self.settle_unneeded_claim(session, ring, member, share).await?;
658                    }
659                    // Applying the share's end records its account's
660                    // revoke, unless the account is still used (§14.2).
661                    let end = match end {
662                        Some(end) => Some(end),
663                        None => {
664                            self.start_share_end(session, member, &record, &work, share).await?
665                        }
666                    };
667                    if let Some(end) = end {
668                        let outcome = self.run_administration(session, ring, member, end).await?;
669                        if let EntryOutcome::Rejected(reason) = &outcome {
670                            tracing::warn!(?id, ?reason, "an invite share's end was refused");
671                        }
672                    }
673                    // The marker goes once a joining device can no longer
674                    // send a first request (`end_request`).
675                    let removal = coven_database::ObjectRemoval {
676                        path: ObjectPath::join_request(self.store(), work.device, work.id)
677                            .as_str()
678                            .to_owned(),
679                        after: kept_until,
680                    };
681                    let children = share.into_iter().chain(end).collect();
682                    // An invite ended by a refusal only a person can fix keeps
683                    // that as its outcome, listed in `coven_operations` until
684                    // the app acknowledges it (§13.2).
685                    let outcome = match refusal {
686                        Some(refusal) => {
687                            let account =
688                                work.account().ok_or(coven_database::DbError::DamagedDatabase)?;
689                            Some((
690                                crate::OperationKind::Invite.listed(),
691                                InviteOutcome::SharingRefused {
692                                    account: account.to_owned(),
693                                    refusal,
694                                },
695                            ))
696                        }
697                        None => None,
698                    };
699                    self.database
700                        .finish_operation_with_removal(id, children, removal, outcome)
701                        .await?;
702                    return Ok(InviteProgress::Finished);
703                }
704            }
705        }
706    }
707
708    /// Move the checked invite to granting its access, in one transaction
709    /// with adopting its account's grant and ending the record of its share,
710    /// `shared`; then ask for the grant, unless another open invite's grant
711    /// already shared the account with an invitation (§14.2). A grant that
712    /// fails is the invite's pending record, and `step` follows the step this
713    /// takes, which that failure belongs to.
714    #[expect(
715        clippy::too_many_arguments,
716        reason = "a step of the invite's advance takes the pass's session, keys and member"
717    )]
718    async fn grant(
719        &self,
720        session: &mut Session,
721        ring: &mut StoreKeyring,
722        member: &MemberIdentity,
723        record: &OperationRecord,
724        mut work: InviteWork,
725        shared: Option<OperationId>,
726        step: &mut Option<u32>,
727    ) -> Result<(), SyncError> {
728        work.state = InviteState::Grant;
729        let changes = match work.account() {
730            Some(account) => vec![crate::sequence_sync::account_change(account, true, true)?],
731            None => Vec::new(),
732        };
733        let update = work.update(record)?;
734        let granting = update.last_step;
735        self.database
736            .advance_operation_with_access::<PendingRecord>(update, changes, shared)
737            .await?;
738        *step = Some(granting);
739        let grant = match work.account() {
740            Some(account) => self
741                .database
742                .provider_access(account.to_owned())
743                .await?
744                .ok_or(coven_database::DbError::DamagedDatabase)?
745                .request
746                .map(|request| request.operation),
747            None => None,
748        };
749        if let Some(grant) = grant {
750            if let Err(error) = self.apply_access(session, ring, member, grant).await {
751                return match sharing_refusal(&error) {
752                    Some(refusal) => self.end_refused(record.id, grant, refusal).await,
753                    None => Err(error),
754                };
755            }
756        }
757        Ok(())
758    }
759
760    /// End the invite whose grant the provider refused for a reason only a
761    /// person can fix, as a failed request check does: it settles, putting
762    /// its marker in the request's place and taking its access back, and
763    /// ends with the refusal as its outcome (§13.2).
764    async fn end_refused(
765        &self,
766        id: OperationId,
767        grant: OperationId,
768        refusal: coven_foundation::sharing::SharingRefusal,
769    ) -> Result<(), SyncError> {
770        let record = self
771            .database
772            .operation(id)
773            .await?
774            .ok_or(coven_database::DbError::OperationChanged(id))?;
775        let mut work = InviteWork::read(&record)?;
776        tracing::warn!(?id, ?refusal, "the provider refused to share the store for an invite");
777        let account = work.account().ok_or(coven_database::DbError::DamagedDatabase)?.to_owned();
778        work.state = InviteState::Settled { share: None, end: None, refusal: Some(refusal) };
779        self.database
780            .advance_operation_refusing_grant(work.update(&record)?, account, grant)
781            .await?;
782        Ok(())
783    }
784
785    /// Put the ended invite's marker in its request's place, and return
786    /// when the marker may go: a week after the invite's expiry, the
787    /// retention grace, so a joining device whose clock lags the inviting
788    /// device's by less than that sends no request after it is gone (§13.2).
789    /// A request sent in between the delete and the create is taken too.
790    async fn end_request(&self, work: &InviteWork) -> Result<u64, SyncError> {
791        let kept_until = kept_until(seconds(work.expires_at)?)?;
792        let path = ObjectPath::join_request(self.store(), work.device, work.id);
793        self.put_marker(&path, kept_until).await?;
794        Ok(kept_until)
795    }
796
797    /// Put the marker that may go at `kept_until` in the place of whatever
798    /// is at `path`, a request or a pairing's handover, and return once it
799    /// is there: delete, then create it, which a request sent in between
800    /// finds taken, and delete again one that came first.
801    pub(crate) async fn put_marker(
802        &self,
803        path: &ObjectPath,
804        kept_until: u64,
805    ) -> Result<(), SyncError> {
806        let marker = InviteEnd { kept_until }.encode();
807        loop {
808            self.storage.delete_if_present(path).await?;
809            match self.storage.create(path, &marker).await {
810                Ok(_) => return Ok(()),
811                Err(error) if error.failure() == StorageFailure::AlreadyExists => {
812                    match self.storage.read(path).await {
813                        // An earlier attempt's marker, or another device's.
814                        Ok(found) if InviteEnd::decode(&found).is_ok() => return Ok(()),
815                        Ok(_) => (),
816                        Err(error) if error.failure() == StorageFailure::NotFound => (),
817                        Err(error) => return Err(error.into()),
818                    }
819                }
820                Err(error) => return Err(error.into()),
821            }
822        }
823    }
824
825    /// The invite checked again against the history this pass caught up
826    /// with, before it grants anything: its maker is still a registered
827    /// admin whose account holds the store's storage, and a replacement's
828    /// member is still active with the pair it expected. The app's write
829    /// checked only the slots its device had applied then (§11.1, §13.2).
830    fn check_invite(
831        &self,
832        session: &Session,
833        member: &MemberIdentity,
834        work: &InviteWork,
835    ) -> Result<(), SyncError> {
836        let me = member.member();
837        let state = &session.history.state;
838        if !self.registered(session) || !state.active_admin(&me) {
839            return Err(SyncError::Rejected(OperationRejection::NotAllowed));
840        }
841        if !session.history.owns_storage(me) {
842            return Err(StorageFailure::NotStoreOwner.into());
843        }
844        if let InviteBinding::Replace { expected } = work.binding {
845            match state.active_member(&work.member) {
846                None => {
847                    return Err(SyncError::Rejected(OperationRejection::TargetGone(
848                        crate::EntryTarget::Member(work.member),
849                    )))
850                }
851                Some(current) if current.keys != expected => {
852                    return Err(SyncError::Rejected(OperationRejection::MemberKeysChanged(
853                        work.member,
854                    )))
855                }
856                Some(_) => (),
857            }
858        }
859        Ok(())
860    }
861
862    /// The code to show, fixed once its access is granted: it names the
863    /// store as now named and this device's applied slot.
864    fn invite_code(
865        &self,
866        session: &Session,
867        work: &InviteWork,
868        invitation: StorageInvitation,
869    ) -> Result<SecretText, SyncError> {
870        let storage = match &work.access {
871            InviteGrant::Account { .. } => InviteStorage::Account(invitation),
872            InviteGrant::S3Key(credentials) => {
873                InviteStorage::S3 { invitation, credentials: credentials.clone() }
874            }
875        };
876        let store =
877            session.history.state.store.as_ref().ok_or(coven_database::DbError::DamagedDatabase)?;
878        let initial_key = session
879            .history
880            .introductions
881            .iter()
882            .find(|intro| intro.audience == Audience::Store)
883            .ok_or(coven_database::DbError::DamagedDatabase)?
884            .key;
885        let code = InviteCode {
886            store: store.id,
887            name: store.name.clone(),
888            inviter: work.inviter.clone(),
889            admits: work.admits(),
890            expires_at: seconds(work.expires_at)?,
891            invite: work.id,
892            member: work.member,
893            secret: work.secret()?,
894            initial_key,
895            inviting_writer: work.device,
896            read_through: session.through,
897            storage: storage.encode()?,
898        }
899        .to_text()?;
900        Ok(SecretText::new(code.to_string()))
901    }
902}
903
904/// How far one call advanced an invite.
905pub(crate) enum InviteProgress {
906    /// Access is granted and the code can be shown.
907    Shown,
908    /// The invite waits on this condition.
909    Waiting(PendingReason),
910    /// The invite's work is done.
911    Finished,
912}
913
914/// The refusal a failed grant carries, when only a person can fix it.
915fn sharing_refusal(error: &SyncError) -> Option<coven_foundation::sharing::SharingRefusal> {
916    match error {
917        SyncError::Storage(error) => match error.failure() {
918            StorageFailure::SharingRefused(refusal) => Some(refusal),
919            _ => None,
920        },
921        _ => None,
922    }
923}
924
925/// When the marker of an invite that expires at `expires`, in seconds since
926/// 1970, may go: the retention grace after it (§13.2). A time the marker's
927/// seconds can't hold is refused as the expiry the clock can't represent is.
928pub(crate) fn kept_until(expires: u64) -> Result<u64, SyncError> {
929    expires.checked_add(super::sequence_retention::GRACE.as_secs()).ok_or_else(|| {
930        StorageFailure::InvalidConfiguration
931            .with_source("the clock cannot represent when an ended invite's marker may go")
932            .into()
933    })
934}
935
936/// A time as whole seconds since the Unix epoch, as codes and markers carry
937/// it.
938pub(crate) fn seconds(at: SystemTime) -> Result<u64, SyncError> {
939    Ok(at
940        .duration_since(std::time::UNIX_EPOCH)
941        .map_err(|error| {
942            StorageFailure::InvalidConfiguration
943                .with_source(format!("an invite's time precedes 1970: {error}"))
944        })?
945        .as_secs())
946}
947
948pub(crate) fn decode_request(
949    bytes: &[u8],
950) -> Result<coven_format::objects::JoinRequest, SyncError> {
951    match Object::decode(bytes)? {
952        Object::JoinRequest(request) => Ok(request),
953        _ => Err(SyncError::InvitationChanged),
954    }
955}
956
957#[cfg(test)]
958#[path = "sequence_invites_tests.rs"]
959pub(crate) mod tests;
960
961#[path = "sequence_invite_request.rs"]
962mod request;
963pub(crate) use request::{Expected, Opened, RequestChecks};
964
965#[path = "sequence_invite_approval.rs"]
966mod approval;
967
968#[path = "sequence_invite_reset.rs"]
969mod reset;
970
971#[path = "sequence_invite_shares.rs"]
972pub(crate) mod shares;
973
974#[path = "sequence_invite_steps.rs"]
975mod steps;
976pub use steps::NewInvite;
977pub(crate) use steps::{approve_request, end_invite, make_invite};
978#[cfg(any(test, feature = "test-utils"))]
979pub use steps::{invite_operation, RecordedInvite, RecordedInviteStage, RecordedJoiner};
980
981#[path = "invite_expiry.rs"]
982pub(crate) mod expiry;