1use crate::{commit_credentials, CredentialKeychains, CredentialRollback, SavedName, SyncError};
8use coven_crypto::custody::{PersonEntries, StoreKeychain};
9use coven_format::codes::RestoreCode;
10use coven_foundation::files::StoreDir;
11use coven_foundation::locks::lock_unpoisoned;
12use coven_storage::providers::OAuthTokenRefresh;
13use coven_storage::{
14 providers::OAuthExchange, ConnectionCredentials, OAuthTokens, StorageCredentials, StorageError,
15 StorageFailure, TokenCustody,
16};
17use std::sync::{Arc, Mutex};
18
19pub struct DeviceCredentials {
23 keychains: CredentialKeychains,
24 oauth: Option<OAuthExchange>,
25 writes: Mutex<()>,
26 refreshing: tokio::sync::Mutex<()>,
27}
28
29impl DeviceCredentials {
30 pub fn new(
34 keychain: Arc<StoreKeychain>,
35 person: Arc<PersonEntries>,
36 directory: StoreDir,
37 oauth: Option<OAuthExchange>,
38 ) -> Self {
39 Self {
40 keychains: CredentialKeychains::new(keychain, person, directory),
41 oauth,
42 writes: Mutex::new(()),
43 refreshing: tokio::sync::Mutex::new(()),
44 }
45 }
46
47 pub fn write<T>(
49 &self,
50 change: impl FnOnce(&CredentialKeychains) -> Result<T, SyncError>,
51 ) -> Result<T, SyncError> {
52 let _write = lock_unpoisoned(&self.writes);
53 change(&self.keychains)
54 }
55
56 pub fn connection(&self) -> Result<Option<ConnectionCredentials>, SyncError> {
58 self.keychains.connection()
59 }
60
61 pub fn location(
64 &self,
65 ) -> Result<coven_database::RecordedLocation<coven_storage::StorageConfig>, SyncError> {
66 self.keychains.location()
67 }
68
69 pub fn tokens(&self) -> Result<OAuthTokens, SyncError> {
72 self.write(held_tokens)
73 }
74
75 pub fn commit_code(
80 &self,
81 code: &RestoreCode,
82 name: &SavedName,
83 ) -> Result<CredentialRollback, SyncError> {
84 self.write(|keychains| {
85 held_tokens(keychains)?;
86 crate::credential_custody::commit_account_code(keychains, code, name)
87 })
88 }
89}
90
91pub(crate) fn held_tokens(keychains: &CredentialKeychains) -> Result<OAuthTokens, SyncError> {
92 let bytes = keychains
93 .storage_credentials()?
94 .ok_or(StorageFailure::Authentication.with_source("no sign-in is in device custody"))?;
95 match StorageCredentials::decode(bytes.as_bytes())? {
96 StorageCredentials::OAuth(tokens) => Ok(tokens),
97 _ => Err(StorageFailure::InvalidConfiguration
98 .with_source("device custody holds no OAuth sign-in")
99 .into()),
100 }
101}
102
103#[async_trait::async_trait]
104impl TokenCustody for DeviceCredentials {
105 async fn replace(&self, rejected: &OAuthTokens) -> Result<OAuthTokens, StorageError> {
106 let _one = self.refreshing.lock().await;
107 let held = held_tokens(&self.keychains).map_err(storage_error)?;
108 if held.access_token.as_str() != rejected.access_token.as_str() {
109 return Ok(held);
110 }
111 let refreshed = refresh(self.oauth.as_ref(), &held).await?;
112 self.commit_refresh(rejected, refreshed)
113 }
114}
115
116impl DeviceCredentials {
117 fn commit_refresh(
121 &self,
122 rejected: &OAuthTokens,
123 refreshed: OAuthTokens,
124 ) -> Result<OAuthTokens, StorageError> {
125 self.write(|keychain| {
126 let held = held_tokens(keychain)?;
127 if held.access_token.as_str() != rejected.access_token.as_str() {
128 return Ok(held);
129 }
130 commit_credentials(keychain, &StorageCredentials::OAuth(refreshed.clone()), None)?;
131 Ok(refreshed)
132 })
133 .map_err(storage_error)
134 }
135}
136
137pub struct SessionSignIn {
141 state: Mutex<(OAuthTokens, Option<Arc<DeviceCredentials>>)>,
144 oauth: Option<OAuthExchange>,
145 refreshing: tokio::sync::Mutex<()>,
146}
147
148impl SessionSignIn {
149 pub fn new(tokens: OAuthTokens, oauth: Option<OAuthExchange>) -> Arc<Self> {
151 Arc::new(Self {
152 state: Mutex::new((tokens, None)),
153 oauth,
154 refreshing: tokio::sync::Mutex::new(()),
155 })
156 }
157
158 pub fn provider(&self) -> coven_storage::CloudProvider {
160 lock_unpoisoned(&self.state).0.access.provider()
161 }
162
163 pub fn tokens(&self) -> Result<OAuthTokens, SyncError> {
165 match &*lock_unpoisoned(&self.state) {
166 (tokens, None) => Ok(tokens.clone()),
167 (_, Some(device)) => device.tokens(),
168 }
169 }
170
171 pub fn publish<T>(
174 &self,
175 device: &Arc<DeviceCredentials>,
176 commit: impl FnOnce(&CredentialKeychains, &OAuthTokens) -> Result<T, SyncError>,
177 ) -> Result<T, SyncError> {
178 let mut state = lock_unpoisoned(&self.state);
179 let (tokens, published) = &mut *state;
180 if published.is_some() {
181 return Err(StorageFailure::InvalidConfiguration
182 .with_source("this sign-in is already in device custody")
183 .into());
184 }
185 let result = device.write(|keychain| commit(keychain, tokens))?;
186 *published = Some(device.clone());
187 Ok(result)
188 }
189
190 pub fn unpublish(&self) {
193 lock_unpoisoned(&self.state).1 = None;
194 }
195}
196
197#[async_trait::async_trait]
198impl TokenCustody for SessionSignIn {
199 async fn replace(&self, rejected: &OAuthTokens) -> Result<OAuthTokens, StorageError> {
200 let _one = self.refreshing.lock().await;
201 let held = match &*lock_unpoisoned(&self.state) {
202 (tokens, None) => Ok(tokens.clone()),
203 (_, Some(device)) => Err(device.clone()),
204 };
205 let held = match held {
206 Ok(held) => held,
207 Err(device) => return device.replace(rejected).await,
208 };
209 if held.access_token.as_str() != rejected.access_token.as_str() {
210 return Ok(held);
211 }
212 let refreshed = refresh(self.oauth.as_ref(), &held).await?;
213 let device = match &mut *lock_unpoisoned(&self.state) {
214 (tokens, None) => {
216 *tokens = refreshed.clone();
217 return Ok(refreshed);
218 }
219 (_, Some(device)) => device.clone(),
220 };
221 device.commit_refresh(rejected, refreshed)
224 }
225}
226
227async fn refresh(
228 oauth: Option<&OAuthExchange>,
229 held: &OAuthTokens,
230) -> Result<OAuthTokens, StorageError> {
231 oauth
232 .ok_or(StorageFailure::InvalidConfiguration.with_source("OAuth clients are absent"))?
233 .refresh(held)
234 .await
235}
236
237fn storage_error(error: SyncError) -> StorageError {
238 match error {
239 SyncError::Storage(error) => error,
240 SyncError::Bug(bug) => bug.into(),
241 error => StorageFailure::File.with_source(error),
243 }
244}
245
246#[cfg(test)]
247#[path = "sign_in_tests.rs"]
248mod tests;