Skip to main content

coven_sync/
sign_in.rs

1//! Custody of an OAuth sign-in: coven's session custody until setup or a
2//! restore publishes the store, or a join saves its invite code; this
3//! installation's device custody after it (§13.2, §20.2, E5, E10). A token is
4//! used until the provider rejects it; its one refresh is committed here
5//! before any connection uses it.
6
7use 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
19/// This installation's committed storage credentials. Every write of them
20/// goes through [`Self::write`], so a refresh commits its replacement only
21/// while custody still holds the tokens the provider rejected.
22pub struct DeviceCredentials {
23    keychains: CredentialKeychains,
24    oauth: Option<OAuthExchange>,
25    writes: Mutex<()>,
26    refreshing: tokio::sync::Mutex<()>,
27}
28
29impl DeviceCredentials {
30    /// Compose once per installation, beside its device-only entries and the
31    /// person's entries: for an open store, or for a join from the moment it keeps
32    /// its sign-in, which the joined store's handle goes on using (§13.2).
33    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    /// Change committed credentials, serialized with every refresh's commit.
48    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    /// The saved location with these credentials; None when either is absent.
57    pub fn connection(&self) -> Result<Option<ConnectionCredentials>, SyncError> {
58        self.keychains.connection()
59    }
60
61    /// The recorded location, with its labels, and whether this device's
62    /// credentials for it are held, as the sync state reads it (§19.1).
63    pub fn location(
64        &self,
65    ) -> Result<coven_database::RecordedLocation<coven_storage::StorageConfig>, SyncError> {
66        self.keychains.location()
67    }
68
69    /// The OAuth tokens committed here, which a new connection starts with.
70    /// Refuses when no OAuth sign-in is committed.
71    pub fn tokens(&self) -> Result<OAuthTokens, SyncError> {
72        self.write(held_tokens)
73    }
74
75    /// Save the restore code with the store's name beside the OAuth sign-in
76    /// committed here, leaving that sign-in as it is: a join publishes this
77    /// way, since it has kept its sign-in here while it waited, refreshes
78    /// included (§13.2). Refuses when no OAuth sign-in is committed.
79    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    /// Commit `refreshed` in place of `rejected`, unless custody holds other
118    /// tokens by now, which then win: a sign-in committed meanwhile, or
119    /// another refresh of the same rejection.
120    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
137/// A sign-in held for this session only, until setup or bootstrap publishes
138/// it to device custody: with the store, or for a join once it saves its
139/// invite code. It then refreshes there (§13.2, §20.2).
140pub struct SessionSignIn {
141    /// The tokens this session holds, or published; with the device custody
142    /// holding them since publication.
143    state: Mutex<(OAuthTokens, Option<Arc<DeviceCredentials>>)>,
144    oauth: Option<OAuthExchange>,
145    refreshing: tokio::sync::Mutex<()>,
146}
147
148impl SessionSignIn {
149    /// Hold tokens from a completed sign-in.
150    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    /// The provider this sign-in is for.
159    pub fn provider(&self) -> coven_storage::CloudProvider {
160        lock_unpoisoned(&self.state).0.access.provider()
161    }
162
163    /// The tokens a new connection starts with.
164    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    /// Commit the held tokens to device custody with `commit`, after which
172    /// rejections refresh there. Returns `commit`'s result; nothing moves if it fails.
173    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    /// Hold the published tokens in this session again, after the commit that
191    /// published them was rolled back.
192    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            // Only this refresh, serialized above, changes held tokens.
215            (tokens, None) => {
216                *tokens = refreshed.clone();
217                return Ok(refreshed);
218            }
219            (_, Some(device)) => device.clone(),
220        };
221        // Publication moved the rejected tokens to device custody meanwhile:
222        // this one refresh is committed there instead (§20.2).
223        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        // Custody could not keep the replacement: nothing was installed.
242        error => StorageFailure::File.with_source(error),
243    }
244}
245
246#[cfg(test)]
247#[path = "sign_in_tests.rs"]
248mod tests;