1use crate::sqlite::StoreSql;
4use crate::{DbError, NewOperation, OperationId, PendingValue};
5use coven_crypto::SecretBytes;
6
7pub(crate) const REQUEST_QUEUED_STEP: u32 = 0;
11pub const REQUEST_FIXED_STEP: u32 = 1;
14pub(crate) const REQUEST_FAILED_STEP: u32 = 2;
15
16pub struct ProviderAccessChange {
18 pub account: String,
20 pub intended: bool,
22 pub initially_granted: bool,
24 pub needs_invitation: bool,
26 pub operation: NewOperation,
28}
29
30#[derive(Clone, Debug, PartialEq, Eq)]
32pub struct ProviderAccessRequest {
33 pub operation: OperationId,
35 pub target: Option<bool>,
37}
38
39#[derive(Debug)]
41pub struct ProviderAccess {
42 pub intended: bool,
44 pub granted: Option<bool>,
46 pub invitation: Option<SecretBytes>,
48 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
68pub(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
80pub(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
89pub(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
104pub(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 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
167pub(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 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;