atlassian-cli-api 0.9.3

API client library for Atlassian Cloud products
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
pub mod error;
pub mod pagination;
pub mod ratelimit;
pub mod retry;

use backoff::backoff::Backoff;
use error::{ApiError, Result};
use ratelimit::RateLimiter;
use reqwest::header::HeaderMap;
use reqwest::{Client, Method, RequestBuilder, StatusCode};
use retry::{retry_with_backoff, RetryConfig};
use secrecy::{ExposeSecret, SecretString};
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::fmt;
use std::time::Duration;
use tracing::{debug, error, warn};
use url::Url;

#[derive(Clone)]
pub enum AuthMethod {
    Basic {
        username: String,
        token: SecretString,
    },
    Bearer {
        token: SecretString,
    },
    GenieKey {
        api_key: SecretString,
    },
}

impl fmt::Debug for AuthMethod {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AuthMethod::Basic { username, .. } => f
                .debug_struct("Basic")
                .field("username", username)
                .field("token", &"[REDACTED]")
                .finish(),
            AuthMethod::Bearer { .. } => f
                .debug_struct("Bearer")
                .field("token", &"[REDACTED]")
                .finish(),
            AuthMethod::GenieKey { .. } => f
                .debug_struct("GenieKey")
                .field("api_key", &"[REDACTED]")
                .finish(),
        }
    }
}

/// Compare two URLs by full origin: scheme, host **and port**.
///
/// Port matters. Comparing scheme and host alone lets `https://site:8443/x`
/// through on a `https://site` profile, and on a localhost profile it lets any
/// other local port receive the profile's credentials.
fn same_origin(a: &Url, b: &Url) -> bool {
    a.scheme() == b.scheme()
        && a.host() == b.host()
        && a.port_or_known_default() == b.port_or_known_default()
}

/// Make a base URL end with `/`.
///
/// `Url::join` drops the base's last path segment unless the base ends with
/// `/`. Idempotent.
pub fn normalize_base_url(mut url: Url) -> Url {
    if url.cannot_be_a_base() {
        return url;
    }

    let path = url.path();
    if !path.ends_with('/') {
        url.set_path(&format!("{path}/"));
    }
    url
}

/// What a 401 says when the server offered no explanation of its own.
const UNAUTHORIZED_FALLBACK: &str = "Invalid or expired credentials";

/// Keep a quoted server message short enough to stay readable on one screen.
const MAX_DETAIL_LEN: usize = 200;

/// Build the error for a 401, keeping whatever reason the server gave.
///
/// Atlassian's gateway explains *why* it rejected the call, for example
/// `{"code":401,"message":"Unauthorized; scope does not match"}`. Reporting
/// every 401 as "Invalid or expired credentials" hid that, so a token missing
/// one scope looked identical to an expired one and sent people re-issuing
/// credentials that were fine all along.
async fn unauthorized_error(response: reqwest::Response) -> ApiError {
    let body = response.text().await.unwrap_or_default();
    ApiError::AuthenticationFailed {
        message: unauthorized_message(&body),
    }
}

/// Combine the generic 401 wording with the server's own message, if any.
fn unauthorized_message(body: &str) -> String {
    match unauthorized_detail(body) {
        Some(detail) => format!("{UNAUTHORIZED_FALLBACK} ({detail})"),
        None => UNAUTHORIZED_FALLBACK.to_string(),
    }
}

/// Pull the human-readable reason out of a 401 body.
///
/// Returns `None` when the body is empty or is an HTML error page, since a
/// login page's markup tells the user nothing.
fn unauthorized_detail(body: &str) -> Option<String> {
    let trimmed = body.trim();
    if trimmed.is_empty() || trimmed.starts_with('<') {
        return None;
    }

    let detail = serde_json::from_str::<serde_json::Value>(trimmed)
        .ok()
        .and_then(|value| json_error_detail(&value))
        .unwrap_or_else(|| trimmed.to_string());

    let detail = detail.trim();
    if detail.is_empty() {
        return None;
    }
    Some(truncate_detail(&scrub_credentials(detail)))
}

/// Find the message field, across the several shapes Atlassian returns.
fn json_error_detail(value: &serde_json::Value) -> Option<String> {
    let direct = ["message", "error_description", "error"]
        .iter()
        .find_map(|key| value.get(*key).and_then(|v| v.as_str()))
        .map(str::to_string);

    direct
        // `{"error": {"message": "..."}}`, which some Atlassian services and
        // most proxies in front of them return. Without this the whole JSON
        // document ends up quoted at the user as though it were prose.
        .or_else(|| {
            value
                .get("error")
                .and_then(|e| e.get("message").or_else(|| e.get("description")))
                .and_then(|v| v.as_str())
                .map(str::to_string)
        })
        // Jira classic instead returns `{"errorMessages": [...]}`.
        .or_else(|| {
            value
                .get("errorMessages")
                .and_then(|v| v.as_array())
                .map(|messages| {
                    messages
                        .iter()
                        .filter_map(|m| m.as_str())
                        .collect::<Vec<_>>()
                        .join("; ")
                })
        })
        .map(|detail| detail.trim().to_string())
        .filter(|detail| !detail.is_empty())
}

/// Replace credential-shaped substrings with a placeholder.
///
/// When a body has no field we recognise we quote it whole, and a gateway or
/// proxy that echoes the request back would then put an `Authorization` value
/// on the user's terminal, into their shell history and into any CI log
/// scraping stderr. Tokens are `SecretString` everywhere else precisely so they
/// cannot leak by accident; this closes the one path that bypasses that.
///
/// It looks for the two auth schemes this client sends and drops what follows,
/// but only when that looks like a credential rather than a word: "Basic auth
/// is not allowed" is a sentence a server really sends, and mangling it into
/// "Basic <redacted> is not allowed" would destroy the message to protect
/// nothing. See `is_credential_shaped`.
fn scrub_credentials(detail: &str) -> String {
    const SCHEMES: [&str; 2] = ["bearer ", "basic "];

    // ASCII-lowercase, so byte offsets stay valid in the original. A full
    // `to_lowercase` can change a string's length and desync the indices.
    let haystack = detail.to_ascii_lowercase();

    let mut out = String::with_capacity(detail.len());
    let mut cursor = 0;

    while cursor < detail.len() {
        let found = SCHEMES
            .iter()
            .filter_map(|scheme| {
                haystack[cursor..]
                    .find(scheme)
                    .map(|at| (cursor + at, *scheme))
            })
            .min_by_key(|(at, _)| *at);

        let Some((at, scheme)) = found else {
            out.push_str(&detail[cursor..]);
            break;
        };

        let value_start = at + scheme.len();
        out.push_str(&detail[cursor..value_start]);

        let value_end = detail[value_start..]
            .find(|c: char| c.is_whitespace() || matches!(c, '"' | '\'' | ',' | '}' | ']' | ')'))
            .map(|offset| value_start + offset)
            .unwrap_or(detail.len());

        if is_credential_shaped(&detail[value_start..value_end]) {
            out.push_str("<redacted>");
            cursor = value_end;
        } else {
            // Not a credential. Leave it, but step past the scheme word so the
            // scan cannot match it again and loop.
            cursor = value_start;
        }
    }

    out
}

/// Whether the token after an auth scheme is a credential rather than a word.
///
/// Credentials here are base64 or a JWT, so: only characters from that
/// alphabet, and either long enough that no English word reaches it, or
/// carrying one of the punctuation marks base64 and JWTs use and prose does
/// not. "auth" and "authentication" fail both tests; `Zm9vOmJhcg==` and
/// `eyJhbGci....sig` pass on punctuation alone, whatever their length.
fn is_credential_shaped(token: &str) -> bool {
    const MIN_OPAQUE_LEN: usize = 16;

    if token.len() < 4 {
        return false;
    }
    if !token
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '/' | '=' | '.' | '_' | '-'))
    {
        return false;
    }

    token.len() >= MIN_OPAQUE_LEN || token.contains(['+', '/', '=', '.'])
}

/// Shorten on a char boundary, so multi-byte text cannot panic the slice.
fn truncate_detail(detail: &str) -> String {
    if detail.chars().count() <= MAX_DETAIL_LEN {
        return detail.to_string();
    }
    let short: String = detail.chars().take(MAX_DETAIL_LEN).collect();
    format!("{short}...")
}

/// The `Retry-After` delay in seconds, when the server sent one. The HTTP-date
/// form is ignored; Atlassian sends seconds.
fn retry_after(response: &reqwest::Response) -> Option<Duration> {
    response
        .headers()
        .get(reqwest::header::RETRY_AFTER)?
        .to_str()
        .ok()?
        .trim()
        .parse::<u64>()
        .ok()
        .map(Duration::from_secs)
}

/// An arbitrary request for [`ApiClient::request_raw`].
pub struct RawRequest<'a> {
    pub method: Method,
    /// Path (and optional query) relative to the client's base URL.
    pub path: &'a str,
    pub headers: HeaderMap,
    pub body: Option<&'a [u8]>,
    /// Overrides the client-wide 30s timeout for this request only.
    pub timeout: Option<Duration>,
}

/// A response with no status-to-error mapping applied.
#[derive(Debug, Clone)]
pub struct RawResponse {
    pub status: u16,
    pub headers: Vec<(String, String)>,
    pub body: Vec<u8>,
}

impl RawResponse {
    pub fn is_success(&self) -> bool {
        (200..300).contains(&self.status)
    }

    /// Case-insensitive header lookup. Returns the first match.
    pub fn header(&self, name: &str) -> Option<&str> {
        self.headers
            .iter()
            .find(|(key, _)| key.eq_ignore_ascii_case(name))
            .map(|(_, value)| value.as_str())
    }
}

#[derive(Clone)]
pub struct ApiClient {
    client: Client,
    /// Same-origin-only redirect policy; used by `request_raw`.
    raw_client: Client,
    base_url: Url,
    auth: Option<AuthMethod>,
    retry_config: RetryConfig,
    rate_limiter: RateLimiter,
}

/// Refuse a request path that the URL parser would restructure.
///
/// Every command builds its path with `format!`, so keeping them safe has meant
/// each call site remembering to encode what it interpolates. That discipline
/// failed repeatedly, and roughly forty interpolation sites across Jira, JSM and
/// Opsgenie have never been audited at all. So the check lives here, at the one
/// point every request passes through.
///
/// **Derived from what the parser does, not from a list of characters.** The
/// first version of this function compared segments against the literal strings
/// `"."` and `".."`, which missed `%2e%2e` — verified to resolve to the parent
/// against the `url` version in the lockfile. The WHATWG parser percent-decodes
/// a segment *once* before deciding whether it is a dot segment, so this does
/// the same. That also gets the negative case right: `%252e%252e` decodes to
/// the literal `%2e%2e`, is not a dot segment, and is correctly allowed —
/// verified, it does not traverse.
///
/// Rejected in the path portion:
///
/// - any segment that percent-decodes to `.` or `..`;
/// - a backslash, which the parser treats as a separator;
/// - a control character, which the parser strips *before* parsing, so
///   `.<TAB>.` becomes `..`;
/// - a space, which the parser strips from the ends of the input, so a trailing
///   one silently addresses the collection.
///
/// The query is exempt: JQL and CQL legitimately contain dots, spaces and `..`
/// ranges, and a query cannot move the request to another resource. A caller
/// needing any of these literally in a path must percent-encode it, which is
/// what `encode_path_segment` in the CLI does.
fn reject_restructuring_path(path: &str) -> Result<()> {
    let restructured = |reason: &str| {
        debug!(
            path,
            reason, "Refusing a path the URL parser would restructure"
        );
        ApiError::InvalidUrl(url::ParseError::InvalidDomainCharacter)
    };

    // A `#` anywhere is refused before the split, not exempted by it. A
    // fragment is never sent on the wire, so an interpolated value containing
    // one silently truncates the path: a repository slug of `r#x` turns
    // `DELETE .../hooks/{uuid}` into `DELETE /2.0/repositories/w/r`. No path
    // this CLI builds contains a literal `#`, so refusing it costs nothing and
    // closes the whole class centrally, rather than one call site at a time.
    if path.contains('#') {
        return Err(restructured("fragment marker truncates the path"));
    }

    // Everything below concerns the path; a query may legitimately contain a
    // dot, a space or a backslash, and cannot move the request elsewhere.
    let path_only = path.split('?').next().unwrap_or(path);

    if path_only.chars().any(|c| c.is_control()) {
        return Err(restructured("control character"));
    }
    if path_only.contains('\\') {
        return Err(restructured("backslash is a path separator"));
    }
    // Only the ends. The parser strips spaces from the ends of the whole input,
    // so a trailing one addresses the collection -- but an interior space is
    // encoded harmlessly, and refusing it broke `bb commit browse` on the
    // ordinary case of a repository file whose name contains a space.
    if path_only.trim_matches(' ') != path_only {
        return Err(restructured("leading or trailing space is stripped"));
    }

    for segment in path_only.split('/') {
        if is_dot_segment(segment) {
            return Err(restructured("dot component"));
        }
    }

    Ok(())
}

/// Whether a raw path segment is a dot segment once decoded.
///
/// Decodes exactly once, because that is what the URL parser does: `%2e%2e` is
/// `..`, while the double-encoded `%252e%252e` is the literal text `%2e%2e` and
/// addresses a real resource.
fn is_dot_segment(segment: &str) -> bool {
    let decoded = decode_once(segment);
    decoded == "." || decoded == ".."
}

/// Value of one ASCII hex digit.
fn hex_value(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,
    }
}

/// Percent-decode a single pass, leaving invalid escapes as written.
fn decode_once(segment: &str) -> String {
    // Read the two hex digits from the bytes, never by slicing the `str`.
    // Slicing panicked on `x-%2é`: byte index 5 lands inside the `é`, so a
    // perfectly ordinary identifier aborted the process before any request.
    let bytes = segment.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'%' && i + 2 < bytes.len() {
            if let (Some(hi), Some(lo)) = (hex_value(bytes[i + 1]), hex_value(bytes[i + 2])) {
                out.push(hi * 16 + lo);
                i += 3;
                continue;
            }
        }
        out.push(bytes[i]);
        i += 1;
    }
    String::from_utf8_lossy(&out).into_owned()
}

impl ApiClient {
    pub fn new(base_url: impl AsRef<str>) -> Result<Self> {
        let url = Url::parse(base_url.as_ref()).map_err(ApiError::InvalidUrl)?;

        // Enforce HTTPS for security (prevent accidental credential leaks over HTTP)
        // Allow HTTP only for localhost/127.0.0.1 (for testing)
        if url.scheme() != "https" {
            let is_localhost = url
                .host_str()
                .map(|h| h == "localhost" || h == "127.0.0.1" || h.starts_with("127."))
                .unwrap_or(false);

            if !is_localhost {
                return Err(ApiError::InvalidUrl(
                    url::ParseError::InvalidDomainCharacter,
                ));
            }
        }

        let url = normalize_base_url(url);

        let client = Client::builder()
            .user_agent(format!("atlassian-cli/{}", env!("CARGO_PKG_VERSION")))
            .timeout(Duration::from_secs(30))
            .build()
            .map_err(ApiError::RequestFailed)?;

        // `request_raw` sends user-chosen methods, bodies and headers, so it gets
        // a client that refuses to leave the profile's origin. The default
        // policy would follow a `Location` anywhere: reqwest strips
        // `Authorization` cross-host, but 307/308 replay the body and custom
        // `-H` headers are not stripped. A stopped redirect is returned to the
        // caller as the 3xx itself, which is the transparent answer for a
        // passthrough. The normal `client` keeps following redirects, because
        // attachment downloads depend on the cross-host hop to Atlassian's
        // media host.
        let origin = url.clone();
        let raw_client = Client::builder()
            .user_agent(format!("atlassian-cli/{}", env!("CARGO_PKG_VERSION")))
            .timeout(Duration::from_secs(30))
            .redirect(reqwest::redirect::Policy::custom(move |attempt| {
                if attempt.previous().len() >= 10 {
                    attempt.error("too many redirects")
                } else if same_origin(attempt.url(), &origin) {
                    attempt.follow()
                } else {
                    attempt.stop()
                }
            }))
            .build()
            .map_err(ApiError::RequestFailed)?;

        Ok(Self {
            client,
            raw_client,
            base_url: url,
            auth: None,
            retry_config: RetryConfig::default(),
            rate_limiter: RateLimiter::new(),
        })
    }

    /// Safely join a path to the base URL, ensuring the origin remains unchanged
    /// to prevent SSRF attacks.
    fn safe_join(&self, path: &str) -> Result<Url> {
        reject_restructuring_path(path)?;

        let joined = self
            .base_url
            .join(path.strip_prefix('/').unwrap_or(path))
            .map_err(ApiError::InvalidUrl)?;

        if !same_origin(&joined, &self.base_url) {
            return Err(ApiError::InvalidUrl(
                url::ParseError::InvalidDomainCharacter,
            ));
        }

        Ok(joined)
    }

    pub fn with_basic_auth(
        mut self,
        username: impl Into<String>,
        token: impl Into<String>,
    ) -> Self {
        self.auth = Some(AuthMethod::Basic {
            username: username.into(),
            token: SecretString::from(token.into()),
        });
        self
    }

    pub fn with_bearer_token(mut self, token: impl Into<String>) -> Self {
        self.auth = Some(AuthMethod::Bearer {
            token: SecretString::from(token.into()),
        });
        self
    }

    pub fn with_genie_key(mut self, api_key: impl Into<String>) -> Self {
        self.auth = Some(AuthMethod::GenieKey {
            api_key: SecretString::from(api_key.into()),
        });
        self
    }

    pub fn with_retry_config(mut self, config: RetryConfig) -> Self {
        self.retry_config = config;
        self
    }

    pub fn base_url(&self) -> &str {
        self.base_url.as_str()
    }

    /// Returns a reference to the underlying HTTP client for raw requests (e.g., multipart uploads).
    pub fn http_client(&self) -> &Client {
        &self.client
    }

    pub async fn get<T: DeserializeOwned>(&self, path: &str) -> Result<T> {
        self.request(Method::GET, path, Option::<&()>::None).await
    }

    pub async fn post<T: DeserializeOwned, B: Serialize + ?Sized>(
        &self,
        path: &str,
        body: &B,
    ) -> Result<T> {
        self.request(Method::POST, path, Some(body)).await
    }

    pub async fn put<T: DeserializeOwned, B: Serialize + ?Sized>(
        &self,
        path: &str,
        body: &B,
    ) -> Result<T> {
        self.request(Method::PUT, path, Some(body)).await
    }

    pub async fn delete<T: DeserializeOwned>(&self, path: &str) -> Result<T> {
        self.request(Method::DELETE, path, Option::<&()>::None)
            .await
    }

    pub async fn delete_with_body<T: DeserializeOwned, B: Serialize + ?Sized>(
        &self,
        path: &str,
        body: &B,
    ) -> Result<T> {
        self.request(Method::DELETE, path, Some(body)).await
    }

    /// DELETE that expects 204 No Content (no response body).
    pub async fn delete_no_content(&self, path: &str) -> Result<()> {
        if let Some(wait_secs) = self.rate_limiter.check_limit().await {
            warn!(wait_secs, "Rate limit reached, waiting");
            tokio::time::sleep(Duration::from_secs(wait_secs)).await;
        }

        let joined = self.safe_join(path)?;

        debug!(method = "DELETE", url = %joined, "Sending delete (no content) request");

        retry_with_backoff(&self.retry_config, || async {
            let mut req = self.client.request(Method::DELETE, joined.clone());
            req = self.apply_auth(req);

            let response = req.send().await.map_err(ApiError::RequestFailed)?;

            self.rate_limiter.update_from_response(&response).await;

            let status = response.status();

            match status {
                StatusCode::UNAUTHORIZED => Err(unauthorized_error(response).await),
                StatusCode::FORBIDDEN => {
                    let message = response
                        .text()
                        .await
                        .unwrap_or_else(|_| "Access forbidden".to_string());
                    Err(ApiError::Forbidden { message })
                }
                StatusCode::NOT_FOUND => {
                    let resource = joined.path().to_string();
                    Err(ApiError::NotFound { resource })
                }
                StatusCode::BAD_REQUEST => {
                    let message = response
                        .text()
                        .await
                        .unwrap_or_else(|_| "Bad request".to_string());
                    Err(ApiError::BadRequest { message })
                }
                StatusCode::GONE => {
                    let message = response
                        .text()
                        .await
                        .unwrap_or_else(|_| "API endpoint has been removed".to_string());
                    Err(ApiError::EndpointGone { message })
                }
                StatusCode::TOO_MANY_REQUESTS => {
                    let retry_after = response
                        .headers()
                        .get("retry-after")
                        .and_then(|v| v.to_str().ok())
                        .and_then(|s| s.parse().ok())
                        .unwrap_or(60);
                    Err(ApiError::RateLimitExceeded { retry_after })
                }
                status if status.is_server_error() => {
                    let message = response
                        .text()
                        .await
                        .unwrap_or_else(|_| "Server error".to_string());
                    Err(ApiError::ServerError {
                        status: status.as_u16(),
                        message,
                    })
                }
                status if status.is_success() => Ok(()),
                _ => {
                    let message = response
                        .text()
                        .await
                        .unwrap_or_else(|_| format!("Unexpected status: {}", status));
                    Err(ApiError::ServerError {
                        status: status.as_u16(),
                        message,
                    })
                }
            }
        })
        .await
    }

    /// Get plain text content from an endpoint.
    /// Sets Accept: text/plain; charset=utf-8 header.
    /// Includes retry logic and rate limiting.
    /// Issue a GET and return one response header, discarding the body.
    ///
    /// Exists for `auth scopes`: Bitbucket reports a token's granted scopes in
    /// `x-oauth-scopes` on any authenticated response, so the scopes can be
    /// read without a dedicated endpoint and without caching anything locally.
    ///
    /// Deliberately no retry wrapper: this is a diagnostic, and a caller asking
    /// "what does my token grant" wants the answer or the error now, not three
    /// backed-off attempts.
    pub async fn response_header(&self, path: &str, header: &str) -> Result<Option<String>> {
        if let Some(wait_secs) = self.rate_limiter.check_limit().await {
            warn!(wait_secs, "Rate limit reached, waiting");
            tokio::time::sleep(Duration::from_secs(wait_secs)).await;
        }

        let joined = self.safe_join(path)?;
        debug!(method = "GET", url = %joined, header, "Reading response header");

        let mut req = self.client.request(Method::GET, joined.clone());
        req = self.apply_auth(req);
        let response = req.send().await.map_err(ApiError::RequestFailed)?;

        self.rate_limiter.update_from_response(&response).await;

        let status = response.status();
        if status == StatusCode::UNAUTHORIZED {
            return Err(unauthorized_error(response).await);
        }
        if status == StatusCode::FORBIDDEN {
            let message = response
                .text()
                .await
                .unwrap_or_else(|_| "Access forbidden".to_string());
            return Err(ApiError::Forbidden { message });
        }

        Ok(response
            .headers()
            .get(header)
            .and_then(|value| value.to_str().ok())
            .map(str::to_string))
    }

    pub async fn get_text(&self, path: &str) -> Result<String> {
        if let Some(wait_secs) = self.rate_limiter.check_limit().await {
            warn!(wait_secs, "Rate limit reached, waiting");
            tokio::time::sleep(Duration::from_secs(wait_secs)).await;
        }

        let joined = self.safe_join(path)?;

        debug!(method = "GET", url = %joined, "Sending text request");

        let result = retry_with_backoff(&self.retry_config, || async {
            let mut req = self.client.request(Method::GET, joined.clone());
            req = self.apply_auth(req);
            req = req.header("Accept", "text/plain, */*;q=0.1");

            let response = req.send().await.map_err(ApiError::RequestFailed)?;

            self.rate_limiter.update_from_response(&response).await;

            let status = response.status();

            match status {
                StatusCode::UNAUTHORIZED => Err(unauthorized_error(response).await),
                StatusCode::FORBIDDEN => {
                    let message = response
                        .text()
                        .await
                        .unwrap_or_else(|_| "Access forbidden".to_string());
                    Err(ApiError::Forbidden { message })
                }
                StatusCode::NOT_FOUND => {
                    let resource = joined.path().to_string();
                    Err(ApiError::NotFound { resource })
                }
                StatusCode::BAD_REQUEST => {
                    let message = response
                        .text()
                        .await
                        .unwrap_or_else(|_| "Bad request".to_string());
                    Err(ApiError::BadRequest { message })
                }
                StatusCode::NOT_ACCEPTABLE => {
                    let message = response
                        .text()
                        .await
                        .unwrap_or_else(|_| "Content not acceptable".to_string());
                    Err(ApiError::ServerError {
                        status: 406,
                        message,
                    })
                }
                StatusCode::GONE => {
                    let message = response
                        .text()
                        .await
                        .unwrap_or_else(|_| "API endpoint has been removed".to_string());
                    Err(ApiError::EndpointGone { message })
                }
                StatusCode::TOO_MANY_REQUESTS => {
                    let retry_after = response
                        .headers()
                        .get("retry-after")
                        .and_then(|v| v.to_str().ok())
                        .and_then(|s| s.parse().ok())
                        .unwrap_or(60);
                    Err(ApiError::RateLimitExceeded { retry_after })
                }
                status if status.is_server_error() => {
                    let message = response
                        .text()
                        .await
                        .unwrap_or_else(|_| "Server error".to_string());
                    Err(ApiError::ServerError {
                        status: status.as_u16(),
                        message,
                    })
                }
                status if status.is_success() => response.text().await.map_err(|e| {
                    error!("Failed to read text response: {}", e);
                    ApiError::InvalidResponse(e.to_string())
                }),
                _ => {
                    let message = response
                        .text()
                        .await
                        .unwrap_or_else(|_| format!("Unexpected status: {}", status));
                    Err(ApiError::ServerError {
                        status: status.as_u16(),
                        message,
                    })
                }
            }
        })
        .await?;

        Ok(result)
    }

    /// Resolve `path` against the base URL, applying the same-origin (SSRF)
    /// check used by every request. Public so callers can validate or preview a
    /// path without sending anything.
    pub fn resolve_url(&self, path: &str) -> Result<Url> {
        self.safe_join(path)
    }

    /// Send an arbitrary request and return the status, headers and body bytes.
    ///
    /// Unlike [`ApiClient::request`], a non-2xx status is returned as
    /// `Ok(RawResponse)` rather than mapped to an [`ApiError`], so callers can
    /// surface the API's own error body. Only transport failures and URL
    /// validation produce `Err`. Same-origin validation, auth and rate limiting
    /// still apply.
    ///
    /// Retries on 429/5xx are limited to idempotent methods. `request` retries
    /// POSTs, which can double-create; a raw passthrough must not inherit that.
    pub async fn request_raw(&self, req: RawRequest<'_>) -> Result<RawResponse> {
        if let Some(wait_secs) = self.rate_limiter.check_limit().await {
            warn!(wait_secs, "Rate limit reached, waiting");
            tokio::time::sleep(Duration::from_secs(wait_secs)).await;
        }

        let joined = self.safe_join(req.path)?;
        debug!(method = %req.method, url = %joined, "Sending raw request");

        let idempotent = matches!(
            req.method,
            Method::GET | Method::HEAD | Method::PUT | Method::DELETE | Method::OPTIONS
        );
        // retry_with_backoff cannot be used here: its closure must signal a
        // retryable outcome as Err, which would discard the RawResponse we have
        // to return on the final attempt.
        let mut backoff = self.retry_config.backoff();
        let mut attempts = 0usize;

        loop {
            attempts += 1;

            let mut builder = self.raw_client.request(req.method.clone(), joined.clone());
            builder = self.apply_auth(builder);
            builder = builder.headers(req.headers.clone());
            if let Some(body) = req.body {
                builder = builder.body(body.to_vec());
            }
            if let Some(timeout) = req.timeout {
                builder = builder.timeout(timeout);
            }

            let response = builder.send().await.map_err(ApiError::RequestFailed)?;
            self.rate_limiter.update_from_response(&response).await;
            let status = response.status();

            let retryable = status == StatusCode::TOO_MANY_REQUESTS || status.is_server_error();
            if idempotent && retryable && attempts < self.retry_config.max_retries {
                if let Some(wait) = backoff.next_backoff() {
                    // A 429 says how long to wait; obey it rather than racing
                    // back in after a short exponential sleep.
                    let wait = retry_after(&response).unwrap_or(wait);
                    warn!(
                        status = status.as_u16(),
                        attempt = attempts,
                        wait_ms = wait.as_millis(),
                        "Raw request failed, retrying"
                    );
                    tokio::time::sleep(wait).await;
                    continue;
                }
            }

            let headers = response
                .headers()
                .iter()
                .map(|(name, value)| {
                    (
                        name.as_str().to_string(),
                        value.to_str().unwrap_or_default().to_string(),
                    )
                })
                .collect();
            let body = response
                .bytes()
                .await
                .map_err(|err| ApiError::InvalidResponse(err.to_string()))?
                .to_vec();

            return Ok(RawResponse {
                status: status.as_u16(),
                headers,
                body,
            });
        }
    }

    /// Get binary content from an endpoint.
    /// Includes retry logic and rate limiting.
    pub async fn get_bytes(&self, path: &str) -> Result<Vec<u8>> {
        if let Some(wait_secs) = self.rate_limiter.check_limit().await {
            warn!(wait_secs, "Rate limit reached, waiting");
            tokio::time::sleep(Duration::from_secs(wait_secs)).await;
        }

        let joined = self.safe_join(path)?;

        debug!(method = "GET", url = %joined, "Sending bytes request");

        let result = retry_with_backoff(&self.retry_config, || async {
            let mut req = self.client.request(Method::GET, joined.clone());
            req = self.apply_auth(req);

            let response = req.send().await.map_err(ApiError::RequestFailed)?;

            self.rate_limiter.update_from_response(&response).await;

            let status = response.status();

            match status {
                StatusCode::UNAUTHORIZED => Err(unauthorized_error(response).await),
                StatusCode::FORBIDDEN => {
                    let message = response
                        .text()
                        .await
                        .unwrap_or_else(|_| "Access forbidden".to_string());
                    Err(ApiError::Forbidden { message })
                }
                StatusCode::NOT_FOUND => {
                    let resource = joined.path().to_string();
                    Err(ApiError::NotFound { resource })
                }
                StatusCode::GONE => {
                    let message = response
                        .text()
                        .await
                        .unwrap_or_else(|_| "API endpoint has been removed".to_string());
                    Err(ApiError::EndpointGone { message })
                }
                StatusCode::TOO_MANY_REQUESTS => {
                    let retry_after = response
                        .headers()
                        .get("retry-after")
                        .and_then(|v| v.to_str().ok())
                        .and_then(|s| s.parse().ok())
                        .unwrap_or(60);
                    Err(ApiError::RateLimitExceeded { retry_after })
                }
                status if status.is_success() => {
                    response.bytes().await.map(|b| b.to_vec()).map_err(|e| {
                        error!("Failed to read bytes response: {}", e);
                        ApiError::InvalidResponse(e.to_string())
                    })
                }
                _ => {
                    let message = response
                        .text()
                        .await
                        .unwrap_or_else(|_| format!("Unexpected status: {}", status));
                    Err(ApiError::ServerError {
                        status: status.as_u16(),
                        message,
                    })
                }
            }
        })
        .await?;

        Ok(result)
    }

    pub async fn request<T: DeserializeOwned, B: Serialize + ?Sized>(
        &self,
        method: Method,
        path: &str,
        body: Option<&B>,
    ) -> Result<T> {
        if let Some(wait_secs) = self.rate_limiter.check_limit().await {
            warn!(wait_secs, "Rate limit reached, waiting");
            tokio::time::sleep(Duration::from_secs(wait_secs)).await;
        }

        let joined = self.safe_join(path)?;

        debug!(method = %method, url = %joined, "Sending request");

        let result = retry_with_backoff(&self.retry_config, || async {
            let mut req = self.client.request(method.clone(), joined.clone());
            req = self.apply_auth(req);

            if let Some(body) = body {
                req = req.json(body);
            }

            let response = req.send().await.map_err(ApiError::RequestFailed)?;

            self.rate_limiter.update_from_response(&response).await;

            let status = response.status();

            match status {
                StatusCode::UNAUTHORIZED => Err(unauthorized_error(response).await),
                StatusCode::FORBIDDEN => {
                    let message = response
                        .text()
                        .await
                        .unwrap_or_else(|_| "Access forbidden".to_string());
                    Err(ApiError::Forbidden { message })
                }
                StatusCode::NOT_FOUND => {
                    let resource = joined.path().to_string();
                    Err(ApiError::NotFound { resource })
                }
                StatusCode::BAD_REQUEST => {
                    let message = response
                        .text()
                        .await
                        .unwrap_or_else(|_| "Bad request".to_string());
                    Err(ApiError::BadRequest { message })
                }
                StatusCode::GONE => {
                    let message = response
                        .text()
                        .await
                        .unwrap_or_else(|_| "API endpoint has been removed".to_string());
                    Err(ApiError::EndpointGone { message })
                }
                StatusCode::TOO_MANY_REQUESTS => {
                    let retry_after = response
                        .headers()
                        .get("retry-after")
                        .and_then(|v| v.to_str().ok())
                        .and_then(|s| s.parse().ok())
                        .unwrap_or(60);
                    Err(ApiError::RateLimitExceeded { retry_after })
                }
                status if status.is_server_error() => {
                    let message = response
                        .text()
                        .await
                        .unwrap_or_else(|_| "Server error".to_string());
                    Err(ApiError::ServerError {
                        status: status.as_u16(),
                        message,
                    })
                }
                status if status.is_success() => {
                    let bytes = response
                        .bytes()
                        .await
                        .map_err(|e| ApiError::InvalidResponse(e.to_string()))?;
                    // Successful responses with an empty (or whitespace-only) body,
                    // e.g. HTTP 204 No Content from Jira update/transition/assign and
                    // most DELETEs, are treated as JSON `null`. Callers that discard
                    // the body (`let _: Value`) then succeed instead of failing to
                    // parse an empty body as JSON.
                    let slice: &[u8] = if bytes.iter().all(|b| b.is_ascii_whitespace()) {
                        b"null"
                    } else {
                        &bytes
                    };
                    serde_json::from_slice::<T>(slice).map_err(|e| {
                        error!("Failed to parse JSON response: {}", e);
                        ApiError::InvalidResponse(e.to_string())
                    })
                }
                _ => {
                    let message = response
                        .text()
                        .await
                        .unwrap_or_else(|_| format!("Unexpected status: {}", status));
                    Err(ApiError::ServerError {
                        status: status.as_u16(),
                        message,
                    })
                }
            }
        })
        .await?;

        Ok(result)
    }

    pub fn apply_auth(&self, request: RequestBuilder) -> RequestBuilder {
        match &self.auth {
            Some(AuthMethod::Basic { username, token }) => {
                request.basic_auth(username, Some(token.expose_secret()))
            }
            Some(AuthMethod::Bearer { token }) => request.bearer_auth(token.expose_secret()),
            Some(AuthMethod::GenieKey { api_key }) => request.header(
                "Authorization",
                format!("GenieKey {}", api_key.expose_secret()),
            ),
            None => request,
        }
    }

    pub fn rate_limiter(&self) -> &RateLimiter {
        &self.rate_limiter
    }
}

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

    /// The net beneath per-call-site encoding. Each of these was verified
    /// against the `url` version in the lockfile to resolve somewhere other
    /// than the segment it names.
    #[test]
    fn a_restructuring_path_is_refused_before_it_is_joined() {
        for bad in [
            "/2.0/repositories/w/r/hooks/..",
            "/2.0/repositories/w/r/hooks/.",
            "/2.0/repositories/w/r/hooks/..\\",
            "/2.0/repositories/w/r/hooks/a\\..\\x",
            "/2.0/repositories/w/r/hooks/.\t.",
            "/2.0/repositories/w/r/hooks/.\n.",
            "/rest/api/3/issue/../../admin",
            // Percent-encoded dot segments: the first version of this guard
            // compared against the literal strings and let every one of these
            // through, each of which resolves to the parent.
            "/2.0/repositories/w/r/hooks/%2e%2e",
            "/2.0/repositories/w/r/hooks/%2E%2e",
            "/2.0/repositories/w/r/hooks/.%2e",
            "/2.0/repositories/w/r/hooks/%2e",
            // A trailing space is stripped from the input, addressing the
            // collection rather than a member.
            "/rest/api/3/issue/ ",
        ] {
            assert!(
                reject_restructuring_path(bad).is_err(),
                "{bad:?} must be refused"
            );
        }
    }

    /// `decode_once` byte-sliced the `str` and aborted the process on an
    /// ordinary identifier: byte index 5 of `x-%2é` lands inside the `é`.
    #[test]
    fn decode_once_does_not_panic_on_a_multibyte_char_after_a_percent() {
        assert_eq!(decode_once("x-%2é"), "x-%2é");
        assert_eq!(decode_once("%2é"), "%2é");
        assert_eq!(decode_once("é%"), "é%");
        assert_eq!(decode_once("%é2"), "%é2");
        // And the request path built from one is refused or accepted, not a crash.
        assert!(reject_restructuring_path("/rest/api/3/issue/x-%2é").is_ok());
    }

    /// A `#` in an interpolated value truncates the path, so it is refused
    /// before the query split rather than exempted by it. A slug of `r#x`
    /// turned a webhook delete into a repository delete.
    #[test]
    fn a_fragment_marker_is_refused_anywhere() {
        assert!(reject_restructuring_path("/2.0/repositories/w/r#x/hooks/u").is_err());
        assert!(reject_restructuring_path("/rest/api/3/issue/KEY-1#x").is_err());
        assert!(reject_restructuring_path("/x?jql=a#b").is_err());
    }

    /// An interior space is encoded harmlessly by the parser; only the ends are
    /// stripped. Refusing every space broke `bb commit browse` for a repository
    /// file whose name contains one.
    #[test]
    fn only_edge_spaces_are_refused() {
        assert!(reject_restructuring_path("/2.0/repositories/w/r/src/main/my file.txt").is_ok());
        assert!(reject_restructuring_path("/rest/api/3/issue/ ").is_err());
        assert!(reject_restructuring_path("/rest/api/3/issue/x ").is_err());
        assert!(reject_restructuring_path(" /rest/api/3/issue/x").is_err());
        // A space in the query is untouched.
        assert!(reject_restructuring_path("/rest/api/3/search/jql?jql=a = b").is_ok());
    }

    /// Double-encoding is not traversal: `%252e%252e` is the literal text
    /// `%2e%2e` and addresses a real resource. Rejecting it would be a false
    /// positive, and decoding more than once would cause one.
    #[test]
    fn a_double_encoded_dot_is_a_real_segment() {
        assert!(reject_restructuring_path("/2.0/repositories/w/r/hooks/%252e%252e").is_ok());
        assert!(!is_dot_segment("%252e%252e"));
        assert_eq!(decode_once("%252e%252e"), "%2e%2e");
    }

    /// The decoder must not mangle a segment that merely contains a `%`.
    #[test]
    fn decode_once_leaves_invalid_escapes_alone() {
        assert_eq!(decode_once("100%"), "100%");
        assert_eq!(decode_once("a%zzb"), "a%zzb");
        assert_eq!(decode_once("%7Babc%7D"), "{abc}");
    }

    /// A query value is not part of the path and cannot move the request, so
    /// JQL containing a dot or a `..` range must still be allowed through.
    #[test]
    fn a_dot_in_the_query_is_not_a_path_component() {
        assert!(
            reject_restructuring_path("/rest/api/3/search/jql?jql=fixVersion%20in%20(1.0)").is_ok()
        );
        assert!(reject_restructuring_path("/x?range=a..b").is_ok());
    }

    use wiremock::matchers::{body_string, header, method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    #[tokio::test]
    async fn test_403_returns_forbidden() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("test"))
            .respond_with(ResponseTemplate::new(403).set_body_string("You do not have access"))
            .mount(&server)
            .await;

        let client = ApiClient::new(server.uri()).unwrap();
        let result: error::Result<serde_json::Value> = client.get("/test").await;

        match result {
            Err(ApiError::Forbidden { message }) => {
                assert!(message.contains("You do not have access"));
            }
            other => panic!("Expected Forbidden, got: {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_401_returns_authentication_failed() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("test"))
            .respond_with(ResponseTemplate::new(401))
            .mount(&server)
            .await;

        let client = ApiClient::new(server.uri()).unwrap();
        let result: error::Result<serde_json::Value> = client.get("/test").await;

        match result {
            Err(ApiError::AuthenticationFailed { message }) => {
                // No body, so the generic wording is all we can say.
                assert_eq!(message, UNAUTHORIZED_FALLBACK);
            }
            other => panic!("Expected AuthenticationFailed, got: {:?}", other),
        }
    }

    /// The scope-mismatch case that cost a full debugging session: the gateway
    /// explained itself and the CLI threw the explanation away.
    #[tokio::test]
    async fn test_401_surfaces_gateway_scope_message() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("test"))
            .respond_with(
                ResponseTemplate::new(401).set_body_string(
                    r#"{"code":401,"message":"Unauthorized; scope does not match"}"#,
                ),
            )
            .mount(&server)
            .await;

        let client = ApiClient::new(server.uri()).unwrap();
        let result: error::Result<serde_json::Value> = client.get("/test").await;

        match result {
            Err(ApiError::AuthenticationFailed { message }) => {
                assert!(
                    message.contains("scope does not match"),
                    "gateway reason was dropped: {message}"
                );
            }
            other => panic!("Expected AuthenticationFailed, got: {:?}", other),
        }
    }

    #[test]
    fn unauthorized_message_falls_back_when_body_is_empty() {
        assert_eq!(unauthorized_message(""), UNAUTHORIZED_FALLBACK);
        assert_eq!(unauthorized_message("   "), UNAUTHORIZED_FALLBACK);
    }

    #[test]
    fn unauthorized_message_keeps_gateway_reason() {
        let body = r#"{"code":401,"message":"Unauthorized; scope does not match"}"#;
        let message = unauthorized_message(body);
        assert!(message.starts_with(UNAUTHORIZED_FALLBACK));
        assert!(message.contains("Unauthorized; scope does not match"));
    }

    #[test]
    fn unauthorized_message_reads_jira_error_messages() {
        let body = r#"{"errorMessages":["Client must be authenticated"],"errors":{}}"#;
        assert!(unauthorized_message(body).contains("Client must be authenticated"));
    }

    #[test]
    fn unauthorized_message_reads_oauth_error_description() {
        let body = r#"{"error":"invalid_token","error_description":"The token expired"}"#;
        assert!(unauthorized_message(body).contains("The token expired"));
    }

    #[test]
    fn unauthorized_message_reads_a_nested_error_object() {
        let body = r#"{"error":{"message":"Token does not have the required scope"}}"#;
        let message = unauthorized_message(body);
        assert!(message.contains("required scope"));
        // The whole document must not be quoted back as though it were prose.
        assert!(
            !message.contains("{\"error\""),
            "raw JSON leaked: {message}"
        );
    }

    /// A body we cannot parse is quoted whole, so a proxy echoing the request
    /// back would otherwise print the token we just sent it.
    #[test]
    fn unauthorized_message_redacts_an_echoed_authorization_header() {
        let body =
            "rejected request: Authorization: Basic Zm9vOmJhcnNlY3JldA== to /rest/api/3/myself";
        let message = unauthorized_message(body);
        assert!(
            !message.contains("Zm9vOmJhcnNlY3JldA=="),
            "the credential survived: {message}"
        );
        assert!(message.contains("Basic <redacted>"));
        assert!(
            message.contains("/rest/api/3/myself"),
            "the useful part of the body was lost: {message}"
        );
    }

    #[test]
    fn unauthorized_message_redacts_a_bearer_token_inside_json() {
        let body = r#"{"message":"bad header \"Bearer eyJhbGciOiJIUzI1NiJ9.payload.sig\""}"#;
        let message = unauthorized_message(body);
        assert!(!message.contains("eyJhbGciOiJIUzI1NiJ9"), "{message}");
        assert!(message.contains("Bearer <redacted>"));
    }

    #[test]
    fn unauthorized_message_redacts_every_occurrence() {
        let body = "Bearer aGVsbG8gd29ybGQgdG9rZW4= and basic dXNlcjpwYXNzd29yZA==";
        let message = unauthorized_message(body);
        for secret in ["aGVsbG8gd29ybGQgdG9rZW4=", "dXNlcjpwYXNzd29yZA=="] {
            assert!(!message.contains(secret), "{secret} survived: {message}");
        }
        assert_eq!(message.matches("<redacted>").count(), 2);
    }

    /// "Basic auth is not allowed" is a sentence servers really send. Redacting
    /// the word after the scheme would destroy the message to protect nothing.
    #[test]
    fn scrub_leaves_ordinary_prose_alone() {
        for prose in [
            "basic authentication is not permitted here",
            "Basic auth is not allowed",
            "use Bearer tokens instead",
            "no credentials at all",
        ] {
            assert_eq!(scrub_credentials(prose), prose, "prose was mangled");
        }
    }

    #[test]
    fn credential_shape_separates_words_from_secrets() {
        for word in ["auth", "authentication", "tokens", "a", ""] {
            assert!(
                !is_credential_shaped(word),
                "{word} is a word, not a secret"
            );
        }
        for secret in [
            "Zm9vOmJhcg==",
            "eyJhbGciOiJIUzI1NiJ9.payload.sig",
            "abcdefghijklmnop",
            "ATATT3xFfGF0abc_def-123",
        ] {
            assert!(is_credential_shaped(secret), "{secret} should be redacted");
        }
    }

    #[test]
    fn unauthorized_message_keeps_plain_text_body() {
        assert!(unauthorized_message("Basic auth is not allowed").contains("Basic auth"));
    }

    #[test]
    fn unauthorized_message_ignores_html_login_page() {
        let body = "<!DOCTYPE html><html><body>Sign in</body></html>";
        assert_eq!(unauthorized_message(body), UNAUTHORIZED_FALLBACK);
    }

    #[test]
    fn unauthorized_message_truncates_long_bodies() {
        let body = format!(r#"{{"message":"{}"}}"#, "x".repeat(500));
        let message = unauthorized_message(&body);
        assert!(message.contains("..."));
        assert!(message.len() < 300, "message was not truncated: {message}");
    }

    /// Multi-byte text must not panic the truncation slice.
    #[test]
    fn unauthorized_message_truncates_on_char_boundary() {
        let body = format!(r#"{{"message":"{}"}}"#, "é".repeat(500));
        assert!(unauthorized_message(&body).contains("..."));
    }

    #[tokio::test]
    async fn test_403_get_text_returns_forbidden() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("text-endpoint"))
            .respond_with(ResponseTemplate::new(403).set_body_string("Forbidden resource"))
            .mount(&server)
            .await;

        let client = ApiClient::new(server.uri()).unwrap();
        let result = client.get_text("/text-endpoint").await;

        match result {
            Err(ApiError::Forbidden { message }) => {
                assert!(message.contains("Forbidden resource"));
            }
            other => panic!("Expected Forbidden, got: {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_403_get_bytes_returns_forbidden() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("bytes-endpoint"))
            .respond_with(ResponseTemplate::new(403).set_body_string("Access denied"))
            .mount(&server)
            .await;

        let client = ApiClient::new(server.uri()).unwrap();
        let result = client.get_bytes("/bytes-endpoint").await;

        match result {
            Err(ApiError::Forbidden { message }) => {
                assert!(message.contains("Access denied"));
            }
            other => panic!("Expected Forbidden, got: {:?}", other),
        }
    }

    // Regression for #45: a successful PUT/POST returning HTTP 204 No Content (empty
    // body) must not fail JSON parsing. Callers discard the body as `Value`.
    #[tokio::test]
    async fn test_204_no_content_put_succeeds() {
        let server = MockServer::start().await;
        Mock::given(method("PUT"))
            .and(path("issue/AEA-1"))
            .respond_with(ResponseTemplate::new(204))
            .mount(&server)
            .await;

        let client = ApiClient::new(server.uri()).unwrap();
        let result: error::Result<serde_json::Value> = client
            .put("/issue/AEA-1", &serde_json::json!({"fields": {}}))
            .await;

        match result {
            Ok(serde_json::Value::Null) => {}
            other => panic!("Expected Ok(Null) for 204, got: {:?}", other),
        }
    }

    // A 200 with an empty/whitespace-only body is also treated as null.
    #[tokio::test]
    async fn test_200_empty_body_succeeds() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("transitions"))
            .respond_with(ResponseTemplate::new(200).set_body_string("  \n"))
            .mount(&server)
            .await;

        let client = ApiClient::new(server.uri()).unwrap();
        let result: error::Result<serde_json::Value> =
            client.post("/transitions", &serde_json::json!({})).await;

        match result {
            Ok(serde_json::Value::Null) => {}
            other => panic!("Expected Ok(Null) for empty 200, got: {:?}", other),
        }
    }

    // A non-empty JSON body on success still parses normally.
    #[tokio::test]
    async fn test_200_json_body_still_parses() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("issue/AEA-1"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(serde_json::json!({"key": "AEA-1"})),
            )
            .mount(&server)
            .await;

        let client = ApiClient::new(server.uri()).unwrap();
        let result: serde_json::Value = client.get("/issue/AEA-1").await.unwrap();
        assert_eq!(result["key"], "AEA-1");
    }

    // -----------------------------------------------------------------------
    // request_raw
    // -----------------------------------------------------------------------

    /// The point of the raw path: a non-2xx status is data, not an error, so the
    /// API's own error body survives instead of being replaced by ApiError.
    #[tokio::test]
    async fn test_request_raw_surfaces_non_2xx_without_erroring() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/rest/api/3/issue/NOPE-1"))
            .respond_with(
                ResponseTemplate::new(404)
                    .set_body_json(serde_json::json!({"errorMessages": ["Issue does not exist"]})),
            )
            .mount(&server)
            .await;

        let client = ApiClient::new(server.uri()).unwrap();
        let response = client
            .request_raw(RawRequest {
                method: Method::GET,
                path: "/rest/api/3/issue/NOPE-1",
                headers: HeaderMap::new(),
                body: None,
                timeout: None,
            })
            .await
            .unwrap();

        assert_eq!(response.status, 404);
        assert!(!response.is_success());
        assert!(response
            .header("Content-Type")
            .unwrap()
            .contains("application/json"));
        assert!(String::from_utf8_lossy(&response.body).contains("Issue does not exist"));
    }

    #[tokio::test]
    async fn test_request_raw_applies_headers_and_body() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/rest/api/3/issue"))
            .and(header("X-Atlassian-Token", "no-check"))
            .and(body_string("{\"fields\":{}}"))
            .respond_with(
                ResponseTemplate::new(201).set_body_json(serde_json::json!({"key": "A-1"})),
            )
            .mount(&server)
            .await;

        let mut headers = HeaderMap::new();
        headers.insert("X-Atlassian-Token", "no-check".parse().unwrap());

        let client = ApiClient::new(server.uri()).unwrap();
        let response = client
            .request_raw(RawRequest {
                method: Method::POST,
                path: "/rest/api/3/issue",
                headers,
                body: Some(b"{\"fields\":{}}"),
                timeout: None,
            })
            .await
            .unwrap();

        assert_eq!(response.status, 201);
    }

    #[tokio::test]
    async fn test_request_raw_retries_5xx_for_get() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/flaky"))
            .respond_with(ResponseTemplate::new(500))
            .expect(3)
            .mount(&server)
            .await;

        let client = ApiClient::new(server.uri())
            .unwrap()
            .with_retry_config(RetryConfig {
                initial_interval: Duration::from_millis(1),
                ..RetryConfig::default()
            });
        let response = client
            .request_raw(RawRequest {
                method: Method::GET,
                path: "/flaky",
                headers: HeaderMap::new(),
                body: None,
                timeout: None,
            })
            .await
            .unwrap();

        assert_eq!(response.status, 500);
    }

    /// Replaying a POST can double-create. `request` does retry POSTs; the raw
    /// path deliberately does not inherit that.
    #[tokio::test]
    async fn test_request_raw_never_retries_post() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/create"))
            .respond_with(ResponseTemplate::new(503))
            .expect(1)
            .mount(&server)
            .await;

        let client = ApiClient::new(server.uri())
            .unwrap()
            .with_retry_config(RetryConfig {
                initial_interval: Duration::from_millis(1),
                ..RetryConfig::default()
            });
        let response = client
            .request_raw(RawRequest {
                method: Method::POST,
                path: "/create",
                headers: HeaderMap::new(),
                body: Some(b"{}"),
                timeout: None,
            })
            .await
            .unwrap();

        assert_eq!(response.status, 503);
    }

    #[tokio::test]
    async fn test_request_raw_rejects_cross_host_path() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .respond_with(ResponseTemplate::new(200))
            .expect(0)
            .mount(&server)
            .await;

        let client = ApiClient::new(server.uri()).unwrap();
        let err = client
            .request_raw(RawRequest {
                method: Method::GET,
                path: "https://evil.example.com/steal",
                headers: HeaderMap::new(),
                body: None,
                timeout: None,
            })
            .await
            .unwrap_err();

        assert!(matches!(err, ApiError::InvalidUrl(_)), "got {err:?}");
    }

    #[test]
    fn test_resolve_url_enforces_same_origin() {
        let client = ApiClient::new("https://site.atlassian.net").unwrap();

        assert_eq!(
            client.resolve_url("/rest/api/3/myself").unwrap().as_str(),
            "https://site.atlassian.net/rest/api/3/myself"
        );
        // Relative paths work with or without the leading slash.
        assert_eq!(
            client.resolve_url("rest/api/3/myself").unwrap().as_str(),
            "https://site.atlassian.net/rest/api/3/myself"
        );
        // Other hosts, scheme downgrades and userinfo tricks are all rejected.
        for bad in [
            "https://evil.example.com/x",
            "http://site.atlassian.net/x",
            "https://site.atlassian.net@evil.example.com/",
            "//evil.example.com/x",
        ] {
            let resolved = client.resolve_url(bad);
            match resolved {
                Err(_) => {}
                // A protocol-relative path is not treated as a host by `join`;
                // pin the behaviour so a future change cannot silently open it up.
                Ok(url) => assert_eq!(url.host_str(), Some("site.atlassian.net"), "{bad}"),
            }
        }
    }

    /// Regression: a base URL carrying a path lost its last segment, so the
    /// API-gateway form used by scoped API tokens dropped the cloud id.
    #[test]
    fn test_resolve_url_keeps_the_base_path() {
        let client = ApiClient::new("https://api.atlassian.com/ex/jira/cloud-id").unwrap();

        assert_eq!(
            client.base_url(),
            "https://api.atlassian.com/ex/jira/cloud-id/"
        );
        assert_eq!(
            client.resolve_url("/rest/api/3/myself").unwrap().as_str(),
            "https://api.atlassian.com/ex/jira/cloud-id/rest/api/3/myself"
        );
        assert_eq!(
            client.resolve_url("rest/api/3/myself").unwrap().as_str(),
            "https://api.atlassian.com/ex/jira/cloud-id/rest/api/3/myself"
        );

        // A base written with the trailing slash resolves the same way.
        let client = ApiClient::new("https://api.atlassian.com/ex/jira/cloud-id/").unwrap();

        assert_eq!(
            client.base_url(),
            "https://api.atlassian.com/ex/jira/cloud-id/"
        );
        assert_eq!(
            client.resolve_url("/rest/api/3/myself").unwrap().as_str(),
            "https://api.atlassian.com/ex/jira/cloud-id/rest/api/3/myself"
        );
        assert_eq!(
            client.resolve_url("rest/api/3/myself").unwrap().as_str(),
            "https://api.atlassian.com/ex/jira/cloud-id/rest/api/3/myself"
        );
    }

    /// The same fix covers a self-hosted product behind a context path, which is
    /// the ordinary way Bamboo is deployed. Before this, `/rest/api/latest/plan`
    /// against `https://example.com/bamboo` resolved to `https://example.com/rest/...`
    /// and 404'd.
    #[test]
    fn test_resolve_url_keeps_a_context_path() {
        let client = ApiClient::new("https://example.com/bamboo").unwrap();

        assert_eq!(
            client
                .resolve_url("/rest/api/latest/plan")
                .unwrap()
                .as_str(),
            "https://example.com/bamboo/rest/api/latest/plan"
        );
    }

    /// Guard against the fix shifting any URL a working profile already resolves.
    /// Every shape below is byte-identical before and after normalisation; only
    /// the previously broken path-bearing bases move.
    #[test]
    fn test_normalisation_does_not_move_existing_product_urls() {
        for (base, path, expected) in [
            (
                "https://x.atlassian.net",
                "/rest/api/3/myself",
                "https://x.atlassian.net/rest/api/3/myself",
            ),
            (
                "https://x.atlassian.net",
                "/wiki/download/attachments/1/f.png?version=1",
                "https://x.atlassian.net/wiki/download/attachments/1/f.png?version=1",
            ),
            (
                "https://api.bitbucket.org",
                "/2.0/repositories/w/r",
                "https://api.bitbucket.org/2.0/repositories/w/r",
            ),
            // Opsgenie's base already carries a path and already ends in a
            // slash, and its request paths are relative, so it is untouched.
            (
                "https://api.opsgenie.com/v2/",
                "alerts/123",
                "https://api.opsgenie.com/v2/alerts/123",
            ),
        ] {
            let client = ApiClient::new(base).unwrap();
            assert_eq!(
                client.resolve_url(path).unwrap().as_str(),
                expected,
                "{base} + {path}"
            );
        }
    }

    /// Regression: comparing scheme and host but not port let any other port on
    /// the same host receive the profile's credentials.
    #[tokio::test]
    async fn test_request_raw_rejects_a_different_port_on_the_same_host() {
        let victim = MockServer::start().await;
        Mock::given(method("GET"))
            .respond_with(ResponseTemplate::new(200).set_body_string("secrets"))
            .expect(0)
            .mount(&victim)
            .await;

        let server = MockServer::start().await;
        let client = ApiClient::new(server.uri()).unwrap();
        let err = client
            .request_raw(RawRequest {
                method: Method::GET,
                path: &format!("{}/steal", victim.uri()),
                headers: HeaderMap::new(),
                body: None,
                timeout: None,
            })
            .await
            .unwrap_err();

        assert!(matches!(err, ApiError::InvalidUrl(_)), "got {err:?}");
    }

    /// `safe_join` only sees the first URL, so a same-origin endpoint could
    /// otherwise bounce a write-capable request anywhere. The raw client stops
    /// at the redirect and hands the 3xx back instead of following it.
    #[tokio::test]
    async fn test_request_raw_does_not_follow_a_cross_origin_redirect() {
        let evil = MockServer::start().await;
        Mock::given(method("POST"))
            .respond_with(ResponseTemplate::new(200).set_body_string("pwned"))
            .expect(0)
            .mount(&evil)
            .await;

        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/rest/api/3/bounce"))
            .respond_with(
                ResponseTemplate::new(307)
                    .insert_header("location", format!("{}/steal", evil.uri()).as_str()),
            )
            .mount(&server)
            .await;

        let client = ApiClient::new(server.uri())
            .unwrap()
            .with_basic_auth("dev@example.com", "token");
        let response = client
            .request_raw(RawRequest {
                method: Method::POST,
                path: "/rest/api/3/bounce",
                headers: HeaderMap::new(),
                body: Some(b"{}"),
                timeout: None,
            })
            .await
            .unwrap();

        assert_eq!(response.status, 307);
        assert!(response.header("location").unwrap().contains("/steal"));
        assert_ne!(response.body, b"pwned".to_vec());
    }

    /// Same-origin redirects are still followed, so ordinary endpoints work.
    #[tokio::test]
    async fn test_request_raw_follows_a_same_origin_redirect() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/from"))
            .respond_with(ResponseTemplate::new(302).insert_header("location", "/to"))
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/to"))
            .respond_with(ResponseTemplate::new(200).set_body_string("arrived"))
            .mount(&server)
            .await;

        let client = ApiClient::new(server.uri()).unwrap();
        let response = client
            .request_raw(RawRequest {
                method: Method::GET,
                path: "/from",
                headers: HeaderMap::new(),
                body: None,
                timeout: None,
            })
            .await
            .unwrap();

        assert_eq!(response.status, 200);
        assert_eq!(response.body, b"arrived".to_vec());
    }

    /// Attachment downloads depend on the cross-host hop to the media host, so
    /// the ordinary client must keep following redirects.
    #[tokio::test]
    async fn test_get_bytes_still_follows_cross_host_redirects() {
        let media = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/file/binary"))
            .respond_with(ResponseTemplate::new(200).set_body_bytes(b"BYTES".to_vec()))
            .mount(&media)
            .await;

        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/content/1"))
            .respond_with(
                ResponseTemplate::new(302)
                    .insert_header("location", format!("{}/file/binary", media.uri()).as_str()),
            )
            .mount(&server)
            .await;

        let client = ApiClient::new(server.uri()).unwrap();
        assert_eq!(client.get_bytes("/content/1").await.unwrap(), b"BYTES");
    }

    #[test]
    fn test_same_origin_compares_scheme_host_and_port() {
        let base = Url::parse("https://site.atlassian.net").unwrap();
        assert!(same_origin(
            &Url::parse("https://site.atlassian.net/x").unwrap(),
            &base
        ));
        // 443 is the known default for https, so an explicit port still matches.
        assert!(same_origin(
            &Url::parse("https://site.atlassian.net:443/x").unwrap(),
            &base
        ));
        for other in [
            "https://site.atlassian.net:8443/x",
            "http://site.atlassian.net/x",
            "https://evil.example.com/x",
        ] {
            assert!(
                !same_origin(&Url::parse(other).unwrap(), &base),
                "{other} must not match"
            );
        }
    }
}