grit-lib 0.5.18

Core library for the grit Git implementation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
//! Default [`HttpClient`] backed by `ureq` (feature `http-ureq`).
//!
//! This is the batteries-included client for embedders who do not want to wire
//! their own HTTP stack. It lifts the core request path from the CLI's
//! `http_client.rs` — a blocking [`ureq::Agent`], the `Git-Protocol` /
//! `User-Agent` / `Content-Type` / `Accept` headers, and reading the response
//! body into a `Vec<u8>` — and adds optional HTTP basic auth driven by a
//! [`CredentialProvider`]: on a `401` it parses `WWW-Authenticate`, fills a
//! credential, and retries once, then `approve`/`reject`s the credential per the
//! retry status (Git's `credential_approve` / `credential_reject`).
//!
//! When authentication is required but cannot be satisfied — no provider wired,
//! the provider cannot supply a usable username/password, an unsupported auth
//! scheme, or rejected credentials — the request fails with the typed
//! [`Error::Auth`] (never a hang), so embedders can detect an auth failure and
//! fall back (e.g. to an interactive/subprocess path) without string-matching.
//!
//! ## Proxy, cookies, and extra headers (config-driven)
//!
//! [`UreqHttpClient::from_config`] reads the Git HTTP config that controls
//! request shaping, lifted from the CLI's `http_client.rs`:
//!
//! * **Proxy** — `http.proxy` (or the `HTTPS_PROXY` / `HTTP_PROXY` / `ALL_PROXY`
//!   environment, honored by `ureq` itself) routes requests through an HTTP(S)
//!   proxy via [`ureq::Proxy`]. `http://user:pass@host:port` proxy auth is
//!   forwarded by `ureq`.
//! * **Cookies** — `http.cookieFile` is parsed (Netscape and `Set-Cookie:`
//!   formats) and a matching `Cookie:` header is sent on each request; with
//!   `http.saveCookies=true` any `Set-Cookie` from the response is appended back
//!   to the file. Lifts `cookie_header_for_url` / `save_response_cookies`.
//! * **Extra headers** — `http.extraHeader` (optionally URL-scoped via
//!   `http.<url>.extraHeader`) adds arbitrary request headers; an empty value
//!   resets the accumulated list, matching Git. Lifts `extra_headers_for_url`.
//!
//! Deliberately omitted vs. the CLI client (and noted for parity): the
//! absolute-form-through-proxy `HttpForward` path and the SOCKS-over-Unix tunnel
//! (`socks*://localhost/path.sock`) — `ureq`'s built-in SOCKS support is not
//! compiled in here, so a SOCKS proxy URL is rejected with a clear error rather
//! than silently mishandled. Also omitted: custom CA bundles, gzip request
//! bodies, and the `GIT_ASKPASS` / `GIT_TRACE_CURL` plumbing. Embedders that need
//! those should implement [`HttpClient`] over their own stack.

use std::env;
use std::io::{self, Read};
use std::path::PathBuf;
use std::sync::Mutex;
use std::time::{Duration, Instant};

use base64::Engine;

use crate::config::{self, parse_i64, ConfigSet};
use crate::credentials::{self, Credential, CredentialProvider};
use crate::error::{Error, Result};
use crate::protocol::client_git_protocol_header_from_config;
use crate::transport_path::redact_url_for_display;

fn url_for_display(url: &str) -> String {
    redact_url_for_display(url)
}

fn auth_error(url: &str, detail: impl std::fmt::Display) -> Error {
    Error::Auth(format!("{}: {}", url_for_display(url), detail))
}

use super::{
    effective_info_refs_url_after_redirect, http_origin_key, http_origins_match, HttpClient,
};

/// A blocking [`ureq`]-backed [`HttpClient`].
///
/// Build with [`UreqHttpClient::new`] for an unauthenticated client, or
/// [`UreqHttpClient::with_credentials`] to wire a [`CredentialProvider`] for
/// HTTP basic auth on `401`. A default `Git-Protocol` header can be set via
/// [`UreqHttpClient::with_git_protocol`]. To honor `http.proxy`,
/// `http.cookieFile`, and `http.extraHeader`, build from a loaded [`ConfigSet`]
/// with [`UreqHttpClient::from_config`].
#[derive(Clone, Debug)]
struct CachedAuthHeader {
    header: String,
    origin: String,
}

/// `UreqHttpClient` struct.
pub struct UreqHttpClient {
    agent: ureq::Agent,
    user_agent: String,
    git_protocol: Option<String>,
    credentials: Option<Box<dyn CredentialProvider + Send + Sync>>,
    /// Cached `Authorization: Basic …` header and the origin it is valid for.
    cached_auth: Mutex<Option<CachedAuthHeader>>,
    /// Origin of the first HTTP request in this session; host-only cookies without
    /// a `Domain` attribute are sent only on this origin.
    hostonly_cookie_scope: Mutex<Option<String>>,
    /// Parsed cookies (from `http.cookieFile`), sent as a `Cookie:` header on
    /// matching URLs. Empty when no cookie file was configured.
    cookies: Vec<CookieSpec>,
    /// The cookie file path (for `http.saveCookies` persistence), if configured.
    cookie_file_path: Option<PathBuf>,
    /// Whether to append `Set-Cookie` response headers back to the cookie file
    /// (`http.saveCookies=true`, only meaningful with a cookie file).
    save_cookies: bool,
    /// Configured `http.extraHeader` rules (optionally URL-scoped).
    extra_headers: Vec<ExtraHeaderRule>,
    /// Merged Git config used for credential URL matching.
    credential_config: ConfigSet,
    /// HTTP read timeouts and low-speed abort thresholds (`http.*` config).
    transport_timeouts: HttpTransportTimeouts,
}

impl UreqHttpClient {
    /// A client with default timeouts and no credential provider.
    #[must_use]
    pub fn new() -> Self {
        Self::with_agent(default_agent(None))
    }

    fn with_agent(agent: ureq::Agent) -> Self {
        Self {
            agent,
            user_agent: default_user_agent(),
            git_protocol: None,
            credentials: None,
            cached_auth: Mutex::new(None),
            hostonly_cookie_scope: Mutex::new(None),
            cookies: Vec::new(),
            cookie_file_path: None,
            save_cookies: false,
            extra_headers: Vec::new(),
            credential_config: ConfigSet::default(),
            transport_timeouts: HttpTransportTimeouts::default(),
        }
    }

    /// A client that uses `provider` to fill HTTP basic-auth credentials when
    /// the server returns `401 Unauthorized`.
    #[must_use]
    pub fn with_credentials(provider: Box<dyn CredentialProvider + Send + Sync>) -> Self {
        let mut c = Self::new();
        c.credentials = Some(provider);
        c
    }

    /// Build a client from merged Git config, honoring the request-shaping HTTP
    /// settings: `http.proxy` (HTTP/HTTPS proxy), `http.cookieFile` +
    /// `http.saveCookies` (cookie jar), and `http.extraHeader` (custom request
    /// headers), `protocol.version` (default `Git-Protocol` header), and
    /// `http.timeout` / low-speed limits for response-body reads.
    ///
    /// # Errors
    ///
    /// Returns an error if `http.proxy` names a proxy scheme that this client
    /// cannot honor (e.g. a SOCKS proxy, which `ureq`'s built-in SOCKS support is
    /// not compiled in for here), `protocol.version` is invalid, or the cookie
    /// file cannot be read.
    pub fn from_config(config: &ConfigSet) -> Result<Self> {
        let proxy = build_proxy(config)?;
        let transport_timeouts = HttpTransportTimeouts::from_config(config);
        let agent = agent_from_timeouts(proxy, &transport_timeouts);
        let mut client = Self::with_agent(agent);

        if let Some(header) = client_git_protocol_header_from_config(config)? {
            client.git_protocol = Some(header);
        }
        client.transport_timeouts = transport_timeouts;

        // Cookies: parse the cookie file (if any) and decide whether to persist.
        client.cookie_file_path = config
            .get("http.cookieFile")
            .map(|v| v.trim().to_string())
            .filter(|v| !v.is_empty())
            .map(PathBuf::from);
        client.cookies = build_cookie_specs(client.cookie_file_path.as_deref())?;
        client.save_cookies = client.cookie_file_path.is_some()
            && config
                .get_bool("http.saveCookies")
                .and_then(std::result::Result::ok)
                .unwrap_or(false);

        // Extra headers (`http.extraHeader`, optionally URL-scoped).
        client.extra_headers = extra_header_rules_from_config(config);
        client.credential_config = config.clone();

        Ok(client)
    }

    /// Wire a [`CredentialProvider`] for HTTP basic auth on `401` (consuming
    /// self), so a [`from_config`](UreqHttpClient::from_config)-built client can
    /// also authenticate.
    #[must_use]
    pub fn with_credential_provider(
        mut self,
        provider: Box<dyn CredentialProvider + Send + Sync>,
    ) -> Self {
        self.credentials = Some(provider);
        self
    }

    /// Set a default `Git-Protocol` request-header value (e.g. `version=2`).
    #[must_use]
    pub fn with_git_protocol(mut self, value: impl Into<String>) -> Self {
        self.git_protocol = Some(value.into());
        self
    }

    /// Override the `User-Agent` header.
    #[must_use]
    pub fn with_user_agent(mut self, ua: impl Into<String>) -> Self {
        self.user_agent = ua.into();
        self
    }

    fn cached_auth_header_for_url(&self, url: &str) -> Option<String> {
        let origin = http_origin_key(url)?;
        let guard = self.cached_auth.lock().ok()?;
        guard
            .as_ref()
            .filter(|entry| entry.origin == origin)
            .map(|entry| entry.header.clone())
    }

    fn store_auth_header(&self, header: String, url: &str) {
        if let Some(origin) = http_origin_key(url) {
            if let Ok(mut g) = self.cached_auth.lock() {
                *g = Some(CachedAuthHeader { header, origin });
            }
        }
    }

    fn clear_auth_header(&self) {
        if let Ok(mut g) = self.cached_auth.lock() {
            *g = None;
        }
    }

    /// Seed cached basic auth for a URL origin (integration tests only).
    #[doc(hidden)]
    pub fn seed_cached_basic_auth(&self, url: &str, username: &str, password: &str) {
        use base64::Engine as _;
        let encoded =
            base64::engine::general_purpose::STANDARD.encode(format!("{username}:{password}"));
        self.store_auth_header(format!("Basic {encoded}"), url);
    }

    fn hostonly_cookie_scope_for_url(&self, url: &str) -> Option<String> {
        let origin = http_origin_key(url)?;
        let mut guard = self.hostonly_cookie_scope.lock().ok()?;
        if guard.is_none() {
            *guard = Some(origin.clone());
        }
        guard.clone()
    }

    fn invalidate_auth_on_cross_origin_redirect(&self, request_url: &str, final_url: &str) {
        if !http_origins_match(request_url, final_url) {
            self.clear_auth_header();
        }
    }

    /// The `Cookie:` header value to send for `url`, or `None` when no cookie
    /// matches. Lifts the CLI's `cookie_header_for_url`.
    fn cookie_header_for_url(&self, url: &str) -> Option<String> {
        if self.cookies.is_empty() {
            return None;
        }
        let scope = self.hostonly_cookie_scope_for_url(url);
        let parsed = url::Url::parse(url).ok();
        let parts = self
            .cookies
            .iter()
            .filter(|cookie| cookie.matches_url(parsed.as_ref(), scope.as_deref()))
            .map(|cookie| cookie.name_value.clone())
            .collect::<Vec<_>>();
        (!parts.is_empty()).then(|| parts.join("; "))
    }

    /// The ordered `(name, value)` extra headers to send for `url`. Lifts the
    /// CLI's `extra_headers_for_url`: an unscoped rule always applies, a
    /// URL-scoped rule applies on a URL-match, and an empty value resets the
    /// accumulated list (Git's `http.extraHeader=` reset).
    fn extra_headers_for_url(&self, url: &str) -> Vec<(String, String)> {
        let mut headers = Vec::new();
        for rule in &self.extra_headers {
            let matches = rule
                .pattern
                .as_deref()
                .is_none_or(|pattern| config::url_matches(pattern, url));
            if !matches {
                continue;
            }
            match &rule.header {
                Some(header) => headers.push(header.clone()),
                None => headers.clear(),
            }
        }
        headers
    }

    /// Persist any `Set-Cookie` from a response back to the cookie file
    /// (`http.saveCookies`). Lifts the CLI's `save_response_cookies`: appends one
    /// `Set-Cookie: <value>` line per cookie, in Git's cookie-file format.
    fn save_response_cookies(&self, set_cookies: &[String]) {
        if !self.save_cookies {
            return;
        }
        let Some(path) = self.cookie_file_path.as_ref() else {
            return;
        };
        let values: Vec<&str> = set_cookies
            .iter()
            .map(|v| v.trim())
            .filter(|v| !v.is_empty())
            .collect();
        if values.is_empty() {
            return;
        }
        if let Some(parent) = path.parent() {
            let _ = std::fs::create_dir_all(parent);
        }
        if let Ok(mut file) = std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(path)
        {
            use std::io::Write as _;
            for value in values {
                let _ = writeln!(file, "Set-Cookie: {value}");
            }
        }
    }
}

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

/// A raw HTTP response captured from ureq (success or error status).
struct RawResponse {
    status: u16,
    www_authenticate: Vec<String>,
    set_cookie: Vec<String>,
    body: Vec<u8>,
    /// The final URL after any redirects ureq followed (from `Response::get_url`).
    final_url: String,
}

fn default_user_agent() -> String {
    format!("grit-lib/{}", env!("CARGO_PKG_VERSION"))
}

/// Git-shaped HTTP timeouts and optional low-speed abort thresholds (`http.*` config).
#[derive(Clone, Debug)]
struct HttpTransportTimeouts {
    connect: Duration,
    /// Whole-request ceiling (`http.timeout`, Git default 600s; `None` when disabled).
    global: Option<Duration>,
    low_speed: Option<LowSpeedSettings>,
}

#[derive(Clone, Copy, Debug)]
struct LowSpeedSettings {
    bytes_per_second: u64,
    window: Duration,
}

impl Default for HttpTransportTimeouts {
    fn default() -> Self {
        Self {
            connect: Duration::from_secs(30),
            global: Some(Duration::from_secs(600)),
            low_speed: None,
        }
    }
}

impl HttpTransportTimeouts {
    fn from_config(config: &ConfigSet) -> Self {
        let global = config
            .get("http.timeout")
            .as_deref()
            .and_then(|v| parse_i64(v).ok())
            .map(|secs| {
                if secs <= 0 {
                    None
                } else {
                    Some(Duration::from_secs(secs as u64))
                }
            })
            .unwrap_or(Some(Duration::from_secs(600)));

        Self {
            connect: Duration::from_secs(30),
            global,
            low_speed: parse_low_speed(config),
        }
    }
}

fn parse_low_speed(config: &ConfigSet) -> Option<LowSpeedSettings> {
    let limit = crate::environment::Environment::empty()
        .var("GIT_HTTP_LOW_SPEED_LIMIT")
        .and_then(|v| parse_i64(v.trim()).ok())
        .or_else(|| {
            config
                .get("http.lowSpeedLimit")
                .and_then(|v| parse_i64(v.trim()).ok())
        });
    let time_secs = crate::environment::Environment::empty()
        .var("GIT_HTTP_LOW_SPEED_TIME")
        .and_then(|v| parse_i64(v.trim()).ok())
        .or_else(|| {
            config
                .get("http.lowSpeedTime")
                .and_then(|v| parse_i64(v.trim()).ok())
        });

    match (limit, time_secs) {
        (Some(lim), Some(secs)) if lim > 0 && secs > 0 => Some(LowSpeedSettings {
            bytes_per_second: lim as u64,
            window: Duration::from_secs(secs as u64),
        }),
        _ => None,
    }
}

/// Wraps a reader to abort when average throughput stays below the configured bytes/sec
/// for the configured window, mirroring curl `LOW_SPEED_LIMIT` / `LOW_SPEED_TIME`.
struct LowSpeedReader<R> {
    inner: R,
    settings: Option<LowSpeedSettings>,
    window_start: Instant,
    window_bytes: u64,
    global_deadline: Option<Instant>,
}

impl<R: Read> LowSpeedReader<R> {
    fn new(inner: R, timeouts: &HttpTransportTimeouts) -> Self {
        let global_deadline = timeouts.global.and_then(|g| Instant::now().checked_add(g));
        Self {
            inner,
            settings: timeouts.low_speed,
            window_start: Instant::now(),
            window_bytes: 0,
            global_deadline,
        }
    }

    fn check_global(&self) -> io::Result<()> {
        if let Some(deadline) = self.global_deadline {
            if Instant::now() >= deadline {
                return Err(io::Error::new(
                    io::ErrorKind::TimedOut,
                    "HTTP transfer exceeded http.timeout",
                ));
            }
        }
        Ok(())
    }

    fn finish_window(&mut self) -> io::Result<()> {
        let Some(settings) = self.settings else {
            self.window_start = Instant::now();
            self.window_bytes = 0;
            return Ok(());
        };
        let elapsed = self.window_start.elapsed();
        if elapsed < settings.window {
            return Ok(());
        }
        let secs = elapsed.as_secs_f64();
        if secs <= 0.0 {
            self.window_start = Instant::now();
            self.window_bytes = 0;
            return Ok(());
        }
        let rate = self.window_bytes as f64 / secs;
        if rate < settings.bytes_per_second as f64 {
            return Err(io::Error::new(
                io::ErrorKind::TimedOut,
                "HTTP transfer speed below http.lowSpeedLimit for http.lowSpeedTime",
            ));
        }
        self.window_start = Instant::now();
        self.window_bytes = 0;
        Ok(())
    }
}

impl<R: Read> Read for LowSpeedReader<R> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        if self.settings.is_some() || self.global_deadline.is_some() {
            self.check_global()?;
            self.finish_window()?;
        }
        let n = self.inner.read(buf)?;
        if n > 0 && self.settings.is_some() {
            self.window_bytes += n as u64;
            self.finish_window()?;
        }
        Ok(n)
    }
}

/// Build a [`ureq::Agent`] with default Git-shaped timeouts and an optional proxy.
fn default_agent(proxy: Option<ureq::Proxy>) -> ureq::Agent {
    agent_from_timeouts(proxy, &HttpTransportTimeouts::default())
}

fn agent_tls_config() -> ureq::tls::TlsConfig {
    #[cfg(feature = "http-ureq-native-tls")]
    {
        use ureq::tls::{RootCerts, TlsConfig, TlsProvider};
        TlsConfig::builder()
            .provider(TlsProvider::NativeTls)
            .root_certs(RootCerts::PlatformVerifier)
            .build()
    }
    #[cfg(not(feature = "http-ureq-native-tls"))]
    {
        use ureq::tls::{TlsConfig, TlsProvider};
        TlsConfig::builder().provider(TlsProvider::Rustls).build()
    }
}

fn agent_from_timeouts(
    proxy: Option<ureq::Proxy>,
    timeouts: &HttpTransportTimeouts,
) -> ureq::Agent {
    ureq::Agent::config_builder()
        .timeout_connect(Some(timeouts.connect))
        .timeout_global(timeouts.global)
        // Return >= 400 responses as `Ok` so the auth-retry logic can inspect the
        // status and `WWW-Authenticate` headers rather than treating them as hard
        // transport errors (ureq's default surfaces them as `Error::StatusCode`).
        .http_status_as_error(false)
        .tls_config(agent_tls_config())
        .proxy(proxy)
        .build()
        .new_agent()
}

/// Resolve `http.proxy` into a [`ureq::Proxy`], or `None` for the direct path.
///
/// `ureq` itself honors the `HTTPS_PROXY` / `HTTP_PROXY` / `ALL_PROXY`
/// environment when no explicit proxy is set on the agent, so we only build a
/// proxy object for the explicit `http.proxy` config. SOCKS proxies (and the
/// `socks*://localhost/path.sock` Unix-socket form) are rejected here: `ureq`'s
/// SOCKS support is not compiled in for this build, so honoring them would
/// silently fail at request time — fail loudly instead. Lifts the relevant parts
/// of the CLI's `build_transport` / `build_transport_from_proxy`.
fn build_proxy(config: &ConfigSet) -> Result<Option<ureq::Proxy>> {
    let Some(raw) = config.get("http.proxy") else {
        return Ok(None);
    };
    let raw = raw.trim();
    if raw.is_empty() {
        // An empty `http.proxy` disables proxying (Git's "no proxy" override);
        // do NOT fall back to the environment.
        return Ok(None);
    }
    let with_scheme = if raw.contains("://") {
        raw.to_string()
    } else {
        format!("http://{raw}")
    };
    let scheme = with_scheme
        .split_once("://")
        .map(|(s, _)| s.to_ascii_lowercase())
        .unwrap_or_default();
    if scheme.starts_with("socks") {
        return Err(Error::Message(format!(
            "http.proxy '{raw}': SOCKS proxies are not supported by the default ureq HTTP client; \
             implement a custom HttpClient or use an HTTP proxy"
        )));
    }
    if scheme != "http" && scheme != "https" {
        return Err(Error::Message(format!(
            "http.proxy '{raw}': unsupported proxy scheme '{scheme}'"
        )));
    }
    let proxy = ureq::Proxy::new(&with_scheme)
        .map_err(|e| Error::Message(format!("invalid http.proxy '{raw}': {e}")))?;
    Ok(Some(proxy))
}

/// Decompose a request URL into a target [`Credential`].
///
/// Git omits the path from HTTP credentials unless `credential.useHttpPath`
/// applies. That lets a host-level token stored for `https://github.com` satisfy
/// requests to any repository on that host, which is how helpers such as macOS
/// `osxkeychain` are normally populated.
fn credential_for_url(url: &str, config: &ConfigSet) -> Option<Credential> {
    let parsed = url::Url::parse(url).ok()?;
    let protocol = parsed.scheme().to_string();
    let host = parsed.host_str()?.to_string();
    let host = if let Some(port) = parsed.port() {
        format!("{host}:{port}")
    } else {
        host
    };
    let path = credentials::use_http_path(config, Some(url))
        .then(|| parsed.path().trim_start_matches('/').to_string())
        .filter(|path| !path.is_empty());
    Some(Credential {
        protocol: Some(protocol),
        host: Some(host),
        path,
        url: Some(url.to_string()),
        ..Default::default()
    })
}

/// Build the `Authorization: Basic …` header value for `cred`.
fn basic_auth_header(cred: &Credential) -> Option<String> {
    let user = cred.username.as_deref()?;
    let pass = cred.password.as_deref().unwrap_or("");
    let raw = format!("{user}:{pass}");
    let encoded = base64::engine::general_purpose::STANDARD.encode(raw.as_bytes());
    Some(format!("Basic {encoded}"))
}

/// True when the server's `WWW-Authenticate` challenges include a Basic scheme
/// (or none at all — be permissive and try basic).
fn offers_basic(challenges: &[String]) -> bool {
    challenges.is_empty()
        || challenges
            .iter()
            .any(|c| c.trim_start().to_ascii_lowercase().starts_with("basic"))
}

/// Resolve the `Git-Protocol` header for one request.
///
/// * `caller == None` — use the client's configured default (if any).
/// * `caller == Some("")` — omit the header (classic v0); do not fall back to the default.
/// * `caller == Some(v)` — send `Git-Protocol: v`.
fn resolve_git_protocol_header<'a>(
    caller: Option<&'a str>,
    client_default: Option<&'a str>,
) -> Option<&'a str> {
    match caller {
        None => client_default,
        Some("") => None,
        Some(v) => Some(v),
    }
}

impl UreqHttpClient {
    fn do_get(
        &self,
        url: &str,
        git_protocol: Option<&str>,
        auth: Option<&str>,
    ) -> Result<RawResponse> {
        let result = retry_interrupted(true, || {
            let mut req = self.agent.get(url).header("User-Agent", &self.user_agent);
            if let Some(v) = resolve_git_protocol_header(git_protocol, self.git_protocol.as_deref())
            {
                req = req.header("Git-Protocol", v);
            }
            if let Some(a) = auth {
                req = req.header("Authorization", a);
            }
            if let Some(cookie) = self.cookie_header_for_url(url) {
                req = req.header("Cookie", &cookie);
            }
            for (name, value) in self.extra_headers_for_url(url) {
                req = req.header(&name, &value);
            }
            req.call()
        });
        finish(result, &self.transport_timeouts)
    }

    fn do_post_open(
        &self,
        url: &str,
        content_type: &str,
        accept: &str,
        body: &[u8],
        git_protocol: Option<&str>,
        auth: Option<&str>,
    ) -> Result<(RawResponseHead, LowSpeedReader<Box<dyn Read + Send>>)> {
        let idempotent = content_type == "application/x-git-upload-pack-request";
        let result = retry_interrupted(idempotent, || {
            let mut req = self
                .agent
                .post(url)
                .header("Content-Type", content_type)
                .header("Accept", accept)
                .header("User-Agent", &self.user_agent);
            if let Some(v) = resolve_git_protocol_header(git_protocol, self.git_protocol.as_deref())
            {
                req = req.header("Git-Protocol", v);
            }
            if let Some(a) = auth {
                req = req.header("Authorization", a);
            }
            if let Some(cookie) = self.cookie_header_for_url(url) {
                req = req.header("Cookie", &cookie);
            }
            for (name, value) in self.extra_headers_for_url(url) {
                req = req.header(&name, &value);
            }
            req.send(body)
        });
        match result {
            Ok(resp) => open_response_body(resp, &self.transport_timeouts),
            Err(e) => Err(http_transport_error(&e)),
        }
    }

    fn do_post(
        &self,
        url: &str,
        content_type: &str,
        accept: &str,
        body: &[u8],
        git_protocol: Option<&str>,
        auth: Option<&str>,
    ) -> Result<RawResponse> {
        // A fetch negotiation request only reads from the server, so it is safe to resend; a
        // push (receive-pack) request is not.
        let idempotent = content_type == "application/x-git-upload-pack-request";
        let result = retry_interrupted(idempotent, || {
            let mut req = self
                .agent
                .post(url)
                .header("Content-Type", content_type)
                .header("Accept", accept)
                .header("User-Agent", &self.user_agent);
            if let Some(v) = resolve_git_protocol_header(git_protocol, self.git_protocol.as_deref())
            {
                req = req.header("Git-Protocol", v);
            }
            if let Some(a) = auth {
                req = req.header("Authorization", a);
            }
            if let Some(cookie) = self.cookie_header_for_url(url) {
                req = req.header("Cookie", &cookie);
            }
            for (name, value) in self.extra_headers_for_url(url) {
                req = req.header(&name, &value);
            }
            req.send(body)
        });
        finish(result, &self.transport_timeouts)
    }

    fn with_auth_retry_post_stream(
        &self,
        url: &str,
        content_type: &str,
        accept: &str,
        body: &[u8],
        git_protocol: Option<&str>,
    ) -> Result<LowSpeedReader<Box<dyn Read + Send>>> {
        let initial_auth = self.cached_auth_header_for_url(url);
        let (head, reader) = self.do_post_open(
            url,
            content_type,
            accept,
            body,
            git_protocol,
            initial_auth.as_deref(),
        )?;
        if head.status != 401 {
            self.invalidate_auth_on_cross_origin_redirect(url, &head.final_url);
            self.save_response_cookies(&head.set_cookie);
            if head.status >= 400 {
                drain_response_body(reader);
                return Err(http_status_error(url, head.status));
            }
            return Ok(reader);
        }
        drain_response_body(reader);
        let Some(provider) = self.credentials.as_ref() else {
            self.clear_auth_header();
            return Err(auth_error(
                url,
                "server requires authentication (401) but no credential provider is configured",
            ));
        };
        if !offers_basic(&head.www_authenticate) {
            return Err(auth_error(
                url,
                format!(
                    "server requires an unsupported auth scheme: {:?}",
                    head.www_authenticate
                ),
            ));
        }
        let auth_url = effective_info_refs_url_after_redirect(url, Some(head.final_url.as_str()));
        let Some(input) = credential_for_url(&auth_url, &self.credential_config) else {
            return Err(auth_error(
                &auth_url,
                "server requires authentication (401) but the URL could not be decomposed into credential fields",
            ));
        };
        let cred = provider
            .fill(&input)
            .map_err(|e| auth_error(&auth_url, format!("could not obtain credentials: {e}")))?;
        let Some(header) = basic_auth_header(&cred) else {
            return Err(auth_error(
                &auth_url,
                "credential helper returned no usable username/password",
            ));
        };
        let (retry_head, retry_reader) =
            self.do_post_open(url, content_type, accept, body, git_protocol, Some(&header))?;
        if retry_head.status == 401 {
            let _ = provider.reject(&cred);
            self.clear_auth_header();
            drain_response_body(retry_reader);
            return Err(auth_error(url, "supplied credentials were rejected (401)"));
        }
        if retry_head.status >= 400 {
            let _ = provider.reject(&cred);
            self.clear_auth_header();
            drain_response_body(retry_reader);
            return Err(http_status_error(url, retry_head.status));
        }
        let _ = provider.approve(&cred);
        if http_origins_match(&auth_url, &retry_head.final_url) {
            self.store_auth_header(header, &auth_url);
        } else {
            self.clear_auth_header();
        }
        self.save_response_cookies(&retry_head.set_cookie);
        Ok(retry_reader)
    }

    /// Run `attempt` (a GET or POST closure) with auth-retry on 401, returning
    /// the response body and the final URL after any followed redirects.
    fn with_auth_retry<F>(&self, url: &str, attempt: F) -> Result<(Vec<u8>, String)>
    where
        F: Fn(&str, Option<&str>) -> Result<RawResponse>,
    {
        let initial_auth = self.cached_auth_header_for_url(url);
        let first = attempt(url, initial_auth.as_deref())?;
        if first.status != 401 {
            self.invalidate_auth_on_cross_origin_redirect(url, &first.final_url);
            self.save_response_cookies(&first.set_cookie);
            return finalize_status(url, first.status, first.body, first.final_url);
        }
        // 401: need credentials. Without a provider, surface a typed auth error
        // (so embedders can detect it and e.g. fall back to a subprocess path)
        // rather than a generic message — and never block.
        let Some(provider) = self.credentials.as_ref() else {
            self.clear_auth_header();
            return Err(auth_error(
                url,
                "server requires authentication (401) but no credential provider is configured",
            ));
        };
        if !offers_basic(&first.www_authenticate) {
            return Err(auth_error(
                url,
                format!(
                    "server requires an unsupported auth scheme: {:?}",
                    first.www_authenticate
                ),
            ));
        }
        let auth_url = effective_info_refs_url_after_redirect(url, Some(first.final_url.as_str()));
        let Some(input) = credential_for_url(&auth_url, &self.credential_config) else {
            return Err(auth_error(
                &auth_url,
                "server requires authentication (401) but the URL could not be decomposed into credential fields",
            ));
        };
        // A provider that cannot supply a credential (no configured helper, or a
        // non-interactive failure) reports it as a typed auth error rather than a
        // generic message, and crucially never blocks on a TTY.
        let cred = provider
            .fill(&input)
            .map_err(|e| auth_error(&auth_url, format!("could not obtain credentials: {e}")))?;
        let Some(header) = basic_auth_header(&cred) else {
            return Err(auth_error(
                &auth_url,
                "credential helper returned no usable username/password",
            ));
        };
        let retry = attempt(&auth_url, Some(&header))?;
        if retry.status == 401 {
            // Credentials were supplied but rejected: erase them and surface a
            // typed auth error.
            let _ = provider.reject(&cred);
            self.clear_auth_header();
            return Err(auth_error(url, "supplied credentials were rejected (401)"));
        }
        if retry.status >= 400 {
            let _ = provider.reject(&cred);
            self.clear_auth_header();
            return Err(http_status_error(url, retry.status));
        }
        // Success: approve + cache the working auth header for this origin only.
        let _ = provider.approve(&cred);
        if http_origins_match(&auth_url, &retry.final_url) {
            self.store_auth_header(header, &auth_url);
        } else {
            self.clear_auth_header();
        }
        self.save_response_cookies(&retry.set_cookie);
        Ok((retry.body, retry.final_url))
    }
}

impl HttpClient for UreqHttpClient {
    fn get(&self, url: &str, git_protocol: Option<&str>) -> Result<Vec<u8>> {
        self.with_auth_retry(url, |target, auth| self.do_get(target, git_protocol, auth))
            .map(|(body, _)| body)
    }

    fn post(
        &self,
        url: &str,
        content_type: &str,
        accept: &str,
        body: &[u8],
        git_protocol: Option<&str>,
    ) -> Result<Vec<u8>> {
        self.with_auth_retry(url, |target, auth| {
            self.do_post(target, content_type, accept, body, git_protocol, auth)
        })
        .map(|(body, _)| body)
    }

    fn post_into_reader(
        &self,
        url: &str,
        content_type: &str,
        accept: &str,
        body: &[u8],
        git_protocol: Option<&str>,
    ) -> Result<Box<dyn Read + Send>> {
        Ok(Box::new(self.with_auth_retry_post_stream(
            url,
            content_type,
            accept,
            body,
            git_protocol,
        )?))
    }

    fn get_with_final_url(
        &self,
        url: &str,
        git_protocol: Option<&str>,
    ) -> Result<(Vec<u8>, Option<String>)> {
        self.with_auth_retry(url, |target, auth| self.do_get(target, git_protocol, auth))
            .map(|(body, final_url)| (body, Some(final_url)))
    }

    fn get_with_final_url_exact(
        &self,
        url: &str,
        git_protocol: Option<&str>,
    ) -> Result<(Vec<u8>, Option<String>)> {
        self.with_auth_retry(url, |target, auth| self.do_get(target, git_protocol, auth))
            .map(|(body, final_url)| (body, Some(final_url)))
    }

    fn git_protocol_header(&self) -> Option<&str> {
        self.git_protocol.as_deref()
    }

    fn reset_auth_after_redirect_rebase(&self) {
        self.clear_auth_header();
    }
}

/// Attempts made for an idempotent request whose socket call fails with `EINTR`.
const INTERRUPTED_ATTEMPTS: usize = 3;

/// Run `send`, resending it when a socket call was interrupted by a signal (`EINTR`) and the
/// request is `idempotent`. `EINTR` means "try again", not a transport failure.
fn retry_interrupted<T>(
    idempotent: bool,
    mut send: impl FnMut() -> std::result::Result<T, ureq::Error>,
) -> std::result::Result<T, ureq::Error> {
    let attempts = if idempotent { INTERRUPTED_ATTEMPTS } else { 1 };
    let mut result = send();
    for _ in 1..attempts {
        match &result {
            Err(ureq::Error::Io(e)) if e.kind() == std::io::ErrorKind::Interrupted => {
                result = send();
            }
            _ => break,
        }
    }
    result
}

/// Convert a ureq call result into a [`RawResponse`], reading the body.
///
/// The agent is configured with `http_status_as_error(false)`, so >= 400
/// responses arrive as `Ok` and are mapped into a `RawResponse` (letting the
/// auth-retry logic inspect the status and `WWW-Authenticate` headers rather
/// than treating them as hard errors). Only genuine transport failures are `Err`.
fn finish(
    result: std::result::Result<ureq::http::Response<ureq::Body>, ureq::Error>,
    timeouts: &HttpTransportTimeouts,
) -> Result<RawResponse> {
    match result {
        Ok(resp) => read_response(resp, timeouts),
        Err(e) => Err(http_transport_error(&e)),
    }
}

fn read_response(
    resp: ureq::http::Response<ureq::Body>,
    timeouts: &HttpTransportTimeouts,
) -> Result<RawResponse> {
    let (head, mut reader) = open_response_body(resp, timeouts)?;
    let mut body = Vec::new();
    reader.read_to_end(&mut body).map_err(Error::Io)?;
    Ok(RawResponse {
        status: head.status,
        www_authenticate: head.www_authenticate,
        set_cookie: head.set_cookie,
        body,
        final_url: head.final_url,
    })
}

/// Response metadata without buffering the body.
struct RawResponseHead {
    status: u16,
    www_authenticate: Vec<String>,
    set_cookie: Vec<String>,
    final_url: String,
}

fn open_response_body(
    resp: ureq::http::Response<ureq::Body>,
    timeouts: &HttpTransportTimeouts,
) -> Result<(RawResponseHead, LowSpeedReader<Box<dyn Read + Send>>)> {
    use ureq::ResponseExt as _;
    let status = resp.status().as_u16();
    let final_url = resp.get_uri().to_string();
    let www_authenticate = header_values(resp.headers(), "WWW-Authenticate");
    let set_cookie = header_values(resp.headers(), "Set-Cookie");
    let reader = resp.into_body().into_reader();
    // Side-band demux already reads in 1 MiB chunks; skip an extra BufReader layer
    // so large clone receives do not copy through two full buffers.
    Ok((
        RawResponseHead {
            status,
            www_authenticate,
            set_cookie,
            final_url,
        },
        LowSpeedReader::new(Box::new(reader) as Box<dyn Read + Send>, timeouts),
    ))
}

fn drain_response_body(mut reader: LowSpeedReader<Box<dyn Read + Send>>) {
    let _ = crate::pack_receive::copy_reader_to_writer(&mut reader, &mut io::sink());
}

/// Collect all values for a header as owned UTF-8 strings (skipping any that
/// aren't valid UTF-8).
fn header_values(headers: &ureq::http::HeaderMap, name: &str) -> Vec<String> {
    headers
        .get_all(name)
        .iter()
        .filter_map(|value| value.to_str().ok())
        .map(ToOwned::to_owned)
        .collect()
}

fn finalize_status(
    url: &str,
    status: u16,
    body: Vec<u8>,
    final_url: String,
) -> Result<(Vec<u8>, String)> {
    if status >= 400 {
        return Err(http_status_error(url, status));
    }
    Ok((body, final_url))
}

fn http_transport_error(err: impl std::fmt::Display) -> Error {
    let msg = credentials::redact_embedded_url_credentials(&err.to_string());
    Error::Message(format!("http transport error: {msg}"))
}

fn http_status_error(url: &str, status: u16) -> Error {
    Error::Message(format!("HTTP {status} from {}", url_for_display(url)))
}

// ---------------------------------------------------------------------------
// Extra headers (`http.extraHeader`) — lifted from the CLI's http_client.rs.
// ---------------------------------------------------------------------------

/// One `http.extraHeader` rule: an optional URL scope (the config subsection),
/// and the header to add (or `None` for an empty value, which resets the list).
#[derive(Clone)]
struct ExtraHeaderRule {
    pattern: Option<String>,
    header: Option<(String, String)>,
}

/// Collect `http.extraHeader` (and `http.<url>.extraHeader`) rules in config
/// order. Lifts the CLI's `extra_header_rules_from_config`.
fn extra_header_rules_from_config(config: &ConfigSet) -> Vec<ExtraHeaderRule> {
    let mut rules = Vec::new();
    for entry in config.entries() {
        let Some((pattern, variable)) = parse_http_config_key(&entry.key) else {
            continue;
        };
        if !variable.eq_ignore_ascii_case("extraheader") {
            continue;
        }
        let pattern = pattern.map(ToOwned::to_owned);
        let Some(raw) = entry.value.as_deref() else {
            rules.push(ExtraHeaderRule {
                pattern,
                header: None,
            });
            continue;
        };
        if raw.trim().is_empty() {
            rules.push(ExtraHeaderRule {
                pattern,
                header: None,
            });
            continue;
        }
        if let Some((name, value)) = raw.split_once(':') {
            let name = name.trim();
            if !name.is_empty() {
                rules.push(ExtraHeaderRule {
                    pattern,
                    header: Some((name.to_string(), value.trim_start().to_string())),
                });
            }
        }
    }
    rules
}

/// Split an `http[.<subsection>].<variable>` config key into `(subsection,
/// variable)`. Lifts the CLI's `parse_http_config_key`.
fn parse_http_config_key(key: &str) -> Option<(Option<&str>, &str)> {
    let first_dot = key.find('.')?;
    let section = &key[..first_dot];
    if !section.eq_ignore_ascii_case("http") {
        return None;
    }
    let rest = &key[first_dot + 1..];
    if let Some(last_dot) = rest.rfind('.') {
        let subsection = &rest[..last_dot];
        let variable = &rest[last_dot + 1..];
        if subsection.is_empty() || variable.is_empty() {
            None
        } else {
            Some((Some(subsection), variable))
        }
    } else if rest.is_empty() {
        None
    } else {
        Some((None, rest))
    }
}

// ---------------------------------------------------------------------------
// Cookies (`http.cookieFile` / `http.saveCookies`) — lifted from http_client.rs.
// ---------------------------------------------------------------------------

/// A single parsed cookie that may be sent on matching requests.
#[derive(Clone, Debug)]
struct CookieSpec {
    name_value: String,
    domain: Option<String>,
    include_subdomains: bool,
    path: Option<String>,
    secure: bool,
    expires_at: Option<i64>,
    host_only_origin: Option<String>,
}

impl CookieSpec {
    /// Whether this cookie should be sent on a request to `url`. Lifts the CLI's
    /// `CookieSpec::matches_url`: honors expiry, `secure` (https-only), the
    /// domain (with optional subdomain inclusion), and the path prefix.
    fn matches_url(&self, url: Option<&url::Url>, hostonly_scope: Option<&str>) -> bool {
        if self.is_expired() {
            return false;
        }
        let Some(url) = url else {
            return false;
        };
        if self.secure && url.scheme() != "https" {
            return false;
        }
        if self.domain.is_none() {
            let bind = self.host_only_origin.as_deref().or(hostonly_scope);
            if let Some(origin) = bind {
                if !http_origins_match(origin, url.as_str()) {
                    return false;
                }
            }
        } else if let Some(domain) = self.domain.as_deref() {
            let Some(host) = url.host_str() else {
                return false;
            };
            if self.include_subdomains {
                if host != domain && !host.ends_with(&format!(".{domain}")) {
                    return false;
                }
            } else if host != domain {
                return false;
            }
        }
        if let Some(path) = self.path.as_deref() {
            if !url.path().starts_with(path) {
                return false;
            }
        }
        true
    }

    fn is_expired(&self) -> bool {
        self.expires_at
            .is_some_and(|expiry| time::OffsetDateTime::now_utc().unix_timestamp() >= expiry)
    }
}

/// Parse the configured cookie file into [`CookieSpec`]s. Lifts the CLI's
/// `build_cookie_specs` / `read_cookie_file_lines`.
fn build_cookie_specs(path: Option<&std::path::Path>) -> Result<Vec<CookieSpec>> {
    let Some(path) = path else {
        return Ok(Vec::new());
    };
    if !path.exists() {
        return Ok(Vec::new());
    }
    let data = std::fs::read_to_string(path)
        .map_err(|e| Error::Message(format!("read cookie file '{}': {e}", path.display())))?;
    let mut out = Vec::new();
    for line in data.lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() || trimmed.starts_with('#') {
            continue;
        }
        if let Some(spec) = parse_cookie_spec(trimmed) {
            out.push(spec);
        }
    }
    Ok(out)
}

fn parse_cookie_spec(line: &str) -> Option<CookieSpec> {
    parse_netscape_cookie(line).or_else(|| parse_header_cookie(line))
}

/// Parse a tab-separated Netscape `cookies.txt` line. Lifts the CLI's
/// `parse_netscape_cookie`.
fn parse_netscape_cookie(line: &str) -> Option<CookieSpec> {
    let cols: Vec<&str> = line.split('\t').collect();
    if cols.len() < 7 {
        return None;
    }
    let domain = cols[0].trim().trim_start_matches('.').to_ascii_lowercase();
    if domain.is_empty() {
        return None;
    }
    let include_subdomains =
        cols[1].trim().eq_ignore_ascii_case("TRUE") || cols[0].starts_with('.');
    let path = cols[2].trim();
    let secure = cols[3].trim().eq_ignore_ascii_case("TRUE");
    let expires_at = cols[4].trim().parse::<i64>().ok().filter(|v| *v > 0);
    let name = cols[5].trim();
    let value = cols[6].trim();
    if name.is_empty() {
        return None;
    }
    Some(CookieSpec {
        name_value: format!("{name}={value}"),
        domain: Some(domain),
        include_subdomains,
        path: (!path.is_empty()).then(|| path.to_string()),
        secure,
        expires_at,
        host_only_origin: None,
    })
}

/// Parse a `Set-Cookie:`-style header line. Lifts the CLI's `parse_header_cookie`.
fn parse_header_cookie(line: &str) -> Option<CookieSpec> {
    let raw = line
        .strip_prefix("Set-Cookie:")
        .or_else(|| line.strip_prefix("set-cookie:"))
        .unwrap_or(line)
        .trim();
    let mut parts = raw.split(';').map(str::trim);
    let name_value = parts.next()?.to_string();
    if !name_value.contains('=') {
        return None;
    }
    let mut cookie = CookieSpec {
        name_value,
        domain: None,
        include_subdomains: false,
        path: None,
        secure: false,
        expires_at: None,
        host_only_origin: None,
    };
    for attr in parts {
        if attr.eq_ignore_ascii_case("secure") {
            cookie.secure = true;
            continue;
        }
        if let Some((key, value)) = attr.split_once('=') {
            if key.eq_ignore_ascii_case("domain") {
                let domain = value.trim().trim_start_matches('.').to_ascii_lowercase();
                if !domain.is_empty() {
                    cookie.include_subdomains = true;
                    cookie.domain = Some(domain);
                }
            } else if key.eq_ignore_ascii_case("path") {
                let path = value.trim();
                if !path.is_empty() {
                    cookie.path = Some(path.to_string());
                }
            }
        }
    }
    Some(cookie)
}

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

    fn interrupted() -> ureq::Error {
        ureq::Error::Io(std::io::Error::from(std::io::ErrorKind::Interrupted))
    }

    #[test]
    fn idempotent_request_is_resent_after_eintr() {
        let mut calls = 0;
        let result = retry_interrupted(true, || {
            calls += 1;
            if calls < 3 {
                Err(interrupted())
            } else {
                Ok(calls)
            }
        });
        assert_eq!(result.ok(), Some(3));
    }

    #[test]
    fn non_idempotent_request_is_not_resent_after_eintr() {
        let mut calls = 0;
        let result: std::result::Result<(), _> = retry_interrupted(false, || {
            calls += 1;
            Err(interrupted())
        });
        assert!(result.is_err());
        assert_eq!(calls, 1);
    }

    #[test]
    fn other_errors_are_not_retried() {
        let mut calls = 0;
        let result: std::result::Result<(), _> = retry_interrupted(true, || {
            calls += 1;
            Err(ureq::Error::Io(std::io::Error::from(
                std::io::ErrorKind::ConnectionRefused,
            )))
        });
        assert!(result.is_err());
        assert_eq!(calls, 1);
    }

    #[test]
    fn netscape_cookie_parses_and_matches() {
        let line = "example.com\tTRUE\t/\tFALSE\t0\tSID\tabc123";
        let spec = parse_cookie_spec(line).expect("parse netscape cookie");
        assert_eq!(spec.name_value, "SID=abc123");
        let url = url::Url::parse("http://example.com/repo.git/info/refs").unwrap();
        assert!(spec.matches_url(Some(&url), None));
        // Different host does not match.
        let other = url::Url::parse("http://other.test/").unwrap();
        assert!(!spec.matches_url(Some(&other), None));
    }

    #[test]
    fn secure_cookie_only_matches_https() {
        let line = "example.com\tTRUE\t/\tTRUE\t0\tS\tv";
        let spec = parse_cookie_spec(line).expect("parse");
        let http = url::Url::parse("http://example.com/").unwrap();
        let https = url::Url::parse("https://example.com/").unwrap();
        assert!(
            !spec.matches_url(Some(&http), None),
            "secure cookie must skip http"
        );
        assert!(
            spec.matches_url(Some(&https), None),
            "secure cookie matches https"
        );
    }

    #[test]
    fn host_only_cookie_file_cookie_respects_session_origin() {
        let line = "Set-Cookie: Foo=1";
        let spec = parse_cookie_spec(line).expect("parse header cookie");
        let gateway = url::Url::parse("http://127.0.0.1:8001/gateway/repo.git/info/refs").unwrap();
        let target = url::Url::parse("http://127.0.0.1:8002/secure/repo.git/info/refs").unwrap();
        let scope = "http://127.0.0.1:8001";
        assert!(spec.matches_url(Some(&gateway), Some(scope)));
        assert!(!spec.matches_url(Some(&target), Some(scope)));
    }

    #[test]
    fn header_cookie_parses_domain_and_path() {
        let line = "Set-Cookie: token=zzz; Domain=example.com; Path=/git; Secure";
        let spec = parse_cookie_spec(line).expect("parse header cookie");
        assert_eq!(spec.name_value, "token=zzz");
        assert_eq!(spec.domain.as_deref(), Some("example.com"));
        assert_eq!(spec.path.as_deref(), Some("/git"));
        assert!(spec.secure);
        // Subdomain inclusion (Domain attribute set).
        let sub = url::Url::parse("https://api.example.com/git/info/refs").unwrap();
        assert!(spec.matches_url(Some(&sub), None));
        // Path that does not match the prefix is rejected.
        let wrong_path = url::Url::parse("https://example.com/other").unwrap();
        assert!(!spec.matches_url(Some(&wrong_path), None));
    }

    #[test]
    fn expired_cookie_does_not_match() {
        let spec = CookieSpec {
            name_value: "x=1".to_owned(),
            domain: Some("example.com".to_owned()),
            include_subdomains: false,
            path: None,
            secure: false,
            expires_at: Some(1), // 1970 — long expired
            host_only_origin: None,
        };
        let url = url::Url::parse("http://example.com/").unwrap();
        assert!(!spec.matches_url(Some(&url), None));
    }

    #[test]
    fn extra_header_rules_apply_scoped_and_unscoped() {
        let mut cfg = ConfigSet::new();
        cfg.add_command_override("http.extraHeader", "X-Global: g")
            .unwrap();
        cfg.add_command_override("http.https://example.com.extraHeader", "X-Scoped: s")
            .unwrap();
        let client = UreqHttpClient::from_config(&cfg).expect("from_config");
        let scoped = client.extra_headers_for_url("https://example.com/repo.git/info/refs");
        assert!(
            scoped.iter().any(|(n, v)| n == "X-Global" && v == "g"),
            "unscoped header should always apply: {scoped:?}"
        );
        assert!(
            scoped.iter().any(|(n, v)| n == "X-Scoped" && v == "s"),
            "URL-scoped header should apply on match: {scoped:?}"
        );
        // A non-matching URL gets only the global header.
        let off = client.extra_headers_for_url("https://other.test/repo.git/info/refs");
        assert!(off.iter().any(|(n, _)| n == "X-Global"));
        assert!(!off.iter().any(|(n, _)| n == "X-Scoped"));
    }

    #[test]
    fn empty_extra_header_resets_list() {
        let mut cfg = ConfigSet::new();
        cfg.add_command_override("http.extraHeader", "X-One: 1")
            .unwrap();
        cfg.add_command_override("http.extraHeader", "").unwrap();
        cfg.add_command_override("http.extraHeader", "X-Two: 2")
            .unwrap();
        let client = UreqHttpClient::from_config(&cfg).expect("from_config");
        let h = client.extra_headers_for_url("https://example.com/");
        assert!(
            !h.iter().any(|(n, _)| n == "X-One"),
            "empty value must reset earlier headers: {h:?}"
        );
        assert!(h.iter().any(|(n, v)| n == "X-Two" && v == "2"));
    }

    #[test]
    fn socks_proxy_is_rejected_clearly() {
        let mut cfg = ConfigSet::new();
        cfg.add_command_override("http.proxy", "socks5://localhost:1080")
            .unwrap();
        match UreqHttpClient::from_config(&cfg) {
            Ok(_) => panic!("SOCKS proxy must be rejected, not silently accepted"),
            Err(e) => {
                let msg = format!("{e}");
                assert!(msg.contains("SOCKS"), "expected a clear SOCKS error: {msg}");
            }
        }
    }

    #[test]
    fn http_proxy_config_builds() {
        let mut cfg = ConfigSet::new();
        cfg.add_command_override("http.proxy", "http://127.0.0.1:3128")
            .unwrap();
        // Building a client with an HTTP proxy must succeed (it just configures
        // the ureq agent; no connection is attempted here).
        UreqHttpClient::from_config(&cfg).expect("http proxy config builds");
    }

    #[test]
    fn empty_proxy_disables_proxying() {
        let mut cfg = ConfigSet::new();
        cfg.add_command_override("http.proxy", "").unwrap();
        let proxy = build_proxy(&cfg).expect("empty proxy ok");
        assert!(proxy.is_none(), "empty http.proxy must disable proxying");
    }

    #[test]
    fn credentials_omit_http_path_by_default() {
        let cfg = ConfigSet::new();
        let cred = credential_for_url(
            "https://github.com/owner/repo.git/info/refs?service=git-upload-pack",
            &cfg,
        )
        .expect("credential target");

        assert_eq!(cred.protocol.as_deref(), Some("https"));
        assert_eq!(cred.host.as_deref(), Some("github.com"));
        assert_eq!(cred.path, None);
    }

    #[test]
    fn credentials_include_http_path_when_configured() {
        let mut cfg = ConfigSet::new();
        cfg.add_command_override("credential.useHttpPath", "true")
            .unwrap();
        let cred = credential_for_url(
            "https://github.com/owner/repo.git/info/refs?service=git-upload-pack",
            &cfg,
        )
        .expect("credential target");

        assert_eq!(cred.path.as_deref(), Some("owner/repo.git/info/refs"));
    }

    #[test]
    fn credentials_include_http_path_when_url_scoped() {
        let mut cfg = ConfigSet::new();
        cfg.add_command_override("credential.https://github.com/owner.useHttpPath", "true")
            .unwrap();
        let matching = credential_for_url(
            "https://github.com/owner/repo.git/info/refs?service=git-upload-pack",
            &cfg,
        )
        .expect("credential target");
        let other = credential_for_url(
            "https://github.com/elsewhere/repo.git/info/refs?service=git-upload-pack",
            &cfg,
        )
        .expect("credential target");

        assert_eq!(matching.path.as_deref(), Some("owner/repo.git/info/refs"));
        assert_eq!(other.path, None);
    }

    #[test]
    fn from_config_rejects_invalid_protocol_version() {
        let mut cfg = ConfigSet::new();
        cfg.add_command_override("protocol.version", "bogus")
            .expect("override");
        match UreqHttpClient::from_config(&cfg) {
            Ok(_) => panic!("invalid protocol.version must be rejected"),
            Err(err) => assert!(
                matches!(err, Error::Config(_)),
                "expected ConfigError, got {err:?}"
            ),
        }
    }

    #[test]
    fn from_config_applies_protocol_version_header() {
        let mut cfg = ConfigSet::new();
        cfg.add_command_override("protocol.version", "2")
            .expect("override");
        let client = UreqHttpClient::from_config(&cfg).expect("from_config");
        assert_eq!(
            client.git_protocol.as_deref(),
            Some("version=2"),
            "protocol.version=2 should set Git-Protocol header"
        );
    }

    #[cfg(feature = "http-ureq-native-tls")]
    #[test]
    fn agent_tls_provider_is_native_when_native_tls_feature_enabled() {
        use ureq::tls::TlsProvider;

        let agent = super::agent_from_timeouts(None, &HttpTransportTimeouts::default());
        assert_eq!(
            agent.config().tls_config().provider(),
            TlsProvider::NativeTls,
            "http-ureq-native-tls must select ureq NativeTls (Secure Transport on macOS)"
        );
    }

    #[cfg(all(feature = "http-ureq", not(feature = "http-ureq-native-tls")))]
    #[test]
    fn agent_tls_provider_is_rustls_without_native_tls_feature() {
        use ureq::tls::TlsProvider;

        let agent = super::agent_from_timeouts(None, &HttpTransportTimeouts::default());
        assert_eq!(agent.config().tls_config().provider(), TlsProvider::Rustls);
    }

    #[test]
    fn low_speed_reader_propagates_body_read_io_errors() {
        struct EofRead;
        impl Read for EofRead {
            fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> {
                Err(io::Error::new(
                    io::ErrorKind::UnexpectedEof,
                    "failed to fill whole buffer",
                ))
            }
        }
        let mut reader = LowSpeedReader::new(EofRead, &HttpTransportTimeouts::default());
        let err = reader
            .read_to_end(&mut Vec::new())
            .expect_err("unexpected eof");
        assert_eq!(err.kind(), io::ErrorKind::UnexpectedEof);
    }

    #[test]
    fn low_speed_reader_aborts_stalled_body_read() {
        struct BytePerSecond(u8);
        impl Read for BytePerSecond {
            fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
                std::thread::sleep(Duration::from_millis(50));
                let n = buf.len().min(self.0 as usize);
                buf[..n].fill(0);
                Ok(n)
            }
        }
        let timeouts = HttpTransportTimeouts {
            connect: Duration::from_secs(30),
            global: Some(Duration::from_secs(600)),
            low_speed: Some(LowSpeedSettings {
                bytes_per_second: 100,
                window: Duration::from_millis(200),
            }),
        };
        let mut reader = LowSpeedReader::new(BytePerSecond(1), &timeouts);
        let mut sink = Vec::new();
        let err = reader
            .read_to_end(&mut sink)
            .expect_err("slow read should abort");
        assert_eq!(err.kind(), io::ErrorKind::TimedOut);
    }

    #[test]
    fn http_status_error_omits_url_credentials() {
        let url =
            "https://x-access-token:SECRET@github.com/o/r.git/info/refs?service=git-upload-pack";
        let err = super::http_status_error(url, 404);
        let msg = format!("{err}");
        assert!(msg.contains("HTTP 404 from https://github.com/o/r.git"));
        assert!(!msg.contains("SECRET"));
        assert!(!msg.contains("x-access-token"));
    }

    #[test]
    fn http_status_error_preserves_at_in_path() {
        let url = "http://user:pass@127.0.0.1:9/org/repo@v1.git/info/refs?service=git-upload-pack";
        let err = super::http_status_error(url, 404);
        let msg = format!("{err}");
        assert!(msg.contains("org/repo@v1.git"));
        assert!(!msg.contains("user:pass"));
    }
}