wiremux-auth 0.11.8

Wiremux TokenProvider, vendor profile catalog, and pasteable OAuth packs.
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
//! HTTP, lock, single-flight, and sanitization helpers.

#[cfg(feature = "net")]
use std::collections::BTreeMap;
#[cfg(feature = "net")]
use std::future::Future;
#[cfg(feature = "net")]
use std::io;
#[cfg(any(feature = "net", test))]
use std::path::{Component, Path, PathBuf};
#[cfg(feature = "net")]
use std::sync::Arc;
#[cfg(feature = "net")]
use std::time::Duration;

#[cfg(feature = "net")]
use tokio::sync::watch;
#[cfg(feature = "net")]
use tracing::{debug, warn};

#[cfg(any(feature = "net", test))]
use crate::error::AuthError;
#[cfg(feature = "net")]
use crate::profile::{OauthPack, TokenRequestFormat};

/// Cap `expires_in` so a millisecond-as-seconds vendor cannot overflow.
#[cfg(feature = "net")]
pub(crate) const MAX_EXPIRES_IN_SECS: u64 = 10 * 365 * 24 * 3600;
/// Hard cap on token-endpoint bodies.
#[cfg(feature = "net")]
pub(crate) const MAX_OAUTH_BODY_BYTES: usize = 1024 * 1024;
/// Hard cap on credential-store files.
#[cfg(feature = "net")]
pub(crate) const MAX_CREDS_BYTES: u64 = 1024 * 1024;
/// Default lock wait.
#[cfg(feature = "net")]
pub(crate) const AUTH_LOCK_TIMEOUT: Duration = Duration::from_secs(10);
/// Connect timeout for token-URL POSTs. A missing host must not wait
/// the full request timeout on each of `token_url` and `token_url_fallback`.
#[cfg(feature = "net")]
pub(crate) const OAUTH_CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
/// Total request timeout for token-URL POSTs.
#[cfg(feature = "net")]
pub(crate) const OAUTH_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);

#[cfg(feature = "net")]
pub(crate) fn duration_from_expires_in_secs(secs: u64) -> Duration {
    Duration::from_secs(secs.min(MAX_EXPIRES_IN_SECS))
}

#[cfg(feature = "net")]
pub(crate) fn oauth_http_client() -> Result<reqwest::Client, AuthError> {
    reqwest::Client::builder()
        .user_agent(format!("wiremux-auth/{}", env!("CARGO_PKG_VERSION")))
        .redirect(reqwest::redirect::Policy::none())
        .connect_timeout(OAUTH_CONNECT_TIMEOUT)
        .timeout(OAUTH_REQUEST_TIMEOUT)
        .build()
        .map_err(|e| AuthError::TokenProvider(format!("failed to build HTTP client: {e}")))
}

/// Shared in-flight refresh so parallel `get_token` issues one POST.
#[cfg(feature = "net")]
pub(crate) struct InFlight {
    inner: Arc<InFlightInner>,
}

#[cfg(feature = "net")]
type RefreshWatch = watch::Receiver<Option<Result<String, String>>>;

#[cfg(feature = "net")]
struct InFlightInner {
    slot: std::sync::Mutex<Option<RefreshWatch>>,
}

#[cfg(feature = "net")]
pub(crate) enum RefreshRole {
    Leader(RefreshLeader),
    Follower(RefreshWatch),
}

#[cfg(feature = "net")]
pub(crate) struct RefreshLeader {
    tx: watch::Sender<Option<Result<String, String>>>,
    inner: Arc<InFlightInner>,
    finished: bool,
}

#[cfg(feature = "net")]
impl InFlight {
    pub(crate) fn new() -> Self {
        Self {
            inner: Arc::new(InFlightInner {
                slot: std::sync::Mutex::new(None),
            }),
        }
    }

    pub(crate) fn claim(&self) -> RefreshRole {
        let mut slot = self.inner.slot.lock().unwrap_or_else(|e| e.into_inner());
        if let Some(rx) = slot.as_ref() {
            return RefreshRole::Follower(rx.clone());
        }
        let (tx, rx) = watch::channel(None);
        *slot = Some(rx);
        RefreshRole::Leader(RefreshLeader {
            tx,
            inner: Arc::clone(&self.inner),
            finished: false,
        })
    }

    pub(crate) fn is_busy(&self) -> bool {
        let slot = self.inner.slot.lock().unwrap_or_else(|e| e.into_inner());
        slot.is_some()
    }
}

#[cfg(feature = "net")]
impl RefreshLeader {
    pub(crate) fn complete(mut self, result: &Result<String, AuthError>) {
        self.finished = true;
        self.clear_slot();
        let shared = match result {
            Ok(token) => Ok(token.clone()),
            Err(err) => Err(err.to_string()),
        };
        let _ = self.tx.send(Some(shared));
    }

    fn clear_slot(&self) {
        let mut slot = self.inner.slot.lock().unwrap_or_else(|e| e.into_inner());
        *slot = None;
    }
}

#[cfg(feature = "net")]
impl Drop for RefreshLeader {
    fn drop(&mut self) {
        if self.finished {
            return;
        }
        self.clear_slot();
        let _ = self.tx.send(Some(Err("token refresh aborted".into())));
    }
}

#[cfg(feature = "net")]
pub(crate) async fn follow_refresh(
    mut rx: watch::Receiver<Option<Result<String, String>>>,
) -> Result<String, AuthError> {
    loop {
        if let Some(result) = rx.borrow().clone() {
            return result.map_err(AuthError::TokenProvider);
        }
        if rx.changed().await.is_err() {
            return Err(AuthError::TokenProvider("token refresh cancelled".into()));
        }
    }
}

#[cfg(feature = "net")]
pub(crate) async fn lead_or_follow<F, Fut>(
    inflight: &InFlight,
    refresh: F,
) -> Result<String, AuthError>
where
    F: FnOnce() -> Fut,
    Fut: Future<Output = Result<String, AuthError>>,
{
    match inflight.claim() {
        RefreshRole::Follower(rx) => follow_refresh(rx).await,
        RefreshRole::Leader(leader) => {
            let result = refresh().await;
            leader.complete(&result);
            result
        }
    }
}

#[cfg(feature = "net")]
pub(crate) fn cached_token_on_lock_failure(
    cached: Option<&str>,
    force: bool,
    err: AuthError,
) -> Result<String, AuthError> {
    if !force && let Some(token) = cached.filter(|t| !t.is_empty()) {
        return Ok(token.to_owned());
    }
    Err(err)
}

#[cfg(feature = "net")]
pub(crate) fn append_oauth_body_chunk(buf: &mut Vec<u8>, chunk: &[u8]) -> Result<(), AuthError> {
    if buf.len().saturating_add(chunk.len()) > MAX_OAUTH_BODY_BYTES {
        return Err(AuthError::TokenProvider(format!(
            "OAuth response body too large (>{MAX_OAUTH_BODY_BYTES} bytes)"
        )));
    }
    buf.extend_from_slice(chunk);
    Ok(())
}

/// POST `application/x-www-form-urlencoded` to an https (or test loopback) URL.
#[cfg(feature = "net")]
pub(crate) async fn post_form_url(
    http: &reqwest::Client,
    url: &str,
    form: &[(&str, &str)],
) -> Result<(u16, String), AuthError> {
    let parsed = parse_token_endpoint(url)?;
    let resp = http.post(parsed).form(form).send().await.map_err(|e| {
        AuthError::TokenProvider(format_oauth_transport_error(
            "token request failed",
            &e,
            url,
        ))
    })?;
    let status = resp.status().as_u16();
    let body = read_oauth_body(resp).await?;
    Ok((status, body))
}

#[cfg(feature = "net")]
pub(crate) fn parse_token_endpoint(url: &str) -> Result<reqwest::Url, AuthError> {
    let parsed = reqwest::Url::parse(url.trim())
        .map_err(|e| AuthError::TokenProvider(format!("token_url is not a valid URL: {e}")))?;
    if parsed.scheme() == "https" {
        return Ok(parsed);
    }
    #[cfg(any(test, feature = "test-util"))]
    if crate::profile::is_loopback_http(url) {
        return Ok(parsed);
    }
    Err(AuthError::TokenProvider(
        "token_url must be https (or loopback http)".into(),
    ))
}

#[cfg(feature = "net")]
pub(crate) fn https_token_url(url: &str) -> Option<reqwest::Url> {
    let parsed = reqwest::Url::parse(url.trim()).ok()?;
    (parsed.scheme() == "https").then_some(parsed)
}

#[cfg(all(feature = "net", any(test, feature = "test-util")))]
fn token_request_loopback(
    http: &reqwest::Client,
    url: reqwest::Url,
    oauth: &OauthPack,
    body: &BTreeMap<String, String>,
    format: TokenRequestFormat,
) -> Result<reqwest::RequestBuilder, AuthError> {
    if !crate::profile::is_loopback_http(url.as_str()) {
        return Err(AuthError::TokenProvider(
            "token_url must be https (or loopback http)".into(),
        ));
    }
    let mut req = http.post(url);
    for (k, v) in &oauth.token_headers {
        req = req.header(k.as_str(), v.as_str());
    }
    Ok(match format {
        TokenRequestFormat::Json => req.json(body),
        TokenRequestFormat::Form => req.form(body),
    })
}

/// One token POST. `context` is the transport-error prefix.
///
/// Refresh must pass `token refresh request failed` so a down token URL
/// can still keep a cached access token.
#[cfg(feature = "net")]
pub(crate) async fn token_post(
    http: &reqwest::Client,
    oauth: &OauthPack,
    url: &str,
    body: &BTreeMap<String, String>,
    format: TokenRequestFormat,
    context: &str,
) -> Result<reqwest::Response, AuthError> {
    let Some(https) = https_token_url(url) else {
        return token_post_non_https(http, oauth, url, body, format, context).await;
    };
    // `https` came from `https_token_url`, which returns only https.
    let mut req = http.post(https);
    for (k, v) in &oauth.token_headers {
        req = req.header(k.as_str(), v.as_str());
    }
    let req = match format {
        TokenRequestFormat::Json => req.json(body),
        TokenRequestFormat::Form => req.form(body),
    };
    req.send()
        .await
        .map_err(|e| AuthError::TokenProvider(format_oauth_transport_error(context, &e, url)))
}

#[cfg(all(feature = "net", any(test, feature = "test-util")))]
async fn token_post_non_https(
    http: &reqwest::Client,
    oauth: &OauthPack,
    url: &str,
    body: &BTreeMap<String, String>,
    format: TokenRequestFormat,
    context: &str,
) -> Result<reqwest::Response, AuthError> {
    if !crate::profile::is_loopback_http(url) {
        return Err(AuthError::TokenProvider(
            "token_url must be https (or loopback http)".into(),
        ));
    }
    let parsed = reqwest::Url::parse(url.trim())
        .map_err(|e| AuthError::TokenProvider(format!("token_url is not a valid URL: {e}")))?;
    token_request_loopback(http, parsed, oauth, body, format)?
        .send()
        .await
        .map_err(|e| AuthError::TokenProvider(format_oauth_transport_error(context, &e, url)))
}

#[cfg(all(feature = "net", not(any(test, feature = "test-util"))))]
async fn token_post_non_https(
    _http: &reqwest::Client,
    _oauth: &OauthPack,
    _url: &str,
    _body: &BTreeMap<String, String>,
    _format: TokenRequestFormat,
    _context: &str,
) -> Result<reqwest::Response, AuthError> {
    Err(AuthError::TokenProvider("token_url must be https".into()))
}

/// POST `token_url`. On HTTP 404, POST `token_url_fallback` once.
///
/// Refresh and login share this rule. The authorize URL is not involved.
#[cfg(feature = "net")]
pub(crate) async fn post_token_with_fallback(
    http: &reqwest::Client,
    oauth: &OauthPack,
    body: &BTreeMap<String, String>,
    context: &str,
) -> Result<(reqwest::Response, String), AuthError> {
    let format = oauth
        .token_request_format
        .unwrap_or(TokenRequestFormat::Form);
    let mut used_url = oauth.token_url.clone();
    let resp = token_post(http, oauth, &used_url, body, format, context).await?;
    let resp = if resp.status() == reqwest::StatusCode::NOT_FOUND {
        if let Some(fallback) = &oauth.token_url_fallback {
            debug!("primary token URL returned 404, trying fallback");
            used_url = fallback.clone();
            token_post(http, oauth, &used_url, body, format, context).await?
        } else {
            resp
        }
    } else {
        resp
    };
    Ok((resp, used_url))
}

#[cfg(feature = "net")]
pub(crate) fn hex_encode(bytes: &[u8]) -> String {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let mut out = String::with_capacity(bytes.len() * 2);
    for &b in bytes {
        out.push(HEX[(b >> 4) as usize] as char);
        out.push(HEX[(b & 0x0f) as usize] as char);
    }
    out
}

#[cfg(feature = "net")]
pub(crate) async fn read_oauth_body(mut resp: reqwest::Response) -> Result<String, AuthError> {
    if let Some(len) = resp.content_length()
        && len > MAX_OAUTH_BODY_BYTES as u64
    {
        return Err(AuthError::TokenProvider(format!(
            "OAuth response body too large (Content-Length: {len} bytes, max {MAX_OAUTH_BODY_BYTES})"
        )));
    }
    let mut buf = Vec::new();
    while let Some(chunk) = resp.chunk().await.map_err(|e| {
        AuthError::TokenProvider(format_oauth_transport_error(
            "failed to read OAuth response body",
            &e,
            resp.url().as_str(),
        ))
    })? {
        append_oauth_body_chunk(&mut buf, &chunk)?;
    }
    Ok(String::from_utf8_lossy(&buf).into_owned())
}

#[cfg(feature = "net")]
pub(crate) fn is_token_rotation_error(body: &str) -> bool {
    let lower = body.to_lowercase();
    lower.contains("refresh_token_reused")
        || lower.contains("invalid_grant")
        || lower.contains("token has been revoked")
        || lower.contains("token_expired")
}

/// `error` + `error_description` only. Never echo raw bodies or tokens.
#[cfg(any(feature = "net", test))]
pub(crate) fn sanitize_oauth_error_body(body: &str) -> String {
    let Ok(value) = serde_json::from_str::<serde_json::Value>(body) else {
        return String::new();
    };
    let Some(obj) = value.as_object() else {
        return String::new();
    };
    let error = obj
        .get("error")
        .and_then(serde_json::Value::as_str)
        .unwrap_or("");
    let desc = obj
        .get("error_description")
        .and_then(serde_json::Value::as_str)
        .unwrap_or("");
    let summary = match (error.is_empty(), desc.is_empty()) {
        (true, true) => return String::new(),
        (false, true) => error.to_owned(),
        (true, false) => desc.to_owned(),
        (false, false) => format!("{error}: {desc}"),
    };
    sanitize_oauth_error_text(&summary)
}

/// Strip controls, redact secret-looking tokens, and cap length.
///
/// Userinfo is removed before the cap. A password whose `@` would
/// otherwise sit past 200 characters must not become the host.
pub fn sanitize_oauth_error_text(text: &str) -> String {
    const MAX_CHARS: usize = 200;
    let urls_first = redact_embedded_urls(text);
    let mut summary: String = urls_first.chars().filter(|c| !c.is_control()).collect();
    summary = redact_secret_looking(&summary);
    if summary.chars().count() > MAX_CHARS {
        summary = summary.chars().take(MAX_CHARS).collect();
    }
    summary
}

fn redact_embedded_urls(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut i = 0;
    while let Some(rel) = s[i..].find("://") {
        let sep = i + rel;
        let scheme_start = scheme_start_before(s, sep);
        if scheme_start == sep {
            out.push_str(&s[i..sep + 3]);
            i = sep + 3;
            continue;
        }
        out.push_str(&s[i..scheme_start]);
        let after = sep + 3;
        let url_end = url_end_from(s, after);
        out.push_str(&redact_url_origin(&s[scheme_start..url_end]));
        i = url_end;
    }
    out.push_str(&s[i..]);
    out
}

fn scheme_start_before(s: &str, sep: usize) -> usize {
    let prefix = &s[..sep];
    let mut start = sep;
    for (idx, ch) in prefix.char_indices().rev() {
        if ch.is_ascii_alphanumeric() || ch == '+' || ch == '.' || ch == '-' {
            start = idx;
        } else {
            break;
        }
    }
    if start < sep
        && s[start..]
            .chars()
            .next()
            .is_some_and(|c| c.is_ascii_alphabetic())
    {
        return start;
    }
    sep
}

fn url_end_from(s: &str, start: usize) -> usize {
    s[start..]
        .char_indices()
        .find(|(_, c)| c.is_whitespace() || matches!(*c, '<' | '>' | '"' | '\'' | ')' | ']' | '}'))
        .map(|(idx, _)| start + idx)
        .unwrap_or(s.len())
}

/// Short reason plus origin only. Never format a raw `reqwest` error.
#[cfg(feature = "net")]
pub fn format_oauth_transport_error(context: &str, err: &reqwest::Error, url: &str) -> String {
    format_oauth_transport_via(context, oauth_transport_reason(err), url)
}

#[cfg(any(feature = "net", test))]
pub fn is_oauth_transport_error(err: &AuthError) -> bool {
    match err {
        AuthError::TokenProvider(msg) => {
            msg.starts_with("token refresh request failed (")
                || msg.starts_with("token request failed (")
                || msg.starts_with("failed to read OAuth response body (")
        }
        _ => false,
    }
}

#[cfg(any(feature = "net", test))]
pub(crate) fn format_oauth_transport_via(context: &str, reason: &str, url: &str) -> String {
    format!("{context} ({reason}) via {}", redact_url_origin(url))
}

#[cfg(feature = "net")]
fn oauth_transport_reason(err: &reqwest::Error) -> &'static str {
    if err.is_timeout() {
        "timeout"
    } else if err.is_connect() {
        "connect"
    } else if err.is_request() {
        "request"
    } else {
        "transport"
    }
}

#[cfg(any(feature = "pkce", feature = "device", test))]
pub(crate) fn format_oauth_http_error(
    context: &str,
    status: impl std::fmt::Display,
    body: &str,
    url: &str,
) -> String {
    let summary = sanitize_oauth_error_body(body);
    let via = redact_url_origin(url);
    if summary.is_empty() {
        format!("{context} (HTTP {status}) via {via}")
    } else {
        format!("{context} (HTTP {status}): {summary} via {via}")
    }
}

/// Sanitized body and origin only. HTTP status lives on [`AuthError::VendorRejected`].
#[cfg(any(feature = "net", test))]
pub(crate) fn vendor_rejected_summary(context: &str, body: &str, url: &str) -> String {
    let summary = sanitize_oauth_error_body(body);
    let via = redact_url_origin(url);
    if summary.is_empty() {
        format!("{context} via {via}")
    } else {
        format!("{context}: {summary} via {via}")
    }
}

/// Redact common token prefixes and JWT-looking blobs.
pub fn redact_secret_looking(s: &str) -> String {
    let mut out = redact_prefix(s, "sk-ant-");
    out = redact_prefix(&out, "sk-");
    out = redact_jwt(&out);
    out = redact_prefix(&out, "rt-");
    out = redact_prefix(&out, "ghp_");
    out = redact_prefix(&out, "gho_");
    out = redact_prefix(&out, "ghs_");
    out = redact_prefix(&out, "ghu_");
    out = redact_prefix(&out, "github_pat_");
    redact_prefix(&out, "AKIA")
}

fn redact_prefix(s: &str, prefix: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut rest = s;
    while let Some(idx) = rest.find(prefix) {
        out.push_str(&rest[..idx]);
        out.push_str("[redacted]");
        rest = &rest[idx + prefix.len()..];
        let end = rest
            .find(|c: char| !(c.is_ascii_alphanumeric() || c == '-' || c == '_'))
            .unwrap_or(rest.len());
        rest = &rest[end..];
    }
    out.push_str(rest);
    out
}

/// Scheme + host/port only. Drops userinfo, path, query, and fragment.
///
/// Percent-encoded `@` is decoded until a pass stops shrinking, then
/// userinfo is cut at the last `@`. A slash, question mark, or hash that
/// decoding reveals ends the host. An authority that never contains `@`
/// is kept as written. Host bytes that are not UTF-8 are lossy-replaced
/// so a non-UTF-8 host cannot fall back to the original userinfo.
pub fn redact_url_origin(raw: &str) -> String {
    let (scheme, rest) = match raw.split_once("://") {
        Some((scheme, rest)) => (Some(scheme), rest),
        None => (None, raw),
    };
    let cut = rest.find(['/', '?', '#']).unwrap_or(rest.len());
    let authority = &rest[..cut];
    let host = host_after_userinfo(authority);
    match scheme {
        Some(scheme) => format!("{scheme}://{host}"),
        None => host,
    }
}

/// Bytes after the last `@` once percent-decoding stops shrinking.
///
/// Callers that never observe `@` get the original authority, not a
/// rewritten host (`api%2Eexample.com` stays encoded). A slash, question
/// mark, or hash that decoding reveals is the end of the host.
fn host_after_userinfo(authority: &str) -> String {
    let decoded = percent_decode_until_stable(authority.as_bytes());
    let Some(at) = decoded.iter().rposition(|byte| *byte == b'@') else {
        return authority.to_string();
    };
    let host = &decoded[at + 1..];
    let end = host
        .iter()
        .position(|byte| matches!(*byte, b'/' | b'?' | b'#'))
        .unwrap_or(host.len());
    String::from_utf8_lossy(&host[..end]).into_owned()
}

/// Repeat [`percent_decode`] until a pass does not shrink.
///
/// Each successful `%HH` shortens the buffer, so `len + 1` passes cannot
/// loop forever.
fn percent_decode_until_stable(input: &[u8]) -> Vec<u8> {
    let mut current = input.to_vec();
    let passes = current.len().saturating_add(1);
    for _ in 0..passes {
        let decoded = percent_decode(&current);
        if decoded.len() >= current.len() {
            break;
        }
        current = decoded;
    }
    current
}

/// Decode one `%HH` pass. Invalid `%` sequences are copied unchanged.
fn percent_decode(input: &[u8]) -> Vec<u8> {
    let mut out = Vec::with_capacity(input.len());
    let mut index = 0;
    while index < input.len() {
        if let Some(byte) = percent_encoded_byte(input, index) {
            out.push(byte);
            index += 3;
        } else {
            out.push(input[index]);
            index += 1;
        }
    }
    out
}

fn percent_encoded_byte(input: &[u8], index: usize) -> Option<u8> {
    let bytes = input.get(index..index.checked_add(3)?)?;
    if bytes[0] != b'%' {
        return None;
    }
    let hi = hex_nibble(bytes[1])?;
    let lo = hex_nibble(bytes[2])?;
    Some((hi << 4) | lo)
}

fn hex_nibble(byte: u8) -> Option<u8> {
    match byte {
        b'0'..=b'9' => Some(byte - b'0'),
        b'a'..=b'f' => Some(byte - b'a' + 10),
        b'A'..=b'F' => Some(byte - b'A' + 10),
        _ => None,
    }
}

fn redact_jwt(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut rest = s;
    while let Some(idx) = rest.find("eyJ") {
        out.push_str(&rest[..idx]);
        out.push_str("[redacted]");
        rest = &rest[idx + 3..];
        let end = rest
            .find(|c: char| !(c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.'))
            .unwrap_or(rest.len());
        rest = &rest[end..];
    }
    out.push_str(rest);
    out
}

/// RAII advisory lock. The sibling `{path}.lock` is left in place on drop.
#[cfg(feature = "net")]
#[derive(Debug)]
pub(crate) struct FileLockGuard {
    file: std::fs::File,
}

#[cfg(feature = "net")]
impl Drop for FileLockGuard {
    fn drop(&mut self) {
        let _ = fs4::FileExt::unlock(&self.file);
    }
}

#[cfg(feature = "net")]
pub(crate) async fn try_acquire_refresh_lock(
    path: Option<&Path>,
    context: &str,
    timeout: Duration,
) -> Result<Option<FileLockGuard>, AuthError> {
    let Some(path) = path else {
        return Ok(None);
    };
    match acquire_file_lock(path, timeout).await {
        Ok(guard) => Ok(Some(guard)),
        Err(AuthError::LockTimeout) => {
            warn!("timed out acquiring file lock for {context}");
            Err(AuthError::LockTimeout)
        }
        Err(e) => {
            warn!("could not acquire file lock for {context}: {e}");
            Err(e)
        }
    }
}

#[cfg(feature = "net")]
pub(crate) async fn acquire_file_lock(
    path: &Path,
    timeout: Duration,
) -> Result<FileLockGuard, AuthError> {
    let lock_path = lock_sibling(path);
    let lock_path_clone = lock_path.clone();
    tokio::task::spawn_blocking(move || lock_exclusive_timeout(&lock_path_clone, timeout))
        .await
        .map_err(|e| AuthError::TokenProvider(format!("spawn_blocking: {e}")))?
}

#[cfg(feature = "net")]
pub(crate) fn lock_sibling(path: &Path) -> PathBuf {
    path.with_extension("lock")
}

#[cfg(feature = "net")]
fn lock_exclusive_timeout(lock_path: &Path, timeout: Duration) -> Result<FileLockGuard, AuthError> {
    use fs4::TryLockError;
    use std::fs::OpenOptions;

    if let Some(parent) = lock_path.parent() {
        std::fs::create_dir_all(parent)
            .map_err(|e| AuthError::io(Some(parent.to_path_buf()), e))?;
    }

    let file = OpenOptions::new()
        .create(true)
        .read(true)
        .write(true)
        .truncate(false)
        .open(lock_path)
        .map_err(|e| AuthError::io(Some(lock_path.to_path_buf()), e))?;

    let start = std::time::Instant::now();
    loop {
        // UFCS: std::fs::File::try_lock (1.89+) would otherwise shadow FileExt.
        match fs4::FileExt::try_lock(&file) {
            Ok(()) => return Ok(FileLockGuard { file }),
            Err(TryLockError::WouldBlock) => {
                if start.elapsed() >= timeout {
                    return Err(AuthError::LockTimeout);
                }
                std::thread::sleep(Duration::from_millis(20));
            }
            Err(TryLockError::Error(e)) if is_lock_busy(&e) => {
                if start.elapsed() >= timeout {
                    return Err(AuthError::LockTimeout);
                }
                std::thread::sleep(Duration::from_millis(20));
            }
            Err(TryLockError::Error(e)) => {
                return Err(AuthError::io(Some(lock_path.to_path_buf()), e));
            }
        }
    }
}

#[cfg(feature = "net")]
fn is_lock_busy(err: &io::Error) -> bool {
    matches!(
        err.kind(),
        io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut | io::ErrorKind::ResourceBusy
    ) || err.raw_os_error()
        == Some(
            #[cfg(unix)]
            35, // EAGAIN / EWOULDBLOCK on some Unix; flock often uses EWOULDBLOCK
            #[cfg(not(unix))]
            33,
        )
}

#[cfg(any(feature = "net", test))]
pub(crate) fn expand_tilde(path: &str) -> PathBuf {
    if path == "~" {
        return home_dir().unwrap_or_else(|| PathBuf::from(path));
    }
    if let Some(rest) = path.strip_prefix("~/")
        && let Some(home) = home_dir()
    {
        return home.join(rest);
    }
    if let Some(rest) = path.strip_prefix("~\\")
        && let Some(home) = home_dir()
    {
        return home.join(rest);
    }
    PathBuf::from(path)
}

/// Expand `~` / relative paths, then refuse anything that leaves `$HOME`.
#[cfg(any(feature = "net", test))]
pub(crate) fn resolve_creds_path(raw: &str) -> Result<PathBuf, AuthError> {
    jail_creds_path(&expand_tilde(raw))
}

/// Refuse `..` and any path that is not under `$HOME` / IsolatedHome.
#[cfg(any(feature = "net", test))]
pub(crate) fn jail_creds_path(path: &Path) -> Result<PathBuf, AuthError> {
    if path.as_os_str().is_empty() || has_parent_dir(path) {
        return Err(creds_path_escapes_home());
    }
    let home = home_dir().filter(|h| !h.as_os_str().is_empty());
    let Some(home) = home else {
        return Err(creds_path_escapes_home());
    };
    let resolved = if path.is_absolute() {
        path.to_path_buf()
    } else {
        home.join(path)
    };
    if has_parent_dir(&resolved) || !path_is_under_home(&resolved, &home) {
        return Err(creds_path_escapes_home());
    }
    Ok(resolved)
}

#[cfg(any(feature = "net", test))]
fn has_parent_dir(path: &Path) -> bool {
    path.components().any(|c| matches!(c, Component::ParentDir))
}

#[cfg(any(feature = "net", test))]
fn path_is_under_home(path: &Path, home: &Path) -> bool {
    let home_canon = std::fs::canonicalize(home).unwrap_or_else(|_| home.to_path_buf());
    if let Ok(canon) = std::fs::canonicalize(path) {
        return canon.starts_with(&home_canon);
    }
    // Missing leaf: canonicalize the first existing ancestor so a parent
    // symlink out of home (`~/out` -> `/tmp`) cannot pass a logical prefix.
    if let Some(resolved) = resolve_via_existing_ancestor(path) {
        return resolved.starts_with(&home_canon);
    }
    // No existing ancestor: keep the logical-prefix fallback
    // (macOS /var/folders -> /private/var/folders).
    if let Ok(rest) = path.strip_prefix(home) {
        return home_canon.join(rest).starts_with(&home_canon);
    }
    path.strip_prefix(&home_canon).is_ok()
}

#[cfg(any(feature = "net", test))]
fn resolve_via_existing_ancestor(path: &Path) -> Option<PathBuf> {
    let mut suffix: Vec<std::ffi::OsString> = Vec::new();
    let mut current = path.to_path_buf();
    loop {
        if current.exists() {
            let mut resolved = std::fs::canonicalize(&current).ok()?;
            for part in suffix.iter().rev() {
                resolved.push(part);
            }
            return Some(resolved);
        }
        let name = current.file_name()?.to_os_string();
        suffix.push(name);
        let parent = current.parent()?;
        if parent.as_os_str().is_empty() || parent == current {
            return None;
        }
        current = parent.to_path_buf();
    }
}

#[cfg(any(feature = "net", test))]
fn creds_path_escapes_home() -> AuthError {
    AuthError::TokenProvider("oauth.creds_path must stay under home".into())
}

#[cfg(any(feature = "net", test))]
pub(crate) fn home_dir() -> Option<PathBuf> {
    std::env::var_os("HOME")
        .or_else(|| std::env::var_os("USERPROFILE"))
        .filter(|raw| !raw.is_empty())
        .map(PathBuf::from)
}

#[cfg(any(feature = "net", test))]
pub(crate) fn percent_encode(input: &str) -> String {
    let mut out = String::with_capacity(input.len() * 3);
    for byte in input.bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
                out.push(byte as char);
            }
            _ => {
                out.push('%');
                out.push(char::from(b"0123456789ABCDEF"[(byte >> 4) as usize]));
                out.push(char::from(b"0123456789ABCDEF"[(byte & 0x0F) as usize]));
            }
        }
    }
    out
}

#[cfg(feature = "net")]
pub(crate) fn format_rfc3339_now_plus(seconds: u64) -> String {
    let seconds = seconds.min(MAX_EXPIRES_IN_SECS);
    let total_secs = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs()
        .saturating_add(seconds);
    format_rfc3339_epoch(total_secs)
}

#[cfg(feature = "net")]
pub(crate) fn format_rfc3339_epoch(total_secs: u64) -> String {
    let secs_per_day: u64 = 86400;
    let mut days = (total_secs / secs_per_day) as i64;
    let day_secs = total_secs % secs_per_day;
    let hour = day_secs / 3600;
    let min = (day_secs % 3600) / 60;
    let sec = day_secs % 60;

    days += 719468;
    let era = days.div_euclid(146097);
    let doe = days.rem_euclid(146097);
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = if m <= 2 { y + 1 } else { y };

    format!("{y:04}-{m:02}-{d:02}T{hour:02}:{min:02}:{sec:02}Z")
}

#[cfg(feature = "net")]
pub(crate) fn parse_rfc3339(s: &str) -> Result<std::time::SystemTime, AuthError> {
    let s = s.trim();
    if s.len() < 19 {
        return Err(AuthError::TokenProvider("date too short".into()));
    }
    if !s.is_ascii() {
        return Err(AuthError::TokenProvider("non-ASCII date".into()));
    }
    let year: i32 = s[0..4]
        .parse()
        .map_err(|e| AuthError::TokenProvider(format!("year: {e}")))?;
    let month: u32 = s[5..7]
        .parse()
        .map_err(|e| AuthError::TokenProvider(format!("month: {e}")))?;
    let day: u32 = s[8..10]
        .parse()
        .map_err(|e| AuthError::TokenProvider(format!("day: {e}")))?;
    let hour: u32 = s[11..13]
        .parse()
        .map_err(|e| AuthError::TokenProvider(format!("hour: {e}")))?;
    let min: u32 = s[14..16]
        .parse()
        .map_err(|e| AuthError::TokenProvider(format!("min: {e}")))?;
    let sec: u32 = s[17..19]
        .parse()
        .map_err(|e| AuthError::TokenProvider(format!("sec: {e}")))?;
    if !(1..=12).contains(&month) {
        return Err(AuthError::TokenProvider(format!(
            "month {month} out of range"
        )));
    }
    if !(1..=31).contains(&day) {
        return Err(AuthError::TokenProvider(format!("day {day} out of range")));
    }
    if hour > 23 || min > 59 || sec > 59 {
        return Err(AuthError::TokenProvider("time out of range".into()));
    }
    let days = days_since_epoch(year, month, day);
    let base_secs = days * 86400 + i64::from(hour) * 3600 + i64::from(min) * 60 + i64::from(sec);
    let tz_start = if s.len() > 19 && s.as_bytes()[19] == b'.' {
        s[20..].find(['Z', '+', '-']).map(|p| p + 20)
    } else if s.len() > 19 {
        Some(19)
    } else {
        None
    };
    let offset_secs: i64 = match tz_start {
        Some(pos) if pos < s.len() && s.as_bytes()[pos] == b'Z' => 0,
        Some(pos) if pos + 5 <= s.len() => {
            let sign: i64 = if s.as_bytes()[pos] == b'+' { 1 } else { -1 };
            let oh: i64 = s[pos + 1..pos + 3]
                .parse()
                .map_err(|e| AuthError::TokenProvider(format!("tz hour: {e}")))?;
            let om_start = if s.as_bytes()[pos + 3] == b':' {
                pos + 4
            } else {
                pos + 3
            };
            if om_start.saturating_add(2) > s.len() {
                return Err(AuthError::TokenProvider("tz min too short".into()));
            }
            let om: i64 = s[om_start..om_start + 2]
                .parse()
                .map_err(|e| AuthError::TokenProvider(format!("tz min: {e}")))?;
            sign * (oh * 3600 + om * 60)
        }
        _ => 0,
    };
    let total_secs = (base_secs - offset_secs).max(0) as u64;
    Ok(std::time::UNIX_EPOCH + Duration::from_secs(total_secs))
}

#[cfg(feature = "net")]
fn days_since_epoch(year: i32, month: u32, day: u32) -> i64 {
    let y = i64::from(if month <= 2 { year - 1 } else { year });
    let m = if month <= 2 {
        i64::from(month) + 9
    } else {
        i64::from(month) - 3
    };
    let d = i64::from(day);
    let era = y.div_euclid(400);
    let yoe = y.rem_euclid(400);
    let doy = (153 * m + 2) / 5 + d - 1;
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
    era * 146097 + doe - 719468
}

#[cfg(feature = "net")]
pub(crate) fn remaining_from_system_time(expiry: std::time::SystemTime) -> Duration {
    match expiry.duration_since(std::time::SystemTime::now()) {
        Ok(remaining) => remaining,
        Err(_) => Duration::ZERO,
    }
}

#[cfg(test)]
pub(crate) fn test_login_oauth(
    token_url: &str,
    fallback: Option<&str>,
    format: &str,
    login: &str,
) -> crate::profile::OauthPack {
    let fb = match fallback {
        Some(url) => format!("token_url_fallback = \"{url}\"\n"),
        None => String::new(),
    };
    let text = format!(
        r#"
schema_version = 1
id = "login-post"
[oauth]
token_url = "{token_url}"
{fb}client_id = "client-1"
redirect_uri = "http://127.0.0.1:9/cb"
token_request_format = "{format}"
login = "{login}"
[oauth.token_headers]
X-Client = "official-app"
"#
    );
    crate::profile::parse_profile_str(&text)
        .expect("test profile")
        .oauth
        .expect("oauth")
}

/// One loopback response. The handle is the raw request, or `NO_REQUEST`
/// if nothing connected within 8 seconds.
#[cfg(test)]
pub(crate) fn capture_one_http_request(
    status: u16,
    body: &str,
) -> (String, std::thread::JoinHandle<String>) {
    use std::io::{ErrorKind, Read, Write};
    use std::net::TcpListener;
    use std::time::{Duration, Instant};

    let listener = TcpListener::bind("127.0.0.1:0").expect("bind mock");
    listener.set_nonblocking(true).expect("nonblocking");
    let addr = listener.local_addr().expect("local_addr");
    let body = body.to_owned();
    let handle = std::thread::spawn(move || {
        let deadline = Instant::now() + Duration::from_secs(8);
        let mut stream = loop {
            match listener.accept() {
                Ok((stream, _)) => break stream,
                Err(err) if err.kind() == ErrorKind::WouldBlock => {
                    if Instant::now() >= deadline {
                        return "NO_REQUEST".to_owned();
                    }
                    std::thread::sleep(Duration::from_millis(10));
                }
                Err(err) => return format!("ACCEPT_ERROR {err}"),
            }
        };
        stream.set_nonblocking(false).ok();
        stream.set_read_timeout(Some(Duration::from_secs(5))).ok();
        let mut buf = Vec::new();
        let mut tmp = [0u8; 1024];
        loop {
            match stream.read(&mut tmp) {
                Ok(0) => break,
                Ok(n) => {
                    buf.extend_from_slice(&tmp[..n]);
                    if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
                        let header = String::from_utf8_lossy(&buf[..pos]);
                        let content_len = header
                            .lines()
                            .find_map(|line| {
                                line.split_once(':').and_then(|(name, value)| {
                                    name.eq_ignore_ascii_case("content-length")
                                        .then_some(value.trim().parse::<usize>().unwrap_or(0))
                                })
                            })
                            .unwrap_or(0);
                        let header_end = pos + 4;
                        while buf.len() < header_end + content_len {
                            match stream.read(&mut tmp) {
                                Ok(0) | Err(_) => break,
                                Ok(n) => buf.extend_from_slice(&tmp[..n]),
                            }
                        }
                        break;
                    }
                    if buf.len() > 32_768 {
                        break;
                    }
                }
                Err(_) => break,
            }
        }
        let req = String::from_utf8_lossy(&buf).into_owned();
        let resp = format!(
            "HTTP/1.1 {status} OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
            body.len()
        );
        let _ = stream.write_all(resp.as_bytes());
        let _ = stream.flush();
        req
    });
    (format!("http://{addr}/oauth/token"), handle)
}

#[cfg(test)]
pub(crate) fn assert_login_token_post(req: &str, json: bool) {
    assert!(
        !req.starts_with("NO_REQUEST"),
        "token endpoint was not called"
    );
    let headers = req.split_once("\r\n\r\n").map(|(h, _)| h).unwrap_or(req);
    let content_type = headers
        .lines()
        .find_map(|line| {
            let (name, value) = line.split_once(':')?;
            name.eq_ignore_ascii_case("content-type")
                .then(|| value.trim().to_ascii_lowercase())
        })
        .unwrap_or_default();
    if json {
        assert!(
            content_type.starts_with("application/json"),
            "expected JSON content-type, got: {req}"
        );
        assert!(
            !content_type.contains("application/x-www-form-urlencoded"),
            "json profile posted a form body, got: {req}"
        );
    } else {
        assert!(
            content_type.starts_with("application/x-www-form-urlencoded"),
            "expected form content-type, got: {req}"
        );
    }
    let header_present = headers.lines().any(|line| {
        let Some((name, value)) = line.split_once(':') else {
            return false;
        };
        name.eq_ignore_ascii_case("x-client") && value.trim() == "official-app"
    });
    assert!(header_present, "token header missing, got: {req}");
}

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

    #[test]
    fn is_oauth_transport_error_matches_send_prefix_only() {
        assert!(is_oauth_transport_error(&AuthError::TokenProvider(
            "token refresh request failed (connect) via https://auth.example.invalid".into(),
        )));
        assert!(is_oauth_transport_error(&AuthError::TokenProvider(
            "token request failed (connect) via https://oauth2.googleapis.com".into(),
        )));
        assert!(is_oauth_transport_error(&AuthError::TokenProvider(
            "failed to read OAuth response body (transport) via https://auth.example.invalid"
                .into(),
        )));
        assert!(!is_oauth_transport_error(&AuthError::TokenProvider(
            "token refresh: invalid JSON: expected value".into(),
        )));
        assert!(!is_oauth_transport_error(&AuthError::TokenProvider(
            "OAuth response body too large (Content-Length: 9 bytes, max 8)".into(),
        )));
        assert!(!is_oauth_transport_error(&AuthError::EmptyWriteRefused));
    }

    #[cfg(feature = "net")]
    #[test]
    fn oauth_connect_timeout_is_shorter_than_request_timeout() {
        assert!(OAUTH_CONNECT_TIMEOUT <= Duration::from_secs(5));
        assert!(OAUTH_CONNECT_TIMEOUT < OAUTH_REQUEST_TIMEOUT);
    }

    #[test]
    fn sanitize_drops_raw_tokens() {
        let body = r#"{"error":"invalid_grant","refresh_token":"rt-LEAK","access_token":"sk-ant-oat01-LEAK","error_description":"revoked sk-ant-oat01-LEAK"}"#;
        let summary = sanitize_oauth_error_body(body);
        assert!(!summary.contains("sk-ant-oat01-LEAK"));
        assert!(!summary.contains("rt-LEAK"));
        assert!(summary.contains("invalid_grant"));
    }

    #[test]
    fn redact_secret_looking_strips_github_pats() {
        let text = redact_secret_looking("paste ghp_ENVSUBST_LEAK_TOKEN_51 into the vendor CLI");
        assert!(!text.contains("ghp_ENVSUBST_LEAK_TOKEN_51"), "{text}");
        assert!(text.contains("[redacted]"), "{text}");
        assert!(text.contains("paste"), "{text}");
    }

    #[test]
    fn redact_url_origin_drops_userinfo_path_and_query() {
        let redacted = redact_url_origin(
            "https://user:s3cret@auth.example.invalid/oauth/token?client_secret=supersecret#frag",
        );
        assert_eq!(redacted, "https://auth.example.invalid");
        assert!(!redacted.contains("s3cret"));
        assert!(!redacted.contains("supersecret"));
        assert!(!redacted.contains("/oauth"));
    }

    #[test]
    fn redact_url_origin_strips_percent_encoded_userinfo() {
        let once = redact_url_origin("https://user:s3cret%40api.example.invalid/v1");
        assert_eq!(once, "https://api.example.invalid");
        assert!(!once.contains("s3cret"), "{once}");

        let twice = redact_url_origin("https://user:s3cret%2540api.example.invalid:8443/v1");
        assert_eq!(twice, "https://api.example.invalid:8443");
        assert!(!twice.contains("s3cret"), "{twice}");

        let thrice = redact_url_origin("https://user:s3cret%252540api.example.invalid/v1");
        assert_eq!(thrice, "https://api.example.invalid");
        assert!(!thrice.contains("s3cret"), "{thrice}");

        let encoded_dot = redact_url_origin("https://api%2Eexample.com/v1");
        assert_eq!(encoded_dot, "https://api%2Eexample.com");

        let ipv6 = redact_url_origin("https://user:s3cret%40[::1]/v1");
        assert_eq!(ipv6, "https://[::1]");
        assert!(!ipv6.contains("s3cret"), "{ipv6}");

        let last = redact_url_origin("https://user:name%40extra:s3cret%40host.example/v1");
        assert_eq!(last, "https://host.example");
        assert!(!last.contains("s3cret"), "{last}");

        let no_scheme = redact_url_origin("user:s3cret%40api.example.invalid/v1");
        assert_eq!(no_scheme, "api.example.invalid");
        assert!(!no_scheme.contains("s3cret"), "{no_scheme}");

        let with_query = redact_url_origin(
            "https://user:s3cret%40api.example.invalid/v1?client_secret=s3cret#frag",
        );
        assert_eq!(with_query, "https://api.example.invalid");
        assert!(!with_query.contains("s3cret"), "{with_query}");
        assert!(!with_query.contains('?'), "{with_query}");
        assert!(!with_query.contains('#'), "{with_query}");

        let raw_last = redact_url_origin("https://user@name:s3cret@host.example/v1");
        assert_eq!(raw_last, "https://host.example");
        assert!(!raw_last.contains("s3cret"), "{raw_last}");

        let lossy = redact_url_origin("https://user:s3cret%40%ff/v1");
        assert!(!lossy.contains("s3cret"), "{lossy}");
        assert_eq!(lossy, "https://\u{FFFD}");
        let lossy_upper = redact_url_origin("https://user:s3cret%40%FF/v1");
        assert!(!lossy_upper.contains("s3cret"), "{lossy_upper}");
        assert_eq!(lossy_upper, "https://\u{FFFD}");

        // Decoding userinfo must not restore a query or path secret.
        let encoded_query =
            redact_url_origin("https://user:s3cret%40api.example.invalid%3Ftoken%3Ds3cret");
        assert_eq!(encoded_query, "https://api.example.invalid");
        assert!(!encoded_query.contains("s3cret"), "{encoded_query}");

        let encoded_path =
            redact_url_origin("https://user:s3cret%40api.example.invalid%2Fv1%2Fsecret-path");
        assert_eq!(encoded_path, "https://api.example.invalid");
        assert!(!encoded_path.contains("secret-path"), "{encoded_path}");

        let twice_query = redact_url_origin(
            "https://user:s3cret%2540api.example.invalid:8443%253Ftoken%253Ds3cret",
        );
        assert_eq!(twice_query, "https://api.example.invalid:8443");
        assert!(!twice_query.contains("s3cret"), "{twice_query}");
    }

    #[test]
    fn format_oauth_transport_error_redacts_userinfo_and_client_secret() {
        let msg = format_oauth_transport_via(
            "auth code exchange failed",
            "connect",
            "https://user:s3cret@auth.example.invalid/oauth/token?client_secret=supersecret",
        );
        assert!(
            msg.contains("via https://auth.example.invalid"),
            "transport error must name the redacted origin, got {msg}"
        );
        assert!(!msg.contains("s3cret"), "{msg}");
        assert!(!msg.contains("client_secret="), "{msg}");
        assert!(!msg.contains("supersecret"), "{msg}");
        assert!(!msg.contains("user:"), "{msg}");
        assert!(!msg.contains("/oauth"), "{msg}");
    }

    #[test]
    fn format_oauth_transport_error_upstream_stream_is_origin_only() {
        let msg = format_oauth_transport_via(
            "upstream stream",
            "transport",
            "https://user:s3cret@api.example.invalid/v1/stream?token=ghp_ENVSUBST_LEAK_TOKEN_51",
        );
        assert!(
            msg.contains("upstream stream"),
            "SSE transport error must keep the stream context, got {msg}"
        );
        assert!(
            msg.contains("via https://api.example.invalid"),
            "SSE transport error must name the redacted origin, got {msg}"
        );
        assert!(!msg.contains("s3cret"), "{msg}");
        assert!(!msg.contains("user:"), "{msg}");
        assert!(!msg.contains("ghp_ENVSUBST_LEAK_TOKEN_51"), "{msg}");
        assert!(!msg.contains("/v1/stream"), "{msg}");
        assert!(!msg.contains("token="), "{msg}");
    }

    #[test]
    fn vendor_rejected_summary_omits_http_status() {
        let summary = vendor_rejected_summary(
            "Azure token request failed",
            r#"{"error":"invalid_client"}"#,
            "https://login.microsoftonline.com/t/oauth2/v2.0/token",
        );
        assert!(
            !summary.contains("HTTP"),
            "summary must not re-wrap HTTP status, got {summary}"
        );
        assert!(summary.contains("invalid_client"), "{summary}");
        assert!(summary.contains("login.microsoftonline.com"), "{summary}");
        let xml = vendor_rejected_summary(
            "STS AssumeRole failed",
            "<ErrorResponse><Error><Code>AccessDenied</Code></Error></ErrorResponse>",
            "https://sts.amazonaws.com/",
        );
        assert!(!xml.contains("HTTP"), "{xml}");
        assert!(xml.contains("AssumeRole"), "{xml}");
    }

    #[test]
    fn format_oauth_http_error_includes_redacted_host() {
        let msg = format_oauth_http_error(
            "token refresh failed",
            401,
            r#"{"error":"invalid_grant"}"#,
            "https://user:s3cret@auth.example.invalid/oauth/token?client_secret=supersecret",
        );
        assert!(
            msg.contains("via https://auth.example.invalid"),
            "HTTP error must name the redacted origin, got {msg}"
        );
        assert!(!msg.contains("s3cret"), "{msg}");
        assert!(!msg.contains("supersecret"), "{msg}");
        assert!(!msg.contains("/oauth"), "{msg}");
        let fallback = format_oauth_http_error(
            "token refresh failed",
            404,
            "",
            "https://fallback.example.invalid/v1/oauth/token",
        );
        assert!(
            fallback.contains("via https://fallback.example.invalid"),
            "fallback host must be distinguishable, got {fallback}"
        );
    }

    #[test]
    fn percent_encode_reserved() {
        assert_eq!(percent_encode("a b"), "a%20b");
        assert_eq!(percent_encode("ok-._~"), "ok-._~");
    }

    #[test]
    fn blank_home_does_not_expand_tilde_to_a_relative_path() {
        let _home = crate::isolated_home::IsolatedHome::new();
        // SAFETY: IsolatedHome holds HOME_TEST_LOCK for this test.
        unsafe {
            std::env::set_var("HOME", "");
            std::env::set_var("USERPROFILE", "");
        }
        assert!(home_dir().is_none());
        assert_eq!(expand_tilde("~/foo"), PathBuf::from("~/foo"));
        let err = resolve_creds_path("~/foo").unwrap_err();
        assert!(
            err.to_string().contains("under home"),
            "blank HOME must not accept a tilde path, got {err}"
        );
    }

    #[test]
    fn expand_tilde_uses_home() {
        let prev = std::env::var_os("HOME");
        // IsolatedHome owns HOME in other tests; this unit test only
        // checks the join, not process-global isolation.
        let expanded = expand_tilde("~/foo/bar");
        if let Some(home) = home_dir() {
            assert_eq!(expanded, home.join("foo/bar"));
        }
        drop(prev);
    }

    #[test]
    fn jail_accepts_canonical_path_when_home_is_a_symlink() {
        let home = crate::isolated_home::IsolatedHome::new();
        let planted = home.plant_credentials(crate::isolated_home::PlantCredentials::JsonPointer {
            relative_path: ".config/github-copilot/hosts.json",
            document: serde_json::json!({"github.com": {"oauth_token": "ghu"}}),
        });
        let canon = std::fs::canonicalize(&planted).expect("canonicalize planted");
        jail_creds_path(&planted).expect("logical plant path");
        jail_creds_path(&canon).expect("canonical path under IsolatedHome");
        let missing = home.path().join(".claude/.credentials.json");
        jail_creds_path(&missing).expect("missing file still under IsolatedHome");
    }

    #[cfg(unix)]
    #[test]
    fn jail_rejects_parent_symlink_out_of_home() {
        let home = crate::isolated_home::IsolatedHome::new();
        let outside = tempfile::tempdir().expect("outside home");
        let link = home.path().join("out");
        std::os::unix::fs::symlink(outside.path(), &link).expect("symlink out of home");
        let stolen = home.path().join("out/stolen.json");
        jail_creds_path(&stolen).expect_err("creds_path must stay under home");

        let ok_dir = home.path().join("ok");
        std::fs::create_dir_all(&ok_dir).expect("mkdir ok");
        let missing = ok_dir.join("missing.json");
        jail_creds_path(&missing).expect("missing file under a real in-home dir");
    }
}