quilt-rs 0.28.0

Rust library for accessing Quilt data packages.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
//! OAuth 2.1 Authorization Code flow with PKCE for Quilt catalog authentication.
//!
//! Implements the following RFCs:
//! - **RFC 6749** — OAuth 2.0 Authorization Framework (core flow)
//! - **RFC 7636** — Proof Key for Code Exchange (PKCE)
//! - **RFC 7591** — OAuth 2.0 Dynamic Client Registration (DCR)
//!
//! Terminology mapping (RFC → code):
//! - *Authorization Endpoint* (RFC 6749 §3.1) → [`catalog_authorize_url`]
//! - *Token Endpoint* (RFC 6749 §3.2) → [`connect_token_url`]
//! - *Authorization Code* (RFC 6749 §1.3.1) → `OAuthParams::code`
//! - *Code Verifier* (RFC 7636 §4.1) → `PkceChallenge::code_verifier`
//! - *Code Challenge* (RFC 7636 §4.2) → `PkceChallenge::code_challenge`
//! - *State* (RFC 6749 §10.12) — CSRF protection token, generated by [`random_state`]
//! - *Client Registration Endpoint* (RFC 7591 §3) → [`connect_register_url`]
//! - *Redirect URI* (RFC 6749 §3.1.2) → `OAuthParams::redirect_uri`

use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;

use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine;
use sha2::Digest;
use sha2::Sha256;

use crate::error::AuthError;
use crate::io::remote::client::HttpClient;
use crate::io::storage::auth::AuthIo;
use crate::io::storage::auth::Credentials;
use crate::io::storage::auth::OAuthClient;
use crate::io::storage::auth::Tokens;
use crate::io::storage::LocalStorage;
use crate::io::storage::Storage;
use crate::paths::DomainPaths;
use crate::uri::Host;
use crate::Error;
use crate::Res;
use chrono::serde::ts_seconds;
use serde::Deserialize;
use serde::Deserializer;
use serde::Serialize;
use tracing::debug;
use tracing::error;
use tracing::info;
use tracing::warn;

/// Parameters for the Token Request (RFC 6749 §4.1.3) with PKCE extension.
pub struct OAuthParams {
    /// Authorization code received from the Authorization Endpoint (RFC 6749 §4.1.2)
    pub code: String,
    /// PKCE code verifier (RFC 7636 §4.1) — sent to the Token Endpoint for verification
    pub code_verifier: String,
    /// Redirect URI (RFC 6749 §3.1.2) — must match the value sent in the Authorization Request
    pub redirect_uri: String,
    /// Client identifier (RFC 6749 §2.2) obtained via DCR.
    ///
    /// The caller is responsible for ensuring this matches the `client_id`
    /// stored in the [`OAuthClient`] for the target host (e.g. by calling
    /// [`Auth::get_or_register_client`] and using its `client_id` directly).
    pub client_id: String,
}

/// PKCE code verifier and challenge pair (RFC 7636).
pub struct PkceChallenge {
    /// Random verifier string — send to token endpoint
    pub code_verifier: String,
    /// S256 hash of verifier — send in the authorize URL
    pub code_challenge: String,
}

/// Generate a PKCE code verifier and its S256 challenge.
///
/// The verifier is 64 random bytes, base64url-encoded (86 characters),
/// well within RFC 7636 §4.1's 43–128 character range.
pub fn pkce_challenge() -> PkceChallenge {
    let mut random_bytes = [0u8; 64];
    getrandom::fill(&mut random_bytes).expect("failed to generate random bytes");

    let code_verifier = URL_SAFE_NO_PAD.encode(random_bytes);
    let code_challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(code_verifier.as_bytes()));

    PkceChallenge {
        code_verifier,
        code_challenge,
    }
}

/// Generate a random `state` parameter for CSRF protection (RFC 6749 §10.12).
pub fn random_state() -> String {
    let mut bytes = [0u8; 16];
    getrandom::fill(&mut bytes).expect("failed to generate random bytes");
    URL_SAFE_NO_PAD.encode(bytes)
}

// --- OAuth endpoint URLs ---
//
// OAuth uses two different hostnames derived from the catalog host:
//
// 1. **Catalog host** (`test.quilt.dev`) — the authorize endpoint lives here
//    because the user's browser session (cookies) is on the catalog.
//
// 2. **Connect host** (`test-connect.quilt.dev`) — the token exchange and
//    client registration (DCR) endpoints live on a separate subdomain.

/// Authorization Endpoint (RFC 6749 §3.1) on the catalog host.
///
/// E.g., `test.quilt.dev` → `https://test.quilt.dev/connect/authorize`
pub fn catalog_authorize_url(host: &Host) -> String {
    format!("https://{host}/connect/authorize")
}

/// Derive the connect server hostname from the catalog host.
///
/// E.g., `test.quilt.dev` → `test-connect.quilt.dev`
///
/// # Assumptions
///
/// The catalog hostname is assumed to have exactly one label before the first
/// dot (e.g. `test` in `test.quilt.dev`). Multi-label prefixes such as
/// `a.b.quilt.dev` are not supported and will produce an incorrect result
/// (`a-connect.b.quilt.dev` instead of a well-defined connect hostname).
pub fn connect_host(host: &Host) -> String {
    let s = host.to_string();
    match s.split_once('.') {
        Some((stack, domain)) => format!("{stack}-connect.{domain}"),
        None => format!("{s}-connect"),
    }
}

/// Token Endpoint (RFC 6749 §3.2) on the connect host.
///
/// E.g., `test.quilt.dev` → `https://test-connect.quilt.dev/auth/token`
fn connect_token_url(host: &Host) -> String {
    format!("https://{}/auth/token", connect_host(host))
}

/// Client Registration Endpoint (RFC 7591 §3) on the connect host.
fn connect_register_url(host: &Host) -> String {
    format!("https://{}/auth/register", connect_host(host))
}

/// DCR request body (RFC 7591).
#[derive(Serialize)]
struct DcrRequest {
    client_name: String,
    redirect_uris: Vec<String>,
    token_endpoint_auth_method: String,
}

/// DCR response body (subset of fields we need).
#[derive(Deserialize)]
struct DcrResponse {
    client_id: String,
}

/// Register a public OAuth client via Dynamic Client Registration (RFC 7591 §3.1).
async fn register_client(
    http_client: &impl HttpClient,
    host: &Host,
    redirect_uri: &str,
) -> Res<OAuthClient> {
    let register_url = connect_register_url(host);

    let request = DcrRequest {
        client_name: "QuiltSync".to_string(),
        redirect_uris: vec![redirect_uri.to_string()],
        token_endpoint_auth_method: "none".to_string(),
    };

    let response: DcrResponse = http_client.post_json(&register_url, &request).await?;

    Ok(OAuthClient {
        client_id: response.client_id,
        redirect_uri: redirect_uri.to_string(),
    })
}

#[derive(Deserialize, Serialize)]
pub struct RemoteTokens {
    pub access_token: String,
    pub refresh_token: String,
    #[serde(with = "ts_seconds")]
    pub expires_at: chrono::DateTime<chrono::Utc>,
}

impl fmt::Debug for RemoteTokens {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RemoteTokens")
            .field("expires_at", &self.expires_at)
            .field("access_token", &"[REDACTED]")
            .field("refresh_token", &"[REDACTED]")
            .finish_non_exhaustive()
    }
}

impl From<RemoteTokens> for Tokens {
    fn from(raw: RemoteTokens) -> Self {
        Tokens {
            access_token: raw.access_token,
            refresh_token: raw.refresh_token,
            expires_at: raw.expires_at,
        }
    }
}

/// Fallback TTL (seconds) when the token endpoint omits `expires_in`.
///
/// RFC 6749 §5.1 marks `expires_in` as RECOMMENDED, not required.
/// We use 1 hour as a conservative default that avoids both excessive
/// refresh loops (too short) and stale-token errors (too long).
const DEFAULT_EXPIRES_IN: i64 = 3600;

fn default_expires_in() -> i64 {
    DEFAULT_EXPIRES_IN
}

/// Token response from the Connect OAuth token endpoint.
///
/// Uses `expires_in` (seconds until expiry) per RFC 6749,
/// unlike `RemoteTokens` which uses `expires_at` (Unix timestamp).
///
/// `refresh_token` is `Option` because RFC 6749 §6 allows the server to omit
/// it when rotating tokens; callers are responsible for falling back to the
/// previous refresh token in that case.
///
/// `expires_in` is optional per RFC 6749 §5.1 (RECOMMENDED, not required);
/// defaults to [`DEFAULT_EXPIRES_IN`] when absent.
#[derive(Deserialize, Serialize)]
struct OAuthTokenResponse {
    access_token: String,
    #[serde(default)]
    refresh_token: Option<String>,
    #[serde(default = "default_expires_in")]
    expires_in: i64,
}

impl fmt::Debug for OAuthTokenResponse {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("OAuthTokenResponse")
            .field("expires_in", &self.expires_in)
            .field("access_token", &"[REDACTED]")
            .field(
                "refresh_token",
                &self.refresh_token.as_ref().map(|_| "[REDACTED]"),
            )
            .finish_non_exhaustive()
    }
}

#[derive(Deserialize, Serialize)]
#[serde(rename_all = "PascalCase")]
struct RemoteCredentials {
    access_key_id: String,
    #[serde(deserialize_with = "date_from_rfc3339")]
    expiration: chrono::DateTime<chrono::Utc>,
    secret_access_key: String,
    session_token: String,
}

impl fmt::Debug for RemoteCredentials {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RemoteCredentials")
            .field("expiration", &self.expiration)
            .field("access_key_id", &"[REDACTED]")
            .field("secret_access_key", &"[REDACTED]")
            .field("session_token", &"[REDACTED]")
            .finish_non_exhaustive()
    }
}

impl From<RemoteCredentials> for Credentials {
    fn from(raw: RemoteCredentials) -> Self {
        Credentials {
            access_key: raw.access_key_id,
            secret_key: raw.secret_access_key,
            token: raw.session_token,
            expires_at: raw.expiration,
        }
    }
}

fn date_from_rfc3339<'de, D: Deserializer<'de>>(
    deserializer: D,
) -> Result<chrono::DateTime<chrono::Utc>, D::Error> {
    use serde::de::Error;
    String::deserialize(deserializer).and_then(|s| {
        chrono::DateTime::parse_from_rfc3339(&s)
            .map_err(|e| Error::custom(format!("Invalid RFC3339 date: {e}")))
            .map(|dt| dt.with_timezone(&chrono::Utc))
    })
}

#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
struct QuiltStackConfig {
    registry_url: url::Url,
}

async fn get_registry_url(http_client: &impl HttpClient, host: &Host) -> Res<url::Host> {
    let QuiltStackConfig { registry_url } = http_client
        .get(&format!("https://{host}/config.json"), None)
        .await?;
    Ok(url::Host::Domain(
        registry_url
            .domain()
            .ok_or(crate::Error::LoginRequiredRegistryUrl(host.to_owned()))?
            .to_string(),
    ))
}

async fn get_auth_tokens(
    http_client: &impl HttpClient,
    host: &Host,
    refresh_token: &str,
) -> Res<Tokens> {
    let registry = get_registry_url(http_client, host).await?;

    let mut form_data: HashMap<String, String> = HashMap::new();
    form_data.insert("refresh_token".to_string(), refresh_token.to_string());
    let tokens_json: RemoteTokens = http_client
        .post(&format!("https://{registry}/api/token"), &form_data)
        .await?;
    let tokens = Tokens::from(tokens_json);

    Ok(tokens)
}

/// Token Request (RFC 6749 §4.1.3) with PKCE code verifier (RFC 7636 §4.5).
async fn exchange_oauth_code(
    http_client: &impl HttpClient,
    host: &Host,
    params: &OAuthParams,
) -> Res<Tokens> {
    let token_url = connect_token_url(host);

    let mut form_data: HashMap<String, String> = HashMap::new();
    form_data.insert("grant_type".to_string(), "authorization_code".to_string());
    form_data.insert("code".to_string(), params.code.clone());
    form_data.insert("code_verifier".to_string(), params.code_verifier.clone());
    form_data.insert("redirect_uri".to_string(), params.redirect_uri.clone());
    form_data.insert("client_id".to_string(), params.client_id.clone());

    let response: OAuthTokenResponse = http_client.post(&token_url, &form_data).await?;
    let expires_at = chrono::Utc::now() + chrono::Duration::seconds(response.expires_in);
    Ok(Tokens {
        access_token: response.access_token,
        refresh_token: response.refresh_token.ok_or_else(|| {
            Error::Auth(
                host.to_owned(),
                AuthError::TokensExchange("server did not return a refresh token".to_string()),
            )
        })?,
        expires_at,
    })
}

/// Refresh Token Request (RFC 6749 §6) — exchange a refresh token for new tokens.
async fn refresh_oauth_tokens(
    http_client: &impl HttpClient,
    host: &Host,
    refresh_token: &str,
    client_id: &str,
) -> Res<Tokens> {
    let token_url = connect_token_url(host);

    let mut form_data: HashMap<String, String> = HashMap::new();
    form_data.insert("grant_type".to_string(), "refresh_token".to_string());
    form_data.insert("refresh_token".to_string(), refresh_token.to_string());
    form_data.insert("client_id".to_string(), client_id.to_string());

    let response: OAuthTokenResponse = http_client.post(&token_url, &form_data).await?;
    let expires_at = chrono::Utc::now() + chrono::Duration::seconds(response.expires_in);
    Ok(Tokens {
        access_token: response.access_token,
        // RFC 6749 §6: server MAY omit the refresh token — retain the previous one if so.
        refresh_token: response
            .refresh_token
            .unwrap_or_else(|| refresh_token.to_string()),
        expires_at,
    })
}

async fn refresh_credentials(
    http_client: &impl HttpClient,
    host: &Host,
    access_token: &str,
) -> Res<Credentials> {
    let registry = get_registry_url(http_client, host).await?;

    let creds_json: RemoteCredentials = http_client
        .get(
            &format!("https://{registry}/api/auth/get_credentials"),
            Some(access_token),
        )
        .await?;

    let credentials = Credentials::from(creds_json);

    Ok(credentials)
}

/// Returns true when an error from the Connect **token endpoint** means the
/// user must log in again.
///
/// Includes HTTP 400 because RFC 6749 §5.2 specifies that a revoked or
/// expired refresh token produces `400 invalid_grant`, not 401.
fn is_token_auth_error(e: &Error) -> bool {
    matches!(
        e,
        Error::Reqwest(re) if re.status().is_some_and(|s| s == 400 || s == 401 || s == 403)
    )
}

/// Returns true when an error from the registry **credentials endpoint** means
/// the user must log in again.
///
/// Only 401/403 — a 400 from the registry means a malformed request (client
/// bug), not an auth failure, so it should propagate rather than prompt login.
fn is_credentials_auth_error(e: &Error) -> bool {
    matches!(
        e,
        Error::Reqwest(re) if re.status().is_some_and(|s| s == 401 || s == 403)
    )
}

#[derive(Debug)]
pub struct Auth<S: Storage = LocalStorage> {
    pub paths: DomainPaths,
    pub storage: Arc<S>,
}

impl<S: Storage> Clone for Auth<S> {
    fn clone(&self) -> Self {
        Self {
            paths: self.paths.clone(),
            storage: Arc::clone(&self.storage),
        }
    }
}

impl<S: Storage + Send + Sync> Auth<S> {
    pub fn new(paths: DomainPaths, storage: Arc<S>) -> Self {
        Self { paths, storage }
    }

    pub async fn login<T: HttpClient>(
        &self,
        http_client: &T,
        host: &Host,
        refresh_token: String,
    ) -> Res {
        info!("⏳ Logging in to host {} with refresh token", host);

        let tokens = match self
            .get_auth_tokens(http_client, host, &refresh_token)
            .await
        {
            Ok(t) => t,
            Err(e) => {
                warn!("❌ Failed to get auth tokens for {}: {}", host, e);
                return Err(e);
            }
        };

        if let Err(e) = self.save_tokens(host, &tokens).await {
            warn!("❌ Failed to save tokens for {}: {}", host, e);
            return Err(e);
        }

        if let Err(e) = self
            .refresh_credentials(http_client, host, &tokens.access_token)
            .await
        {
            warn!("❌ Failed to refresh credentials for {}: {}", host, e);
            return Err(e);
        }

        info!("✔️ Successfully logged in and authenticated to {}", host);
        Ok(())
    }

    /// Get a stored OAuth client_id for the host, or register a new one via DCR.
    pub async fn get_or_register_client<T: HttpClient>(
        &self,
        http_client: &T,
        host: &Host,
        redirect_uri: &str,
    ) -> Res<OAuthClient> {
        let auth_io = AuthIo::new(self.storage.clone(), self.paths.auth_host(host));

        if let Some(client) = auth_io.read_client().await? {
            if client.redirect_uri == redirect_uri {
                info!("✔️ Found existing OAuth client for {}", host);
                return Ok(client);
            }
            info!(
                "⚠️ Cached client has stale redirect_uri, re-registering for {}",
                host
            );
        }

        info!("⏳ Registering new OAuth client for {}", host);
        let client = register_client(http_client, host, redirect_uri).await?;
        auth_io.write_client(&client).await?;
        info!(
            "✔️ Registered OAuth client for {}: {}",
            host, client.client_id
        );

        Ok(client)
    }

    /// Login using OAuth 2.1 Authorization Code flow with PKCE.
    ///
    /// Exchanges the authorization code for tokens, then fetches S3 credentials.
    ///
    /// # State / CSRF verification
    ///
    /// This method does not verify the `state` parameter returned by the
    /// Authorization Endpoint. The caller is responsible for comparing the
    /// `state` value in the callback against the value generated by
    /// [`random_state`] before calling this method (RFC 6749 §10.12).
    pub async fn login_oauth<T: HttpClient>(
        &self,
        http_client: &T,
        host: &Host,
        params: OAuthParams,
    ) -> Res {
        info!("⏳ OAuth login for host {}", host);

        let tokens = exchange_oauth_code(http_client, host, &params)
            .await
            .map_err(|e| {
                warn!("❌ Failed to exchange OAuth code for {}: {}", host, e);
                e
            })?;

        self.save_tokens(host, &tokens).await.map_err(|e| {
            warn!("❌ Failed to save tokens for {}: {}", host, e);
            e
        })?;

        self.refresh_credentials(http_client, host, &tokens.access_token)
            .await
            .map_err(|e| {
                warn!("❌ Failed to refresh credentials for {}: {}", host, e);
                e
            })?;

        info!("✔️ OAuth login successful for {}", host);
        Ok(())
    }

    async fn get_auth_tokens<T: HttpClient>(
        &self,
        http_client: &T,
        host: &Host,
        refresh_token: &str,
    ) -> Res<Tokens> {
        debug!("⏳ Getting auth tokens for host {:?}", host);
        let tokens = get_auth_tokens(http_client, host, refresh_token).await?;
        debug!("✔️ Successfully retrieved auth tokens");
        Ok(tokens)
    }

    async fn save_tokens(&self, host: &Host, tokens: &Tokens) -> Res<()> {
        debug!("⏳ Saving tokens for host {:?}", host);
        let auth_io = AuthIo::new(self.storage.clone(), self.paths.auth_host(host));
        auth_io.write_tokens(tokens).await?;
        debug!(
            "✔️ Successfully saved tokens to the {:?}",
            self.paths.auth_host(host)
        );
        Ok(())
    }

    /// Use the refresh token to obtain new access + refresh tokens from the
    /// Connect token endpoint (RFC 6749 §6), then persist them.
    async fn refresh_tokens<T: HttpClient>(
        &self,
        http_client: &T,
        auth_io: &AuthIo<Arc<S>>,
        host: &Host,
        tokens: &Tokens,
    ) -> Res<Tokens> {
        let client = auth_io
            .read_client()
            .await?
            .ok_or(crate::Error::LoginRequired(Some(host.to_owned())))?;

        let new_tokens =
            refresh_oauth_tokens(http_client, host, &tokens.refresh_token, &client.client_id)
                .await?;

        auth_io.write_tokens(&new_tokens).await?;
        info!("✔️ Successfully refreshed tokens for {}", host);

        Ok(new_tokens)
    }

    async fn refresh_credentials<T: HttpClient>(
        &self,
        http_client: &T,
        host: &Host,
        access_token: &str,
    ) -> Res<Credentials> {
        debug!("⏳ Refreshing credentials for host {:?}", host);
        let credentials = refresh_credentials(http_client, host, access_token).await?;

        let auth_io = AuthIo::new(self.storage.clone(), self.paths.auth_host(host));
        auth_io.write_credentials(&credentials).await?;

        debug!(
            "✔️ Successfully refreshed credentials in {:?}",
            self.paths.auth_host(host)
        );
        Ok(credentials)
    }

    pub async fn get_credentials_or_refresh<T: HttpClient>(
        &self,
        http_client: &T,
        host: &Host,
    ) -> Res<Credentials> {
        info!("⏳ Getting or refreshing credentials for {}", host);
        let auth_io = AuthIo::new(self.storage.clone(), self.paths.auth_host(host));

        match auth_io.read_credentials().await {
            Ok(Some(creds)) => {
                debug!("✔️ Found valid credentials for {}", host);
                return Ok(creds);
            }
            Ok(None) => {
                info!("❌ No existing credentials found for {}", host);
            }
            Err(e) => {
                error!("❌ Failed to read credentials for {}: {}", host, e);
                return Err(Error::Auth(
                    host.to_owned(),
                    AuthError::CredentialsRead(e.to_string()),
                ));
            }
        }

        let tokens = match auth_io.read_tokens().await {
            Ok(Some(tokens)) => tokens,
            Ok(None) => {
                warn!("❌ No tokens found for {}, login required", host);
                return Err(crate::Error::LoginRequired(Some(host.to_owned())));
            }
            Err(e) => {
                error!("❌ Failed to read tokens for {}: {}", host, e);
                return Err(Error::Auth(
                    host.to_owned(),
                    AuthError::TokensRead(e.to_string()),
                ));
            }
        };

        // If the access token is expired, try to refresh it using the refresh token.
        let access_token =
            if tokens.expires_at <= chrono::Utc::now() + chrono::Duration::seconds(60) {
                info!(
                    "⏳ Access token expired for {}, refreshing via refresh token",
                    host
                );
                match self
                    .refresh_tokens(http_client, &auth_io, host, &tokens)
                    .await
                {
                    Ok(new_tokens) => new_tokens.access_token,
                    Err(e) => {
                        if is_token_auth_error(&e) {
                            warn!(
                                "❌ Auth error refreshing tokens for {}, login required: {}",
                                host, e
                            );
                            return Err(crate::Error::LoginRequired(Some(host.to_owned())));
                        } else if matches!(e, crate::Error::LoginRequired(_)) {
                            warn!("❌ No OAuth client registered for {}, login required", host);
                            return Err(e);
                        } else {
                            warn!("❌ Failed to refresh tokens for {}: {}", host, e);
                            return Err(e);
                        }
                    }
                }
            } else {
                tokens.access_token
            };

        info!("⏳ Refreshing credentials using access token for {}", host);
        match self
            .refresh_credentials(http_client, host, &access_token)
            .await
        {
            Ok(creds) => {
                info!("✔️ Successfully refreshed credentials for {}", host);
                Ok(creds)
            }
            Err(e) => {
                if is_credentials_auth_error(&e) {
                    warn!(
                        "❌ Auth error refreshing credentials for {}, login required: {}",
                        host, e
                    );
                    Err(crate::Error::LoginRequired(Some(host.to_owned())))
                } else {
                    warn!("❌ Failed to refresh credentials for {}: {}", host, e);
                    Err(e)
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use async_trait::async_trait;
    use reqwest::header::HeaderMap;
    use test_log::test;

    use crate::io::storage::mocks::MockStorage;
    use crate::paths::DomainPaths;

    const ACCESS_TOKEN: &str = "test-access-token";
    const REFRESH_TOKEN: &str = "test-refresh-token";
    const TIMESTAMP: i64 = 1708444800;

    fn get_host() -> Host {
        "test.quilt.dev".parse().unwrap()
    }

    fn get_registry() -> String {
        "registry-test.quilt.dev".to_string()
    }

    struct TestHttpClient;

    #[async_trait]
    impl HttpClient for TestHttpClient {
        async fn get<T: serde::de::DeserializeOwned>(
            &self,
            url: &str,
            auth_token: Option<&str>,
        ) -> Res<T> {
            let registry = get_registry();

            match url {
                u if u == format!("https://{}/config.json", get_host()) => {
                    let config = QuiltStackConfig {
                        registry_url: format!("https://{registry}").parse()?,
                    };
                    Ok(serde_json::from_value(serde_json::to_value(config)?)?)
                }
                u if u == format!("https://{registry}/api/auth/get_credentials") => {
                    assert_eq!(auth_token, Some(ACCESS_TOKEN));
                    let creds = RemoteCredentials {
                        access_key_id: "test-access-key".to_string(),
                        secret_access_key: "test-secret-key".to_string(),
                        session_token: "test-session-token".to_string(),
                        expiration: chrono::DateTime::from_timestamp(TIMESTAMP, 0).unwrap(),
                    };
                    Ok(serde_json::from_value(serde_json::to_value(creds)?)?)
                }
                _ => panic!("Unexpected URL: {url}"),
            }
        }

        async fn head(&self, _url: &str) -> Res<HeaderMap> {
            unimplemented!("head is not used in this test")
        }

        async fn post<T: serde::de::DeserializeOwned>(
            &self,
            url: &str,
            form_data: &HashMap<String, String>,
        ) -> Res<T> {
            assert_eq!(url, format!("https://{}/api/token", get_registry()));

            // Verify form data contains the refresh token
            assert_eq!(form_data.get("refresh_token").unwrap(), REFRESH_TOKEN);

            let tokens = RemoteTokens {
                access_token: ACCESS_TOKEN.to_string(),
                refresh_token: "new-refresh-token".to_string(),
                expires_at: chrono::DateTime::from_timestamp(TIMESTAMP, 0).unwrap(),
            };
            Ok(serde_json::from_value(serde_json::to_value(tokens)?)?)
        }

        async fn post_json<T: serde::de::DeserializeOwned, B: serde::Serialize + Send + Sync>(
            &self,
            _url: &str,
            _body: &B,
        ) -> Res<T> {
            unimplemented!("post_json is not used in this test")
        }
    }

    #[test(tokio::test)]
    async fn test_get_registry_url() {
        let client = TestHttpClient;
        let result = get_registry_url(&client, &get_host()).await.unwrap();
        assert_eq!(
            result,
            url::Host::Domain("registry-test.quilt.dev".to_string())
        );
    }

    #[test(tokio::test)]
    async fn test_get_auth_tokens() {
        let client = TestHttpClient;
        let tokens = get_auth_tokens(&client, &get_host(), REFRESH_TOKEN)
            .await
            .unwrap();
        assert_eq!(tokens.access_token, ACCESS_TOKEN);
        assert_eq!(tokens.refresh_token, "new-refresh-token");
        assert_eq!(
            tokens.expires_at,
            chrono::DateTime::from_timestamp(1708444800, 0).unwrap()
        );
    }

    #[test(tokio::test)]
    async fn test_refresh_credentials() {
        let client = TestHttpClient;
        let credentials = refresh_credentials(&client, &get_host(), ACCESS_TOKEN)
            .await
            .unwrap();
        assert_eq!(credentials.access_key, "test-access-key");
        assert_eq!(credentials.secret_key, "test-secret-key");
        assert_eq!(credentials.token, "test-session-token");
        assert_eq!(
            credentials.expires_at,
            chrono::DateTime::from_timestamp(1708444800, 0).unwrap()
        );
    }

    #[test(tokio::test)]
    async fn test_auth_refresh_credentials() -> Res {
        let storage = Arc::new(MockStorage::default());
        let paths = DomainPaths::new(storage.temp_dir.path().to_path_buf());
        let auth = Auth::new(paths.clone(), storage.clone());
        let host = get_host();

        let credentials = auth
            .refresh_credentials(&TestHttpClient, &host, ACCESS_TOKEN)
            .await?;

        // Verify returned credentials
        assert_eq!(credentials.access_key, "test-access-key");
        assert_eq!(credentials.secret_key, "test-secret-key");
        assert_eq!(credentials.token, "test-session-token");
        assert_eq!(
            credentials.expires_at,
            chrono::DateTime::from_timestamp(TIMESTAMP, 0).unwrap()
        );

        // Verify credentials were persisted. Note: read_credentials() filters
        // expired credentials, so we deserialize directly from the raw bytes.
        use crate::io::storage::StorageExt;
        let creds_path = paths.auth_host(&host).join(crate::paths::AUTH_CREDENTIALS);
        let bytes = storage.read_bytes(&creds_path).await?;
        let read_creds: Credentials = serde_json::from_slice(&bytes)?;
        assert_eq!(read_creds.access_key, credentials.access_key);
        assert_eq!(read_creds.secret_key, credentials.secret_key);
        assert_eq!(read_creds.token, credentials.token);
        assert_eq!(read_creds.expires_at, credentials.expires_at);

        Ok(())
    }

    #[test]
    fn test_remote_credentials_deserialization() {
        // Test valid RFC3339 date
        let valid_json = r#"{
            "AccessKeyId": "test-key",
            "Expiration": "2024-02-20T15:00:00Z",
            "SecretAccessKey": "test-secret",
            "SessionToken": "test-token"
        }"#;

        let creds: RemoteCredentials = serde_json::from_str(valid_json).unwrap();
        assert_eq!(creds.access_key_id, "test-key");
        assert_eq!(creds.secret_access_key, "test-secret");
        assert_eq!(creds.session_token, "test-token");
        assert_eq!(
            creds.expiration,
            chrono::DateTime::parse_from_rfc3339("2024-02-20T15:00:00Z")
                .unwrap()
                .with_timezone(&chrono::Utc)
        );

        // Test invalid RFC3339 date
        let invalid_json = r#"{
            "AccessKeyId": "test-key",
            "Expiration": "2024-02-20 15:00:00",
            "SecretAccessKey": "test-secret",
            "SessionToken": "test-token"
        }"#;

        let error = serde_json::from_str::<RemoteCredentials>(invalid_json).unwrap_err();
        assert!(error.to_string().contains("Invalid RFC3339 date"));
    }

    const AUTH_CODE: &str = "test-auth-code";
    const CODE_VERIFIER: &str = "test-code-verifier-that-is-at-least-43-characters-long";
    const CLIENT_ID: &str = "test-client-id";
    const REDIRECT_URI: &str = "quilt://auth/callback?host=test.quilt.dev";

    struct OAuthTestHttpClient {
        /// The access token expected when hitting the credentials endpoint.
        expected_credentials_token: &'static str,
    }

    impl Default for OAuthTestHttpClient {
        fn default() -> Self {
            Self {
                expected_credentials_token: ACCESS_TOKEN,
            }
        }
    }

    #[async_trait]
    impl HttpClient for OAuthTestHttpClient {
        async fn get<T: serde::de::DeserializeOwned>(
            &self,
            url: &str,
            auth_token: Option<&str>,
        ) -> Res<T> {
            let registry = get_registry();

            match url {
                u if u == format!("https://{}/config.json", get_host()) => {
                    let config = QuiltStackConfig {
                        registry_url: format!("https://{registry}").parse()?,
                    };
                    Ok(serde_json::from_value(serde_json::to_value(config)?)?)
                }
                u if u == format!("https://{registry}/api/auth/get_credentials") => {
                    assert_eq!(auth_token, Some(self.expected_credentials_token));
                    let creds = RemoteCredentials {
                        access_key_id: "oauth-access-key".to_string(),
                        secret_access_key: "oauth-secret-key".to_string(),
                        session_token: "oauth-session-token".to_string(),
                        expiration: chrono::DateTime::from_timestamp(TIMESTAMP, 0).unwrap(),
                    };
                    Ok(serde_json::from_value(serde_json::to_value(creds)?)?)
                }
                _ => panic!("Unexpected GET URL: {url}"),
            }
        }

        async fn head(&self, _url: &str) -> Res<HeaderMap> {
            unimplemented!()
        }

        async fn post<T: serde::de::DeserializeOwned>(
            &self,
            url: &str,
            form_data: &HashMap<String, String>,
        ) -> Res<T> {
            assert_eq!(url, connect_token_url(&get_host()));

            let tokens = match form_data.get("grant_type").map(String::as_str) {
                Some("authorization_code") => {
                    assert_eq!(form_data.get("code").unwrap(), AUTH_CODE);
                    assert_eq!(form_data.get("code_verifier").unwrap(), CODE_VERIFIER);
                    assert_eq!(form_data.get("redirect_uri").unwrap(), REDIRECT_URI);
                    assert_eq!(form_data.get("client_id").unwrap(), CLIENT_ID);
                    OAuthTokenResponse {
                        access_token: ACCESS_TOKEN.to_string(),
                        refresh_token: Some("oauth-refresh-token".to_string()),
                        expires_in: 3600,
                    }
                }
                Some("refresh_token") => {
                    assert_eq!(form_data.get("refresh_token").unwrap(), REFRESH_TOKEN);
                    assert_eq!(form_data.get("client_id").unwrap(), CLIENT_ID);
                    OAuthTokenResponse {
                        access_token: "refreshed-access-token".to_string(),
                        refresh_token: Some("new-refresh-token".to_string()),
                        expires_in: 3600,
                    }
                }
                other => panic!("Unexpected grant_type: {other:?}"),
            };
            Ok(serde_json::from_value(serde_json::to_value(&tokens)?)?)
        }

        async fn post_json<T: serde::de::DeserializeOwned, B: serde::Serialize + Send + Sync>(
            &self,
            url: &str,
            body: &B,
        ) -> Res<T> {
            assert_eq!(url, connect_register_url(&get_host()));
            let json = serde_json::to_value(body)?;
            assert_eq!(json["client_name"], "QuiltSync");
            assert_eq!(json["token_endpoint_auth_method"], "none");
            let redirect_uris = json["redirect_uris"].as_array().expect("redirect_uris");
            assert_eq!(redirect_uris.len(), 1);
            assert!(redirect_uris[0]
                .as_str()
                .unwrap()
                .starts_with("quilt://auth/callback?host="));
            Ok(serde_json::from_value(serde_json::json!({
                "client_id": "test-dcr-client-id"
            }))?)
        }
    }

    #[test]
    fn test_connect_host() {
        let host: Host = "test.quilt.dev".parse().unwrap();
        assert_eq!(connect_host(&host), "test-connect.quilt.dev");
    }

    #[test]
    fn test_connect_token_url() {
        let host: Host = "test.quilt.dev".parse().unwrap();
        assert_eq!(
            connect_token_url(&host),
            "https://test-connect.quilt.dev/auth/token"
        );
    }

    #[test(tokio::test)]
    async fn test_exchange_oauth_code() {
        let client = OAuthTestHttpClient::default();
        let params = OAuthParams {
            code: AUTH_CODE.to_string(),
            code_verifier: CODE_VERIFIER.to_string(),
            redirect_uri: REDIRECT_URI.to_string(),
            client_id: CLIENT_ID.to_string(),
        };
        let tokens = exchange_oauth_code(&client, &get_host(), &params)
            .await
            .unwrap();
        assert_eq!(tokens.access_token, ACCESS_TOKEN);
        assert_eq!(tokens.refresh_token, "oauth-refresh-token");
    }

    #[test]
    fn test_pkce_challenge() {
        let pkce = pkce_challenge();

        // Verifier should be 86 characters (64 bytes base64url-encoded without padding)
        assert_eq!(pkce.code_verifier.len(), 86);

        // Challenge should be 43 characters (SHA-256 is 32 bytes, base64url-encoded)
        assert_eq!(pkce.code_challenge.len(), 43);

        // Verify the challenge is the S256 hash of the verifier
        let expected_challenge =
            URL_SAFE_NO_PAD.encode(Sha256::digest(pkce.code_verifier.as_bytes()));
        assert_eq!(pkce.code_challenge, expected_challenge);

        // Two calls should produce different verifiers
        let pkce2 = pkce_challenge();
        assert_ne!(pkce.code_verifier, pkce2.code_verifier);
    }

    // RFC 7636 §4.1: code verifier must use only unreserved chars: ALPHA / DIGIT / "-" / "." / "_" / "~"
    #[test]
    fn test_pkce_verifier_charset_rfc7636() {
        let pkce = pkce_challenge();
        for ch in pkce.code_verifier.chars() {
            assert!(
                ch.is_ascii_alphanumeric() || matches!(ch, '-' | '.' | '_' | '~'),
                "code_verifier contains char '{ch}' not allowed by RFC 7636 §4.1"
            );
        }
    }

    #[test(tokio::test)]
    async fn test_login_oauth() -> Res {
        let storage = Arc::new(MockStorage::default());
        let paths = DomainPaths::new(storage.temp_dir.path().to_path_buf());
        let auth = Auth::new(paths, storage);
        let host = get_host();

        let params = OAuthParams {
            code: AUTH_CODE.to_string(),
            code_verifier: CODE_VERIFIER.to_string(),
            redirect_uri: REDIRECT_URI.to_string(),
            client_id: CLIENT_ID.to_string(),
        };

        auth.login_oauth(&OAuthTestHttpClient::default(), &host, params)
            .await?;
        Ok(())
    }

    #[test(tokio::test)]
    async fn test_refresh_oauth_tokens() -> Res {
        let tokens = refresh_oauth_tokens(
            &OAuthTestHttpClient::default(),
            &get_host(),
            REFRESH_TOKEN,
            CLIENT_ID,
        )
        .await?;
        assert_eq!(tokens.access_token, "refreshed-access-token");
        assert_eq!(tokens.refresh_token, "new-refresh-token");
        Ok(())
    }

    // RFC 6749 §6: if the server omits `refresh_token` in the refresh response,
    // the client MUST retain the previous refresh token.
    #[test(tokio::test)]
    async fn test_refresh_oauth_tokens_retains_old_when_omitted() -> Res {
        struct NoRefreshTokenClient;

        #[async_trait]
        impl HttpClient for NoRefreshTokenClient {
            async fn get<T: serde::de::DeserializeOwned>(
                &self,
                _: &str,
                _: Option<&str>,
            ) -> Res<T> {
                unimplemented!()
            }
            async fn head(&self, _: &str) -> Res<reqwest::header::HeaderMap> {
                unimplemented!()
            }
            async fn post<T: serde::de::DeserializeOwned>(
                &self,
                _: &str,
                _: &HashMap<String, String>,
            ) -> Res<T> {
                let resp = OAuthTokenResponse {
                    access_token: "new-access-token".to_string(),
                    refresh_token: None, // server omits refresh_token
                    expires_in: DEFAULT_EXPIRES_IN,
                };
                Ok(serde_json::from_value(serde_json::to_value(resp)?)?)
            }
            async fn post_json<
                T: serde::de::DeserializeOwned,
                B: serde::Serialize + Send + Sync,
            >(
                &self,
                _: &str,
                _: &B,
            ) -> Res<T> {
                unimplemented!()
            }
        }

        let tokens =
            refresh_oauth_tokens(&NoRefreshTokenClient, &get_host(), REFRESH_TOKEN, CLIENT_ID)
                .await?;
        assert_eq!(tokens.access_token, "new-access-token");
        // Old refresh token must be retained
        assert_eq!(tokens.refresh_token, REFRESH_TOKEN);
        Ok(())
    }

    // RFC 6749 §4.1.4 + §5.1: initial code exchange MUST return a refresh_token;
    // if the server omits it the client should surface an error (not silently proceed).
    #[test(tokio::test)]
    async fn test_exchange_oauth_code_errors_when_refresh_token_missing() {
        struct NoRefreshTokenClient;

        #[async_trait]
        impl HttpClient for NoRefreshTokenClient {
            async fn get<T: serde::de::DeserializeOwned>(
                &self,
                _: &str,
                _: Option<&str>,
            ) -> Res<T> {
                unimplemented!()
            }
            async fn head(&self, _: &str) -> Res<reqwest::header::HeaderMap> {
                unimplemented!()
            }
            async fn post<T: serde::de::DeserializeOwned>(
                &self,
                _: &str,
                _: &HashMap<String, String>,
            ) -> Res<T> {
                let resp = OAuthTokenResponse {
                    access_token: ACCESS_TOKEN.to_string(),
                    refresh_token: None,
                    expires_in: DEFAULT_EXPIRES_IN,
                };
                Ok(serde_json::from_value(serde_json::to_value(resp)?)?)
            }
            async fn post_json<
                T: serde::de::DeserializeOwned,
                B: serde::Serialize + Send + Sync,
            >(
                &self,
                _: &str,
                _: &B,
            ) -> Res<T> {
                unimplemented!()
            }
        }

        let params = OAuthParams {
            code: AUTH_CODE.to_string(),
            code_verifier: CODE_VERIFIER.to_string(),
            redirect_uri: REDIRECT_URI.to_string(),
            client_id: CLIENT_ID.to_string(),
        };
        let result = exchange_oauth_code(&NoRefreshTokenClient, &get_host(), &params).await;
        assert!(
            matches!(result, Err(Error::Auth(_, AuthError::TokensExchange(_)))),
            "expected TokensExchange error, got: {result:?}"
        );
    }

    // RFC 6749 §5.1: `expires_in` is RECOMMENDED, not required. If omitted,
    // the client should fall back to a safe default rather than failing.
    #[test]
    fn test_oauth_token_response_missing_expires_in() {
        let json = r#"{"access_token":"tok","refresh_token":"ref"}"#;
        let resp: OAuthTokenResponse = serde_json::from_str(json).unwrap();
        assert_eq!(resp.expires_in, DEFAULT_EXPIRES_IN);
    }

    const REFRESHED_ACCESS_TOKEN: &str = "refreshed-access-token";

    #[test(tokio::test)]
    async fn test_get_credentials_or_refresh_with_expired_token() -> Res {
        let storage = Arc::new(MockStorage::default());
        let paths = DomainPaths::new(storage.temp_dir.path().to_path_buf());
        let auth = Auth::new(paths.clone(), storage.clone());
        let host = get_host();

        // Seed an expired access token and a stored OAuth client.
        let auth_io = AuthIo::new(storage, paths.auth_host(&host));
        auth_io
            .write_tokens(&Tokens {
                access_token: "expired-access-token".to_string(),
                refresh_token: REFRESH_TOKEN.to_string(),
                expires_at: chrono::Utc::now() - chrono::Duration::seconds(300),
            })
            .await?;
        auth_io
            .write_client(&OAuthClient {
                client_id: CLIENT_ID.to_string(),
                redirect_uri: REDIRECT_URI.to_string(),
            })
            .await?;

        let client = OAuthTestHttpClient {
            expected_credentials_token: REFRESHED_ACCESS_TOKEN,
        };
        let creds = auth.get_credentials_or_refresh(&client, &host).await?;

        // Credentials should come from the refreshed access token.
        assert_eq!(creds.access_key, "oauth-access-key");

        // Verify the new tokens were persisted by reading them back.
        let persisted = auth_io
            .read_tokens()
            .await?
            .expect("tokens should be persisted");
        assert_eq!(persisted.access_token, REFRESHED_ACCESS_TOKEN);
        assert_eq!(persisted.refresh_token, "new-refresh-token");

        Ok(())
    }

    #[test(tokio::test)]
    async fn test_get_or_register_client() -> Res {
        let storage = Arc::new(MockStorage::default());
        let paths = DomainPaths::new(storage.temp_dir.path().to_path_buf());
        let auth = Auth::new(paths, storage);
        let host = get_host();

        // First call registers via DCR
        let client = auth
            .get_or_register_client(&OAuthTestHttpClient::default(), &host, REDIRECT_URI)
            .await?;
        assert_eq!(client.client_id, "test-dcr-client-id");
        assert_eq!(client.redirect_uri, REDIRECT_URI);

        // Second call with same redirect_uri reads from storage (no DCR call)
        let client2 = auth
            .get_or_register_client(&OAuthTestHttpClient::default(), &host, REDIRECT_URI)
            .await?;
        assert_eq!(client2.client_id, "test-dcr-client-id");

        // Third call with different redirect_uri re-registers
        let new_redirect = "quilt://auth/callback?host=other.quilt.dev";
        let client3 = auth
            .get_or_register_client(&OAuthTestHttpClient::default(), &host, new_redirect)
            .await?;
        assert_eq!(client3.client_id, "test-dcr-client-id");
        assert_eq!(client3.redirect_uri, new_redirect);

        Ok(())
    }

    #[test]
    fn remote_tokens_debug_redacts_secrets() {
        let tokens = RemoteTokens {
            access_token: "secret-access".to_string(),
            refresh_token: "secret-refresh".to_string(),
            expires_at: chrono::DateTime::from_timestamp(TIMESTAMP, 0).unwrap(),
        };
        let output = format!("{:?}", tokens);
        assert!(output.contains("[REDACTED]"));
        assert!(!output.contains("secret-access"));
        assert!(!output.contains("secret-refresh"));
    }

    #[test]
    fn oauth_token_response_debug_redacts_secrets() {
        let response = OAuthTokenResponse {
            access_token: "secret-access".to_string(),
            refresh_token: Some("secret-refresh".to_string()),
            expires_in: 3600,
        };
        let output = format!("{:?}", response);
        assert!(output.contains("[REDACTED]"));
        assert!(!output.contains("secret-access"));
        assert!(!output.contains("secret-refresh"));
    }

    #[test]
    fn oauth_token_response_debug_none_refresh_token() {
        let response = OAuthTokenResponse {
            access_token: "secret-access".to_string(),
            refresh_token: None,
            expires_in: 3600,
        };
        let output = format!("{:?}", response);
        assert!(output.contains("refresh_token: None"));
        assert!(!output.contains("secret-access"));
    }

    #[test]
    fn remote_credentials_debug_redacts_secrets() {
        let creds = RemoteCredentials {
            access_key_id: "secret-key-id".to_string(),
            expiration: chrono::DateTime::from_timestamp(TIMESTAMP, 0).unwrap(),
            secret_access_key: "secret-access-key".to_string(),
            session_token: "secret-session-token".to_string(),
        };
        let output = format!("{:?}", creds);
        assert!(output.contains("[REDACTED]"));
        assert!(!output.contains("secret-key-id"));
        assert!(!output.contains("secret-access-key"));
        assert!(!output.contains("secret-session-token"));
    }
}