sdx 1.13.0

Native Xet client library for Shardline's Xet frontend.
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
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
//! Authentication for Xet repositories: issue, cache, and transparently
//! refresh repo+revision-scoped read/write CAS tokens.
//!
//! Tokens are issued against the shardline token-issuance wire contract (the
//! "Step 1 — Token Issuance" section of `docs/XET_NATIVE_CLI.md`, design §5.2
//! of `docs/SDX_PLAN.md`):
//!
//! - `GET /api/{provider}/{owner}/{repo}/xet-read-token/{rev}` and
//!   `GET /api/{provider}/{owner}/{repo}/xet-write-token/{rev}`, using the
//!   route constants exported by `shardline-xet-adapter`.
//! - Authentication is either `Authorization: Bearer <server-token>` or
//!   `X-Shardline-Provider-Key: <api-key>`.
//! - The response is `{"casUrl": <string>, "exp": <unix-seconds>,
//!   "accessToken": <opaque-bearer>}` — the field names/types match the
//!   server's `XetCasTokenResponse` (`crates/shardline-server/src/model.rs`).
//!
//! Tokens are opaque to the client, repo+revision-scoped, and split read/write
//! (write ⊃ read). The [`TokenService`] caches `accessToken` + `exp` per scope
//! and transparently re-issues when fewer than
//! [`REFRESH_BUFFER_SECONDS`] remain before `exp`. Refresh is **single-flight**
//! (concurrent callers await the same in-flight issuance) and **loop-guarded**:
//! a token the server issues with less than the buffer remaining is surfaced as
//! [`AuthError::ShortLivedToken`] instead of being cached, which would
//! immediately trigger another refresh.

use std::{
    fmt,
    future::Future,
    path::PathBuf,
    pin::Pin,
    sync::{Arc, Mutex, MutexGuard},
    time::{Duration, SystemTime, UNIX_EPOCH},
};

use futures_util::FutureExt;
use futures_util::future::Shared;
use reqwest::{RequestBuilder, Response, StatusCode, Url};
use serde::Deserialize;
use shardline_xet_adapter::{XET_READ_TOKEN_ROUTE, XET_WRITE_TOKEN_ROUTE};
use thiserror::Error;

use crate::config::{
    Credential, CredentialResolutionError, read_token_file, resolve_credential_from_env,
};

/// Refresh a cached token when fewer than this many seconds remain before `exp`.
/// The reference client uses the same 30-second buffer.
pub const REFRESH_BUFFER_SECONDS: u64 = 30;

// Token envelopes are small control responses, not bulk transfer bodies.
// Keep a generous hard bound even when Content-Length is absent or misleading.
const MAX_TOKEN_RESPONSE_BYTES: usize = 1024 * 1024;

/// Header carrying the provider bootstrap API key on token-issuance requests.
pub const PROVIDER_KEY_HEADER_NAME: &str = "x-shardline-provider-key";

/// Repository identity scoping token issuance.
///
/// Each segment is interpolated into the token route path, so all values are
/// the path-segment forms the server expects (e.g. `github`, `team`,
/// `assets`, `main`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RepositoryId {
    /// Provider name path segment.
    pub provider: String,
    /// Repository owner path segment.
    pub owner: String,
    /// Repository name path segment.
    pub repo: String,
    /// Revision path segment.
    pub revision: String,
}

/// HTTP client configuration for token-issuance requests.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HttpConfig {
    connect_timeout: Duration,
    request_timeout: Duration,
}

impl HttpConfig {
    /// Defaults: 60-second connect timeout, 60-second total request timeout.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            connect_timeout: Duration::from_secs(60),
            request_timeout: Duration::from_secs(60),
        }
    }

    /// Sets the connect timeout.
    #[must_use]
    pub const fn with_connect_timeout(mut self, timeout: Duration) -> Self {
        self.connect_timeout = timeout;
        self
    }

    /// Sets the total request timeout.
    #[must_use]
    pub const fn with_request_timeout(mut self, timeout: Duration) -> Self {
        self.request_timeout = timeout;
        self
    }

    /// Returns the connect timeout.
    #[must_use]
    pub const fn connect_timeout(&self) -> Duration {
        self.connect_timeout
    }

    /// Returns the total request timeout.
    #[must_use]
    pub const fn request_timeout(&self) -> Duration {
        self.request_timeout
    }
}

impl Default for HttpConfig {
    fn default() -> Self {
        Self::new()
    }
}

/// Configuration for the [`TokenService`]: endpoint, repository identity,
/// credential sources, optional subject, and HTTP timeouts.
///
/// Credential sources are resolved in priority order:
///
/// 1. explicit static token ([`Auth::with_token`])
/// 2. explicit API key ([`Auth::with_api_key`])
/// 3. token file ([`Auth::with_token_file`])
/// 4. environment (`SHARDLINE_TOKEN` / `SHARDLINE_API_KEY` /
///    `SHARDLINE_TOKEN_FILE`, resolved by [`crate::config`])
///
/// Config-file `[auth]` section parsing is CLI scope and is intentionally
/// not handled here.
#[derive(Clone)]
pub struct Auth {
    base_url: Url,
    repository: RepositoryId,
    token: Option<String>,
    api_key: Option<String>,
    token_file: Option<PathBuf>,
    subject: Option<String>,
    http: HttpConfig,
}

impl fmt::Debug for Auth {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Auth")
            .field("base_url", &self.base_url)
            .field("repository", &self.repository)
            .field("token", &"<redacted>")
            .field("api_key", &"<redacted>")
            .field("token_file", &self.token_file)
            .field("subject", &self.subject)
            .field("http", &self.http)
            .finish()
    }
}

impl Auth {
    /// Creates an [`Auth`] for `repository` at `base_url`.
    ///
    /// # Errors
    ///
    /// Returns [`AuthError::InvalidBaseUrl`] when `base_url` is not a
    /// parseable HTTP(S) URL that can serve as a base for the token routes.
    pub fn new(base_url: &str, repository: RepositoryId) -> Result<Self, AuthError> {
        let base_url = Url::parse(base_url).map_err(|source| AuthError::InvalidBaseUrl {
            url: base_url.to_owned(),
            detail: source.to_string(),
        })?;
        if base_url.cannot_be_a_base() {
            return Err(AuthError::InvalidBaseUrl {
                url: base_url.to_string(),
                detail: "URL cannot be used as a base URL".to_owned(),
            });
        }
        Ok(Self {
            base_url,
            repository,
            token: None,
            api_key: None,
            token_file: None,
            subject: None,
            http: HttpConfig::default(),
        })
    }

    /// Returns the API base URL used for token issuance.
    #[must_use]
    pub fn base_url(&self) -> &str {
        self.base_url.as_str()
    }

    /// Returns the repository identity this auth is scoped to.
    #[must_use]
    pub const fn repository(&self) -> &RepositoryId {
        &self.repository
    }

    /// Sets an explicit opaque bearer token (highest credential priority).
    #[must_use]
    #[allow(clippy::missing_const_for_fn)]
    pub fn with_token(mut self, token: String) -> Self {
        self.token = Some(token);
        self
    }

    /// Sets an explicit provider bootstrap API key.
    #[must_use]
    #[allow(clippy::missing_const_for_fn)]
    pub fn with_api_key(mut self, api_key: String) -> Self {
        self.api_key = Some(api_key);
        self
    }

    /// Sets an explicit token file path containing an opaque bearer token.
    #[must_use]
    #[allow(clippy::missing_const_for_fn)]
    pub fn with_token_file(mut self, path: PathBuf) -> Self {
        self.token_file = Some(path);
        self
    }

    /// Sets the optional `?subject=` query parameter sent with every issuance.
    #[must_use]
    #[allow(clippy::missing_const_for_fn)]
    pub fn with_subject(mut self, subject: String) -> Self {
        self.subject = Some(subject);
        self
    }

    /// Sets the HTTP client configuration (timeouts).
    #[must_use]
    pub const fn with_http(mut self, http: HttpConfig) -> Self {
        self.http = http;
        self
    }

    /// Builds the [`TokenService`] for this configuration.
    ///
    /// # Errors
    ///
    /// Returns [`AuthError::Transport`] when the HTTP client cannot be built.
    pub fn build(self) -> Result<TokenService, AuthError> {
        let client = reqwest::Client::builder()
            .connect_timeout(self.http.connect_timeout)
            .timeout(self.http.request_timeout)
            .redirect(token_redirect_policy(&self.base_url))
            .build()
            .map_err(|source| AuthError::Transport {
                message: source.to_string(),
                source: Arc::new(source),
            })?;
        Ok(TokenService::with_clock(
            client,
            self,
            Arc::new(unix_now_seconds),
        ))
    }

    fn token_url(&self, scope: Scope) -> Url {
        let mut url = self.base_url.clone();
        let base_path = url.path().trim_end_matches('/');
        let path = format!("{base_path}{}", self.token_path(scope));
        // `set_path` replaces the path wholesale; the base path prefix is
        // preserved by appending the route to it (mirrors
        // `shardline_xet_adapter::build_xorb_transfer_url`).
        url.set_path(&path);
        if let Some(subject) = &self.subject {
            url.query_pairs_mut().append_pair("subject", subject);
        }
        url
    }

    fn token_path(&self, scope: Scope) -> String {
        let route = match scope {
            Scope::Read => XET_READ_TOKEN_ROUTE,
            Scope::Write => XET_WRITE_TOKEN_ROUTE,
        };
        route
            .replace(
                "{provider}",
                &crate::tree::encode_path_segment(&self.repository.provider),
            )
            .replace(
                "{owner}",
                &crate::tree::encode_path_segment(&self.repository.owner),
            )
            .replace(
                "{repo}",
                &crate::tree::encode_path_segment(&self.repository.repo),
            )
            .replace(
                "{rev}",
                &crate::tree::encode_path_segment(&self.repository.revision),
            )
    }

    fn resolve_credential(
        &self,
        env: &dyn Fn(&str) -> Option<String>,
    ) -> Result<Credential, AuthError> {
        if let Some(token) = &self.token {
            return Ok(Credential::Bearer(token.clone()));
        }
        if let Some(api_key) = &self.api_key {
            return Ok(Credential::ProviderKey(api_key.clone()));
        }
        if let Some(path) = &self.token_file {
            let contents = read_token_file(path).map_err(|source| AuthError::TokenFile {
                path: path.clone(),
                source: Arc::new(source),
            })?;
            return Ok(Credential::Bearer(contents));
        }
        let env_credential = resolve_credential_from_env(env)?;
        env_credential.ok_or(AuthError::MissingCredential)
    }
}

/// A repo+revision-scoped CAS token issued for one scope (read or write).
///
/// `token` is the opaque bearer string to present as
/// `Authorization: Bearer <token>` on CAS requests; `cas_url` is the base URL
/// for the CAS data plane advertised by the server.
#[derive(Clone, PartialEq, Eq)]
pub struct ScopedToken {
    /// Opaque bearer token for CAS requests.
    pub token: String,
    /// Token expiration timestamp as Unix seconds.
    pub exp: u64,
    /// CAS base URL advertised by the server (`casUrl`).
    pub cas_url: String,
}

impl fmt::Debug for ScopedToken {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ScopedToken")
            .field("token", &"<redacted>")
            .field("exp", &self.exp)
            .field("cas_url", &self.cas_url)
            .finish()
    }
}

/// Errors surfaced by the token service.
///
/// Clone so errors can be shared between callers of a single-flight refresh.
#[derive(Debug, Clone, Error)]
pub enum AuthError {
    /// No credential resolved from any configured source.
    #[error(
        "no credential available: set a token, api key, or token file (or SHARDLINE_TOKEN / \
         SHARDLINE_API_KEY / SHARDLINE_TOKEN_FILE)"
    )]
    MissingCredential,
    /// The server rejected the credential with HTTP 401 Unauthorized.
    #[error("token issuance rejected (401 unauthorized): {message}")]
    Unauthorized {
        /// Error message from the server response body, when present.
        message: String,
    },
    /// The credential lacks the required scope (HTTP 403 Forbidden).
    #[error("token issuance denied (403 forbidden): {message}")]
    Forbidden {
        /// Error message from the server response body, when present.
        message: String,
    },
    /// Any other non-success HTTP status (e.g. 5xx).
    #[error("token issuance failed with HTTP {status}: {message}")]
    HttpStatus {
        /// The HTTP status code.
        status: u16,
        /// Error message from the server response body, when present.
        message: String,
    },
    /// The server issued a token that expires within the refresh buffer.
    #[error("token issued with expiration {exp} within the {buffer}s refresh buffer")]
    ShortLivedToken {
        /// The expiration timestamp the server issued.
        exp: u64,
        /// The configured refresh buffer in seconds.
        buffer: u64,
    },
    /// Transport-level failure (connect, DNS, timeout, TLS, ...).
    #[error("token issuance transport error: {message}")]
    Transport {
        /// Human-readable description of the transport failure.
        message: String,
        /// Underlying reqwest error.
        #[source]
        source: Arc<reqwest::Error>,
    },
    /// The response body could not be parsed as a token response.
    #[error("failed to parse token issuance response: {message}")]
    Parse {
        /// Human-readable description of the parse failure.
        message: String,
        /// Underlying serialization error.
        #[source]
        source: Arc<serde_json::Error>,
    },
    /// The configured token file could not be read.
    #[error("failed to read token file {path:?}: {source}")]
    TokenFile {
        /// Path that could not be read.
        path: PathBuf,
        /// Underlying I/O error.
        #[source]
        source: Arc<std::io::Error>,
    },
    /// The configured base URL is not usable for token issuance.
    #[error("invalid token issuance base URL {url:?}: {detail}")]
    InvalidBaseUrl {
        /// The offending URL.
        url: String,
        /// Why it was rejected.
        detail: String,
    },
}

impl From<reqwest::Error> for AuthError {
    fn from(source: reqwest::Error) -> Self {
        Self::Transport {
            message: source.to_string(),
            source: Arc::new(source),
        }
    }
}

impl From<serde_json::Error> for AuthError {
    fn from(source: serde_json::Error) -> Self {
        Self::Parse {
            message: source.to_string(),
            source: Arc::new(source),
        }
    }
}

impl From<CredentialResolutionError> for AuthError {
    fn from(error: CredentialResolutionError) -> Self {
        match error {
            CredentialResolutionError::TokenFile { path, source } => AuthError::TokenFile {
                path,
                source: Arc::new(source),
            },
        }
    }
}

/// Type of an in-flight token issuance.
type RefreshFuture = Pin<Box<dyn Future<Output = Result<ScopedToken, AuthError>> + Send>>;

/// Environment variable lookup used for credential fallback.
type EnvLookup = Arc<dyn Fn(&str) -> Option<String> + Send + Sync>;

/// Scope of a CAS token: read (downloads) or write (uploads).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Scope {
    /// `xet-read-token` scope.
    Read,
    /// `xet-write-token` scope.
    Write,
}

/// Per-scope cache plus the in-flight refresh future for single-flight.
#[derive(Default)]
struct CacheState {
    read: Option<ScopedToken>,
    write: Option<ScopedToken>,
    read_inflight: Option<Shared<RefreshFuture>>,
    write_inflight: Option<Shared<RefreshFuture>>,
}

/// Token-issuance client with per-scope caching and transparent refresh.
///
/// Resolves the repo+revision-scoped read/write CAS token used for downloads
/// and uploads. Cheap to clone and share across tasks: the shared state lives
/// behind an [`Arc`], and at most one issuance request is in flight per scope
/// (concurrent callers share the same in-flight refresh).
///
/// # Examples
///
/// ```no_run
/// # async fn example() -> Result<(), sdx::AuthError> {
/// use sdx::{Auth, RepositoryId};
///
/// let tokens = Auth::new(
///     "http://127.0.0.1:8080",
///     RepositoryId {
///         provider: "github".to_owned(),
///         owner: "team".to_owned(),
///         repo: "assets".to_owned(),
///         revision: "main".to_owned(),
///     },
/// )?
/// .with_api_key("bootstrap".to_owned())
/// .build()?;
///
/// // Resolve a read-scoped token for downloads (`write_token` for uploads);
/// // repeated calls hit the cache and only re-issue near expiration.
/// let read = tokens.read_token().await?;
/// println!("CAS base: {}", read.cas_url);
/// # Ok(())
/// # }
/// ```
#[derive(Clone)]
pub struct TokenService {
    inner: Arc<TokenServiceInner>,
}

struct TokenServiceInner {
    client: reqwest::Client,
    auth: Auth,
    env: EnvLookup,
    clock: Arc<dyn Fn() -> u64 + Send + Sync>,
    state: Mutex<CacheState>,
}

impl TokenService {
    fn with_clock(
        client: reqwest::Client,
        auth: Auth,
        clock: Arc<dyn Fn() -> u64 + Send + Sync>,
    ) -> Self {
        Self::with_deps(client, auth, clock, Arc::new(process_env))
    }

    fn with_deps(
        client: reqwest::Client,
        auth: Auth,
        clock: Arc<dyn Fn() -> u64 + Send + Sync>,
        env: EnvLookup,
    ) -> Self {
        Self {
            inner: Arc::new(TokenServiceInner {
                client,
                auth,
                env,
                clock,
                state: Mutex::new(CacheState::default()),
            }),
        }
    }

    /// Returns a read-scoped CAS token, issuing or refreshing as needed.
    ///
    /// # Errors
    ///
    /// Returns [`AuthError`] when no credential is configured, issuance fails,
    /// the response cannot be parsed, or the server issues a token already
    /// inside the refresh buffer.
    pub async fn read_token(&self) -> Result<ScopedToken, AuthError> {
        self.token(Scope::Read).await
    }

    /// Returns a write-scoped CAS token, issuing or refreshing as needed.
    ///
    /// # Errors
    ///
    /// Returns [`AuthError`] when no credential is configured, issuance fails,
    /// the response cannot be parsed, or the server issues a token already
    /// inside the refresh buffer.
    pub async fn write_token(&self) -> Result<ScopedToken, AuthError> {
        self.token(Scope::Write).await
    }

    /// Returns the CAS base URL from the most recently issued token, if any.
    #[must_use]
    pub fn cas_url(&self) -> Option<String> {
        let state = self.lock_state();
        state
            .read
            .as_ref()
            .or(state.write.as_ref())
            .map(|token| token.cas_url.clone())
    }

    /// Core single-flight, loop-guarded token resolution for `scope`.
    async fn token(&self, scope: Scope) -> Result<ScopedToken, AuthError> {
        let now = self.now();
        let shared = {
            let mut state = self.lock_state();
            if let Some(cached) = cached(scope, &state)
                && cached.exp.saturating_sub(now) >= REFRESH_BUFFER_SECONDS
            {
                return Ok(cached);
            }
            inflight(scope, &state).unwrap_or_else(|| {
                let future = self.start_refresh(scope);
                let started = future.shared();
                *inflight_mut(scope, &mut state) = Some(started.clone());
                started
            })
        };
        // Keep an unpolled handle for identity comparison: Shared::ptr_eq
        // returns false once either compared handle has itself terminated.
        let result = shared.clone().await;
        let mut state = self.lock_state();
        let owns_refresh = inflight(scope, &state).is_some_and(|current| current.ptr_eq(&shared));
        if owns_refresh {
            *inflight_mut(scope, &mut state) = None;
        }
        let token = result?;
        let remaining = token.exp.saturating_sub(self.now());
        if remaining < REFRESH_BUFFER_SECONDS {
            // Loop guard: the server issued a token already inside the refresh
            // buffer (or already expired). Surfacing an error instead of
            // caching it prevents an immediate re-issue loop on the next call.
            return Err(AuthError::ShortLivedToken {
                exp: token.exp,
                buffer: REFRESH_BUFFER_SECONDS,
            });
        }
        // A delayed observer of a completed or invalidated refresh must not
        // replace a newer cached token or clear a newer in-flight refresh.
        if owns_refresh {
            *cached_mut(scope, &mut state) = Some(token.clone());
        }
        Ok(token)
    }

    fn start_refresh(&self, scope: Scope) -> RefreshFuture {
        // The cached shared future must not retain its owning state: a last
        // cancelled waiter could otherwise leave a permanent Arc cycle.
        Box::pin(issue_token(
            self.inner.client.clone(),
            self.inner.auth.clone(),
            self.inner.env.clone(),
            scope,
        ))
    }

    /// Drops the cached read token so the next [`read_token`](Self::read_token)
    /// re-issues one. Used by the M4 retry layer to force a fresh token after a
    /// 401/403 (the server rejected the cached token even though it is within
    /// its expiration window).
    pub(crate) fn invalidate_read(&self) {
        self.invalidate(Scope::Read);
    }

    /// Drops the cached write token so the next [`write_token`](Self::write_token)
    /// re-issues one. Used by the M4 retry layer on upload 403s.
    pub(crate) fn invalidate_write(&self) {
        self.invalidate(Scope::Write);
    }

    fn invalidate(&self, scope: Scope) {
        let mut state = self.lock_state();
        *cached_mut(scope, &mut state) = None;
        *inflight_mut(scope, &mut state) = None;
    }

    fn now(&self) -> u64 {
        (self.inner.clock)()
    }

    fn lock_state(&self) -> MutexGuard<'_, CacheState> {
        self.inner
            .state
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
    }
}

async fn issue_token(
    client: reqwest::Client,
    auth: Auth,
    env: EnvLookup,
    scope: Scope,
) -> Result<ScopedToken, AuthError> {
    let credential = auth.resolve_credential(env.as_ref())?;
    let url = auth.token_url(scope);
    let request = client.get(url);
    let request = apply_credential(request, credential);
    let response = request.send().await?;
    let status = response.status();
    if !status.is_success() {
        let message = error_message(response).await;
        return Err(http_error(status, message));
    }
    let bytes = read_token_response(response).await?;
    let parsed: XetCasTokenResponse = serde_json::from_slice(&bytes)?;
    Ok(ScopedToken {
        token: parsed.access_token,
        exp: parsed.exp,
        cas_url: parsed.cas_url,
    })
}

fn cached(scope: Scope, state: &CacheState) -> Option<ScopedToken> {
    match scope {
        Scope::Read => state.read.clone(),
        Scope::Write => state.write.clone(),
    }
}

const fn cached_mut(scope: Scope, state: &mut CacheState) -> &mut Option<ScopedToken> {
    match scope {
        Scope::Read => &mut state.read,
        Scope::Write => &mut state.write,
    }
}

fn inflight(scope: Scope, state: &CacheState) -> Option<Shared<RefreshFuture>> {
    match scope {
        Scope::Read => state.read_inflight.clone(),
        Scope::Write => state.write_inflight.clone(),
    }
}

fn inflight_mut(scope: Scope, state: &mut CacheState) -> &mut Option<Shared<RefreshFuture>> {
    match scope {
        Scope::Read => &mut state.read_inflight,
        Scope::Write => &mut state.write_inflight,
    }
}

fn apply_credential(request: RequestBuilder, credential: Credential) -> RequestBuilder {
    match credential {
        Credential::Bearer(token) => request.bearer_auth(token),
        Credential::ProviderKey(key) => request.header(PROVIDER_KEY_HEADER_NAME, key),
    }
}

/// Bootstrap credentials belong only to the configured issuer origin.
/// Reqwest's built-in redirect stripping does not cover our custom key header.
fn token_redirect_policy(base_url: &Url) -> reqwest::redirect::Policy {
    let origin = base_url.origin();
    reqwest::redirect::Policy::custom(move |attempt| {
        if attempt.url().origin() != origin {
            attempt.error("token issuance redirect leaves the configured origin")
        } else {
            // Keep the normal redirect-loop limit for same-origin migrations.
            reqwest::redirect::Policy::default().redirect(attempt)
        }
    })
}

const fn http_error(status: StatusCode, message: String) -> AuthError {
    let code = status.as_u16();
    match code {
        401 => AuthError::Unauthorized { message },
        403 => AuthError::Forbidden { message },
        _ => AuthError::HttpStatus {
            status: code,
            message,
        },
    }
}

async fn read_token_response(mut response: Response) -> Result<Vec<u8>, AuthError> {
    if response.content_length().is_some_and(|length| {
        usize::try_from(length).unwrap_or(usize::MAX) > MAX_TOKEN_RESPONSE_BYTES
    }) {
        return Err(token_response_too_large());
    }
    let mut bytes = Vec::new();
    while let Some(chunk) = response.chunk().await? {
        if bytes.len().saturating_add(chunk.len()) > MAX_TOKEN_RESPONSE_BYTES {
            return Err(token_response_too_large());
        }
        bytes.extend_from_slice(&chunk);
    }
    Ok(bytes)
}

fn token_response_too_large() -> AuthError {
    <serde_json::Error as serde::de::Error>::custom(format!(
        "token issuance response exceeds {MAX_TOKEN_RESPONSE_BYTES} bytes"
    ))
    .into()
}

async fn error_message(response: Response) -> String {
    match read_token_response(response).await {
        Ok(bytes) => serde_json::from_slice::<ErrorBody>(&bytes)
            .map(|parsed| parsed.error)
            .unwrap_or_else(|_error| String::from_utf8_lossy(&bytes).into_owned()),
        Err(error) => error.to_string(),
    }
}

/// Server error envelope `{"error": "..."}`.
#[derive(Debug, Deserialize)]
struct ErrorBody {
    error: String,
}

/// Wire response type matching the server's `XetCasTokenResponse`.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct XetCasTokenResponse {
    cas_url: String,
    exp: u64,
    access_token: String,
}

fn process_env(name: &str) -> Option<String> {
    std::env::var(name).ok()
}

fn unix_now_seconds() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs()
}

#[cfg(test)]
mod tests {
    use std::{
        collections::HashMap,
        sync::{
            Arc,
            atomic::{AtomicU64, Ordering},
        },
        time::Duration,
    };

    use serde_json::json;
    use wiremock::{
        Mock, MockServer, ResponseTemplate,
        matchers::{header, method, path, query_param},
    };

    use super::{Auth, AuthError, EnvLookup, REFRESH_BUFFER_SECONDS, RepositoryId, TokenService};
    use crate::config::{SHARDLINE_API_KEY_ENV, SHARDLINE_TOKEN_ENV, SHARDLINE_TOKEN_FILE_ENV};

    /// Fixed "now" for clock-controlled tests (far from any real unix time).
    const NOW: u64 = 1_000_000_000;

    fn repository() -> RepositoryId {
        RepositoryId {
            provider: "github".to_owned(),
            owner: "team".to_owned(),
            repo: "assets".to_owned(),
            revision: "main".to_owned(),
        }
    }

    fn read_path() -> String {
        "/api/github/team/assets/xet-read-token/main".to_owned()
    }

    fn write_path() -> String {
        "/api/github/team/assets/xet-write-token/main".to_owned()
    }

    fn token_response(exp: u64, access_token: &str, cas_url: &str) -> ResponseTemplate {
        ResponseTemplate::new(200).set_body_json(json!({
            "casUrl": cas_url,
            "exp": exp,
            "accessToken": access_token,
        }))
    }

    fn service(auth: Auth, now: &Arc<AtomicU64>) -> TokenService {
        let clock: Arc<dyn Fn() -> u64 + Send + Sync> = {
            let now = Arc::clone(now);
            Arc::new(move || now.load(Ordering::Relaxed))
        };
        TokenService::with_clock(reqwest::Client::new(), auth, clock)
    }

    fn service_with_env(auth: Auth, env: HashMap<String, String>) -> TokenService {
        let now = Arc::new(AtomicU64::new(NOW));
        let clock: Arc<dyn Fn() -> u64 + Send + Sync> = {
            let now = Arc::clone(&now);
            Arc::new(move || now.load(Ordering::Relaxed))
        };
        let env: EnvLookup = Arc::new(move |name| env.get(name).cloned());
        TokenService::with_deps(reqwest::Client::new(), auth, clock, env)
    }

    async fn request_count(server: &MockServer) -> usize {
        server.received_requests().await.unwrap_or_default().len()
    }

    fn bearer_auth(token: &str) -> String {
        format!("Bearer {token}")
    }

    #[tokio::test]
    async fn read_token_uses_read_endpoint_with_interpolated_path() {
        let server = MockServer::start().await;
        let now = Arc::new(AtomicU64::new(NOW));
        Mock::given(method("GET"))
            .and(path(read_path()))
            .respond_with(token_response(NOW + 3600, "read-token", &server.uri()))
            .mount(&server)
            .await;
        let auth = Auth::new(&server.uri(), repository())
            .unwrap()
            .with_token("server-token".to_owned());
        let service = service(auth, &now);

        let token = service.read_token().await.unwrap();
        assert_eq!(token.token, "read-token");
        assert_eq!(request_count(&server).await, 1);
    }

    #[tokio::test]
    async fn write_token_uses_write_endpoint_with_interpolated_path() {
        let server = MockServer::start().await;
        let now = Arc::new(AtomicU64::new(NOW));
        Mock::given(method("GET"))
            .and(path(write_path()))
            .respond_with(token_response(NOW + 3600, "write-token", &server.uri()))
            .mount(&server)
            .await;
        let auth = Auth::new(&server.uri(), repository())
            .unwrap()
            .with_token("server-token".to_owned());
        let service = service(auth, &now);

        let token = service.write_token().await.unwrap();
        assert_eq!(token.token, "write-token");
        assert_eq!(request_count(&server).await, 1);
    }

    #[tokio::test]
    async fn read_and_write_scopes_issue_distinct_tokens() {
        let server = MockServer::start().await;
        let now = Arc::new(AtomicU64::new(NOW));
        Mock::given(method("GET"))
            .and(path(read_path()))
            .respond_with(token_response(NOW + 3600, "read-token", &server.uri()))
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path(write_path()))
            .respond_with(token_response(NOW + 3600, "write-token", &server.uri()))
            .mount(&server)
            .await;
        let auth = Auth::new(&server.uri(), repository())
            .unwrap()
            .with_token("server-token".to_owned());
        let service = service(auth, &now);

        let read = service.read_token().await.unwrap();
        let write = service.write_token().await.unwrap();
        assert_eq!(read.token, "read-token");
        assert_eq!(write.token, "write-token");
        assert_ne!(read.token, write.token);
        assert_eq!(request_count(&server).await, 2);
    }

    #[tokio::test]
    async fn bearer_token_sent_via_authorization_header() {
        let server = MockServer::start().await;
        let now = Arc::new(AtomicU64::new(NOW));
        Mock::given(method("GET"))
            .and(path(read_path()))
            .and(header("authorization", &bearer_auth("server-token")))
            .respond_with(token_response(NOW + 3600, "read-token", &server.uri()))
            .mount(&server)
            .await;
        let auth = Auth::new(&server.uri(), repository())
            .unwrap()
            .with_token("server-token".to_owned());
        let service = service(auth, &now);

        let token = service.read_token().await.unwrap();
        assert_eq!(token.token, "read-token");
        assert_eq!(request_count(&server).await, 1);
    }

    #[tokio::test]
    async fn api_key_sent_via_provider_key_header() {
        let server = MockServer::start().await;
        let now = Arc::new(AtomicU64::new(NOW));
        Mock::given(method("GET"))
            .and(path(read_path()))
            .and(header("x-shardline-provider-key", "bootstrap-key"))
            .respond_with(token_response(NOW + 3600, "read-token", &server.uri()))
            .mount(&server)
            .await;
        let auth = Auth::new(&server.uri(), repository())
            .unwrap()
            .with_api_key("bootstrap-key".to_owned());
        let service = service(auth, &now);

        let token = service.read_token().await.unwrap();
        assert_eq!(token.token, "read-token");
        assert_eq!(request_count(&server).await, 1);
    }

    #[tokio::test]
    async fn provider_key_does_not_follow_redirect_to_another_origin() {
        let issuer = MockServer::start().await;
        let other_origin = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path(read_path()))
            .respond_with(
                ResponseTemplate::new(302)
                    .insert_header("location", format!("{}/issued", other_origin.uri())),
            )
            .mount(&issuer)
            .await;
        Mock::given(method("GET"))
            .and(header("x-shardline-provider-key", "test-bootstrap-key"))
            .respond_with(token_response(
                super::unix_now_seconds() + 3600,
                "redirected-token",
                &issuer.uri(),
            ))
            .mount(&other_origin)
            .await;
        let tokens = Auth::new(&issuer.uri(), repository())
            .unwrap()
            .with_api_key("test-bootstrap-key".to_owned())
            .build()
            .unwrap();

        assert!(tokens.read_token().await.is_err());
        assert_eq!(request_count(&issuer).await, 1);
        assert_eq!(request_count(&other_origin).await, 0);
    }

    #[tokio::test]
    async fn provider_key_follows_same_origin_redirect() {
        let issuer = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path(read_path()))
            .respond_with(ResponseTemplate::new(302).insert_header("location", "/issued"))
            .mount(&issuer)
            .await;
        Mock::given(method("GET"))
            .and(path("/issued"))
            .and(header("x-shardline-provider-key", "test-bootstrap-key"))
            .respond_with(token_response(
                super::unix_now_seconds() + 3600,
                "redirected-token",
                &issuer.uri(),
            ))
            .mount(&issuer)
            .await;
        let tokens = Auth::new(&issuer.uri(), repository())
            .unwrap()
            .with_api_key("test-bootstrap-key".to_owned())
            .build()
            .unwrap();

        assert_eq!(tokens.read_token().await.unwrap().token, "redirected-token");
        assert_eq!(request_count(&issuer).await, 2);
    }

    #[tokio::test]
    async fn token_issuance_same_origin_redirect_loop_is_bounded() {
        let issuer = MockServer::start().await;
        Mock::given(method("GET"))
            .respond_with(ResponseTemplate::new(302).insert_header("location", read_path()))
            .mount(&issuer)
            .await;
        let tokens = Auth::new(&issuer.uri(), repository())
            .unwrap()
            .with_api_key("test-bootstrap-key".to_owned())
            .build()
            .unwrap();
        let result = tokio::time::timeout(Duration::from_secs(2), tokens.read_token())
            .await
            .expect("redirect loop must not stall token issuance");
        assert!(matches!(result, Err(AuthError::Transport { .. })));
        let requests = request_count(&issuer).await;
        assert!((2..=11).contains(&requests), "request count: {requests}");
    }

    #[tokio::test]
    async fn parses_exact_camel_case_response_fields() {
        let server = MockServer::start().await;
        let now = Arc::new(AtomicU64::new(NOW));
        // Literal wire body matching the server's XetCasTokenResponse.
        Mock::given(method("GET"))
            .and(path(read_path()))
            .respond_with(ResponseTemplate::new(200).set_body_raw(
                br#"{"casUrl":"http://cas.internal:8080/","exp":1700000000,"accessToken":"opaque-bearer"}"#,
                "application/json",
            ))
            .mount(&server)
            .await;
        let auth = Auth::new(&server.uri(), repository())
            .unwrap()
            .with_token("server-token".to_owned());
        let service = service(auth, &now);

        let token = service.read_token().await.unwrap();
        assert_eq!(token.token, "opaque-bearer");
        assert_eq!(token.exp, 1_700_000_000);
        assert_eq!(token.cas_url, "http://cas.internal:8080/");
    }

    #[tokio::test]
    async fn cas_url_surfaced_from_response() {
        let server = MockServer::start().await;
        let now = Arc::new(AtomicU64::new(NOW));
        Mock::given(method("GET"))
            .and(path(read_path()))
            .respond_with(token_response(NOW + 3600, "read-token", &server.uri()))
            .mount(&server)
            .await;
        let auth = Auth::new(&server.uri(), repository())
            .unwrap()
            .with_token("server-token".to_owned());
        let service = service(auth, &now);

        let token = service.read_token().await.unwrap();
        assert_eq!(token.cas_url, server.uri());
        assert_eq!(service.cas_url(), Some(server.uri()));
    }

    #[tokio::test]
    async fn caching_repeated_calls_issue_once() {
        let server = MockServer::start().await;
        let now = Arc::new(AtomicU64::new(NOW));
        Mock::given(method("GET"))
            .and(path(read_path()))
            .respond_with(token_response(NOW + 3600, "cached-token", &server.uri()))
            .mount(&server)
            .await;
        let auth = Auth::new(&server.uri(), repository())
            .unwrap()
            .with_token("server-token".to_owned());
        let service = service(auth, &now);

        let first = service.read_token().await.unwrap();
        let second = service.read_token().await.unwrap();
        let third = service.read_token().await.unwrap();
        assert_eq!(first.token, "cached-token");
        assert_eq!(second.token, "cached-token");
        assert_eq!(third.token, "cached-token");
        assert_eq!(request_count(&server).await, 1);
    }

    #[tokio::test]
    async fn refresh_token_within_buffer_reissues() {
        let server = MockServer::start().await;
        let now = Arc::new(AtomicU64::new(NOW));
        // First issuance: a long-lived token.
        Mock::given(method("GET"))
            .and(path(read_path()))
            .respond_with(token_response(NOW + 3600, "token-1", &server.uri()))
            .up_to_n_times(1)
            .mount(&server)
            .await;
        // After the clock enters the 30s buffer, the second issuance gets a
        // fresh long-lived token. Same priority => insertion order decides.
        Mock::given(method("GET"))
            .and(path(read_path()))
            .respond_with(token_response(NOW + 7200, "token-2", &server.uri()))
            .mount(&server)
            .await;
        let auth = Auth::new(&server.uri(), repository())
            .unwrap()
            .with_token("server-token".to_owned());
        let service = service(auth, &now);

        let first = service.read_token().await.unwrap();
        assert_eq!(first.token, "token-1");
        assert_eq!(request_count(&server).await, 1);

        // Advance the clock so the cached token is inside the 30s buffer.
        now.store(NOW + 3600 - REFRESH_BUFFER_SECONDS + 1, Ordering::Relaxed);
        let second = service.read_token().await.unwrap();
        assert_eq!(second.token, "token-2");
        assert_eq!(request_count(&server).await, 2);
    }

    #[tokio::test]
    async fn cancelled_last_refresh_waiter_releases_inner_for_both_scopes() {
        for scope in [super::Scope::Read, super::Scope::Write] {
            let server = MockServer::start().await;
            let now = Arc::new(AtomicU64::new(NOW));
            Mock::given(method("GET"))
                .respond_with(
                    token_response(NOW + 3600, "token", &server.uri())
                        .set_delay(Duration::from_millis(100)),
                )
                .mount(&server)
                .await;
            let auth = Auth::new(&server.uri(), repository())
                .unwrap()
                .with_token("server-token".to_owned());
            // Unpolled services have no in-flight future and release normally.
            let unpolled = service(auth.clone(), &now);
            let weak = Arc::downgrade(&unpolled.inner);
            drop(unpolled);
            assert!(weak.upgrade().is_none());

            let tokens = service(auth.clone(), &now);
            let weak = Arc::downgrade(&tokens.inner);
            let mut first = Box::pin(tokens.token(scope));
            let mut second = Box::pin(tokens.token(scope));
            assert!(futures_util::poll!(&mut first).is_pending());
            assert!(futures_util::poll!(&mut second).is_pending());
            drop(first);
            assert!(weak.upgrade().is_some());
            drop(second);
            drop(tokens);
            assert!(weak.upgrade().is_none());

            let completed = service(auth, &now);
            let weak = Arc::downgrade(&completed.inner);
            assert_eq!(completed.token(scope).await.unwrap().token, "token");
            drop(completed);
            assert!(weak.upgrade().is_none());
        }
    }

    #[tokio::test]
    async fn cancelled_refresh_can_resume_without_duplicate_issuance() {
        for scope in [super::Scope::Read, super::Scope::Write] {
            let server = MockServer::start().await;
            let now = Arc::new(AtomicU64::new(NOW));
            Mock::given(method("GET"))
                .respond_with(
                    token_response(NOW + 3600, "resumed-token", &server.uri())
                        .set_delay(Duration::from_millis(50)),
                )
                .mount(&server)
                .await;
            let tokens = service(
                Auth::new(&server.uri(), repository())
                    .unwrap()
                    .with_token("server-token".to_owned()),
                &now,
            );
            let mut initial = Box::pin(tokens.token(scope));
            assert!(futures_util::poll!(&mut initial).is_pending());
            drop(initial);
            assert_eq!(tokens.token(scope).await.unwrap().token, "resumed-token");
            assert_eq!(tokens.token(scope).await.unwrap().token, "resumed-token");
            assert_eq!(request_count(&server).await, 1);
        }
    }

    #[tokio::test]
    async fn single_flight_concurrent_reads_one_request() {
        let server = MockServer::start().await;
        let now = Arc::new(AtomicU64::new(NOW));
        Mock::given(method("GET"))
            .and(path(read_path()))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_delay(Duration::from_millis(200))
                    .set_body_json(json!({
                        "casUrl": server.uri(),
                        "exp": NOW + 3600,
                        "accessToken": "shared-token",
                    })),
            )
            .mount(&server)
            .await;
        let auth = Auth::new(&server.uri(), repository())
            .unwrap()
            .with_token("server-token".to_owned());
        let service = service(auth, &now);

        let tasks: Vec<_> = (0..10)
            .map(|_| {
                let service = service.clone();
                tokio::spawn(async move { service.read_token().await })
            })
            .collect();
        let results = futures_util::future::join_all(tasks).await;
        for result in results {
            let token = result.unwrap().unwrap();
            assert_eq!(token.token, "shared-token");
        }
        assert_eq!(request_count(&server).await, 1);
    }

    #[tokio::test]
    async fn delayed_refresh_waiter_cannot_replace_a_newer_cached_token() {
        for scope in [super::Scope::Read, super::Scope::Write] {
            let server = MockServer::start().await;
            let now = Arc::new(AtomicU64::new(NOW));
            Mock::given(method("GET"))
                .respond_with(token_response(NOW + 3600, "old-token", &server.uri()))
                .up_to_n_times(1)
                .mount(&server)
                .await;
            Mock::given(method("GET"))
                .respond_with(token_response(NOW + 3600, "new-token", &server.uri()))
                .mount(&server)
                .await;
            let auth = Auth::new(&server.uri(), repository())
                .unwrap()
                .with_token("test-credential".to_owned());
            let tokens = service(auth, &now);
            // Hold one observer of the old single-flight result unpolled
            // while another observer completes and a replacement is issued.
            let mut delayed = Box::pin(tokens.token(scope));
            assert!(futures_util::poll!(&mut delayed).is_pending());
            assert_eq!(tokens.token(scope).await.unwrap().token, "old-token");
            tokens.invalidate(scope);
            assert_eq!(tokens.token(scope).await.unwrap().token, "new-token");
            assert_eq!(delayed.await.unwrap().token, "old-token");
            assert_eq!(tokens.token(scope).await.unwrap().token, "new-token");
            assert_eq!(request_count(&server).await, 2);
        }
    }

    #[tokio::test]
    async fn invalidation_discards_an_inflight_refresh_without_recaching_its_result() {
        for scope in [super::Scope::Read, super::Scope::Write] {
            let server = MockServer::start().await;
            let now = Arc::new(AtomicU64::new(NOW));
            Mock::given(method("GET"))
                .respond_with(
                    token_response(NOW + 3600, "old-token", &server.uri())
                        .set_delay(Duration::from_millis(100)),
                )
                .up_to_n_times(1)
                .mount(&server)
                .await;
            Mock::given(method("GET"))
                .respond_with(token_response(NOW + 3600, "new-token", &server.uri()))
                .mount(&server)
                .await;
            let auth = Auth::new(&server.uri(), repository())
                .unwrap()
                .with_token("test-credential".to_owned());
            let tokens = service(auth, &now);
            let mut old_refresh = Box::pin(tokens.token(scope));
            assert!(futures_util::poll!(&mut old_refresh).is_pending());
            tokio::time::timeout(Duration::from_secs(2), async {
                while request_count(&server).await == 0 {
                    assert!(futures_util::poll!(&mut old_refresh).is_pending());
                    tokio::task::yield_now().await;
                }
            })
            .await
            .expect("the old issuance request must reach the mock server");
            tokens.invalidate(scope);
            assert_eq!(tokens.token(scope).await.unwrap().token, "new-token");
            assert_eq!(old_refresh.await.unwrap().token, "old-token");
            assert_eq!(tokens.token(scope).await.unwrap().token, "new-token");
            assert_eq!(request_count(&server).await, 2);
        }
    }

    #[tokio::test]
    async fn refresh_loop_guard_surfaces_error_and_stays_bounded() {
        let server = MockServer::start().await;
        let now = Arc::new(AtomicU64::new(NOW));
        Mock::given(method("GET"))
            .and(path(read_path()))
            .respond_with(token_response(NOW + 5, "too-short", &server.uri()))
            .mount(&server)
            .await;
        let auth = Auth::new(&server.uri(), repository())
            .unwrap()
            .with_token("server-token".to_owned());
        let service = service(auth, &now);

        let first = service.read_token().await;
        assert!(matches!(first, Err(AuthError::ShortLivedToken { .. })));
        let second = service.read_token().await;
        assert!(matches!(second, Err(AuthError::ShortLivedToken { .. })));
        // Each call issues at most one request; no refresh loop is entered.
        assert_eq!(request_count(&server).await, 2);
    }

    #[tokio::test]
    async fn unauthorized_status_maps_to_typed_error() {
        let server = MockServer::start().await;
        let now = Arc::new(AtomicU64::new(NOW));
        Mock::given(method("GET"))
            .and(path(read_path()))
            .respond_with(
                ResponseTemplate::new(401).set_body_json(json!({"error": "missing provider key"})),
            )
            .mount(&server)
            .await;
        let auth = Auth::new(&server.uri(), repository())
            .unwrap()
            .with_token("server-token".to_owned());
        let service = service(auth, &now);

        let err = service.read_token().await.unwrap_err();
        assert!(matches!(err, AuthError::Unauthorized { .. }));
        assert!(err.to_string().contains("missing provider key"));
    }

    #[tokio::test]
    async fn forbidden_status_maps_to_typed_error() {
        let server = MockServer::start().await;
        let now = Arc::new(AtomicU64::new(NOW));
        Mock::given(method("GET"))
            .and(path(read_path()))
            .respond_with(
                ResponseTemplate::new(403).set_body_json(json!({"error": "insufficient scope"})),
            )
            .mount(&server)
            .await;
        let auth = Auth::new(&server.uri(), repository())
            .unwrap()
            .with_token("server-token".to_owned());
        let service = service(auth, &now);

        let err = service.read_token().await.unwrap_err();
        assert!(matches!(err, AuthError::Forbidden { .. }));
        assert!(err.to_string().contains("insufficient scope"));
    }

    #[tokio::test]
    async fn server_error_status_maps_to_typed_error() {
        let server = MockServer::start().await;
        let now = Arc::new(AtomicU64::new(NOW));
        Mock::given(method("GET"))
            .and(path(read_path()))
            .respond_with(ResponseTemplate::new(500).set_body_json(json!({"error": "internal"})))
            .mount(&server)
            .await;
        let auth = Auth::new(&server.uri(), repository())
            .unwrap()
            .with_token("server-token".to_owned());
        let service = service(auth, &now);

        let err = service.read_token().await.unwrap_err();
        assert!(matches!(err, AuthError::HttpStatus { status: 500, .. }));
        assert!(err.to_string().contains("internal"));
    }

    #[tokio::test]
    async fn non_json_response_body_is_parse_error() {
        let server = MockServer::start().await;
        let now = Arc::new(AtomicU64::new(NOW));
        Mock::given(method("GET"))
            .and(path(read_path()))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_raw(b"<html>not a token response</html>", "text/html"),
            )
            .mount(&server)
            .await;
        let auth = Auth::new(&server.uri(), repository())
            .unwrap()
            .with_token("server-token".to_owned());
        let service = service(auth, &now);

        let err = service.read_token().await.unwrap_err();
        assert!(matches!(err, AuthError::Parse { .. }));
    }

    #[tokio::test]
    async fn oversized_token_responses_fail_with_and_without_content_length() {
        for chunked in [false, true] {
            let server = MockServer::start().await;
            let now = Arc::new(AtomicU64::new(NOW));
            let mut response = ResponseTemplate::new(200).set_body_json(json!({
                "casUrl": server.uri(),
                "exp": NOW + 3600,
                "accessToken": "test-token",
                "padding": "x".repeat(super::MAX_TOKEN_RESPONSE_BYTES),
            }));
            if chunked {
                response = response.insert_header("transfer-encoding", "chunked");
            }
            Mock::given(method("GET"))
                .respond_with(response)
                .mount(&server)
                .await;
            let probe = reqwest::get(server.uri()).await.unwrap();
            assert_eq!(probe.content_length().is_none(), chunked);
            drop(probe);
            let auth = Auth::new(&server.uri(), repository())
                .unwrap()
                .with_token("test-credential".to_owned());
            let tokens = service(auth, &now);
            assert!(matches!(
                tokens.read_token().await,
                Err(AuthError::Parse { .. })
            ));
            assert!(tokens.cas_url().is_none());
        }
    }

    #[tokio::test]
    async fn oversized_error_response_keeps_status_with_a_bounded_message() {
        let server = MockServer::start().await;
        let now = Arc::new(AtomicU64::new(NOW));
        Mock::given(method("GET"))
            .respond_with(
                ResponseTemplate::new(503)
                    .insert_header("transfer-encoding", "chunked")
                    .set_body_string("x".repeat(super::MAX_TOKEN_RESPONSE_BYTES + 1)),
            )
            .mount(&server)
            .await;
        let auth = Auth::new(&server.uri(), repository())
            .unwrap()
            .with_token("test-credential".to_owned());
        let tokens = service(auth, &now);
        let error = tokens.read_token().await.unwrap_err();
        assert!(matches!(&error, AuthError::HttpStatus { status: 503, .. }));
        let message = error.to_string();
        assert!(message.len() < 1024);
        assert!(message.contains("exceeds"));
    }

    #[tokio::test]
    async fn subject_query_param_transmitted_when_configured() {
        let server = MockServer::start().await;
        let now = Arc::new(AtomicU64::new(NOW));
        Mock::given(method("GET"))
            .and(path(read_path()))
            .and(query_param("subject", "alice"))
            .respond_with(token_response(NOW + 3600, "read-token", &server.uri()))
            .mount(&server)
            .await;
        let auth = Auth::new(&server.uri(), repository())
            .unwrap()
            .with_token("server-token".to_owned())
            .with_subject("alice".to_owned());
        let service = service(auth, &now);

        service.read_token().await.unwrap();
        let requests = server.received_requests().await.unwrap_or_default();
        assert_eq!(
            requests[0].url.path(),
            "/api/github/team/assets/xet-read-token/main"
        );
        assert_eq!(requests[0].url.query(), Some("subject=alice"));
    }

    #[tokio::test]
    async fn no_subject_query_when_not_configured() {
        let server = MockServer::start().await;
        let now = Arc::new(AtomicU64::new(NOW));
        Mock::given(method("GET"))
            .and(path(read_path()))
            .respond_with(token_response(NOW + 3600, "read-token", &server.uri()))
            .mount(&server)
            .await;
        let auth = Auth::new(&server.uri(), repository())
            .unwrap()
            .with_token("server-token".to_owned());
        let service = service(auth, &now);

        service.read_token().await.unwrap();
        let requests = server.received_requests().await.unwrap_or_default();
        assert_eq!(
            requests[0].url.path(),
            "/api/github/team/assets/xet-read-token/main"
        );
        assert_eq!(requests[0].url.query(), None);
    }

    #[tokio::test]
    async fn explicit_token_beats_env_credentials() {
        let server = MockServer::start().await;
        let mut env = HashMap::new();
        env.insert(SHARDLINE_TOKEN_ENV.to_owned(), "env-token".to_owned());
        Mock::given(method("GET"))
            .and(path(read_path()))
            .and(header("authorization", &bearer_auth("explicit-token")))
            .respond_with(token_response(NOW + 3600, "read-token", &server.uri()))
            .mount(&server)
            .await;
        let auth = Auth::new(&server.uri(), repository())
            .unwrap()
            .with_token("explicit-token".to_owned());
        let service = service_with_env(auth, env);

        service.read_token().await.unwrap();
        assert_eq!(request_count(&server).await, 1);
    }

    #[tokio::test]
    async fn explicit_api_key_beats_env_token() {
        let server = MockServer::start().await;
        let mut env = HashMap::new();
        env.insert(SHARDLINE_TOKEN_ENV.to_owned(), "env-token".to_owned());
        Mock::given(method("GET"))
            .and(path(read_path()))
            .and(header("x-shardline-provider-key", "explicit-key"))
            .respond_with(token_response(NOW + 3600, "read-token", &server.uri()))
            .mount(&server)
            .await;
        let auth = Auth::new(&server.uri(), repository())
            .unwrap()
            .with_api_key("explicit-key".to_owned());
        let service = service_with_env(auth, env);

        service.read_token().await.unwrap();
        assert_eq!(request_count(&server).await, 1);
    }

    #[tokio::test]
    async fn missing_credential_errors_before_any_request() {
        let server = MockServer::start().await;
        let auth = Auth::new(&server.uri(), repository()).unwrap();
        let service = service_with_env(auth, HashMap::new());

        let err = service.read_token().await.unwrap_err();
        assert!(matches!(err, AuthError::MissingCredential));
        assert_eq!(request_count(&server).await, 0);
    }

    #[tokio::test]
    async fn token_file_credential_reads_and_sends_bearer() {
        let server = MockServer::start().await;
        let now = Arc::new(AtomicU64::new(NOW));
        let dir = tempfile::tempdir().unwrap();
        let token_file = dir.path().join("token");
        std::fs::write(&token_file, "  file-token\n").unwrap();
        Mock::given(method("GET"))
            .and(path(read_path()))
            .and(header("authorization", &bearer_auth("file-token")))
            .respond_with(token_response(NOW + 3600, "read-token", &server.uri()))
            .mount(&server)
            .await;
        let auth = Auth::new(&server.uri(), repository())
            .unwrap()
            .with_token_file(token_file);
        let service = service(auth, &now);

        service.read_token().await.unwrap();
        assert_eq!(request_count(&server).await, 1);
    }

    #[tokio::test]
    async fn env_token_used_when_no_explicit_credential() {
        let server = MockServer::start().await;
        let mut env = HashMap::new();
        env.insert(SHARDLINE_TOKEN_ENV.to_owned(), "env-token".to_owned());
        Mock::given(method("GET"))
            .and(path(read_path()))
            .and(header("authorization", &bearer_auth("env-token")))
            .respond_with(token_response(NOW + 3600, "read-token", &server.uri()))
            .mount(&server)
            .await;
        let auth = Auth::new(&server.uri(), repository()).unwrap();
        let service = service_with_env(auth, env);

        service.read_token().await.unwrap();
        assert_eq!(request_count(&server).await, 1);
    }

    #[tokio::test]
    async fn env_api_key_used_when_no_explicit_credential() {
        let server = MockServer::start().await;
        let mut env = HashMap::new();
        env.insert(SHARDLINE_API_KEY_ENV.to_owned(), "env-key".to_owned());
        Mock::given(method("GET"))
            .and(path(read_path()))
            .and(header("x-shardline-provider-key", "env-key"))
            .respond_with(token_response(NOW + 3600, "read-token", &server.uri()))
            .mount(&server)
            .await;
        let auth = Auth::new(&server.uri(), repository()).unwrap();
        let service = service_with_env(auth, env);

        service.read_token().await.unwrap();
        assert_eq!(request_count(&server).await, 1);
    }

    #[tokio::test]
    async fn env_token_file_credential_reads_and_sends_bearer() {
        let server = MockServer::start().await;
        let dir = tempfile::tempdir().unwrap();
        let token_file = dir.path().join("token");
        std::fs::write(&token_file, "  env-file-token\n").unwrap();
        let mut env = HashMap::new();
        env.insert(
            SHARDLINE_TOKEN_FILE_ENV.to_owned(),
            token_file.to_string_lossy().into_owned(),
        );
        Mock::given(method("GET"))
            .and(path(read_path()))
            .and(header("authorization", &bearer_auth("env-file-token")))
            .respond_with(token_response(NOW + 3600, "read-token", &server.uri()))
            .mount(&server)
            .await;
        let auth = Auth::new(&server.uri(), repository()).unwrap();
        let service = service_with_env(auth, env);

        service.read_token().await.unwrap();
        assert_eq!(request_count(&server).await, 1);
    }

    #[test]
    fn invalid_base_url_rejected_at_construction() {
        let error = Auth::new("not a url", repository()).unwrap_err();
        assert!(matches!(error, AuthError::InvalidBaseUrl { .. }));
    }

    #[test]
    fn non_base_url_rejected_at_construction() {
        let error = Auth::new("mailto:user@example.com", repository()).unwrap_err();
        assert!(matches!(error, AuthError::InvalidBaseUrl { .. }));
    }
}