Skip to main content

coven_sync/
sequence_access.rs

1//! Provider requests follow intentions committed with authenticated membership.
2use crate::{
3    history::History,
4    sequence_sync::{SequenceSync, Session},
5    OperationKind, OperationRejection, PendingReason, PendingRecord, PendingSubject, SyncError,
6};
7use coven_crypto::{MemberIdentity, StoreKeyring};
8use coven_database::operation_kind;
9use coven_database::{OperationId, ProviderAccessChange};
10use coven_format::MemberAccess;
11use coven_foundation::id_source::MemberId;
12use std::collections::BTreeSet;
13
14impl History {
15    /// The access Set up storage recorded, once it applied. Its kind is the
16    /// store's: an account holds the store, or each member has an S3 key
17    /// (§10.3).
18    pub(crate) fn store_access(&self) -> Option<&MemberAccess> {
19        self.storage.as_ref().map(|(_, access)| access)
20    }
21
22    /// Whether `member` administers the storage: on a store an account
23    /// holds, the member whose account it is; on S3, any admin (§14.2).
24    pub(crate) fn owns_storage(&self, member: MemberId) -> bool {
25        match self.store_access() {
26            Some(MemberAccess::ProviderAccount(_)) => self.holds_store(member),
27            Some(MemberAccess::S3AccessKey { .. }) => self.state.active_admin(&member),
28            None => false,
29        }
30    }
31
32    /// Whether `member` is active and reaches storage through the account
33    /// Set up storage recorded, the account that holds the store (§20.9). No
34    /// account holds an S3 store.
35    pub(crate) fn holds_store(&self, member: MemberId) -> bool {
36        let Some(created @ MemberAccess::ProviderAccount(_)) = self.store_access() else {
37            return false;
38        };
39        self.state
40            .active_member(&member)
41            .and_then(|current| current.access.as_ref())
42            .is_some_and(|current| created.same_credential(current))
43    }
44
45    /// Whether `member` may reach storage with `access` (format.md D6): it
46    /// is the kind of access the store's creation records, a provider
47    /// account or an S3 key (§10.3), and the member whose account holds the
48    /// store stays on that account. Moved to another, no member would reach
49    /// storage through it, and nobody could share the store or take sharing
50    /// back (§20.9).
51    pub(crate) fn access_allowed(
52        &self,
53        member: MemberId,
54        access: &MemberAccess,
55    ) -> Result<(), OperationRejection> {
56        let Some(created) = self.store_access().filter(|created| created.same_kind(access)) else {
57            return Err(OperationRejection::NotAllowed);
58        };
59        if self.holds_store(member) && !created.same_credential(access) {
60            return Err(OperationRejection::StoreOwner);
61        }
62        Ok(())
63    }
64
65    /// Intentions after this state: an account stays shared while an active
66    /// member reaches storage through it or an open invite share names it
67    /// (§14.2). Only the owner's devices change sharing, so only they record
68    /// the work: another device could neither do it nor see it done, and a
69    /// wait it showed would never end.
70    pub(crate) fn provider_access(
71        &self,
72        member: MemberId,
73    ) -> Result<Vec<ProviderAccessChange>, SyncError> {
74        let mut changes = Vec::new();
75        if !self.owns_storage(member) {
76            return Ok(changes);
77        }
78        let mut accounts = BTreeSet::new();
79        // Coven shares nothing on S3: the person deletes a key in the
80        // provider's console, and coven records nothing (§14.3).
81        let members = self.recorded_access().filter_map(|(_, _, access)| match access {
82            MemberAccess::ProviderAccount(account) => Some(account.as_str()),
83            MemberAccess::S3AccessKey { .. } => None,
84        });
85        let shares = self.invite_shares.values().map(|share| share.account.as_str());
86        for account in members.chain(shares) {
87            let account = MemberAccess::normalized_account(account);
88            if !accounts.insert(account.clone()) {
89                continue;
90            }
91            let intended = self.account_intended(&account);
92            // A member's access entry describes a grant already made,
93            // and an invite share one its own device makes: a device
94            // that first learns of an account never grants it itself.
95            changes.push(ProviderAccessChange {
96                initially_granted: true,
97                ..crate::sequence_sync::account_change(&account, intended, false)?
98            });
99        }
100        Ok(changes)
101    }
102}
103
104impl SequenceSync {
105    /// Refuse `access` as this member's own where history would refuse
106    /// recording it (format.md D6). A restore checks before registering its
107    /// device, so a member who could never record the access it signed in
108    /// with leaves no device behind (§20.9).
109    pub async fn check_access(&self, access: &MemberAccess) -> Result<(), SyncError> {
110        let member = self.member.read()?.ok_or(coven_storage::StorageFailure::MemberKeysMissing)?;
111        let session = self.session.lock().await;
112        Ok(session.history.access_allowed(member.member(), access)?)
113    }
114
115    pub(crate) async fn resume_access(
116        &self,
117        session: &mut Session,
118        ring: &mut StoreKeyring,
119        member: &MemberIdentity,
120    ) -> Result<(), SyncError> {
121        for record in self.database.operations().await? {
122            if record.kind != operation_kind::PROVIDER_ACCESS
123                || !self.operation_ready(&record, ring).await?
124            {
125                continue;
126            }
127            let scope = self.waits.begin_attempt(record.id);
128            let result = coven_database::in_commit_scope(
129                scope,
130                self.apply_access(session, ring, member, record.id),
131            )
132            .await;
133            self.settle_resumed(record.id, OperationKind::RevokeAccess, result, ring).await?;
134        }
135        Ok(())
136    }
137
138    pub(crate) async fn apply_access(
139        &self,
140        session: &mut Session,
141        ring: &mut StoreKeyring,
142        member: &MemberIdentity,
143        id: OperationId,
144    ) -> Result<(), SyncError> {
145        loop {
146            self.state.check()?;
147            let record = self
148                .database
149                .operation(id)
150                .await?
151                .ok_or(coven_database::DbError::OperationChanged(id))?;
152            let account: String = serde_json::from_slice(&record.data)?;
153            let condition = |reason| {
154                PendingRecord::new(
155                    PendingSubject::Operation { id, kind: OperationKind::RevokeAccess },
156                    reason,
157                )
158            };
159            // Only the owner's devices record provider work (`provider_access`).
160            if !session.history.owns_storage(member.member()) {
161                return Err(coven_database::DbError::Invariant {
162                    what: "provider work runs on a device whose member's account holds the store",
163                }
164                .into());
165            }
166            let target = if record.last_step == coven_database::REQUEST_FIXED_STEP {
167                self.database
168                    .provider_access(account.clone())
169                    .await?
170                    .and_then(|state| state.request)
171                    .and_then(|request| request.target)
172                    .ok_or(coven_database::DbError::DamagedDatabase)?
173            } else {
174                self.database.start_provider_request::<PendingRecord>(account.clone(), id).await?
175            };
176            let invitation = if target {
177                match self.storage.grant_access(&account).await? {
178                    coven_storage::AccessGrant::Granted { invitation } => {
179                        Some(invitation.encode()?)
180                    }
181                    coven_storage::AccessGrant::CreateAccessKey => {
182                        return Err(coven_storage::StorageFailure::InvalidConfiguration
183                            .with_source("account sharing cannot create an S3 key")
184                            .into())
185                    }
186                }
187            } else {
188                let shares = self.storage.revoke_access(&account).await?;
189                if !shares.is_empty() {
190                    let pending = condition(PendingReason::AccessRemains {
191                        account: account.clone(),
192                        shares,
193                    });
194                    if self
195                        .database
196                        .fail_provider_request(account, id, record.data, pending.clone())
197                        .await?
198                    {
199                        return Err(SyncError::Pending(Box::new(pending)));
200                    }
201                    // An entry intends the account shared again: grant it.
202                    continue;
203                }
204                None
205            };
206            self.read_forward(session, ring, member).await?;
207            if self
208                .database
209                .complete_provider_request::<PendingRecord>(account, id, target, invitation)
210                .await?
211            {
212                return Ok(());
213            }
214        }
215    }
216}
217
218#[cfg(test)]
219#[path = "sequence_access_tests.rs"]
220mod tests;