origincloud-core 0.37.0

The client every service crate of the Origin Cloud SDK uses: credentials, endpoints, retries, errors, long-running operations and read-your-writes.
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
//! Credentials: where the access token each call is sent with comes from.
//!
//! In a browser (`wasm32-unknown-unknown`) there are [`AccessToken`] and
//! the [`Credentials`] trait, for credentials of the page's own. The
//! providers that read the environment, files, a CI job's token or an
//! instance's metadata service, and `default_credentials`, which chains
//! them, are native only: a browser has none of these, and
//! [`ClientBuilder::build`](crate::ClientBuilder::build) without
//! credentials fails with [`Error::NoCredentials`] there. `ServiceAccount`
//! is there only with the feature `service-account-wasm`, for runtimes
//! that aren't a browser.

use std::fmt;
#[cfg(not(target_arch = "wasm32"))]
use std::path::PathBuf;
use std::sync::Arc;
#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
use std::sync::OnceLock;
#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
use std::time::{Duration, SystemTime};

#[cfg(not(target_arch = "wasm32"))]
use chrono::{DateTime, Utc};
#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
use serde::Deserialize;

use crate::Error;
use crate::runtime::MaybeSendFuture;
#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
use crate::runtime::{Mutex, now};
#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
use crate::transport::read_capped;

/// The identity provider's token endpoint, where service account
/// credentials and the CLI's session are exchanged for access tokens.
pub const TOKEN_URL: &str =
    "https://auth.origincloud.eu/realms/origincloud/protocol/openid-connect/token";

#[cfg(not(target_arch = "wasm32"))]
const ENV_ACCESS_TOKEN: &str = "ORIGINCLOUD_ACCESS_TOKEN";
#[cfg(not(target_arch = "wasm32"))]
const ENV_CLIENT_ID: &str = "ORIGINCLOUD_CLIENT_ID";
#[cfg(not(target_arch = "wasm32"))]
const ENV_CLIENT_SECRET: &str = "ORIGINCLOUD_CLIENT_SECRET";
#[cfg(not(target_arch = "wasm32"))]
const ENV_METADATA_DISABLED: &str = "ORIGINCLOUD_METADATA_DISABLED";
#[cfg(not(target_arch = "wasm32"))]
const ENV_METADATA_ENDPOINT: &str = "ORIGINCLOUD_METADATA_ENDPOINT";
#[cfg(not(target_arch = "wasm32"))]
const ENV_OIDC_DISABLED: &str = "ORIGINCLOUD_OIDC_DISABLED";
#[cfg(not(target_arch = "wasm32"))]
const ENV_OIDC_TOKEN_FILE: &str = "ORIGINCLOUD_OIDC_TOKEN_FILE";
#[cfg(not(target_arch = "wasm32"))]
const ENV_OIDC_TOKEN: &str = "ORIGINCLOUD_OIDC_TOKEN";
#[cfg(not(target_arch = "wasm32"))]
const ENV_OIDC_AUDIENCE: &str = "ORIGINCLOUD_OIDC_AUDIENCE";
#[cfg(not(target_arch = "wasm32"))]
const ENV_STS_ENDPOINT: &str = "ORIGINCLOUD_STS_ENDPOINT";
#[cfg(not(target_arch = "wasm32"))]
const ENV_GITHUB_REQUEST_URL: &str = "ACTIONS_ID_TOKEN_REQUEST_URL";
#[cfg(not(target_arch = "wasm32"))]
const ENV_GITHUB_REQUEST_TOKEN: &str = "ACTIONS_ID_TOKEN_REQUEST_TOKEN";

/// The security token service, where a CI job's OIDC token is exchanged
/// for an access token.
pub const STS_ENDPOINT: &str = "https://sts.origincloudapis.eu";

/// The audience a GitHub Actions job's OIDC token is requested for.
pub const OIDC_AUDIENCE: &str = "https://sts.origincloudapis.eu";

/// How long before its expiry an exchanged access token is replaced.
#[cfg(not(target_arch = "wasm32"))]
const FEDERATED_EXPIRY_MARGIN: Duration = Duration::from_secs(60);

/// The waits before an exchange the STS answered with `503` (it can't
/// check the token right now) is sent again.
#[cfg(not(target_arch = "wasm32"))]
const STS_RETRY_DELAYS: [Duration; 2] = [Duration::from_millis(200), Duration::from_millis(400)];

#[cfg(not(target_arch = "wasm32"))]
const TOKEN_EXCHANGE_GRANT: &str = "urn:ietf:params:oauth:grant-type:token-exchange";
#[cfg(not(target_arch = "wasm32"))]
const JWT_TOKEN_TYPE: &str = "urn:ietf:params:oauth:token-type:jwt";

/// The instance metadata service, which software on an instance reaches
/// at this link-local address.
pub const METADATA_ENDPOINT: &str = "http://169.254.169.254";

/// How long a metadata-service session is asked for: the most it grants.
#[cfg(not(target_arch = "wasm32"))]
const METADATA_SESSION_TTL: Duration = Duration::from_secs(6 * 60 * 60);
#[cfg(not(target_arch = "wasm32"))]
const METADATA_SESSION_TTL_HEADER: &str = "x-origincloud-metadata-token-ttl-seconds";
#[cfg(not(target_arch = "wasm32"))]
const METADATA_SESSION_HEADER: &str = "x-origincloud-metadata-token";

/// How long reaching the metadata service may take, and opening a session
/// in all: off an instance, the chain's last step fails within them.
#[cfg(not(target_arch = "wasm32"))]
const METADATA_CONNECT_TIMEOUT: Duration = Duration::from_secs(1);
#[cfg(not(target_arch = "wasm32"))]
const METADATA_SESSION_TIMEOUT: Duration = Duration::from_secs(2);

/// How long a credential request may take.
#[cfg(not(target_arch = "wasm32"))]
const METADATA_REQUEST_TIMEOUT: Duration = Duration::from_secs(5);

/// How long before its expiry the metadata service's credential, which
/// lives five minutes, is replaced.
#[cfg(not(target_arch = "wasm32"))]
const METADATA_EXPIRY_MARGIN: Duration = Duration::from_secs(60);

/// The waits before a request the metadata service answered with `503`
/// (it can't sign right now) is sent again.
#[cfg(not(target_arch = "wasm32"))]
const METADATA_RETRY_DELAYS: [Duration; 2] =
    [Duration::from_millis(100), Duration::from_millis(200)];

/// The OAuth client the CLI logs in as, which its refresh token belongs to.
#[cfg(not(target_arch = "wasm32"))]
const CLI_CLIENT_ID: &str = "origin-cli";

/// How long before its expiry a token is replaced, so that it doesn't
/// expire on the way.
#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
const EXPIRY_MARGIN: Duration = Duration::from_secs(30);

/// The most of a token response that is read.
#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
const MAX_TOKEN_RESPONSE_BYTES: usize = 1 << 20;

/// How long a token request may take.
#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
const TOKEN_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);

/// What [`Credentials::token`] returns: `Send` natively; not in a
/// browser, where a fetch is a JavaScript promise.
pub type TokenFuture<'a> = MaybeSendFuture<'a, Result<String, Error>>;

/// Credentials supply the access token each call is sent with. `Send +
/// Sync` on every target, so a client can live in a UI framework's
/// reactive state (Leptos 0.8 keeps memo values `Send + Sync` even in a
/// browser); only the future [`token`](Self::token) returns is `!Send` there.
pub trait Credentials: Send + Sync + fmt::Debug {
    /// A valid access token.
    fn token(&self) -> TokenFuture<'_>;
}

/// The first credentials found, in this order:
///
/// 1. `ORIGINCLOUD_ACCESS_TOKEN`: an access token, sent as it is.
/// 2. `ORIGINCLOUD_CLIENT_ID` and `ORIGINCLOUD_CLIENT_SECRET`: a service
///    account's credential, exchanged for access tokens as they expire.
///    Only one of the two set is an error.
/// 3. A CI job's OIDC token, exchanged at the security token service
///    ([`Federated`]): from the file `ORIGINCLOUD_OIDC_TOKEN_FILE` names,
///    or else from `ORIGINCLOUD_OIDC_TOKEN`, which holds the token itself
///    (as GitLab CI's `id_tokens` set it), or else from GitHub Actions, in
///    a job granted `permissions: id-token: write`. Once found, its errors
///    are returned, not passed over. `ORIGINCLOUD_OIDC_DISABLED=true`
///    leaves this step out; `ORIGINCLOUD_STS_ENDPOINT` asks another address
///    than [`STS_ENDPOINT`], and `ORIGINCLOUD_OIDC_AUDIENCE` requests
///    GitHub's token for another audience than [`OIDC_AUDIENCE`].
/// 4. The session the `origin` CLI stored at its last login
///    (`origin id login`).
/// 5. The instance's metadata service, on an instance that runs as a
///    service account ([`InstanceMetadata`]). Nothing is requested until a
///    token is; off an instance, that fails with [`Error::NoCredentials`]
///    within about two seconds. `ORIGINCLOUD_METADATA_DISABLED=true` leaves
///    this step out; `ORIGINCLOUD_METADATA_ENDPOINT` asks another address
///    than [`METADATA_ENDPOINT`].
///
/// It fails with [`Error::NoCredentials`] when the metadata service is
/// left out and there are no others.
#[cfg(not(target_arch = "wasm32"))]
pub fn default_credentials() -> Result<Arc<dyn Credentials>, Error> {
    from_environment(&|name| std::env::var(name).ok())
}

/// [`default_credentials`] with the environment read through `env`.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn from_environment(
    env: &dyn Fn(&str) -> Option<String>,
) -> Result<Arc<dyn Credentials>, Error> {
    let var = |name: &str| env(name).filter(|v| !v.is_empty());
    if let Some(token) = var(ENV_ACCESS_TOKEN) {
        return Ok(Arc::new(AccessToken::new(token)));
    }
    match (var(ENV_CLIENT_ID), var(ENV_CLIENT_SECRET)) {
        (Some(id), Some(secret)) => return Ok(Arc::new(ServiceAccount::new(id, secret))),
        (None, None) => {}
        _ => {
            return Err(Error::Config(format!(
                "{ENV_CLIENT_ID} and {ENV_CLIENT_SECRET} must be set together"
            )));
        }
    }
    if let Some(federated) = federated_from(&var) {
        return Ok(Arc::new(federated));
    }
    if let Some(path) = cli_session_path(env)
        && let Some(session) = CliSession::load_from(path)?
    {
        return Ok(Arc::new(session));
    }
    if var(ENV_METADATA_DISABLED).is_some_and(|v| v.eq_ignore_ascii_case("true")) {
        return Err(Error::NoCredentials);
    }
    let metadata = InstanceMetadata::new();
    Ok(Arc::new(match var(ENV_METADATA_ENDPOINT) {
        Some(endpoint) => metadata.with_endpoint(endpoint),
        None => metadata,
    }))
}

/// In a browser there is no environment, no file system and no metadata
/// service, and a secret in a page is anybody's: the page supplies its own
/// [`Credentials`] (an [`AccessToken`], or one that refreshes its session).
#[cfg(target_arch = "wasm32")]
pub(crate) fn from_environment(
    _env: &dyn Fn(&str) -> Option<String>,
) -> Result<Arc<dyn Credentials>, Error> {
    Err(Error::NoCredentials)
}

/// The federated step of the chain, when the environment holds a CI job's
/// OIDC token: a token file, which can be rotated in place, before a token
/// given as it is, before GitHub Actions.
#[cfg(not(target_arch = "wasm32"))]
fn federated_from(var: &dyn Fn(&str) -> Option<String>) -> Option<Federated> {
    if var(ENV_OIDC_DISABLED).is_some_and(|v| v.eq_ignore_ascii_case("true")) {
        return None;
    }
    let mut federated = if let Some(path) = var(ENV_OIDC_TOKEN_FILE) {
        Federated::from_file(path)
    } else if let Some(token) = var(ENV_OIDC_TOKEN) {
        Federated::with_source(JobToken::Given {
            token,
            variable: Some(ENV_OIDC_TOKEN),
        })
    } else if let (Some(url), Some(token)) =
        (var(ENV_GITHUB_REQUEST_URL), var(ENV_GITHUB_REQUEST_TOKEN))
    {
        Federated::github_actions(url, token)
    } else {
        return None;
    };
    if let Some(endpoint) = var(ENV_STS_ENDPOINT) {
        federated = federated.with_endpoint(endpoint);
    }
    if let Some(audience) = var(ENV_OIDC_AUDIENCE) {
        federated = federated.with_audience(audience);
    }
    Some(federated)
}

/// An access token, sent as it is. It is not renewed: a service account's
/// lives five minutes.
#[derive(Clone)]
pub struct AccessToken(String);

impl AccessToken {
    /// Credentials that always send `token`.
    pub fn new(token: impl Into<String>) -> Self {
        Self(token.into())
    }
}

impl fmt::Debug for AccessToken {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("AccessToken(..)")
    }
}

impl Credentials for AccessToken {
    fn token(&self) -> TokenFuture<'_> {
        Box::pin(async move { Ok(self.0.clone()) })
    }
}

/// A service account's client ID and secret, exchanged for access tokens
/// with the client credentials grant as they expire.
///
/// On `wasm32-unknown-unknown` it exists only with the feature
/// `service-account-wasm`, for runtimes that aren't a browser: a web
/// page, and a Web Worker too, is shipped to whoever loads it, secret and
/// all.
#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
pub struct ServiceAccount {
    client_id: String,
    client_secret: String,
    token_url: String,
    http: Option<reqwest::Client>,
    cache: Mutex<Cached>,
}

#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
impl ServiceAccount {
    /// The service account `client_id` with the secret `client_secret`.
    pub fn new(client_id: impl Into<String>, client_secret: impl Into<String>) -> Self {
        Self {
            client_id: client_id.into(),
            client_secret: client_secret.into(),
            token_url: TOKEN_URL.to_owned(),
            http: None,
            cache: Mutex::default(),
        }
    }

    /// Requests tokens at `url` instead of [`TOKEN_URL`].
    pub fn with_token_url(mut self, url: impl Into<String>) -> Self {
        self.token_url = url.into();
        self
    }

    /// Sends the token requests with `http`, instead of the client all
    /// credentials share. Each request is bounded by 30 seconds either way.
    pub fn with_http_client(mut self, http: reqwest::Client) -> Self {
        self.http = Some(http);
        self
    }
}

#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
impl fmt::Debug for ServiceAccount {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ServiceAccount")
            .field("client_id", &self.client_id)
            .field("token_url", &self.token_url)
            .finish_non_exhaustive()
    }
}

#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
impl Credentials for ServiceAccount {
    fn token(&self) -> TokenFuture<'_> {
        Box::pin(async move {
            let mut cache = self.cache.lock().await;
            if let Some(token) = cache.valid() {
                return Ok(token);
            }
            let granted = request_token(
                self.http.as_ref(),
                &self.token_url,
                &[
                    ("grant_type", "client_credentials"),
                    ("client_id", &self.client_id),
                    ("client_secret", &self.client_secret),
                ],
            )
            .await?;
            cache.token = granted.access_token.clone();
            cache.expiry = Some(granted.expiry());
            Ok(granted.access_token)
        })
    }
}

/// The session the `origin` CLI stored at its last login, renewed from its
/// refresh token when its access token has expired. The renewed session
/// stays in memory: the CLI's file is never written.
#[cfg(not(target_arch = "wasm32"))]
pub struct CliSession {
    token_url: String,
    http: Option<reqwest::Client>,
    state: Mutex<SessionState>,
}

#[cfg(not(target_arch = "wasm32"))]
struct SessionState {
    cached: Cached,
    refresh_token: String,
    refresh_expiry: Option<SystemTime>,
}

/// The file the CLI stores its session in.
#[cfg(not(target_arch = "wasm32"))]
#[derive(Deserialize)]
struct StoredSession {
    #[serde(default)]
    access_token: String,
    #[serde(default)]
    expires: Option<DateTime<Utc>>,
    #[serde(default)]
    refresh_token: String,
    #[serde(default)]
    refresh_expires: Option<DateTime<Utc>>,
}

#[cfg(not(target_arch = "wasm32"))]
impl CliSession {
    /// The session the CLI stored, or `None` when it stored none: under
    /// `$XDG_DATA_HOME`, or `~/.local/share`, on every platform, at
    /// `origincloud/session.json`.
    pub fn load() -> Result<Option<Self>, Error> {
        match cli_session_path(&|name| std::env::var(name).ok()) {
            Some(path) => Self::load_from(path),
            None => Ok(None),
        }
    }

    /// The session stored at `path`, or `None` when there is no file.
    pub fn load_from(path: impl Into<PathBuf>) -> Result<Option<Self>, Error> {
        let path = path.into();
        let data = match std::fs::read(&path) {
            Ok(data) => data,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(e) => return Err(Error::Credentials(format!("reading the CLI session: {e}"))),
        };
        let stored: StoredSession = serde_json::from_slice(&data).map_err(|e| {
            Error::Credentials(format!("reading the CLI session {}: {e}", path.display()))
        })?;
        Ok(Some(Self {
            token_url: TOKEN_URL.to_owned(),
            http: None,
            state: Mutex::new(SessionState {
                cached: Cached {
                    token: stored.access_token,
                    expiry: stored.expires.map(SystemTime::from),
                },
                refresh_token: stored.refresh_token,
                refresh_expiry: stored.refresh_expires.map(SystemTime::from),
            }),
        }))
    }

    /// Renews the session at `url` instead of [`TOKEN_URL`].
    pub fn with_token_url(mut self, url: impl Into<String>) -> Self {
        self.token_url = url.into();
        self
    }

    /// Sends the renewals with `http`, instead of the client all
    /// credentials share. Each renewal is bounded by 30 seconds either way.
    pub fn with_http_client(mut self, http: reqwest::Client) -> Self {
        self.http = Some(http);
        self
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl fmt::Debug for CliSession {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CliSession")
            .field("token_url", &self.token_url)
            .finish_non_exhaustive()
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl Credentials for CliSession {
    fn token(&self) -> TokenFuture<'_> {
        Box::pin(async move {
            let mut state = self.state.lock().await;
            if let Some(token) = state.cached.valid() {
                return Ok(token);
            }
            if state
                .refresh_expiry
                .is_none_or(|expiry| SystemTime::now() >= expiry)
            {
                return Err(Error::Credentials(
                    "the CLI session has expired: log in again with `origin id login`".to_owned(),
                ));
            }
            let refresh_token = state.refresh_token.clone();
            let granted = request_token(
                self.http.as_ref(),
                &self.token_url,
                &[
                    ("grant_type", "refresh_token"),
                    ("client_id", CLI_CLIENT_ID),
                    ("refresh_token", &refresh_token),
                ],
            )
            .await
            .map_err(|e| match e {
                Error::Credentials(message) => {
                    Error::Credentials(format!("renewing the CLI session: {message}"))
                }
                other => other,
            })?;
            if !granted.refresh_token.is_empty() {
                state.refresh_token = granted.refresh_token.clone();
                state.refresh_expiry =
                    Some(SystemTime::now() + seconds(granted.refresh_expires_in));
            }
            state.cached = Cached {
                token: granted.access_token.clone(),
                expiry: Some(granted.expiry()),
            };
            Ok(granted.access_token)
        })
    }
}

/// The credential of the service account the instance runs as, from the
/// instance's metadata service: a session is opened for six hours, and each
/// access token, which lives five minutes, requested with it a minute
/// before the last one expires. The requests never go through a proxy,
/// which the metadata service refuses, and one it can't answer right now
/// (`503`) is sent again twice.
#[cfg(not(target_arch = "wasm32"))]
pub struct InstanceMetadata {
    endpoint: String,
    http: Option<reqwest::Client>,
    state: Mutex<MetadataState>,
}

#[cfg(not(target_arch = "wasm32"))]
#[derive(Default)]
struct MetadataState {
    session: Cached,
    cached: Cached,
}

/// The metadata service's credential.
#[cfg(not(target_arch = "wasm32"))]
#[derive(Deserialize)]
struct Issued {
    access_token: String,
    expires_at: DateTime<Utc>,
}

#[cfg(not(target_arch = "wasm32"))]
impl InstanceMetadata {
    /// The metadata service at [`METADATA_ENDPOINT`].
    pub fn new() -> Self {
        Self {
            endpoint: METADATA_ENDPOINT.to_owned(),
            http: None,
            state: Mutex::default(),
        }
    }

    /// Asks the metadata service at `url` instead of [`METADATA_ENDPOINT`].
    pub fn with_endpoint(mut self, url: impl Into<String>) -> Self {
        self.endpoint = url.into().trim_end_matches('/').to_owned();
        self
    }

    /// Sends the requests with `http`, as it is configured, instead of a
    /// client without a proxy that gives up connecting after a second.
    /// Opening a session is bounded by two seconds either way, and
    /// requesting a credential by five.
    pub fn with_http_client(mut self, http: reqwest::Client) -> Self {
        self.http = Some(http);
        self
    }

    fn http(&self) -> Result<&reqwest::Client, Error> {
        static CLIENT: OnceLock<Result<reqwest::Client, String>> = OnceLock::new();
        if let Some(http) = &self.http {
            return Ok(http);
        }
        CLIENT
            .get_or_init(|| {
                reqwest::Client::builder()
                    .no_proxy()
                    .connect_timeout(METADATA_CONNECT_TIMEOUT)
                    .build()
                    .map_err(|e| e.to_string())
            })
            .as_ref()
            .map_err(|e| Error::Credentials(format!("reaching the metadata service: {e}")))
    }

    /// A new session. Off an instance, there is no metadata service to
    /// answer, or another one: another cloud's, at the same address, which
    /// refuses the request as one it doesn't know. Either way, no
    /// credentials.
    async fn open_session(&self) -> Result<String, Error> {
        let request = self
            .http()?
            .put(format!("{}/latest/api/token", self.endpoint))
            .timeout(METADATA_SESSION_TIMEOUT)
            .header(
                METADATA_SESSION_TTL_HEADER,
                METADATA_SESSION_TTL.as_secs().to_string(),
            );
        let (status, body) = send_retrying(request, &METADATA_RETRY_DELAYS)
            .await
            .map_err(|_| Error::NoCredentials)?;
        match status.as_u16() {
            200 => Ok(String::from_utf8_lossy(&body).trim().to_owned()),
            403 => Err(refused_through_a_proxy()),
            503 => Err(Error::Credentials(
                "the metadata service refused a session (HTTP 503)".to_owned(),
            )),
            _ => Err(Error::NoCredentials),
        }
    }

    /// The credential, or `None` when the session is no longer valid.
    async fn request_credential(&self, session: &str) -> Result<Option<Issued>, Error> {
        let failed =
            |e: reqwest::Error| Error::Credentials(format!("reaching the metadata service: {e}"));
        let request = self
            .http()?
            .get(format!(
                "{}/latest/meta-data/service-account/token",
                self.endpoint
            ))
            .timeout(METADATA_REQUEST_TIMEOUT)
            .header(METADATA_SESSION_HEADER, session)
            .header(reqwest::header::ACCEPT, "application/json");
        let (status, body) = send_retrying(request, &METADATA_RETRY_DELAYS)
            .await
            .map_err(failed)?;
        match status.as_u16() {
            200 => {}
            401 => return Ok(None),
            404 => {
                return Err(Error::Credentials(
                    "the instance runs as no service account".to_owned(),
                ));
            }
            403 => return Err(refused_through_a_proxy()),
            status => {
                return Err(Error::Credentials(format!(
                    "the metadata service answered HTTP {status}"
                )));
            }
        }
        match serde_json::from_slice::<Issued>(&body) {
            Ok(issued) if !issued.access_token.is_empty() => Ok(Some(issued)),
            _ => Err(Error::Credentials(
                "the metadata service's answer is not a credential".to_owned(),
            )),
        }
    }
}

/// Sends `request`, and again after each of `delays` while it is answered
/// with `503`.
#[cfg(not(target_arch = "wasm32"))]
async fn send_retrying(
    request: reqwest::RequestBuilder,
    delays: &[Duration],
) -> Result<(reqwest::StatusCode, Vec<u8>), reqwest::Error> {
    let mut delays = delays.iter();
    loop {
        let attempt = request
            .try_clone()
            .expect("a credential request has no streamed body");
        let answer = read_bounded(attempt.send().await?).await?;
        match delays.next() {
            Some(delay) if answer.0 == reqwest::StatusCode::SERVICE_UNAVAILABLE => {
                tokio::time::sleep(*delay).await;
            }
            _ => return Ok(answer),
        }
    }
}

#[cfg(not(target_arch = "wasm32"))]
fn refused_through_a_proxy() -> Error {
    Error::Credentials(
        "the metadata service refused a request that came through a proxy".to_owned(),
    )
}

#[cfg(not(target_arch = "wasm32"))]
impl Default for InstanceMetadata {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl fmt::Debug for InstanceMetadata {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("InstanceMetadata")
            .field("endpoint", &self.endpoint)
            .finish_non_exhaustive()
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl Credentials for InstanceMetadata {
    fn token(&self) -> TokenFuture<'_> {
        Box::pin(async move {
            let mut state = self.state.lock().await;
            if let Some(token) = state.cached.valid_for(METADATA_EXPIRY_MARGIN) {
                return Ok(token);
            }
            // A session refused as no longer valid is opened again, once.
            for _ in 0..2 {
                let session = match state.session.valid() {
                    Some(session) => session,
                    None => {
                        let session = self.open_session().await?;
                        state.session = Cached {
                            token: session.clone(),
                            expiry: Some(SystemTime::now() + METADATA_SESSION_TTL),
                        };
                        session
                    }
                };
                match self.request_credential(&session).await? {
                    Some(issued) => {
                        state.cached = Cached {
                            token: issued.access_token.clone(),
                            expiry: Some(issued.expires_at.into()),
                        };
                        return Ok(issued.access_token);
                    }
                    None => state.session = Cached::default(),
                }
            }
            Err(Error::Credentials(
                "the metadata service answered HTTP 401".to_owned(),
            ))
        })
    }
}

/// A CI job's OIDC token, exchanged at the security token service for the
/// access token of the `WORKLOAD` service account a federated credential
/// trusts the job as. The access token is reused until a minute before it
/// expires; then a fresh job token is fetched and exchanged again, or a
/// token given as it is ([`Federated::from_token`]) exchanged again. An
/// exchange the STS can't check right now (`503`) is sent again twice.
#[cfg(not(target_arch = "wasm32"))]
pub struct Federated {
    source: JobToken,
    endpoint: String,
    audience: String,
    http: Option<reqwest::Client>,
    cache: Mutex<Cached>,
}

/// Where the job's token comes from.
#[cfg(not(target_arch = "wasm32"))]
enum JobToken {
    File(PathBuf),
    /// A token given as it is, from the environment variable `variable`
    /// names, if any.
    Given {
        token: String,
        variable: Option<&'static str>,
    },
    GitHubActions {
        request_url: String,
        request_token: String,
    },
}

/// The claims of a job token that are read before it is exchanged.
#[cfg(not(target_arch = "wasm32"))]
#[derive(Deserialize)]
struct JobTokenClaims {
    exp: Option<f64>,
}

/// GitHub's answer to a job token request.
#[cfg(not(target_arch = "wasm32"))]
#[derive(Deserialize)]
struct GitHubToken {
    value: String,
}

#[cfg(not(target_arch = "wasm32"))]
impl Federated {
    /// The token in the file at `path`, read again at every exchange, so
    /// that a rotated token is picked up: any CI provider's, or a
    /// Kubernetes projected service account token.
    pub fn from_file(path: impl Into<PathBuf>) -> Self {
        Self::with_source(JobToken::File(path.into()))
    }

    /// The token `token`, exchanged as it is: any CI provider's, such as the
    /// one GitLab CI sets in the variable its `id_tokens` names. It can't
    /// be renewed: each renewal of the access token exchanges it again,
    /// until it expires itself, and from then on fails without asking the
    /// STS.
    pub fn from_token(token: impl Into<String>) -> Self {
        Self::with_source(JobToken::Given {
            token: token.into(),
            variable: None,
        })
    }

    /// A GitHub Actions job's token, requested at `request_url` with
    /// `request_token`: the values of `ACTIONS_ID_TOKEN_REQUEST_URL` and
    /// `ACTIONS_ID_TOKEN_REQUEST_TOKEN`, which GitHub sets in a job
    /// granted `permissions: id-token: write`.
    pub fn github_actions(
        request_url: impl Into<String>,
        request_token: impl Into<String>,
    ) -> Self {
        Self::with_source(JobToken::GitHubActions {
            request_url: request_url.into(),
            request_token: request_token.into(),
        })
    }

    fn with_source(source: JobToken) -> Self {
        Self {
            source,
            endpoint: STS_ENDPOINT.to_owned(),
            audience: OIDC_AUDIENCE.to_owned(),
            http: None,
            cache: Mutex::default(),
        }
    }

    /// Exchanges the token at the STS at `url` instead of [`STS_ENDPOINT`].
    pub fn with_endpoint(mut self, url: impl Into<String>) -> Self {
        self.endpoint = url.into().trim_end_matches('/').to_owned();
        self
    }

    /// Requests GitHub's token for `audience` instead of [`OIDC_AUDIENCE`].
    /// A token file's or a given token's audience is whatever its issuer
    /// put in it.
    pub fn with_audience(mut self, audience: impl Into<String>) -> Self {
        self.audience = audience.into();
        self
    }

    /// Sends the requests with `http`, instead of the client all
    /// credentials share. Each request is bounded by 30 seconds either way.
    pub fn with_http_client(mut self, http: reqwest::Client) -> Self {
        self.http = Some(http);
        self
    }

    fn http(&self) -> Result<&reqwest::Client, Error> {
        match &self.http {
            Some(http) => Ok(http),
            None => default_http_client()
                .map_err(|e| Error::Credentials(format!("exchanging the CI job's token: {e}"))),
        }
    }

    /// A fresh job token.
    async fn job_token(&self, http: &reqwest::Client) -> Result<String, Error> {
        match &self.source {
            JobToken::File(path) => {
                let read = std::fs::read_to_string(path).map_err(|e| {
                    Error::Credentials(format!(
                        "reading the OIDC token file {}: {e}",
                        path.display()
                    ))
                })?;
                let token = read.trim();
                if token.is_empty() {
                    return Err(Error::Credentials(format!(
                        "the OIDC token file {} is empty",
                        path.display()
                    )));
                }
                Ok(token.to_owned())
            }
            JobToken::Given { token, variable } => {
                let token = token.trim();
                if token.is_empty() {
                    return Err(Error::Credentials(format!(
                        "the CI job's OIDC token{} is empty",
                        in_variable(*variable)
                    )));
                }
                if let Some(expiry) = job_token_expiry(token)
                    && expiry <= SystemTime::now()
                {
                    let expiry = DateTime::<Utc>::from(expiry)
                        .to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
                    return Err(Error::Credentials(format!(
                        "the CI job's OIDC token{} expired at {expiry}; a token given as it is \
                         can't be renewed: ask the CI provider for a longer-lived one, or use \
                         {ENV_OIDC_TOKEN_FILE}",
                        in_variable(*variable)
                    )));
                }
                Ok(token.to_owned())
            }
            JobToken::GitHubActions {
                request_url,
                request_token,
            } => {
                let failed = |reason: &dyn fmt::Display| {
                    Error::Credentials(format!(
                        "requesting the GitHub Actions job's OIDC token: {reason}; \
                         the workflow needs `permissions: id-token: write`"
                    ))
                };
                let separator = if request_url.contains('?') { '&' } else { '?' };
                let audience: String =
                    url::form_urlencoded::byte_serialize(self.audience.as_bytes()).collect();
                let response = http
                    .get(format!("{request_url}{separator}audience={audience}"))
                    .timeout(TOKEN_REQUEST_TIMEOUT)
                    .header(
                        reqwest::header::AUTHORIZATION,
                        format!("bearer {request_token}"),
                    )
                    .header(reqwest::header::ACCEPT, "application/json")
                    .send()
                    .await
                    .map_err(|e| failed(&e))?;
                let (status, body) = read_bounded(response).await.map_err(|e| failed(&e))?;
                if status != reqwest::StatusCode::OK {
                    return Err(failed(&format_args!("HTTP {}", status.as_u16())));
                }
                match serde_json::from_slice::<GitHubToken>(&body) {
                    Ok(token) if !token.value.is_empty() => Ok(token.value),
                    _ => Err(Error::Credentials(
                        "requesting the GitHub Actions job's OIDC token: the answer holds no token"
                            .to_owned(),
                    )),
                }
            }
        }
    }

    /// The job's token exchanged for an access token.
    async fn exchange(&self, http: &reqwest::Client, job_token: &str) -> Result<Granted, Error> {
        let request = http
            .post(format!("{}/v1/token", self.endpoint))
            .timeout(TOKEN_REQUEST_TIMEOUT)
            .header(reqwest::header::ACCEPT, "application/json")
            .form(&[
                ("grant_type", TOKEN_EXCHANGE_GRANT),
                ("subject_token", job_token),
                ("subject_token_type", JWT_TOKEN_TYPE),
            ]);
        let (status, body) = send_retrying(request, &STS_RETRY_DELAYS)
            .await
            .map_err(|e| Error::Credentials(format!("exchanging the CI job's token: {e}")))?;
        let parsed = serde_json::from_slice::<Granted>(&body);
        let granted = parsed.as_ref().ok();
        let error = granted.map_or("", |g| g.error.as_str());
        match status.as_u16() {
            200 => match parsed {
                Ok(granted) if !granted.access_token.is_empty() => Ok(granted),
                _ => Err(Error::Credentials(
                    "exchanging the CI job's token: the STS's answer is not a token response"
                        .to_owned(),
                )),
            },
            503 => Err(Error::Credentials(
                "exchanging the CI job's token: the STS can't check it right now \
                 (HTTP 503, 3 attempts); try again later"
                    .to_owned(),
            )),
            _ if error == "invalid_grant" => Err(Error::Credentials(
                "the STS refused the CI job's token (invalid_grant): check the federated \
                 credential's issuer, audience and conditions against the token's claims"
                    .to_owned(),
            )),
            status => {
                let reason = match granted {
                    Some(g) if !g.error_description.is_empty() => &g.error_description,
                    Some(g) if !g.error.is_empty() => &g.error,
                    _ => "not a token response",
                };
                Err(Error::Credentials(format!(
                    "exchanging the CI job's token: the STS answered HTTP {status}: {reason}"
                )))
            }
        }
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl fmt::Debug for Federated {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut debug = f.debug_struct("Federated");
        match &self.source {
            JobToken::File(path) => debug.field("token_file", path),
            JobToken::Given { .. } => debug.field("source", &"token"),
            JobToken::GitHubActions { .. } => debug.field("source", &"GitHub Actions"),
        };
        debug
            .field("endpoint", &self.endpoint)
            .field("audience", &self.audience)
            .finish_non_exhaustive()
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl Credentials for Federated {
    fn token(&self) -> TokenFuture<'_> {
        Box::pin(async move {
            let mut cache = self.cache.lock().await;
            if let Some(token) = cache.valid_for(FEDERATED_EXPIRY_MARGIN) {
                return Ok(token);
            }
            let http = self.http()?;
            let job_token = self.job_token(http).await?;
            let granted = self.exchange(http, &job_token).await?;
            *cache = Cached {
                token: granted.access_token.clone(),
                expiry: Some(granted.expiry()),
            };
            Ok(granted.access_token)
        })
    }
}

/// ` in VARIABLE`, naming where a given job token came from, if anywhere.
#[cfg(not(target_arch = "wasm32"))]
fn in_variable(variable: Option<&str>) -> String {
    variable.map_or_else(String::new, |name| format!(" in {name}"))
}

/// When a job token (a JWT) expires, as its unverified `exp` claim says:
/// `None` when it has none, or isn't a JWT whose claims can be read, which
/// is left to the STS to judge.
#[cfg(not(target_arch = "wasm32"))]
fn job_token_expiry(token: &str) -> Option<SystemTime> {
    use base64::Engine as _;
    use base64::engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig};

    const BASE64URL: GeneralPurpose = GeneralPurpose::new(
        &base64::alphabet::URL_SAFE,
        GeneralPurposeConfig::new().with_decode_padding_mode(DecodePaddingMode::Indifferent),
    );
    let payload = token.split('.').nth(1)?;
    let claims: JobTokenClaims = serde_json::from_slice(&BASE64URL.decode(payload).ok()?).ok()?;
    let exp = claims.exp?;
    if !exp.is_finite() || exp < 0.0 {
        return None;
    }
    SystemTime::UNIX_EPOCH.checked_add(Duration::try_from_secs_f64(exp).ok()?)
}

/// Where the CLI stores its session: under `XDG_DATA_HOME`, or
/// `~/.local/share`, on every platform.
#[cfg(not(target_arch = "wasm32"))]
fn cli_session_path(env: &dyn Fn(&str) -> Option<String>) -> Option<PathBuf> {
    let base = match env("XDG_DATA_HOME").filter(|v| !v.is_empty()) {
        Some(base) => PathBuf::from(base),
        None => home_dir(env)?.join(".local").join("share"),
    };
    Some(base.join("origincloud").join("session.json"))
}

#[cfg(not(target_arch = "wasm32"))]
fn home_dir(env: &dyn Fn(&str) -> Option<String>) -> Option<PathBuf> {
    let name = if cfg!(windows) { "USERPROFILE" } else { "HOME" };
    env(name).filter(|v| !v.is_empty()).map(PathBuf::from)
}

/// One access token, replaced once it is about to expire.
#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
#[derive(Default)]
struct Cached {
    token: String,
    expiry: Option<SystemTime>,
}

#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
impl Cached {
    fn valid(&self) -> Option<String> {
        self.valid_for(EXPIRY_MARGIN)
    }

    /// The token, unless it expires within `margin`.
    fn valid_for(&self, margin: Duration) -> Option<String> {
        let expiry = self.expiry?;
        (!self.token.is_empty() && now() + margin < expiry).then(|| self.token.clone())
    }
}

/// A token endpoint's answer.
#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
#[derive(Deserialize, Default)]
#[serde(default)]
struct Granted {
    access_token: String,
    expires_in: i64,
    refresh_token: String,
    refresh_expires_in: i64,
    error: String,
    error_description: String,
}

#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
impl Granted {
    fn expiry(&self) -> SystemTime {
        now() + seconds(self.expires_in)
    }
}

#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
fn seconds(n: i64) -> Duration {
    Duration::from_secs(u64::try_from(n).unwrap_or_default())
}

/// The HTTP client token requests are sent with unless the credentials
/// name one: one for the process, created by the first request.
#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
fn default_http_client() -> Result<&'static reqwest::Client, &'static str> {
    static CLIENT: OnceLock<Result<reqwest::Client, String>> = OnceLock::new();
    CLIENT
        .get_or_init(|| {
            reqwest::Client::builder()
                .build()
                .map_err(|e| e.to_string())
        })
        .as_ref()
        .map_err(String::as_str)
}

#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
async fn request_token(
    http: Option<&reqwest::Client>,
    url: &str,
    form: &[(&str, &str)],
) -> Result<Granted, Error> {
    let failed = |e: &dyn fmt::Display| Error::Credentials(format!("requesting a token: {e}"));
    let http = match http {
        Some(http) => http,
        None => default_http_client().map_err(|e| failed(&e))?,
    };
    let response = http
        .post(url)
        .timeout(TOKEN_REQUEST_TIMEOUT)
        .header(reqwest::header::ACCEPT, "application/json")
        .form(form)
        .send()
        .await
        .map_err(|e| failed(&e))?;
    let (status, body) = read_bounded(response).await.map_err(|e| failed(&e))?;
    let granted: Granted = serde_json::from_slice(&body).map_err(|_| {
        Error::Credentials(format!(
            "requesting a token: HTTP {}, not a token response",
            status.as_u16()
        ))
    })?;
    if status != reqwest::StatusCode::OK || granted.access_token.is_empty() {
        let reason = if granted.error_description.is_empty() {
            &granted.error
        } else {
            &granted.error_description
        };
        return Err(Error::Credentials(format!(
            "the token request was refused (HTTP {}): {reason}",
            status.as_u16()
        )));
    }
    Ok(granted)
}

/// A response's status and its body, up to the most of a token response
/// that is read.
#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
async fn read_bounded(
    response: reqwest::Response,
) -> Result<(reqwest::StatusCode, Vec<u8>), reqwest::Error> {
    let status = response.status();
    let (body, _truncated) = read_capped(response, MAX_TOKEN_RESPONSE_BYTES).await?;
    Ok((status, body))
}

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

    fn env(vars: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
        let vars: HashMap<String, String> = vars
            .iter()
            .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
            .collect();
        move |name| vars.get(name).cloned()
    }

    fn now() -> DateTime<Utc> {
        SystemTime::now().into()
    }

    fn data_home() -> PathBuf {
        let dir =
            std::env::temp_dir().join(format!("origincloud-sdk-test-{}", uuid::Uuid::new_v4()));
        std::fs::create_dir_all(dir.join("origincloud")).unwrap();
        dir
    }

    fn write_session(
        dir: &std::path::Path,
        expires: DateTime<Utc>,
        refresh_expires: DateTime<Utc>,
    ) -> PathBuf {
        let path = dir.join("origincloud").join("session.json");
        let data = serde_json::json!({
            "version": 1,
            "access_token": "stored-access",
            "expires": expires.to_rfc3339(),
            "refresh_token": "stored-refresh",
            "refresh_expires": refresh_expires.to_rfc3339(),
            "token_type": "Bearer",
        });
        std::fs::write(&path, data.to_string()).unwrap();
        path
    }

    #[tokio::test]
    async fn an_access_token_in_the_environment_comes_first() {
        let credentials = from_environment(&env(&[
            (ENV_ACCESS_TOKEN, "from-env"),
            (ENV_CLIENT_ID, "id"),
            (ENV_CLIENT_SECRET, "secret"),
        ]))
        .unwrap();
        assert_eq!(credentials.token().await.unwrap(), "from-env");
    }

    #[test]
    fn a_service_account_in_the_environment_comes_before_the_cli_session() {
        let dir = data_home();
        let hour = chrono::Duration::hours(1);
        write_session(&dir, now() + hour, now() + hour);
        let credentials = from_environment(&env(&[
            ("XDG_DATA_HOME", dir.to_str().unwrap()),
            (ENV_CLIENT_ID, "id"),
            (ENV_CLIENT_SECRET, "secret"),
        ]))
        .unwrap();
        assert!(
            format!("{credentials:?}").starts_with("ServiceAccount"),
            "{credentials:?}"
        );
    }

    const GITHUB: [(&str, &str); 2] = [
        (
            ENV_GITHUB_REQUEST_URL,
            "https://github.invalid/idtoken?api-version=2.0",
        ),
        (ENV_GITHUB_REQUEST_TOKEN, "github-request-token"),
    ];

    fn with<'a>(
        base: &[(&'a str, &'a str)],
        more: &[(&'a str, &'a str)],
    ) -> Vec<(&'a str, &'a str)> {
        base.iter().chain(more).copied().collect()
    }

    #[test]
    fn a_service_account_comes_before_a_ci_job_s_token() {
        let credentials = from_environment(&env(&with(
            &GITHUB,
            &[(ENV_CLIENT_ID, "id"), (ENV_CLIENT_SECRET, "secret")],
        )))
        .unwrap();
        assert!(
            format!("{credentials:?}").starts_with("ServiceAccount"),
            "{credentials:?}"
        );
    }

    #[test]
    fn a_ci_job_s_token_comes_before_the_cli_session() {
        let dir = data_home();
        let hour = chrono::Duration::hours(1);
        write_session(&dir, now() + hour, now() + hour);
        let credentials = from_environment(&env(&with(
            &GITHUB,
            &[("XDG_DATA_HOME", dir.to_str().unwrap())],
        )))
        .unwrap();
        let debug = format!("{credentials:?}");
        assert!(debug.starts_with("Federated"), "{debug}");
        assert!(debug.contains("GitHub Actions"), "{debug}");
        assert!(debug.contains(&format!("{STS_ENDPOINT:?}")), "{debug}");
        assert!(!debug.contains("github-request-token"), "{debug}");
        assert!(!debug.contains("github.invalid"), "{debug}");
    }

    #[test]
    fn a_token_file_comes_before_github_actions() {
        let credentials = from_environment(&env(&with(
            &GITHUB,
            &[(ENV_OIDC_TOKEN_FILE, "/var/run/secrets/token")],
        )))
        .unwrap();
        let debug = format!("{credentials:?}");
        assert!(
            debug.starts_with(r#"Federated { token_file: "/var/run/secrets/token""#),
            "{debug}"
        );
    }

    #[test]
    fn a_token_in_the_environment_is_exchanged() {
        let credentials = from_environment(&env(&[(ENV_OIDC_TOKEN, "gitlab-job-token")])).unwrap();
        let debug = format!("{credentials:?}");
        assert!(
            debug.starts_with(r#"Federated { source: "token""#),
            "{debug}"
        );
        assert!(!debug.contains("gitlab-job-token"), "{debug}");
    }

    #[test]
    fn a_token_file_comes_before_a_token_in_the_environment() {
        let credentials = from_environment(&env(&[
            (ENV_OIDC_TOKEN, "gitlab-job-token"),
            (ENV_OIDC_TOKEN_FILE, "/var/run/secrets/token"),
        ]))
        .unwrap();
        let debug = format!("{credentials:?}");
        assert!(
            debug.starts_with(r#"Federated { token_file: "/var/run/secrets/token""#),
            "{debug}"
        );
    }

    #[test]
    fn a_token_in_the_environment_comes_before_github_actions() {
        let credentials = from_environment(&env(&with(
            &GITHUB,
            &[(ENV_OIDC_TOKEN, "gitlab-job-token")],
        )))
        .unwrap();
        let debug = format!("{credentials:?}");
        assert!(
            debug.starts_with(r#"Federated { source: "token""#),
            "{debug}"
        );
    }

    #[test]
    fn a_token_in_the_environment_is_left_out_with_the_federated_step() {
        let dir = data_home();
        let credentials = from_environment(&env(&[
            (ENV_OIDC_TOKEN, "gitlab-job-token"),
            (ENV_OIDC_DISABLED, "true"),
            ("XDG_DATA_HOME", dir.to_str().unwrap()),
        ]))
        .unwrap();
        assert!(
            format!("{credentials:?}").starts_with("InstanceMetadata"),
            "{credentials:?}"
        );
    }

    /// An unsigned JWT with the claims `claims`.
    fn jwt(claims: &str) -> String {
        use base64::Engine as _;
        let encode = |part: &str| base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(part);
        format!(
            "{}.{}.",
            encode(r#"{"alg":"none","typ":"JWT"}"#),
            encode(claims)
        )
    }

    #[tokio::test]
    async fn an_expired_token_in_the_environment_names_the_variable() {
        let token = jwt(r#"{"sub":"project_path:group/project","exp":1577836800}"#);
        let credentials = from_environment(&env(&[
            (ENV_OIDC_TOKEN, &token),
            (ENV_STS_ENDPOINT, "http://127.0.0.1:9"),
        ]))
        .unwrap();
        let message = credentials.token().await.unwrap_err().to_string();
        assert!(
            message.contains(
                "the CI job's OIDC token in ORIGINCLOUD_OIDC_TOKEN expired at 2020-01-01T00:00:00Z"
            ),
            "{message}"
        );
        assert!(message.contains("ORIGINCLOUD_OIDC_TOKEN_FILE"), "{message}");
        assert!(!message.contains(&token), "{message}");
    }

    #[test]
    fn a_job_token_s_expiry_is_read_from_its_claims() {
        let at = |secs| Some(SystemTime::UNIX_EPOCH + Duration::from_secs(secs));
        assert_eq!(
            job_token_expiry(&jwt(r#"{"exp":1577836800}"#)),
            at(1577836800)
        );
        assert_eq!(
            job_token_expiry(&jwt(r#"{"exp":1577836800.5}"#)),
            at(1577836800).map(|t| t + Duration::from_millis(500))
        );
        // Padded base64url, as some issuers write it.
        let padded = {
            use base64::Engine as _;
            let claims = base64::engine::general_purpose::URL_SAFE.encode(r#"{"exp":12}"#);
            assert!(claims.ends_with("=="), "{claims}");
            format!("e30.{claims}.")
        };
        assert_eq!(job_token_expiry(&padded), at(12));
        for unreadable in [
            jwt(r#"{"sub":"no expiry"}"#),
            jwt(r#"{"exp":"tomorrow"}"#),
            jwt(r#"{"exp":-1}"#),
            jwt("not json"),
            "not-a-jwt".to_owned(),
            "a.%%%.c".to_owned(),
        ] {
            assert_eq!(job_token_expiry(&unreadable), None, "{unreadable}");
        }
    }

    #[test]
    fn github_actions_needs_both_its_variables() {
        let dir = data_home();
        for half in GITHUB {
            let credentials =
                from_environment(&env(&[half, ("XDG_DATA_HOME", dir.to_str().unwrap())])).unwrap();
            assert!(
                format!("{credentials:?}").starts_with("InstanceMetadata"),
                "{credentials:?}"
            );
        }
    }

    #[test]
    fn the_federated_step_can_be_left_out() {
        let dir = data_home();
        let credentials = from_environment(&env(&with(
            &GITHUB,
            &[
                (ENV_OIDC_TOKEN_FILE, "/var/run/secrets/token"),
                (ENV_OIDC_DISABLED, "True"),
                ("XDG_DATA_HOME", dir.to_str().unwrap()),
            ],
        )))
        .unwrap();
        assert!(
            format!("{credentials:?}").starts_with("InstanceMetadata"),
            "{credentials:?}"
        );
    }

    #[test]
    fn the_sts_and_the_audience_can_be_named() {
        let credentials = from_environment(&env(&with(
            &GITHUB,
            &[
                (ENV_STS_ENDPOINT, "http://127.0.0.1:8080/"),
                (ENV_OIDC_AUDIENCE, "https://sts.example"),
            ],
        )))
        .unwrap();
        let debug = format!("{credentials:?}");
        assert!(
            debug.contains(r#"endpoint: "http://127.0.0.1:8080", audience: "https://sts.example""#),
            "{debug}"
        );
    }

    #[test]
    fn half_a_service_account_is_refused() {
        let err = from_environment(&env(&[(ENV_CLIENT_ID, "id")])).unwrap_err();
        assert!(err.to_string().contains("must be set together"), "{err}");
        let err = from_environment(&env(&[(ENV_CLIENT_SECRET, "secret")])).unwrap_err();
        assert!(err.to_string().contains("must be set together"), "{err}");
    }

    #[test]
    fn without_others_the_metadata_service_comes_last() {
        let dir = data_home();
        let credentials =
            from_environment(&env(&[("XDG_DATA_HOME", dir.to_str().unwrap())])).unwrap();
        assert!(
            format!("{credentials:?}").starts_with("InstanceMetadata"),
            "{credentials:?}"
        );
    }

    #[test]
    fn the_metadata_service_s_address_can_be_named() {
        let dir = data_home();
        let credentials = from_environment(&env(&[
            ("XDG_DATA_HOME", dir.to_str().unwrap()),
            (ENV_METADATA_ENDPOINT, "http://127.0.0.1:8080/"),
        ]))
        .unwrap();
        assert!(
            format!("{credentials:?}").contains(r#"endpoint: "http://127.0.0.1:8080""#),
            "{credentials:?}"
        );
    }

    #[test]
    fn no_credentials_at_all_without_the_metadata_service() {
        let dir = data_home();
        let err = from_environment(&env(&[
            ("XDG_DATA_HOME", dir.to_str().unwrap()),
            (ENV_METADATA_DISABLED, "TRUE"),
        ]))
        .unwrap_err();
        assert!(matches!(err, Error::NoCredentials), "{err}");
    }

    #[test]
    fn the_session_is_found_under_the_home_directory_without_xdg_data_home() {
        let path = cli_session_path(&env(&[
            ("HOME", "/home/someone"),
            ("USERPROFILE", "/home/someone"),
        ]))
        .unwrap();
        assert_eq!(
            path,
            PathBuf::from("/home/someone/.local/share/origincloud/session.json")
        );
    }

    #[tokio::test]
    async fn the_cli_session_is_used_as_stored() {
        let dir = data_home();
        write_session(
            &dir,
            now() + chrono::Duration::hours(1),
            now() + chrono::Duration::hours(2),
        );
        let credentials =
            from_environment(&env(&[("XDG_DATA_HOME", dir.to_str().unwrap())])).unwrap();
        assert_eq!(credentials.token().await.unwrap(), "stored-access");
    }

    #[tokio::test]
    async fn a_cli_session_past_its_refresh_expiry_asks_to_log_in() {
        let dir = data_home();
        let path = write_session(
            &dir,
            now() - chrono::Duration::hours(1),
            now() - chrono::Duration::minutes(1),
        );
        let session = CliSession::load_from(path).unwrap().unwrap();
        let err = session.token().await.unwrap_err();
        assert!(err.to_string().contains("origin id login"), "{err}");
    }
}