Skip to main content

agent_storage/
external_connection.rs

1//! Provider-independent persistence for external OAuth connections.
2use crate::UserId;
3use async_trait::async_trait;
4use chrono::{DateTime, Utc};
5use ring::{
6    aead::{AES_256_GCM, Aad, LessSafeKey, Nonce, UnboundKey},
7    rand::{SecureRandom, SystemRandom},
8};
9use rusqlite::{Connection, OptionalExtension, params};
10use serde::{Deserialize, Serialize};
11use sha2::{Digest, Sha256};
12use std::{path::Path, str::FromStr, sync::Arc};
13use thiserror::Error;
14use tokio::sync::Mutex;
15use uuid::Uuid;
16
17const NONCE_LEN: usize = 12;
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
19#[serde(transparent)]
20pub struct ExternalConnectionId(Uuid);
21impl ExternalConnectionId {
22    pub fn new() -> Self {
23        Self(Uuid::new_v4())
24    }
25}
26impl Default for ExternalConnectionId {
27    fn default() -> Self {
28        Self::new()
29    }
30}
31impl std::fmt::Display for ExternalConnectionId {
32    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33        self.0.fmt(f)
34    }
35}
36impl FromStr for ExternalConnectionId {
37    type Err = uuid::Error;
38    fn from_str(s: &str) -> Result<Self, Self::Err> {
39        Uuid::parse_str(s).map(Self)
40    }
41}
42
43#[derive(Clone)]
44pub struct CredentialCipher {
45    key: [u8; 32],
46}
47impl CredentialCipher {
48    pub fn new(key: [u8; 32]) -> Self {
49        Self { key }
50    }
51    fn cipher(&self) -> Result<LessSafeKey, ExternalConnectionStorageError> {
52        UnboundKey::new(&AES_256_GCM, &self.key)
53            .map(LessSafeKey::new)
54            .map_err(|_| ExternalConnectionStorageError::Encryption)
55    }
56    /// Encrypts using AES-256-GCM; output is nonce || ciphertext || tag.
57    pub fn encrypt(&self, plain: &[u8]) -> Result<Vec<u8>, ExternalConnectionStorageError> {
58        let mut nonce = [0u8; NONCE_LEN];
59        SystemRandom::new()
60            .fill(&mut nonce)
61            .map_err(|_| ExternalConnectionStorageError::Encryption)?;
62        let mut data = plain.to_vec();
63        self.cipher()?
64            .seal_in_place_append_tag(Nonce::assume_unique_for_key(nonce), Aad::empty(), &mut data)
65            .map_err(|_| ExternalConnectionStorageError::Encryption)?;
66        let mut out = nonce.to_vec();
67        out.extend(data);
68        Ok(out)
69    }
70    pub fn decrypt(&self, data: &[u8]) -> Result<Vec<u8>, ExternalConnectionStorageError> {
71        if data.len() < NONCE_LEN + 16 {
72            return Err(ExternalConnectionStorageError::Encryption);
73        }
74        let nonce: [u8; NONCE_LEN] = data[..NONCE_LEN]
75            .try_into()
76            .map_err(|_| ExternalConnectionStorageError::Encryption)?;
77        let mut ciphertext = data[NONCE_LEN..].to_vec();
78        self.cipher()?
79            .open_in_place(
80                Nonce::assume_unique_for_key(nonce),
81                Aad::empty(),
82                &mut ciphertext,
83            )
84            .map(|v| v.to_vec())
85            .map_err(|_| ExternalConnectionStorageError::Encryption)
86    }
87}
88#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
89#[serde(rename_all = "snake_case")]
90pub enum ExternalConnectionStatus {
91    Active,
92    Revoked,
93}
94impl ExternalConnectionStatus {
95    fn parse(s: &str) -> Result<Self, ExternalConnectionStorageError> {
96        match s {
97            "active" => Ok(Self::Active),
98            "revoked" => Ok(Self::Revoked),
99            _ => Err(ExternalConnectionStorageError::Backend(format!(
100                "invalid connection status: {s}"
101            ))),
102        }
103    }
104}
105#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
106pub struct ExternalConnection {
107    pub id: ExternalConnectionId,
108    pub owner_id: UserId,
109    pub provider: String,
110    pub provider_subject: String,
111    pub display_email: Option<String>,
112    /// Never include ciphertext in serialized API responses.
113    #[serde(skip)]
114    pub encrypted_refresh_token: Vec<u8>,
115    pub granted_scopes: Vec<String>,
116    pub status: ExternalConnectionStatus,
117    pub created_at: DateTime<Utc>,
118    pub updated_at: DateTime<Utc>,
119    pub revoked_at: Option<DateTime<Utc>>,
120}
121pub struct NewExternalConnection {
122    pub owner_id: UserId,
123    pub provider: String,
124    pub provider_subject: String,
125    pub display_email: Option<String>,
126    pub refresh_token: String,
127    pub granted_scopes: Vec<String>,
128}
129pub struct NewExternalAuthorization {
130    pub user_id: UserId,
131    pub provider: String,
132    pub state: String,
133    pub pkce_verifier: String,
134    pub requested_scopes: Vec<String>,
135    pub expires_at: DateTime<Utc>,
136}
137pub struct ConsumedExternalAuthorization {
138    pub id: Uuid,
139    pub user_id: UserId,
140    pub provider: String,
141    pub pkce_verifier: String,
142    pub requested_scopes: Vec<String>,
143    pub created_at: DateTime<Utc>,
144}
145
146#[derive(Debug, Error)]
147pub enum ExternalConnectionStorageError {
148    #[error("external connection was not found")]
149    NotFound,
150    #[error("external connection already exists for this provider account")]
151    AlreadyExists,
152    #[error("pending authorization was not found")]
153    AuthorizationNotFound,
154    #[error("pending authorization has expired")]
155    AuthorizationExpired,
156    #[error("pending authorization has already been consumed")]
157    AuthorizationConsumed,
158    #[error("authorization provider does not match")]
159    ProviderMismatch,
160    #[error("required value is empty")]
161    EmptyRequiredValue,
162    #[error("refresh token must not be empty")]
163    EmptyRefreshToken,
164    #[error("credential encryption or authentication failed")]
165    Encryption,
166    #[error("external connection storage backend failed: {0}")]
167    Backend(String),
168}
169#[async_trait]
170pub trait ExternalConnectionStore: Send + Sync {
171    async fn create_connection(
172        &self,
173        input: NewExternalConnection,
174    ) -> Result<ExternalConnection, ExternalConnectionStorageError>;
175    async fn get_connection(
176        &self,
177        owner: UserId,
178        id: ExternalConnectionId,
179    ) -> Result<Option<ExternalConnection>, ExternalConnectionStorageError>;
180    /// Decrypt a refresh token for a trusted server-side provider operation.
181    /// This must never be exposed through an HTTP response or agent tool.
182    async fn refresh_token(
183        &self,
184        owner: UserId,
185        id: ExternalConnectionId,
186    ) -> Result<String, ExternalConnectionStorageError>;
187    async fn list_connections(
188        &self,
189        owner: UserId,
190    ) -> Result<Vec<ExternalConnection>, ExternalConnectionStorageError>;
191    /// None preserves the existing encrypted refresh token.
192    async fn update_credentials(
193        &self,
194        owner: UserId,
195        id: ExternalConnectionId,
196        token: Option<String>,
197        scopes: Vec<String>,
198    ) -> Result<ExternalConnection, ExternalConnectionStorageError>;
199    async fn revoke_connection(
200        &self,
201        owner: UserId,
202        id: ExternalConnectionId,
203    ) -> Result<(), ExternalConnectionStorageError>;
204    async fn begin_authorization(
205        &self,
206        input: NewExternalAuthorization,
207    ) -> Result<Uuid, ExternalConnectionStorageError>;
208    /// Atomically consumes state and decrypts its PKCE verifier; a state succeeds once.
209    async fn consume_authorization(
210        &self,
211        provider: &str,
212        state: &str,
213        now: DateTime<Utc>,
214    ) -> Result<ConsumedExternalAuthorization, ExternalConnectionStorageError>;
215}
216#[derive(Clone)]
217pub struct SqliteExternalConnectionStore {
218    db: Arc<Mutex<Connection>>,
219    cipher: CredentialCipher,
220}
221impl SqliteExternalConnectionStore {
222    pub fn open(path: impl AsRef<Path>, key: [u8; 32]) -> Result<Self, rusqlite::Error> {
223        let db = Connection::open(path)?;
224        db.busy_timeout(std::time::Duration::from_secs(5))?;
225        db.execute_batch("PRAGMA foreign_keys=ON;")?;
226        db.execute_batch(include_str!("../migrations/0001_identity_and_families.sql"))?;
227        db.execute_batch(include_str!("../migrations/0002_family_invitations.sql"))?;
228        db.execute_batch(include_str!("../migrations/0003_external_connections.sql"))?;
229        Ok(Self {
230            db: Arc::new(Mutex::new(db)),
231            cipher: CredentialCipher::new(key),
232        })
233    }
234}
235fn backend(e: rusqlite::Error) -> ExternalConnectionStorageError {
236    ExternalConnectionStorageError::Backend(e.to_string())
237}
238fn time(s: &str) -> Result<DateTime<Utc>, ExternalConnectionStorageError> {
239    DateTime::parse_from_rfc3339(s)
240        .map(|v| v.with_timezone(&Utc))
241        .map_err(|e| ExternalConnectionStorageError::Backend(e.to_string()))
242}
243fn ensure_user(db: &Connection, id: UserId) -> Result<(), rusqlite::Error> {
244    let n = Utc::now().to_rfc3339();
245    db.execute(
246        "INSERT OR IGNORE INTO users(id,display_name,created_at,updated_at) VALUES(?1,NULL,?2,?2)",
247        params![id.to_string(), n],
248    )?;
249    Ok(())
250}
251fn scopes(v: &[String]) -> Result<String, ExternalConnectionStorageError> {
252    serde_json::to_string(v).map_err(|e| ExternalConnectionStorageError::Backend(e.to_string()))
253}
254fn parse_scopes(v: &str) -> Result<Vec<String>, ExternalConnectionStorageError> {
255    serde_json::from_str(v).map_err(|e| ExternalConnectionStorageError::Backend(e.to_string()))
256}
257fn state_hash(s: &str) -> String {
258    Sha256::digest(s.as_bytes())
259        .iter()
260        .map(|b| format!("{b:02x}"))
261        .collect()
262}
263fn load(
264    db: &Connection,
265    owner: UserId,
266    id: ExternalConnectionId,
267) -> Result<Option<ExternalConnection>, ExternalConnectionStorageError> {
268    let row=db.query_row("SELECT provider,provider_subject,display_email,encrypted_refresh_token,granted_scopes,status,created_at,updated_at,revoked_at FROM external_connections WHERE owner_id=?1 AND id=?2",params![owner.to_string(),id.to_string()],|r|Ok((r.get::<_,String>(0)?,r.get::<_,String>(1)?,r.get::<_,Option<String>>(2)?,r.get::<_,Vec<u8>>(3)?,r.get::<_,String>(4)?,r.get::<_,String>(5)?,r.get::<_,String>(6)?,r.get::<_,String>(7)?,r.get::<_,Option<String>>(8)?))).optional().map_err(backend)?;
269    row.map(|(p, s, e, t, sc, st, c, u, r)| {
270        Ok(ExternalConnection {
271            id,
272            owner_id: owner,
273            provider: p,
274            provider_subject: s,
275            display_email: e,
276            encrypted_refresh_token: t,
277            granted_scopes: parse_scopes(&sc)?,
278            status: ExternalConnectionStatus::parse(&st)?,
279            created_at: time(&c)?,
280            updated_at: time(&u)?,
281            revoked_at: r.map(|v| time(&v)).transpose()?,
282        })
283    })
284    .transpose()
285}
286#[async_trait]
287impl ExternalConnectionStore for SqliteExternalConnectionStore {
288    async fn create_connection(
289        &self,
290        x: NewExternalConnection,
291    ) -> Result<ExternalConnection, ExternalConnectionStorageError> {
292        if x.provider.trim().is_empty() || x.provider_subject.trim().is_empty() {
293            return Err(ExternalConnectionStorageError::EmptyRequiredValue);
294        }
295        if x.refresh_token.is_empty() {
296            return Err(ExternalConnectionStorageError::EmptyRefreshToken);
297        }
298        let token = self.cipher.encrypt(x.refresh_token.as_bytes())?;
299        let scopes = scopes(&x.granted_scopes)?;
300        let id = ExternalConnectionId::new();
301        let now = Utc::now().to_rfc3339();
302        let db = self.db.lock().await;
303        ensure_user(&db, x.owner_id).map_err(backend)?;
304        // Reauthorizing an existing Google account updates its credentials and
305        // reactivates a previously disconnected EME connection without
306        // changing the stable internal connection ID.
307        let stored_id: String = db
308            .query_row(
309                "INSERT INTO external_connections(
310                    id,owner_id,provider,provider_subject,display_email,
311                    encrypted_refresh_token,granted_scopes,status,created_at,updated_at,revoked_at
312                 ) VALUES(?1,?2,?3,?4,?5,?6,?7,'active',?8,?8,NULL)
313                 ON CONFLICT(owner_id,provider,provider_subject) DO UPDATE SET
314                    display_email=excluded.display_email,
315                    encrypted_refresh_token=excluded.encrypted_refresh_token,
316                    granted_scopes=excluded.granted_scopes,
317                    status='active',
318                    updated_at=excluded.updated_at,
319                    revoked_at=NULL
320                 RETURNING id",
321                params![
322                    id.to_string(),
323                    x.owner_id.to_string(),
324                    x.provider.trim(),
325                    x.provider_subject.trim(),
326                    x.display_email,
327                    token,
328                    scopes,
329                    now
330                ],
331                |row| row.get(0),
332            )
333            .map_err(backend)?;
334        let stored_id = ExternalConnectionId::from_str(&stored_id)
335            .map_err(|error| ExternalConnectionStorageError::Backend(error.to_string()))?;
336        load(&db, x.owner_id, stored_id)?.ok_or(ExternalConnectionStorageError::NotFound)
337    }
338    async fn get_connection(
339        &self,
340        o: UserId,
341        id: ExternalConnectionId,
342    ) -> Result<Option<ExternalConnection>, ExternalConnectionStorageError> {
343        let db = self.db.lock().await;
344        load(&db, o, id)
345    }
346    async fn refresh_token(
347        &self,
348        owner: UserId,
349        id: ExternalConnectionId,
350    ) -> Result<String, ExternalConnectionStorageError> {
351        let db = self.db.lock().await;
352        let connection = load(&db, owner, id)?.ok_or(ExternalConnectionStorageError::NotFound)?;
353        let plaintext = self.cipher.decrypt(&connection.encrypted_refresh_token)?;
354        String::from_utf8(plaintext).map_err(|_| ExternalConnectionStorageError::Encryption)
355    }
356
357    async fn list_connections(
358        &self,
359        o: UserId,
360    ) -> Result<Vec<ExternalConnection>, ExternalConnectionStorageError> {
361        let db = self.db.lock().await;
362        let mut q = db
363            .prepare("SELECT id FROM external_connections WHERE owner_id=?1 ORDER BY created_at,id")
364            .map_err(backend)?;
365        let rows = q
366            .query_map([o.to_string()], |r| r.get::<_, String>(0))
367            .map_err(backend)?;
368        let mut out = Vec::new();
369        for row in rows {
370            let id = ExternalConnectionId::from_str(&row.map_err(backend)?)
371                .map_err(|e| ExternalConnectionStorageError::Backend(e.to_string()))?;
372            if let Some(v) = load(&db, o, id)? {
373                out.push(v)
374            }
375        }
376        Ok(out)
377    }
378    async fn update_credentials(
379        &self,
380        o: UserId,
381        id: ExternalConnectionId,
382        token: Option<String>,
383        s: Vec<String>,
384    ) -> Result<ExternalConnection, ExternalConnectionStorageError> {
385        let s = scopes(&s)?;
386        let token = token
387            .map(|v| {
388                if v.is_empty() {
389                    Err(ExternalConnectionStorageError::EmptyRefreshToken)
390                } else {
391                    self.cipher.encrypt(v.as_bytes())
392                }
393            })
394            .transpose()?;
395        let db = self.db.lock().await;
396        let now = Utc::now().to_rfc3339();
397        let n=if let Some(t)=token{db.execute("UPDATE external_connections SET encrypted_refresh_token=?1,granted_scopes=?2,updated_at=?3 WHERE owner_id=?4 AND id=?5 AND status='active'",params![t,s,now,o.to_string(),id.to_string()])}else{db.execute("UPDATE external_connections SET granted_scopes=?1,updated_at=?2 WHERE owner_id=?3 AND id=?4 AND status='active'",params![s,now,o.to_string(),id.to_string()])}.map_err(backend)?;
398        if n == 0 {
399            return Err(ExternalConnectionStorageError::NotFound);
400        }
401        load(&db, o, id)?.ok_or(ExternalConnectionStorageError::NotFound)
402    }
403    async fn revoke_connection(
404        &self,
405        o: UserId,
406        id: ExternalConnectionId,
407    ) -> Result<(), ExternalConnectionStorageError> {
408        let db = self.db.lock().await;
409        let now = Utc::now().to_rfc3339();
410        let n=db.execute("UPDATE external_connections SET status='revoked',revoked_at=?1,updated_at=?1 WHERE owner_id=?2 AND id=?3 AND status='active'",params![now,o.to_string(),id.to_string()]).map_err(backend)?;
411        if n == 0 {
412            Err(ExternalConnectionStorageError::NotFound)
413        } else {
414            Ok(())
415        }
416    }
417    async fn begin_authorization(
418        &self,
419        x: NewExternalAuthorization,
420    ) -> Result<Uuid, ExternalConnectionStorageError> {
421        if x.provider.trim().is_empty() || x.state.is_empty() || x.pkce_verifier.is_empty() {
422            return Err(ExternalConnectionStorageError::EmptyRequiredValue);
423        }
424        let now = Utc::now();
425        if x.expires_at <= now {
426            return Err(ExternalConnectionStorageError::AuthorizationExpired);
427        }
428        let verifier = self.cipher.encrypt(x.pkce_verifier.as_bytes())?;
429        let scopes = scopes(&x.requested_scopes)?;
430        let id = Uuid::new_v4();
431        let db = self.db.lock().await;
432        ensure_user(&db, x.user_id).map_err(backend)?;
433        db.execute("INSERT INTO pending_external_authorizations(id,user_id,provider,state_hash,encrypted_pkce_verifier,requested_scopes,created_at,expires_at,consumed_at) VALUES(?1,?2,?3,?4,?5,?6,?7,?8,NULL)",params![id.to_string(),x.user_id.to_string(),x.provider.trim(),state_hash(&x.state),verifier,scopes,now.to_rfc3339(),x.expires_at.to_rfc3339()]).map_err(backend)?;
434        Ok(id)
435    }
436    async fn consume_authorization(
437        &self,
438        p: &str,
439        state: &str,
440        now: DateTime<Utc>,
441    ) -> Result<ConsumedExternalAuthorization, ExternalConnectionStorageError> {
442        if p.trim().is_empty() || state.is_empty() {
443            return Err(ExternalConnectionStorageError::EmptyRequiredValue);
444        }
445        let mut db = self.db.lock().await;
446        let tx = db.transaction().map_err(backend)?;
447        let row=tx.query_row("SELECT id,user_id,provider,encrypted_pkce_verifier,requested_scopes,created_at,expires_at,consumed_at FROM pending_external_authorizations WHERE state_hash=?1",[state_hash(state)],|r|Ok((r.get::<_,String>(0)?,r.get::<_,String>(1)?,r.get::<_,String>(2)?,r.get::<_,Vec<u8>>(3)?,r.get::<_,String>(4)?,r.get::<_,String>(5)?,r.get::<_,String>(6)?,r.get::<_,Option<String>>(7)?))).optional().map_err(backend)?.ok_or(ExternalConnectionStorageError::AuthorizationNotFound)?;
448        let (id, user, provider, verifier, sc, created, expires, consumed) = row;
449        if provider != p {
450            return Err(ExternalConnectionStorageError::ProviderMismatch);
451        }
452        if consumed.is_some() {
453            return Err(ExternalConnectionStorageError::AuthorizationConsumed);
454        }
455        if time(&expires)? <= now {
456            return Err(ExternalConnectionStorageError::AuthorizationExpired);
457        }
458        let n=tx.execute("UPDATE pending_external_authorizations SET consumed_at=?1 WHERE id=?2 AND consumed_at IS NULL",params![now.to_rfc3339(),id]).map_err(backend)?;
459        if n != 1 {
460            return Err(ExternalConnectionStorageError::AuthorizationConsumed);
461        }
462        tx.commit().map_err(backend)?;
463        let verifier = String::from_utf8(self.cipher.decrypt(&verifier)?)
464            .map_err(|_| ExternalConnectionStorageError::Encryption)?;
465        Ok(ConsumedExternalAuthorization {
466            id: Uuid::parse_str(&id)
467                .map_err(|e| ExternalConnectionStorageError::Backend(e.to_string()))?,
468            user_id: UserId::from_str(&user)
469                .map_err(|e| ExternalConnectionStorageError::Backend(e.to_string()))?,
470            provider,
471            pkce_verifier: verifier,
472            requested_scopes: parse_scopes(&sc)?,
473            created_at: time(&created)?,
474        })
475    }
476}
477
478#[cfg(test)]
479mod tests {
480    use super::*;
481    use chrono::Duration;
482    fn path() -> std::path::PathBuf {
483        std::env::temp_dir().join(format!("eme-ext-{}.sqlite", Uuid::new_v4()))
484    }
485    fn key() -> [u8; 32] {
486        [0x42; 32]
487    }
488    #[test]
489    fn cipher_rejects_tampering() {
490        let c = CredentialCipher::new(key());
491        let mut v = c.encrypt(b"secret").unwrap();
492        assert_eq!(c.decrypt(&v).unwrap(), b"secret");
493        let i = v.len() - 1;
494        v[i] ^= 1;
495        assert!(c.decrypt(&v).is_err());
496    }
497    #[tokio::test]
498    async fn stores_multiple_accounts_and_preserves_refresh_token() {
499        let p = path();
500        let u = UserId::new();
501        let s = SqliteExternalConnectionStore::open(&p, key()).unwrap();
502        let a = s
503            .create_connection(NewExternalConnection {
504                owner_id: u,
505                provider: "google".into(),
506                provider_subject: "a".into(),
507                display_email: None,
508                refresh_token: "refresh-a".into(),
509                granted_scopes: vec![],
510            })
511            .await
512            .unwrap();
513        s.create_connection(NewExternalConnection {
514            owner_id: u,
515            provider: "google".into(),
516            provider_subject: "b".into(),
517            display_email: None,
518            refresh_token: "refresh-b".into(),
519            granted_scopes: vec![],
520        })
521        .await
522        .unwrap();
523        let b = s
524            .update_credentials(u, a.id, None, vec!["new-scope".into()])
525            .await
526            .unwrap();
527        assert_eq!(a.encrypted_refresh_token, b.encrypted_refresh_token);
528        assert_eq!(
529            CredentialCipher::new(key())
530                .decrypt(&b.encrypted_refresh_token)
531                .unwrap(),
532            b"refresh-a"
533        );
534        assert_eq!(s.list_connections(u).await.unwrap().len(), 2);
535
536        s.revoke_connection(u, a.id).await.unwrap();
537        let reconnected = s
538            .create_connection(NewExternalConnection {
539                owner_id: u,
540                provider: "google".into(),
541                provider_subject: "a".into(),
542                display_email: Some("a@example.com".into()),
543                refresh_token: "replacement-refresh".into(),
544                granted_scopes: vec!["scope".into()],
545            })
546            .await
547            .unwrap();
548        assert_eq!(reconnected.id, a.id);
549        assert_eq!(reconnected.status, ExternalConnectionStatus::Active);
550        assert_eq!(
551            CredentialCipher::new(key())
552                .decrypt(&reconnected.encrypted_refresh_token)
553                .unwrap(),
554            b"replacement-refresh"
555        );
556        assert_eq!(s.list_connections(u).await.unwrap().len(), 2);
557        drop(s);
558        let _ = std::fs::remove_file(p);
559    }
560    #[tokio::test]
561    async fn state_is_single_use_and_pkce_is_encrypted() {
562        let p = path();
563        let s = SqliteExternalConnectionStore::open(&p, key()).unwrap();
564        let u = UserId::new();
565        let id = s
566            .begin_authorization(NewExternalAuthorization {
567                user_id: u,
568                provider: "google".into(),
569                state: "random".into(),
570                pkce_verifier: "secret-verifier".into(),
571                requested_scopes: vec!["scope".into()],
572                expires_at: Utc::now() + Duration::minutes(5),
573            })
574            .await
575            .unwrap();
576        let x = s
577            .consume_authorization("google", "random", Utc::now())
578            .await
579            .unwrap();
580        assert_eq!(x.id, id);
581        assert_eq!(x.pkce_verifier, "secret-verifier");
582        assert!(matches!(
583            s.consume_authorization("google", "random", Utc::now())
584                .await,
585            Err(ExternalConnectionStorageError::AuthorizationConsumed)
586        ));
587        drop(s);
588        let _ = std::fs::remove_file(p);
589    }
590}