Skip to main content

coven_database/
provider_access.rs

1//! Account intentions, confirmed provider state and their durable request (§14.2).
2
3use crate::sqlite::StoreSql;
4use crate::{DbError, NewOperation, OperationId, PendingValue};
5use coven_crypto::SecretBytes;
6
7/// A provider-access operation's steps (§14.2): queued; its request's
8/// target fixed, before storage is called; and an inconclusive request
9/// reported, to be fixed again on retry.
10pub(crate) const REQUEST_QUEUED_STEP: u32 = 0;
11/// The step a provider-access operation reaches once its request's target
12/// is fixed, before storage is called.
13pub const REQUEST_FIXED_STEP: u32 = 1;
14pub(crate) const REQUEST_FAILED_STEP: u32 = 2;
15
16/// One account's intention derived from membership and this device's invitations.
17pub struct ProviderAccessChange {
18    /// Provider account identity.
19    pub account: String,
20    /// Whether a current member or open invite needs the account.
21    pub intended: bool,
22    /// Received access entries describe grants already delivered.
23    pub initially_granted: bool,
24    /// An open invite also needs the provider's acceptance information.
25    pub needs_invitation: bool,
26    /// The journal payload identifying this account.
27    pub operation: NewOperation,
28}
29
30/// A request remains associated with its account until confirmation matches intention.
31#[derive(Clone, Debug, PartialEq, Eq)]
32pub struct ProviderAccessRequest {
33    /// Its stable pending subject.
34    pub operation: OperationId,
35    /// Fixed before sending; absent while ready.
36    pub target: Option<bool>,
37}
38
39/// A request makes confirmation unknown until the provider supplies evidence.
40#[derive(Debug)]
41pub struct ProviderAccess {
42    /// Latest membership and invitation intention.
43    pub intended: bool,
44    /// Confirmed grant, or unknown when a request has no conclusive reply.
45    pub granted: Option<bool>,
46    /// Encoded provider acceptance information from a confirmed grant.
47    pub invitation: Option<SecretBytes>,
48    /// Unfinished work, including a failed request.
49    pub request: Option<ProviderAccessRequest>,
50}
51
52pub(crate) fn read(db: &StoreSql, account: &str) -> Result<Option<ProviderAccess>, DbError> {
53    Ok(db.query("SELECT intended,granted,invitation,operation,target FROM _coven_provider_access WHERE account=?1", [account], |row| {
54        let operation: Option<i64> = row.get(3)?;
55        let target: Option<bool> = row.get(4)?;
56        if operation.is_none() && target.is_some() { return Err(crate::write_encoding::damaged(4, sqlive::rusqlite::types::Type::Integer)); }
57        Ok(ProviderAccess { intended: row.get(0)?, granted: row.get(1)?, invitation: row.get::<_,Option<Vec<u8>>>(2)?.map(SecretBytes::new),
58            request: operation.map(|id| ProviderAccessRequest { operation: OperationId(id), target }) })
59    }).map(|mut rows| rows.pop())?)
60}
61
62pub(crate) fn finish(db: &StoreSql, account: &str, id: OperationId) -> Result<(), DbError> {
63    db.execute("UPDATE _coven_provider_access SET operation=NULL,target=NULL WHERE account=?1 AND operation=?2", (account,id.0))?;
64    crate::operation::finish(db, id)?;
65    Ok(())
66}
67
68/// Queue the account's request `id` again with no target fixed, ending the
69/// wait its last attempt left.
70pub(crate) fn requeue(db: &StoreSql, account: &str, id: OperationId) -> Result<(), DbError> {
71    crate::operation::set_step(db, id, REQUEST_QUEUED_STEP)?;
72    crate::retry::clear(db, crate::RetrySubject::Operation(id))?;
73    db.execute(
74        "UPDATE _coven_provider_access SET target=NULL WHERE account=?1 AND target IS NOT NULL",
75        [account],
76    )?;
77    Ok(())
78}
79
80/// Fix a request's target to the account's intention before storage is
81/// called. A revoke may remove the direct share supplying acceptance
82/// tokens even when other permissions remain, so neither confirmation is
83/// kept.
84pub(crate) fn fix_target(db: &StoreSql, account: &str) -> Result<(), DbError> {
85    db.execute("UPDATE _coven_provider_access SET granted=NULL,invitation=NULL,target=intended WHERE account=?1", [account])?;
86    Ok(())
87}
88
89/// The provider confirmed `target`, with its acceptance information when
90/// it granted access; the request has no target fixed any more.
91pub(crate) fn confirm(
92    db: &StoreSql,
93    account: &str,
94    target: bool,
95    invitation: Option<&SecretBytes>,
96) -> Result<(), DbError> {
97    db.execute(
98        "UPDATE _coven_provider_access SET granted=?1,invitation=?2,target=NULL WHERE account=?3",
99        (target, invitation.map(SecretBytes::as_bytes), account),
100    )?;
101    Ok(())
102}
103
104/// Called inside the same transaction as membership or an invitation change.
105pub(crate) fn adopt<P: PendingValue>(
106    db: &StoreSql,
107    changes: &[ProviderAccessChange],
108) -> Result<(), DbError> {
109    for change in changes {
110        let before = match read(db, &change.account)? {
111            Some(before) => before,
112            None => {
113                db.execute(
114                    "INSERT INTO _coven_provider_access(account,intended,granted) VALUES(?1,?2,?3)",
115                    (&change.account, change.intended, change.initially_granted),
116                )?;
117                ProviderAccess {
118                    intended: change.intended,
119                    granted: Some(change.initially_granted),
120                    invitation: None,
121                    request: None,
122                }
123            }
124        };
125        db.execute(
126            "UPDATE _coven_provider_access SET intended=?1 WHERE account=?2 AND intended!=?1",
127            (change.intended, &change.account),
128        )?;
129        if let Some(request) = &before.request {
130            let record =
131                crate::operation::find(db, request.operation)?.ok_or(DbError::DamagedDatabase)?;
132            // An in-flight completion must first account for its fixed target.
133            // Unchanged membership also preserves a previously reported failure.
134            if record.last_step == REQUEST_FIXED_STEP
135                || (record.last_step == REQUEST_FAILED_STEP && before.intended == change.intended)
136            {
137                continue;
138            }
139        }
140        let needed = before.granted != Some(change.intended)
141            || (change.intended && change.needs_invitation && before.invitation.is_none());
142        if !needed {
143            if let Some(request) = before.request {
144                finish(db, &change.account, request.operation)?;
145            }
146            continue;
147        }
148        let id = match before.request {
149            Some(request) => {
150                requeue(db, &change.account, request.operation)?;
151                request.operation
152            }
153            None => {
154                let id = crate::operation::insert(db, &change.operation)?;
155                db.execute(
156                    "UPDATE _coven_provider_access SET operation=?1 WHERE account=?2",
157                    (id.0, &change.account),
158                )?;
159                id
160            }
161        };
162        crate::pending::save(db, &P::provider_access(id, change.account.clone(), change.intended))?;
163    }
164    Ok(())
165}
166
167/// Take back accounts whose confirmed grant can no longer be trusted: the
168/// person confirmed that a lost owner device, whose grants may have landed
169/// after this device's revocations, can land nothing more (§20.9). Each
170/// account forgets its confirmed grant and queues a request for its
171/// intention, so a revocation follows any grant that landed before the
172/// confirmation. An account with a request between its fixed target and its
173/// reply fails the call with `ProviderRequestRunning`, and nothing changes:
174/// that request's reply may precede the confirmation.
175pub(crate) fn retake<P: PendingValue>(
176    db: &StoreSql,
177    changes: &[ProviderAccessChange],
178) -> Result<(), DbError> {
179    for change in changes {
180        if let Some(request) = read(db, &change.account)?.and_then(|state| state.request) {
181            let record =
182                crate::operation::find(db, request.operation)?.ok_or(DbError::DamagedDatabase)?;
183            if record.last_step == REQUEST_FIXED_STEP {
184                return Err(DbError::ProviderRequestRunning);
185            }
186            if record.last_step == REQUEST_FAILED_STEP {
187                // A reported failure waits for the app's retry; this
188                // request is that retry.
189                requeue(db, &change.account, request.operation)?;
190            }
191        }
192        db.execute(
193            "INSERT INTO _coven_provider_access(account,intended) VALUES(?1,?2) \
194             ON CONFLICT(account) DO NOTHING",
195            (&change.account, change.intended),
196        )?;
197        db.execute(
198            "UPDATE _coven_provider_access SET granted=NULL,invitation=NULL WHERE account=?1",
199            [&change.account],
200        )?;
201    }
202    adopt::<P>(db, changes)
203}
204
205#[cfg(test)]
206#[path = "provider_access_tests.rs"]
207pub(crate) mod tests;