secretx-core 0.2.0

Core traits and types for the secretx secrets retrieval library.
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
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
//! Core traits and types for the secretx secrets retrieval library.
//!
//! Backend crates depend on this crate and implement [`SecretStore`] and/or
//! [`SigningBackend`]. Use [`SecretUri::parse`] to parse `secretx://` URIs
//! in backend constructors.

use std::collections::HashMap;
use std::iter::Peekable;
use std::str::Chars;
use zeroize::Zeroizing;

// ── SecretValue ──────────────────────────────────────────────────────────────

/// A secret value whose memory is zeroed on drop.
///
/// Does not implement `Debug`, `Display`, or `Clone` to prevent accidental
/// leakage. Use [`as_bytes`](SecretValue::as_bytes) for comparisons in tests.
pub struct SecretValue(Zeroizing<Vec<u8>>);

impl SecretValue {
    pub fn new(bytes: Vec<u8>) -> Self {
        SecretValue(Zeroizing::new(bytes))
    }

    pub fn as_bytes(&self) -> &[u8] {
        &self.0
    }

    pub fn into_bytes(self) -> Zeroizing<Vec<u8>> {
        self.0
    }

    /// Decode as UTF-8 without copying. Fails if not valid UTF-8.
    pub fn as_str(&self) -> Result<&str, SecretError> {
        std::str::from_utf8(&self.0)
            .map_err(|_| SecretError::DecodeFailed("not valid UTF-8".into()))
    }

    /// Parse as a JSON object and extract a single string field.
    ///
    /// Common for secrets that bundle multiple values as JSON,
    /// e.g. `{"username":"foo","password":"bar"}`.
    ///
    /// Uses a hand-rolled JSON scanner so that only the requested field's value
    /// is allocated. A full-tree parser (e.g. serde_json) would allocate copies
    /// of every field value, leaving other secret strings in unzeroized heap
    /// memory even after the parse result is dropped.
    pub fn extract_field(&self, field: &str) -> Result<SecretValue, SecretError> {
        json_extract_string_field(self.as_bytes(), field)
    }

    /// Navigate through nested JSON objects and return the raw bytes of the
    /// value at `path`'s final key as a new `SecretValue`.
    ///
    /// Each key in `path` must exist in the current JSON object.  All
    /// intermediate values (`path[..path.len()-1]`) must be JSON objects.
    /// The final value may be any JSON type.
    ///
    /// # Example (Vault KV v2)
    ///
    /// Given `{"data": {"data": {"password": "s3cret"}}, ...}`,
    /// `extract_path(&["data", "data"])` returns a `SecretValue` containing
    /// the bytes of `{"password": "s3cret"}`.  Call [`SecretValue::extract_field`] on
    /// the result to retrieve a specific secret field.
    pub fn extract_path(&self, path: &[&str]) -> Result<SecretValue, SecretError> {
        let raw = json_navigate(self.as_bytes(), path)?;
        Ok(SecretValue::new(raw.to_vec()))
    }

    /// Navigate through nested JSON objects and extract a string field.
    ///
    /// Equivalent to `self.extract_path(path)?.extract_field(field)` but
    /// avoids an intermediate allocation: the nested object bytes are sliced
    /// from the original input with no copy, and only the target field value
    /// is placed in a `Zeroizing` buffer.
    pub fn extract_path_field(
        &self,
        path: &[&str],
        field: &str,
    ) -> Result<SecretValue, SecretError> {
        let raw = json_navigate(self.as_bytes(), path)?;
        json_extract_string_field(raw, field)
    }
}

// ── JSON field extractor ──────────────────────────────────────────────────────
//
// Hand-rolled, allocation-minimal JSON object scanner used by
// `SecretValue::extract_field`.  Only the value for the requested field is
// allocated; all other field values are skipped without copying.
//
// Why not serde_json?
// serde_json deserializes all field values into plain (non-Zeroizing) String
// allocations.  Even after the parse result is dropped, those allocations are
// not zeroed, so every other secret string in the object would linger in heap
// memory until the allocator happens to reuse those pages.  This scanner avoids
// that by never touching non-target fields and writing only the target value
// into a Zeroizing buffer.
//
// DO NOT replace this scanner with serde_json.  The zeroization guarantee is
// the reason this code exists — it is not wheel-reinvention.  If a contributor
// suggests switching to serde_json, point them here.
//
// Future: this logic is a candidate for extraction into a small standalone
// crate (e.g. `zeroizing-json-field`) so the wider Rust secrets ecosystem can
// benefit.  No mainstream JSON crate provides this guarantee today.
//
// Supports: flat objects, all JSON string escapes (including \uXXXX and
// surrogate pairs), string and non-string values (non-string values are
// skipped, not returned).

/// Extract a single string-valued field from a flat JSON object.
fn json_extract_string_field(bytes: &[u8], field: &str) -> Result<SecretValue, SecretError> {
    let s = std::str::from_utf8(bytes)
        .map_err(|_| SecretError::DecodeFailed("not valid UTF-8".into()))?;

    let mut chars = s.chars().peekable();

    json_skip_ws(&mut chars);
    json_expect(&mut chars, '{')?;

    // Handle empty object.
    json_skip_ws(&mut chars);
    if chars.peek() == Some(&'}') {
        return Err(SecretError::DecodeFailed(format!(
            "field `{field}` not found"
        )));
    }

    loop {
        // Each iteration: we are positioned at the start of a key string ('"').
        json_expect(&mut chars, '"')?;
        let key = json_parse_string(&mut chars)?;

        json_skip_ws(&mut chars);
        json_expect(&mut chars, ':')?;
        json_skip_ws(&mut chars);

        if key == field {
            if chars.peek() != Some(&'"') {
                return Err(SecretError::DecodeFailed(format!(
                    "field `{field}` is not a string"
                )));
            }
            chars.next(); // consume opening '"'
            let value = json_parse_string(&mut chars)?;
            // Validate post-value structure.  Without this check, trailing
            // garbage immediately after the target field's value is silently
            // ignored, but the same garbage positioned before the target field
            // would cause an error — an asymmetry that is hard to debug.
            json_skip_ws(&mut chars);
            match chars.peek() {
                Some(&',') | Some(&'}') => {}
                Some(&c) => {
                    return Err(SecretError::DecodeFailed(format!(
                        "expected ',' or '}}' after value of field `{field}`, got '{c}'"
                    )));
                }
                None => {
                    return Err(SecretError::DecodeFailed(
                        "unexpected end of input after field value".into(),
                    ));
                }
            }
            return Ok(SecretValue::new(value.into_bytes()));
        }

        // Skip the value for a non-matching key.
        json_skip_value(&mut chars)?;

        // After each pair: expect ',' (more items) or '}' (end of object).
        json_skip_ws(&mut chars);
        match chars.next() {
            Some(',') => {
                json_skip_ws(&mut chars);
                // Guard against trailing comma before '}'.
                if chars.peek() == Some(&'}') {
                    return Err(SecretError::DecodeFailed(
                        "trailing comma in JSON object".into(),
                    ));
                }
            }
            Some('}') => {
                return Err(SecretError::DecodeFailed(format!(
                    "field `{field}` not found"
                )));
            }
            Some(c) => {
                return Err(SecretError::DecodeFailed(format!(
                    "expected ',' or '}}' in JSON object, got '{c}'"
                )));
            }
            None => {
                return Err(SecretError::DecodeFailed(
                    "unexpected end of JSON object".into(),
                ));
            }
        }
    }
}

fn json_skip_ws(chars: &mut Peekable<Chars<'_>>) {
    while matches!(
        chars.peek(),
        Some(' ') | Some('\t') | Some('\n') | Some('\r')
    ) {
        chars.next();
    }
}

fn json_expect(chars: &mut Peekable<Chars<'_>>, expected: char) -> Result<(), SecretError> {
    match chars.next() {
        Some(c) if c == expected => Ok(()),
        Some(c) => Err(SecretError::DecodeFailed(format!(
            "expected '{expected}', got '{c}'"
        ))),
        None => Err(SecretError::DecodeFailed(format!(
            "expected '{expected}', got end of input"
        ))),
    }
}

/// Parse a JSON string after the opening `"` has been consumed.
/// Allocates only the returned `String`; no other heap buffers are created.
fn json_parse_string(chars: &mut Peekable<Chars<'_>>) -> Result<String, SecretError> {
    let mut result = String::new();
    loop {
        match chars.next() {
            None => return Err(SecretError::DecodeFailed("unterminated JSON string".into())),
            Some('"') => return Ok(result),
            Some('\\') => match chars.next() {
                None => {
                    return Err(SecretError::DecodeFailed(
                        "truncated escape in JSON string".into(),
                    ))
                }
                Some('"') => result.push('"'),
                Some('\\') => result.push('\\'),
                Some('/') => result.push('/'),
                Some('b') => result.push('\x08'),
                Some('f') => result.push('\x0C'),
                Some('n') => result.push('\n'),
                Some('r') => result.push('\r'),
                Some('t') => result.push('\t'),
                Some('u') => {
                    let ch = json_consume_unicode_escape(chars)?;
                    result.push(ch);
                }
                Some(c) => {
                    return Err(SecretError::DecodeFailed(format!(
                        "unknown JSON escape '\\{c}'"
                    )))
                }
            },
            // RFC 8259 §7: U+0000–U+001F must be escaped; a bare control
            // character in a JSON string is invalid.
            Some(c) if (c as u32) < 0x20 => {
                return Err(SecretError::DecodeFailed(format!(
                    "unescaped control character U+{:04X} in JSON string",
                    c as u32
                )));
            }
            Some(c) => result.push(c),
        }
    }
}

/// Consume a `\uXXXX` escape sequence; the `\u` has already been consumed.
///
/// Handles surrogate pairs: if the first code unit is a high surrogate
/// (0xD800–0xDBFF) the immediately following `\uXXXX` low surrogate
/// (0xDC00–0xDFFF) is also consumed and the two are combined into the
/// supplementary Unicode scalar value.  A lone surrogate (either high without
/// a following low, or low without a preceding high) is rejected.
///
/// Returns the decoded Unicode scalar value so callers that are building a
/// string can push it directly.  Callers that are only skipping (not
/// extracting) can discard the return value; validation still runs.
fn json_consume_unicode_escape(chars: &mut Peekable<Chars<'_>>) -> Result<char, SecretError> {
    let hex: String = chars.by_ref().take(4).collect();
    if hex.len() != 4 {
        return Err(SecretError::DecodeFailed(
            "truncated \\uXXXX escape in JSON string".into(),
        ));
    }
    let code = u32::from_str_radix(&hex, 16)
        .map_err(|_| SecretError::DecodeFailed("invalid hex digits in \\uXXXX escape".into()))?;

    if (0xD800..=0xDBFF).contains(&code) {
        // High surrogate: RFC 8259 §7 requires an immediately following
        // \uXXXX low surrogate.  Combine the pair into a supplementary
        // code point: U+10000 + (H - 0xD800) * 0x400 + (L - 0xDC00).
        if chars.next() != Some('\\') || chars.next() != Some('u') {
            return Err(SecretError::DecodeFailed(format!(
                "\\u{code:04X} is a high surrogate not followed by \\uXXXX"
            )));
        }
        let low_hex: String = chars.by_ref().take(4).collect();
        if low_hex.len() != 4 {
            return Err(SecretError::DecodeFailed(
                "truncated \\uXXXX low-surrogate escape".into(),
            ));
        }
        let low = u32::from_str_radix(&low_hex, 16).map_err(|_| {
            SecretError::DecodeFailed("invalid hex digits in \\uXXXX low-surrogate escape".into())
        })?;
        if !(0xDC00..=0xDFFF).contains(&low) {
            return Err(SecretError::DecodeFailed(format!(
                "\\u{code:04X} is a high surrogate but \\u{low:04X} is not a low surrogate"
            )));
        }
        let codepoint = 0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00);
        // All valid surrogate pairs produce U+10000..=U+10FFFF which are
        // always valid Unicode scalar values.
        char::from_u32(codepoint).ok_or_else(|| {
            SecretError::DecodeFailed(
                "surrogate pair decoded to invalid Unicode scalar value".into(),
            )
        })
    } else if (0xDC00..=0xDFFF).contains(&code) {
        // Lone low surrogate with no preceding high surrogate.
        Err(SecretError::DecodeFailed(format!(
            "\\u{code:04X} is a lone low surrogate"
        )))
    } else {
        char::from_u32(code).ok_or_else(|| {
            SecretError::DecodeFailed("\\uXXXX escape is not a valid Unicode scalar value".into())
        })
    }
}

/// Skip over a JSON value (string, number, bool, null, array, or object)
/// without allocating its content.
fn json_skip_value(chars: &mut Peekable<Chars<'_>>) -> Result<(), SecretError> {
    match chars.peek().copied() {
        Some('"') => {
            chars.next(); // consume '"'
            json_skip_string(chars)
        }
        Some('t') => json_skip_literal(chars, "true"),
        Some('f') => json_skip_literal(chars, "false"),
        Some('n') => json_skip_literal(chars, "null"),
        Some(c) if c == '-' || c.is_ascii_digit() => json_skip_number(chars),
        Some('[') => json_skip_container(chars, '[', ']'),
        Some('{') => json_skip_container(chars, '{', '}'),
        Some(c) => Err(SecretError::DecodeFailed(format!(
            "unexpected character '{c}' at start of JSON value"
        ))),
        None => Err(SecretError::DecodeFailed(
            "unexpected end of input in JSON value".into(),
        )),
    }
}

/// Skip a JSON string after the opening `"` has been consumed.
///
/// Validates `\uXXXX` escapes including surrogate pairs, consistent with
/// `json_parse_string`. A high surrogate not followed by a low surrogate, or a
/// lone low surrogate, is rejected — invalid JSON is rejected regardless of
/// which field is being extracted.
fn json_skip_string(chars: &mut Peekable<Chars<'_>>) -> Result<(), SecretError> {
    loop {
        match chars.next() {
            None => return Err(SecretError::DecodeFailed("unterminated JSON string".into())),
            Some('"') => return Ok(()),
            Some('\\') => match chars.next() {
                None => {
                    return Err(SecretError::DecodeFailed(
                        "truncated escape in JSON string".into(),
                    ))
                }
                Some('u') => {
                    // Validate the escape (including surrogate pairs) but
                    // discard the decoded char — we are skipping, not
                    // extracting.
                    json_consume_unicode_escape(chars)?;
                }
                Some('"' | '\\' | '/' | 'b' | 'f' | 'n' | 'r' | 't') => {}
                Some(c) => {
                    return Err(SecretError::DecodeFailed(format!(
                        "unknown JSON escape '\\{c}'"
                    )));
                }
            },
            // RFC 8259 §7: U+0000–U+001F must be escaped; reject bare
            // control characters in skipped strings too.
            Some(c) if (c as u32) < 0x20 => {
                return Err(SecretError::DecodeFailed(format!(
                    "unescaped control character U+{:04X} in JSON string",
                    c as u32
                )));
            }
            Some(_) => {}
        }
    }
}

fn json_skip_literal(chars: &mut Peekable<Chars<'_>>, literal: &str) -> Result<(), SecretError> {
    for expected in literal.chars() {
        match chars.next() {
            Some(c) if c == expected => {}
            Some(c) => {
                return Err(SecretError::DecodeFailed(format!(
                    "invalid JSON literal: expected '{expected}', got '{c}'"
                )))
            }
            None => {
                return Err(SecretError::DecodeFailed(
                    "unexpected end of input in JSON literal".into(),
                ))
            }
        }
    }
    Ok(())
}

// json_skip_number (char-based, below) and skip_number_b (byte-based, in the
// byte-level navigation section) implement the same RFC 8259 §6 grammar but
// cannot be unified: json_skip_number advances a shared Peekable<Chars>
// iterator and returns (), while skip_number_b takes a positional byte index
// and returns the new position.  The two calling conventions are incompatible.
// If you update one, update the other to match.
fn json_skip_number(chars: &mut Peekable<Chars<'_>>) -> Result<(), SecretError> {
    if chars.peek() == Some(&'-') {
        chars.next();
    }
    // RFC 8259 §6: an integer part (one or more digits) must follow the
    // optional minus sign.  A bare '-' is not a valid JSON number.
    if !chars.peek().map(|c| c.is_ascii_digit()).unwrap_or(false) {
        return Err(SecretError::DecodeFailed(
            "invalid JSON number: expected digit after '-'".into(),
        ));
    }
    // Consume the first integer digit.  RFC 8259 §6: if it is '0', no
    // further digits may appear in the integer part — leading zeros like
    // 01 or 007 are not valid JSON numbers.
    let first = chars.next().expect("peeked above");
    if first == '0' && chars.peek().map(|c| c.is_ascii_digit()).unwrap_or(false) {
        return Err(SecretError::DecodeFailed(
            "invalid JSON number: leading zeros are not allowed".into(),
        ));
    }
    // Consume remaining integer digits.  When first == '0' the leading-zero
    // check above guarantees the next char is not a digit, so this is a no-op.
    while chars.peek().map(|c| c.is_ascii_digit()).unwrap_or(false) {
        chars.next();
    }
    if chars.peek() == Some(&'.') {
        chars.next();
        // RFC 8259 §6: frac = decimal-point 1*DIGIT — at least one digit
        // must follow the decimal point.  `1.` is not a valid JSON number.
        if !chars.peek().map(|c| c.is_ascii_digit()).unwrap_or(false) {
            return Err(SecretError::DecodeFailed(
                "invalid JSON number: expected digit after decimal point".into(),
            ));
        }
        while chars.peek().map(|c| c.is_ascii_digit()).unwrap_or(false) {
            chars.next();
        }
    }
    if matches!(chars.peek(), Some('e') | Some('E')) {
        chars.next();
        if matches!(chars.peek(), Some('+') | Some('-')) {
            chars.next();
        }
        // RFC 8259 §6: at least one digit must follow the exponent indicator.
        if !chars.peek().map(|c| c.is_ascii_digit()).unwrap_or(false) {
            return Err(SecretError::DecodeFailed(
                "invalid JSON number: exponent has no digits".into(),
            ));
        }
        while chars.peek().map(|c| c.is_ascii_digit()).unwrap_or(false) {
            chars.next();
        }
    }
    Ok(())
}

/// Skip a JSON array `[...]` or object `{...}`, handling nested structures and
/// strings (which may contain the closing bracket as escaped characters).
///
/// # Limitation: mixed bracket types are not validated
///
/// This function only counts occurrences of the *specific* `open`/`close` pair
/// it was called with.  A structurally invalid input like `[{]}` will be
/// accepted: `[` opens depth 1, `{` is ignored (wrong bracket type), `]`
/// closes depth 0 and returns `Ok`.  The iterator position after the call is
/// correct (we stop at `]`), but the remaining `}` will be unexpected in the
/// caller and will produce a parse error there.
///
/// This is acceptable because `json_extract_string_field` only calls this
/// function to skip non-target field values, not to validate the JSON
/// structure.  The outer loop will detect the malformed trailing `}` and
/// return `DecodeFailed`.  Do not rely on this function as a structural
/// validator for bracket-type matching.
fn json_skip_container(
    chars: &mut Peekable<Chars<'_>>,
    open: char,
    close: char,
) -> Result<(), SecretError> {
    // Consume the opening bracket/brace.
    chars.next();
    let mut depth = 1usize;
    loop {
        match chars.next() {
            None => {
                return Err(SecretError::DecodeFailed(
                    "unterminated JSON container".into(),
                ))
            }
            Some('"') => json_skip_string(chars)?,
            Some(c) if c == open => depth += 1,
            Some(c) if c == close => {
                depth -= 1;
                if depth == 0 {
                    return Ok(());
                }
            }
            Some(_) => {}
        }
    }
}

// ── Byte-level JSON navigation ────────────────────────────────────────────────
//
// These functions provide zero-allocation navigation through nested JSON
// objects.  Unlike the char-based `json_extract_string_field` above, they
// track byte positions so they can return `&[u8]` sub-slices of the input.
//
// Why byte-level and not char-level?
// `Peekable<Chars<'_>>` does not expose byte offsets.  A byte-level scanner
// is safe for JSON because all structural characters ('{', '}', '[', ']',
// ':', ',', '"', '\\') are ASCII (< 0x80) and cannot appear as continuation
// bytes in multi-byte UTF-8 sequences.  Key strings with non-ASCII chars are
// handled by dropping back to `str` for the char boundary.

/// Navigate through `path` in nested JSON objects and return a raw byte slice
/// of the value at the final key.  An empty `path` returns `bytes` unchanged.
fn json_navigate<'a>(bytes: &'a [u8], path: &[&str]) -> Result<&'a [u8], SecretError> {
    let mut current = bytes;
    for key in path {
        current = json_find_value_b(current, key)?;
    }
    Ok(current)
}

/// Find `key` in the JSON object `bytes` and return a raw byte sub-slice of
/// its value.  Leading/trailing whitespace of the value is excluded.
fn json_find_value_b<'a>(bytes: &'a [u8], key: &str) -> Result<&'a [u8], SecretError> {
    // Validate UTF-8 so that scan_string_key_b can safely use str operations.
    if std::str::from_utf8(bytes).is_err() {
        return Err(SecretError::DecodeFailed("not valid UTF-8".into()));
    }

    let mut pos = skip_ws_b(bytes, 0);
    if bytes.get(pos) != Some(&b'{') {
        return Err(SecretError::DecodeFailed("expected JSON object '{'".into()));
    }
    pos += 1;
    pos = skip_ws_b(bytes, pos);

    // Handle empty object.
    if bytes.get(pos) == Some(&b'}') {
        return Err(SecretError::DecodeFailed(format!("key `{key}` not found")));
    }

    loop {
        pos = skip_ws_b(bytes, pos);
        if bytes.get(pos) != Some(&b'"') {
            return Err(SecretError::DecodeFailed("expected '\"' for key".into()));
        }
        let (k, new_pos) = scan_string_key_b(bytes, pos + 1)?;
        pos = new_pos;

        pos = skip_ws_b(bytes, pos);
        if bytes.get(pos) != Some(&b':') {
            return Err(SecretError::DecodeFailed("expected ':' after key".into()));
        }
        pos += 1;
        pos = skip_ws_b(bytes, pos);

        let value_start = pos;
        let value_end = skip_value_b(bytes, pos)?;

        if k == key {
            // skip_value_b stops exactly after the last byte of the value
            // token; no trailing whitespace is included in [value_start..value_end].
            return Ok(&bytes[value_start..value_end]);
        }

        pos = skip_ws_b(bytes, value_end);
        match bytes.get(pos) {
            Some(&b',') => {
                pos += 1;
                pos = skip_ws_b(bytes, pos);
                // Guard against trailing comma.
                if bytes.get(pos) == Some(&b'}') {
                    return Err(SecretError::DecodeFailed(
                        "trailing comma in JSON object".into(),
                    ));
                }
            }
            Some(&b'}') => {
                return Err(SecretError::DecodeFailed(format!("key `{key}` not found")));
            }
            Some(&c) => {
                return Err(SecretError::DecodeFailed(format!(
                    "expected ',' or '}}' in JSON object, got byte {c:#04x}"
                )));
            }
            None => {
                return Err(SecretError::DecodeFailed(
                    "unexpected end of JSON object".into(),
                ));
            }
        }
    }
}

/// Advance past ASCII whitespace; return the new position.
fn skip_ws_b(bytes: &[u8], mut pos: usize) -> usize {
    while matches!(
        bytes.get(pos),
        Some(b' ') | Some(b'\t') | Some(b'\n') | Some(b'\r')
    ) {
        pos += 1;
    }
    pos
}

/// Parse a JSON key string, starting just AFTER the opening `"`.
/// Returns `(decoded_key, byte_position_after_closing_quote)`.
///
/// Handles all JSON string escapes including `\uXXXX` and surrogate pairs.
/// Multi-byte UTF-8 characters in keys are passed through correctly.
fn scan_string_key_b(bytes: &[u8], mut pos: usize) -> Result<(String, usize), SecretError> {
    let mut key = String::new();
    while pos < bytes.len() {
        let b = bytes[pos];
        pos += 1;
        match b {
            b'"' => return Ok((key, pos)),
            b'\\' => {
                if pos >= bytes.len() {
                    return Err(SecretError::DecodeFailed(
                        "truncated escape in JSON key".into(),
                    ));
                }
                let e = bytes[pos];
                pos += 1;
                match e {
                    b'"' => key.push('"'),
                    b'\\' => key.push('\\'),
                    b'/' => key.push('/'),
                    b'b' => key.push('\x08'),
                    b'f' => key.push('\x0C'),
                    b'n' => key.push('\n'),
                    b'r' => key.push('\r'),
                    b't' => key.push('\t'),
                    b'u' => {
                        if pos + 4 > bytes.len() {
                            return Err(SecretError::DecodeFailed(
                                "truncated \\uXXXX in JSON key".into(),
                            ));
                        }
                        let hex = std::str::from_utf8(&bytes[pos..pos + 4]).map_err(|_| {
                            SecretError::DecodeFailed("non-ASCII bytes in \\uXXXX escape".into())
                        })?;
                        let code = u32::from_str_radix(hex, 16).map_err(|_| {
                            SecretError::DecodeFailed("invalid hex digits in \\uXXXX".into())
                        })?;
                        pos += 4;
                        if (0xD800..=0xDBFF).contains(&code) {
                            // High surrogate — must be followed by \uXXXX low surrogate.
                            if bytes.get(pos..pos + 2) != Some(b"\\u") {
                                return Err(SecretError::DecodeFailed(format!(
                                    "\\u{code:04X} is a high surrogate not followed by \\uXXXX"
                                )));
                            }
                            if pos + 6 > bytes.len() {
                                return Err(SecretError::DecodeFailed(
                                    "truncated low-surrogate \\uXXXX".into(),
                                ));
                            }
                            let low_hex =
                                std::str::from_utf8(&bytes[pos + 2..pos + 6]).map_err(|_| {
                                    SecretError::DecodeFailed(
                                        "non-ASCII bytes in low-surrogate \\uXXXX".into(),
                                    )
                                })?;
                            let low = u32::from_str_radix(low_hex, 16).map_err(|_| {
                                SecretError::DecodeFailed(
                                    "invalid hex in low-surrogate \\uXXXX".into(),
                                )
                            })?;
                            if !(0xDC00..=0xDFFF).contains(&low) {
                                return Err(SecretError::DecodeFailed(format!(
                                    "\\u{code:04X} high surrogate not followed by low surrogate (got \\u{low:04X})"
                                )));
                            }
                            let cp = 0x10000u32 + ((code - 0xD800) << 10) + (low - 0xDC00);
                            key.push(char::from_u32(cp).ok_or_else(|| {
                                SecretError::DecodeFailed(
                                    "surrogate pair decoded to invalid scalar".into(),
                                )
                            })?);
                            pos += 6;
                        } else if (0xDC00..=0xDFFF).contains(&code) {
                            return Err(SecretError::DecodeFailed(format!(
                                "\\u{code:04X} is a lone low surrogate"
                            )));
                        } else {
                            key.push(char::from_u32(code).ok_or_else(|| {
                                SecretError::DecodeFailed(
                                    "\\uXXXX decoded to invalid Unicode scalar".into(),
                                )
                            })?);
                        }
                    }
                    _ => {
                        return Err(SecretError::DecodeFailed(format!(
                            "unknown JSON escape '\\{}'",
                            e as char
                        )))
                    }
                }
            }
            b if b < 0x20 => {
                return Err(SecretError::DecodeFailed(format!(
                    "unescaped control character {b:#04x} in JSON key"
                )));
            }
            b if b < 0x80 => {
                // Plain ASCII.
                key.push(b as char);
            }
            _ => {
                // Multi-byte UTF-8 sequence.  UTF-8 validity was confirmed by
                // json_find_value_b; `bytes[pos-1..]` starts at the lead byte.
                let rest = std::str::from_utf8(&bytes[pos - 1..])
                    .expect("UTF-8 validity confirmed at json_find_value_b entry");
                let ch = rest
                    .chars()
                    .next()
                    .expect("non-empty slice has at least one char");
                key.push(ch);
                pos += ch.len_utf8() - 1; // already consumed lead byte above
            }
        }
    }
    Err(SecretError::DecodeFailed("unterminated JSON string".into()))
}

/// Skip a JSON value at `pos` and return the byte position past its last byte.
fn skip_value_b(bytes: &[u8], pos: usize) -> Result<usize, SecretError> {
    match bytes.get(pos) {
        Some(b'"') => skip_string_b(bytes, pos + 1),
        Some(b'{') => skip_container_b(bytes, pos + 1, b'}'),
        Some(b'[') => skip_container_b(bytes, pos + 1, b']'),
        Some(b't') => expect_literal_b(bytes, pos, b"true"),
        Some(b'f') => expect_literal_b(bytes, pos, b"false"),
        Some(b'n') => expect_literal_b(bytes, pos, b"null"),
        Some(&c) if c == b'-' || c.is_ascii_digit() => skip_number_b(bytes, pos),
        Some(&c) => Err(SecretError::DecodeFailed(format!(
            "unexpected byte {c:#04x} at start of JSON value"
        ))),
        None => Err(SecretError::DecodeFailed(
            "unexpected end of input at JSON value".into(),
        )),
    }
}

/// Skip a JSON string body (call after consuming the opening `"`).
/// Returns the byte position past the closing `"`.
fn skip_string_b(bytes: &[u8], mut pos: usize) -> Result<usize, SecretError> {
    while pos < bytes.len() {
        match bytes[pos] {
            b'"' => return Ok(pos + 1),
            b'\\' => {
                pos += 1;
                if pos >= bytes.len() {
                    return Err(SecretError::DecodeFailed(
                        "truncated escape in JSON string".into(),
                    ));
                }
                // For \uXXXX skip 'u' + 4 hex digits.
                //
                // Surrogate pairs (\uHHHH\uLLLL) are NOT validated here: this
                // path skips values without decoding them, and validating
                // surrogates would require hex parsing and lookahead beyond what
                // a byte-level skip warrants.  The char-level skip
                // (json_skip_string, used by extract_field) does validate
                // surrogates.  If surrogate-level validation is needed on the
                // byte-level path, use extract_field instead of extract_path.
                pos += if bytes[pos] == b'u' { 5 } else { 1 };
            }
            // RFC 8259 §7: U+0000–U+001F must be escaped; reject bare control
            // characters in skipped strings, consistent with json_skip_string.
            b if b < 0x20 => {
                return Err(SecretError::DecodeFailed(format!(
                    "unescaped control character {b:#04x} in JSON string"
                )));
            }
            // All other bytes — including multi-byte UTF-8 continuation bytes
            // (≥ 0x80) — are skipped one byte at a time.  They cannot be '"'
            // or '\' (both ASCII), so this is safe.
            _ => pos += 1,
        }
    }
    Err(SecretError::DecodeFailed("unterminated JSON string".into()))
}

/// Skip a JSON `{...}` or `[...]` body (call after consuming the opening
/// bracket).  `close` is the expected closing byte (`b'}'` or `b']'`).
fn skip_container_b(bytes: &[u8], mut pos: usize, close: u8) -> Result<usize, SecretError> {
    let mut depth: u32 = 1;
    while pos < bytes.len() {
        match bytes[pos] {
            b'"' => pos = skip_string_b(bytes, pos + 1)?,
            b'{' | b'[' => {
                depth += 1;
                pos += 1;
            }
            b'}' | b']' => {
                depth -= 1;
                if depth == 0 {
                    if bytes[pos] != close {
                        return Err(SecretError::DecodeFailed("mismatched JSON brackets".into()));
                    }
                    return Ok(pos + 1);
                }
                pos += 1;
            }
            _ => pos += 1,
        }
    }
    Err(SecretError::DecodeFailed(
        "unterminated JSON container".into(),
    ))
}

/// Verify `bytes[pos..]` starts with `literal` and return `pos + literal.len()`.
fn expect_literal_b(bytes: &[u8], pos: usize, literal: &[u8]) -> Result<usize, SecretError> {
    let end = pos + literal.len();
    if bytes.get(pos..end) == Some(literal) {
        Ok(end)
    } else {
        Err(SecretError::DecodeFailed(format!(
            "expected JSON literal `{}`",
            std::str::from_utf8(literal).unwrap_or("?")
        )))
    }
}

/// Skip a JSON number starting at `pos` and return the position past its end.
///
/// Implements the same RFC 8259 §6 grammar as `json_skip_number` (char-based)
/// but operates on a positional byte index rather than a `Peekable<Chars>`
/// iterator.  The two cannot be unified — see the comment above
/// `json_skip_number` for the reason.  If you update one, update the other.
fn skip_number_b(bytes: &[u8], mut pos: usize) -> Result<usize, SecretError> {
    if bytes.get(pos) == Some(&b'-') {
        pos += 1;
    }
    if !bytes.get(pos).is_some_and(u8::is_ascii_digit) {
        return Err(SecretError::DecodeFailed(
            "invalid JSON number: expected digit".into(),
        ));
    }
    // Consume the first integer digit.  RFC 8259 §6: if it is '0', no
    // further digits may appear in the integer part — leading zeros like
    // 01 or 007 are not valid JSON numbers.
    let first = bytes[pos];
    pos += 1;
    if first == b'0' && bytes.get(pos).is_some_and(u8::is_ascii_digit) {
        return Err(SecretError::DecodeFailed(
            "invalid JSON number: leading zeros are not allowed".into(),
        ));
    }
    while bytes.get(pos).is_some_and(u8::is_ascii_digit) {
        pos += 1;
    }
    if bytes.get(pos) == Some(&b'.') {
        pos += 1;
        // RFC 8259: at least one digit must follow the decimal point.
        if !bytes.get(pos).is_some_and(u8::is_ascii_digit) {
            return Err(SecretError::DecodeFailed(
                "invalid JSON number: expected digit after '.'".into(),
            ));
        }
        while bytes.get(pos).is_some_and(u8::is_ascii_digit) {
            pos += 1;
        }
    }
    if matches!(bytes.get(pos), Some(b'e') | Some(b'E')) {
        pos += 1;
        if matches!(bytes.get(pos), Some(b'+') | Some(b'-')) {
            pos += 1;
        }
        // RFC 8259: at least one digit must follow the exponent marker.
        if !bytes.get(pos).is_some_and(u8::is_ascii_digit) {
            return Err(SecretError::DecodeFailed(
                "invalid JSON number: expected digit in exponent".into(),
            ));
        }
        while bytes.get(pos).is_some_and(u8::is_ascii_digit) {
            pos += 1;
        }
    }
    Ok(pos)
}

// ── SecretError ───────────────────────────────────────────────────────────────

/// Errors returned by secret store operations.
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
pub enum SecretError {
    /// Backend returned no secret for this name/path.
    #[error("secret not found")]
    NotFound,

    /// Backend returned an error.
    #[error("backend `{backend}` error: {source}")]
    Backend {
        backend: &'static str,
        #[source]
        source: Box<dyn std::error::Error + Send + Sync>,
    },

    /// URI was syntactically invalid or named an unknown/disabled backend.
    #[error("invalid URI: {0}")]
    InvalidUri(String),

    /// Secret was present but could not be decoded as expected.
    #[error("decode failed: {0}")]
    DecodeFailed(String),

    /// Backend is not available (unreachable, token expired, etc.).
    #[error("backend `{backend}` unavailable: {source}")]
    Unavailable {
        backend: &'static str,
        #[source]
        source: Box<dyn std::error::Error + Send + Sync>,
    },
}

// ── SecretUri helpers ─────────────────────────────────────────────────────────

/// Percent-decode a URI component string (path segment or query value).
///
/// Decodes `%XX` escape sequences where `XX` is a pair of hex digits.
/// Returns `Err(SecretError::InvalidUri)` if a `%` is not followed by two
/// valid hex digits.
fn percent_decode(s: &str) -> Result<String, SecretError> {
    let bytes = s.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'%' {
            if i + 2 >= bytes.len() {
                return Err(SecretError::InvalidUri(format!(
                    "incomplete percent-encoding at position {i} in `{s}`"
                )));
            }
            let hi = hex_digit(bytes[i + 1]).ok_or_else(|| {
                SecretError::InvalidUri(format!(
                    "invalid percent-encoding `%{}{}` at position {i} in `{s}`",
                    bytes[i + 1] as char,
                    bytes[i + 2] as char
                ))
            })?;
            let lo = hex_digit(bytes[i + 2]).ok_or_else(|| {
                SecretError::InvalidUri(format!(
                    "invalid percent-encoding `%{}{}` at position {i} in `{s}`",
                    bytes[i + 1] as char,
                    bytes[i + 2] as char
                ))
            })?;
            out.push((hi << 4) | lo);
            i += 3;
        } else {
            out.push(bytes[i]);
            i += 1;
        }
    }
    String::from_utf8(out).map_err(|_| {
        SecretError::InvalidUri(format!(
            "percent-decoded bytes in `{s}` are not valid UTF-8"
        ))
    })
}

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

// ── SecretUri ─────────────────────────────────────────────────────────────────

/// A parsed `secretx://` URI.
///
/// All backend `from_uri` constructors should parse with this type rather than
/// rolling their own string splitting.
///
/// # URI structure
///
/// ```text
/// secretx://<backend>/<path>[?key=val&key2=val2]
/// ```
///
/// Absolute file paths use a double slash after the backend:
///
/// ```text
/// secretx://file//etc/secrets/key   →  backend="file", path="/etc/secrets/key"
/// secretx://file/relative/path      →  backend="file", path="relative/path"
/// ```
///
/// # Field access
///
/// All fields are private. Use the accessor methods [`SecretUri::backend`],
/// [`SecretUri::path`], and [`SecretUri::param`] to read URI components.
/// This preserves the ability to change the internal representation (e.g.
/// multi-value params or a different map type) without a breaking API change.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SecretUri {
    backend: String,
    path: String,
    params: HashMap<String, String>,
}

impl SecretUri {
    const SCHEME: &'static str = "secretx://";

    /// Parse a `secretx://` URI.
    ///
    /// Returns [`SecretError::InvalidUri`] if the URI does not start with
    /// `secretx://` or has an empty backend component.
    pub fn parse(uri: &str) -> Result<Self, SecretError> {
        let rest = uri.strip_prefix(Self::SCHEME).ok_or_else(|| {
            SecretError::InvalidUri(format!("URI must start with `secretx://`, got: {uri}"))
        })?;

        // Split query string from path.
        let (path_part, query_part) = match rest.find('?') {
            Some(i) => (&rest[..i], Some(&rest[i + 1..])),
            None => (rest, None),
        };

        // Split backend name from the rest of the path on the first '/'.
        let (backend, raw_path) = match path_part.find('/') {
            Some(i) => (&path_part[..i], &path_part[i + 1..]),
            None => (path_part, ""),
        };

        if backend.is_empty() {
            return Err(SecretError::InvalidUri(format!(
                "missing backend name in URI: {uri}"
            )));
        }

        // raw_path starts with '/' for absolute paths (the double-slash encoding):
        //   secretx://file//etc/key  →  raw_path = "/etc/key"   (absolute)
        //   secretx://file/rel/key   →  raw_path = "rel/key"    (relative)
        let path = percent_decode(raw_path)?;

        // Parse query parameters, percent-decoding both keys and values.
        let mut params = HashMap::new();
        if let Some(q) = query_part {
            for pair in q.split('&').filter(|s| !s.is_empty()) {
                match pair.find('=') {
                    Some(i) => {
                        let key = percent_decode(&pair[..i])?;
                        let val = percent_decode(&pair[i + 1..])?;
                        params.insert(key, val);
                    }
                    None => {
                        params.insert(percent_decode(pair)?, String::new());
                    }
                }
            }
        }

        Ok(SecretUri {
            backend: backend.to_string(),
            path,
            params,
        })
    }

    /// Return the backend name, e.g. `"aws-sm"`, `"file"`, `"env"`.
    pub fn backend(&self) -> &str {
        &self.backend
    }

    /// Return the backend-specific path component of the URI.
    pub fn path(&self) -> &str {
        &self.path
    }

    /// Return a query parameter value by key, or `None` if absent.
    pub fn param(&self, key: &str) -> Option<&str> {
        self.params.get(key).map(String::as_str)
    }
}

// ── SecretStore ───────────────────────────────────────────────────────────────

/// A backend that retrieves and stores secrets.
///
/// Implement this trait in a backend crate. Provide a `from_uri` constructor
/// as a plain method (not part of this trait) that calls [`SecretUri::parse`]
/// and validates the backend component. URI dispatch is handled by
/// `secretx::from_uri` in the umbrella crate.
///
/// Each `SecretStore` instance is bound to exactly one secret, identified by
/// the URI passed to `from_uri`. There is no key parameter on `get` or `put`;
/// which secret is returned is determined entirely by the URI, not by the call
/// site.
#[async_trait::async_trait]
pub trait SecretStore: Send + Sync {
    /// Retrieve the secret.
    async fn get(&self) -> Result<SecretValue, SecretError>;

    /// Write or update the secret. Not supported by all backends.
    async fn put(&self, value: SecretValue) -> Result<(), SecretError>;

    /// Force a fresh fetch from the source, bypassing any cache layer, and
    /// return the new value.
    async fn refresh(&self) -> Result<SecretValue, SecretError>;
}

// ── SigningBackend ────────────────────────────────────────────────────────────

/// Key algorithm used by a [`SigningBackend`].
///
/// This enum is `#[non_exhaustive]` so that new algorithms (e.g. P-384,
/// Ed448) can be added in a minor version without breaking downstream
/// code that matches on it.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SigningAlgorithm {
    Ed25519,
    EcdsaP256Sha256,
    RsaPss2048Sha256,
}

/// A signing backend where the private key never leaves the HSM.
///
/// Implemented by AWS KMS, Azure Key Vault HSM, PKCS#11, wolfHSM, and local
/// key backends. Call sites are identical regardless of backend.
#[async_trait::async_trait]
pub trait SigningBackend: Send + Sync {
    /// Sign `message` using the backend key. Returns raw signature bytes.
    async fn sign(&self, message: &[u8]) -> Result<Vec<u8>, SecretError>;

    /// Return the public key as DER-encoded SubjectPublicKeyInfo.
    async fn public_key_der(&self) -> Result<Vec<u8>, SecretError>;

    /// Key algorithm identifier.
    ///
    /// Returns an error if the backend cannot determine the algorithm (e.g. the
    /// HSM is offline).  For backends where the algorithm is fixed at
    /// construction time (AWS KMS, local-signing) this always returns `Ok`.
    fn algorithm(&self) -> Result<SigningAlgorithm, SecretError>;
}

// ── Blocking adapter ─────────────────────────────────────────────────────────

/// Run an async block on a dedicated scoped thread with its own single-threaded
/// tokio runtime.
///
/// This is the correct pattern for backends that need to execute async code
/// synchronously at construction time (e.g. AWS client initialization via
/// `aws_config::load_from_env`).  Unlike `block_in_place` or `Handle::block_on`,
/// this never panics when called from within an existing `current_thread` runtime
/// because the async work runs on a *new* OS thread with its *own* runtime.
///
/// # Errors
///
/// Returns `Err(SecretError::Backend)` if the tokio runtime cannot be built or
/// if the spawned thread panics.  The `backend` argument is included in the
/// error for diagnostics.
#[cfg(feature = "blocking")]
pub fn run_on_new_thread<F, Fut, T>(f: F, backend: &'static str) -> Result<T, SecretError>
where
    F: FnOnce() -> Fut + Send,
    Fut: std::future::Future<Output = Result<T, SecretError>>,
    T: Send,
{
    let mut result: Option<Result<T, SecretError>> = None;
    std::thread::scope(|s| {
        let join = s.spawn(|| {
            tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .map_err(|e| SecretError::Backend {
                    backend,
                    source: e.into(),
                })
                .and_then(|rt| rt.block_on(f()))
        });
        result = Some(join.join().unwrap_or_else(|_| {
            Err(SecretError::Backend {
                backend,
                source: "client init thread panicked".into(),
            })
        }));
    });
    result.expect("scope always sets result before exiting")
}

/// Synchronous wrapper for [`SecretStore::get`].
///
/// Works both inside an existing tokio runtime and outside one (creates a
/// single-threaded runtime for the call).  When called from within an existing
/// runtime the call is offloaded to a scoped OS thread with its own runtime so
/// that `block_on` does not panic.
///
/// Call [`SecretStore::get`] from a synchronous context.
///
/// When called outside of any tokio runtime a single-threaded runtime is built
/// on the calling thread. When called from inside an existing runtime, a scoped
/// thread with its own single-threaded runtime is spawned.
///
/// # Panics
/// Does not panic in normal use.  Panics only if the spawned helper thread
/// itself panics (i.e. if tokio runtime construction fails).
///
/// # Limitations
///
/// The scoped runtime is a **fresh, isolated runtime** that lasts only for the
/// duration of the `get` call. If the inner store (or a wrapper like
/// `CachingStore`) internally calls `tokio::spawn` or
/// `tokio::task::spawn_blocking`, those tasks run on the scoped thread's
/// runtime and are **silently dropped** when `block_on` returns. Do not use
/// `get_blocking` with stores that depend on background tasks surviving across
/// calls (e.g. connection-pool health-check tasks, re-auth loops).
#[cfg(feature = "blocking")]
pub fn get_blocking(store: &dyn SecretStore) -> Result<SecretValue, SecretError> {
    // When called from outside any tokio runtime, spin up a one-shot
    // current-thread runtime directly on this thread.
    //
    // When called from inside an existing runtime (current_thread or
    // multi-thread), block_on would panic if called on the same thread.
    // Instead, use std::thread::scope to spawn a scoped thread that borrows
    // `store` and `name` safely. The scope guarantees the thread is joined
    // before it exits, so no lifetime transmutation is needed.
    match tokio::runtime::Handle::try_current() {
        Err(_) => tokio::runtime::Builder::new_current_thread()
            .build()
            .map_err(|e| SecretError::Backend {
                backend: "blocking",
                source: e.into(),
            })?
            .block_on(store.get()),
        Ok(_) => {
            let mut result: Option<Result<SecretValue, SecretError>> = None;
            std::thread::scope(|s| {
                let join = s.spawn(|| {
                    tokio::runtime::Builder::new_current_thread()
                        .build()
                        .map_err(|e| SecretError::Backend {
                            backend: "blocking",
                            source: e.into(),
                        })?
                        .block_on(store.get())
                });
                result = Some(join.join().unwrap_or_else(|_| {
                    Err(SecretError::Backend {
                        backend: "blocking",
                        source: "get_blocking thread panicked".into(),
                    })
                }));
            });
            result.expect("scope always sets result before exiting")
        }
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────────

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

    // SecretValue tests

    #[test]
    fn secret_value_as_bytes() {
        let v = SecretValue::new(b"hello".to_vec());
        assert_eq!(v.as_bytes(), b"hello");
    }

    #[test]
    fn secret_value_as_str() {
        let v = SecretValue::new(b"hello".to_vec());
        assert_eq!(v.as_str().unwrap(), "hello");
    }

    #[test]
    fn secret_value_as_str_invalid_utf8() {
        let v = SecretValue::new(vec![0xff, 0xfe]);
        assert!(matches!(v.as_str(), Err(SecretError::DecodeFailed(_))));
    }

    #[test]
    fn extract_field_ok() {
        let v = SecretValue::new(br#"{"password":"hunter2","user":"alice"}"#.to_vec());
        let pw = v.extract_field("password").unwrap();
        assert_eq!(pw.as_bytes(), b"hunter2");
    }

    #[test]
    fn extract_field_missing() {
        let v = SecretValue::new(br#"{"user":"alice"}"#.to_vec());
        assert!(matches!(
            v.extract_field("password"),
            Err(SecretError::DecodeFailed(_))
        ));
    }

    #[test]
    fn extract_field_not_string() {
        let v = SecretValue::new(br#"{"count":42}"#.to_vec());
        assert!(matches!(
            v.extract_field("count"),
            Err(SecretError::DecodeFailed(_))
        ));
    }

    #[test]
    fn extract_field_invalid_json() {
        let v = SecretValue::new(b"not json".to_vec());
        assert!(matches!(
            v.extract_field("x"),
            Err(SecretError::DecodeFailed(_))
        ));
    }

    // RFC 8259 §7: surrogate pair \uHHHH\uLLLL must decode to the correct
    // supplementary code point.  Oracle: U+1F600 (GRINNING FACE) is 😀;
    // its UTF-8 encoding 0xF0 0x9F 0x98 0x80 is independent of this code.
    #[test]
    fn extract_field_surrogate_pair() {
        // \uD83D\uDE00 is the surrogate pair for U+1F600 (😀)
        let v = SecretValue::new(br#"{"pw":"\uD83D\uDE00"}"#.to_vec());
        let pw = v.extract_field("pw").unwrap();
        assert_eq!(pw.as_bytes(), "😀".as_bytes());
    }

    // \uD800 alone (no follow-up low surrogate) must be rejected.
    #[test]
    fn extract_field_lone_high_surrogate() {
        let v = SecretValue::new(br#"{"pw":"\uD800"}"#.to_vec());
        assert!(matches!(
            v.extract_field("pw"),
            Err(SecretError::DecodeFailed(_))
        ));
    }

    // \uDC00 alone (no preceding high surrogate) must be rejected.
    #[test]
    fn extract_field_lone_low_surrogate() {
        let v = SecretValue::new(br#"{"pw":"\uDC00"}"#.to_vec());
        assert!(matches!(
            v.extract_field("pw"),
            Err(SecretError::DecodeFailed(_))
        ));
    }

    // High surrogate followed by a non-low-surrogate \uXXXX must be rejected.
    #[test]
    fn extract_field_high_surrogate_wrong_follow() {
        // \uD800\u0041 — A is not a low surrogate
        let v = SecretValue::new(br#"{"pw":"\uD800\u0041"}"#.to_vec());
        assert!(matches!(
            v.extract_field("pw"),
            Err(SecretError::DecodeFailed(_))
        ));
    }

    // High surrogate followed by a non-\u sequence must be rejected.
    #[test]
    fn extract_field_high_surrogate_no_follow() {
        // \uD800abc — 'a' is not the start of \uXXXX
        let v = SecretValue::new(br#"{"pw":"\uD800abc"}"#.to_vec());
        assert!(matches!(
            v.extract_field("pw"),
            Err(SecretError::DecodeFailed(_))
        ));
    }

    // Surrogate validation in the *skip* path (non-extracted fields).
    // These test that json_skip_string validates surrogates consistently with
    // json_parse_string — invalid JSON is rejected regardless of which field
    // the invalid sequence appears in.

    #[test]
    fn skip_field_lone_high_surrogate_rejected() {
        // "other" field has lone high surrogate; "password" is valid.
        // extract_field must fail even though the targeted field is fine.
        let v = SecretValue::new(br#"{"other":"\uD800","password":"hunter2"}"#.to_vec());
        assert!(matches!(
            v.extract_field("password"),
            Err(SecretError::DecodeFailed(_))
        ));
    }

    #[test]
    fn skip_field_lone_low_surrogate_rejected() {
        let v = SecretValue::new(br#"{"other":"\uDC00","password":"hunter2"}"#.to_vec());
        assert!(matches!(
            v.extract_field("password"),
            Err(SecretError::DecodeFailed(_))
        ));
    }

    #[test]
    fn skip_field_surrogate_pair_valid() {
        // Valid surrogate pair in a non-extracted field must not cause failure.
        // \uD83D\uDE00 = U+1F600 (😀)
        let v = SecretValue::new(br#"{"emoji":"\uD83D\uDE00","password":"hunter2"}"#.to_vec());
        let pw = v.extract_field("password").unwrap();
        assert_eq!(pw.as_bytes(), b"hunter2");
    }

    // Malformed JSON number validation (json_skip_number).
    // Oracle: RFC 8259 §6 — exponent must contain at least one digit.

    // RFC 8259 §6: an integer part must follow the optional minus.
    // A bare '-' with no digits is not a valid JSON number.
    #[test]
    fn skip_number_bare_minus_rejected() {
        let v = SecretValue::new(br#"{"count":-,"password":"hunter2"}"#.to_vec());
        assert!(matches!(
            v.extract_field("password"),
            Err(SecretError::DecodeFailed(_))
        ));
    }

    #[test]
    fn skip_number_bare_exponent_rejected() {
        // "count" has an exponent with no digits — invalid per RFC 8259.
        let v = SecretValue::new(br#"{"count":1e,"password":"hunter2"}"#.to_vec());
        assert!(matches!(
            v.extract_field("password"),
            Err(SecretError::DecodeFailed(_))
        ));
    }

    #[test]
    fn skip_number_signed_exponent_no_digits_rejected() {
        let v = SecretValue::new(br#"{"count":1e+,"password":"hunter2"}"#.to_vec());
        assert!(matches!(
            v.extract_field("password"),
            Err(SecretError::DecodeFailed(_))
        ));
    }

    #[test]
    fn skip_number_valid_exponent_accepted() {
        // RFC 8259-valid exponent must not cause failure.
        let v = SecretValue::new(br#"{"count":1e3,"password":"hunter2"}"#.to_vec());
        let pw = v.extract_field("password").unwrap();
        assert_eq!(pw.as_bytes(), b"hunter2");
    }

    // RFC 8259 §6: a non-zero integer part must not have leading zeros.
    // Oracle: RFC 8259 §6 grammar — int = zero / (digit1-9 *DIGIT).
    // Any real JSON parser (jq, Python json.loads) rejects 01 and 007.

    #[test]
    fn skip_number_leading_zero_two_digits_rejected() {
        // 01 — leading zero in front of non-zero digit, invalid per RFC 8259.
        let v = SecretValue::new(br#"{"count":01,"password":"hunter2"}"#.to_vec());
        assert!(matches!(
            v.extract_field("password"),
            Err(SecretError::DecodeFailed(_))
        ));
    }

    #[test]
    fn skip_number_leading_zero_multi_digit_rejected() {
        // 007 — leading zeros, invalid per RFC 8259.
        let v = SecretValue::new(br#"{"count":007,"password":"hunter2"}"#.to_vec());
        assert!(matches!(
            v.extract_field("password"),
            Err(SecretError::DecodeFailed(_))
        ));
    }

    #[test]
    fn skip_number_bare_zero_accepted() {
        // 0 alone is valid per RFC 8259 (zero = %x30).
        let v = SecretValue::new(br#"{"count":0,"password":"hunter2"}"#.to_vec());
        let pw = v.extract_field("password").unwrap();
        assert_eq!(pw.as_bytes(), b"hunter2");
    }

    #[test]
    fn skip_number_negative_leading_zero_rejected() {
        // -01 — leading zero after minus, invalid per RFC 8259.
        let v = SecretValue::new(br#"{"count":-01,"password":"hunter2"}"#.to_vec());
        assert!(matches!(
            v.extract_field("password"),
            Err(SecretError::DecodeFailed(_))
        ));
    }

    #[test]
    fn skip_number_negative_zero_accepted() {
        // -0 is a valid JSON number (negative zero).
        let v = SecretValue::new(br#"{"count":-0,"password":"hunter2"}"#.to_vec());
        let pw = v.extract_field("password").unwrap();
        assert_eq!(pw.as_bytes(), b"hunter2");
    }

    // RFC 8259 §6: frac = decimal-point 1*DIGIT — digit(s) required after '.'.
    // Oracle: Python json.loads('{"x":1.}') raises ValueError; jq raises error.

    #[test]
    fn skip_number_no_fractional_digits_rejected() {
        // 1. — decimal point with no fractional digits, invalid per RFC 8259.
        let v = SecretValue::new(br#"{"count":1.,"password":"hunter2"}"#.to_vec());
        assert!(matches!(
            v.extract_field("password"),
            Err(SecretError::DecodeFailed(_))
        ));
    }

    #[test]
    fn skip_number_negative_no_fractional_digits_rejected() {
        // -1. — same violation after a minus sign.
        let v = SecretValue::new(br#"{"count":-1.,"password":"hunter2"}"#.to_vec());
        assert!(matches!(
            v.extract_field("password"),
            Err(SecretError::DecodeFailed(_))
        ));
    }

    #[test]
    fn skip_number_zero_no_fractional_digits_rejected() {
        // 0. — leading zero with decimal point but no fractional digit.
        let v = SecretValue::new(br#"{"count":0.,"password":"hunter2"}"#.to_vec());
        assert!(matches!(
            v.extract_field("password"),
            Err(SecretError::DecodeFailed(_))
        ));
    }

    #[test]
    fn skip_number_fractional_digits_accepted() {
        // 1.5 — valid decimal number must not cause failure.
        let v = SecretValue::new(br#"{"count":1.5,"password":"hunter2"}"#.to_vec());
        let pw = v.extract_field("password").unwrap();
        assert_eq!(pw.as_bytes(), b"hunter2");
    }

    // RFC 8259 §7: unknown single-char escapes (e.g. \z) are invalid.
    // json_skip_string must reject them consistently with json_parse_string.

    #[test]
    fn skip_field_unknown_escape_rejected() {
        // \z is not a valid JSON escape.  Extracting "password" from a document
        // where "other" contains \z must fail — invalid JSON is invalid regardless
        // of which field is the extraction target.
        let v = SecretValue::new(br#"{"other":"\z","password":"hunter2"}"#.to_vec());
        assert!(matches!(
            v.extract_field("password"),
            Err(SecretError::DecodeFailed(_))
        ));
    }

    #[test]
    fn skip_field_all_valid_single_char_escapes_accepted() {
        // All eight valid single-char escapes in a skipped field must not fail.
        // Oracle: RFC 8259 §7 — the allowed escapes are \" \\ \/ \b \f \n \r \t.
        let v = SecretValue::new(br#"{"other":"\"\\\/\b\f\n\r\t","password":"hunter2"}"#.to_vec());
        let pw = v.extract_field("password").unwrap();
        assert_eq!(pw.as_bytes(), b"hunter2");
    }

    // RFC 8259 §7: U+0000–U+001F are control characters that must be escaped.
    // Oracle: RFC 8259 §7 grammar — unescaped = %x20-21 / %x23-5B / %x5D-10FFFF.
    // Python json.loads('{"k":"\x00"}') raises ValueError.

    #[test]
    fn extract_field_null_byte_in_value_rejected() {
        // U+0000 (NUL) directly in a JSON string value is invalid per RFC 8259 §7.
        let v = SecretValue::new(b"{\"key\":\"val\x00ue\"}".to_vec());
        assert!(matches!(
            v.extract_field("key"),
            Err(SecretError::DecodeFailed(_))
        ));
    }

    #[test]
    fn extract_field_control_char_soh_rejected() {
        // U+0001 (SOH) — lowest non-null control character.
        let v = SecretValue::new(b"{\"key\":\"\x01\"}".to_vec());
        assert!(matches!(
            v.extract_field("key"),
            Err(SecretError::DecodeFailed(_))
        ));
    }

    #[test]
    fn extract_field_control_char_us_rejected() {
        // U+001F (US) — highest control character in the prohibited range.
        let v = SecretValue::new(b"{\"key\":\"\x1f\"}".to_vec());
        assert!(matches!(
            v.extract_field("key"),
            Err(SecretError::DecodeFailed(_))
        ));
    }

    #[test]
    fn extract_field_space_accepted() {
        // U+0020 (SPACE) is the first non-control character; must be accepted.
        let v = SecretValue::new(b"{\"key\":\"val ue\"}".to_vec());
        assert_eq!(v.extract_field("key").unwrap().as_bytes(), b"val ue");
    }

    // Trailing garbage after target field value.
    // Oracle: the same input with a different target field order must fail
    // consistently regardless of whether the garbage comes before or after
    // the target field.

    #[test]
    fn extract_field_trailing_garbage_first_field_rejected() {
        // Target field is first; garbage appears before the closing '}'.
        let v = SecretValue::new(br#"{"password":"hunter2" GARBAGE}"#.to_vec());
        assert!(
            matches!(
                v.extract_field("password"),
                Err(SecretError::DecodeFailed(_))
            ),
            "trailing garbage after first field must be rejected"
        );
    }

    #[test]
    fn extract_field_trailing_garbage_last_field_rejected() {
        // Target field is last; garbage appears after its value.
        let v = SecretValue::new(br#"{"other":"x","password":"hunter2" GARBAGE}"#.to_vec());
        assert!(
            matches!(
                v.extract_field("password"),
                Err(SecretError::DecodeFailed(_))
            ),
            "trailing garbage after last field must be rejected"
        );
    }

    #[test]
    fn skip_field_control_char_in_other_field_rejected() {
        // Control char in a skipped field must be caught even when extracting
        // a different field — invalid JSON is invalid regardless of target.
        let v = SecretValue::new(b"{\"other\":\"\x01bad\",\"password\":\"hunter2\"}".to_vec());
        assert!(matches!(
            v.extract_field("password"),
            Err(SecretError::DecodeFailed(_))
        ));
    }

    // SecretUri tests

    #[test]
    fn uri_env() {
        let u = SecretUri::parse("secretx://env/MY_SECRET").unwrap();
        assert_eq!(u.backend, "env");
        assert_eq!(u.path, "MY_SECRET");
        assert!(u.params.is_empty());
    }

    #[test]
    fn uri_file_relative() {
        let u = SecretUri::parse("secretx://file/relative/path/key").unwrap();
        assert_eq!(u.backend, "file");
        assert_eq!(u.path, "relative/path/key");
    }

    #[test]
    fn uri_file_absolute() {
        let u = SecretUri::parse("secretx://file//etc/secrets/key").unwrap();
        assert_eq!(u.backend, "file");
        assert_eq!(u.path, "/etc/secrets/key");
    }

    #[test]
    fn uri_aws_sm_with_params() {
        let u =
            SecretUri::parse("secretx://aws-sm/prod/signing-key?field=password&version=AWSCURRENT")
                .unwrap();
        assert_eq!(u.backend, "aws-sm");
        assert_eq!(u.path, "prod/signing-key");
        assert_eq!(u.param("field"), Some("password"));
        assert_eq!(u.param("version"), Some("AWSCURRENT"));
    }

    #[test]
    fn uri_pkcs11_with_lib() {
        let u = SecretUri::parse("secretx://pkcs11/0/my-key?lib=/usr/lib/libsofthsm2.so").unwrap();
        assert_eq!(u.backend, "pkcs11");
        assert_eq!(u.path, "0/my-key");
        assert_eq!(u.param("lib"), Some("/usr/lib/libsofthsm2.so"));
    }

    #[test]
    fn uri_no_path() {
        let u = SecretUri::parse("secretx://wolfhsm/my-key").unwrap();
        assert_eq!(u.backend, "wolfhsm");
        assert_eq!(u.path, "my-key");
    }

    #[test]
    fn uri_wrong_scheme() {
        assert!(matches!(
            SecretUri::parse("https://example.com/secret"),
            Err(SecretError::InvalidUri(_))
        ));
    }

    #[test]
    fn uri_empty_backend() {
        assert!(matches!(
            SecretUri::parse("secretx:///path"),
            Err(SecretError::InvalidUri(_))
        ));
    }

    #[test]
    fn uri_missing_param() {
        let u = SecretUri::parse("secretx://aws-sm/my-secret").unwrap();
        assert_eq!(u.param("field"), None);
    }

    #[test]
    fn uri_percent_decoded_path() {
        let u = SecretUri::parse("secretx://env/MY%20SECRET").unwrap();
        assert_eq!(u.path, "MY SECRET");
    }

    #[test]
    fn uri_percent_decoded_param_value() {
        let u = SecretUri::parse("secretx://aws-sm/my-secret?field=my%20field").unwrap();
        assert_eq!(u.param("field"), Some("my field"));
    }

    #[test]
    fn uri_percent_decoded_param_key() {
        let u = SecretUri::parse("secretx://aws-sm/my-secret?my%20key=val").unwrap();
        assert_eq!(u.param("my key"), Some("val"));
    }

    #[test]
    fn uri_invalid_percent_encoding() {
        assert!(matches!(
            SecretUri::parse("secretx://env/MY%ZZsecret"),
            Err(SecretError::InvalidUri(_))
        ));
    }

    #[test]
    fn uri_incomplete_percent_encoding() {
        assert!(matches!(
            SecretUri::parse("secretx://env/MY%2"),
            Err(SecretError::InvalidUri(_))
        ));
    }

    #[cfg(feature = "blocking")]
    #[test]
    fn get_blocking_outside_runtime() {
        use std::sync::Arc;

        struct FakeStore;

        #[async_trait::async_trait]
        impl SecretStore for FakeStore {
            async fn get(&self) -> Result<SecretValue, SecretError> {
                Ok(SecretValue::new(b"test-value".to_vec()))
            }
            async fn put(&self, _: SecretValue) -> Result<(), SecretError> {
                Ok(())
            }
            async fn refresh(&self) -> Result<SecretValue, SecretError> {
                self.get().await
            }
        }

        let store = Arc::new(FakeStore);
        let v = get_blocking(store.as_ref()).unwrap();
        assert_eq!(v.as_bytes(), b"test-value");
    }

    // Test the inside-runtime code path: get_blocking called from within an
    // existing tokio runtime must spawn a scoped thread rather than calling
    // block_on on the current executor thread (which would panic).
    // Oracle: the value returned must equal what FakeStore::get produces.
    #[cfg(feature = "blocking")]
    #[tokio::test]
    async fn get_blocking_inside_runtime() {
        use std::sync::Arc;

        struct FakeStore;

        #[async_trait::async_trait]
        impl SecretStore for FakeStore {
            async fn get(&self) -> Result<SecretValue, SecretError> {
                Ok(SecretValue::new(b"inside-runtime".to_vec()))
            }
            async fn put(&self, _: SecretValue) -> Result<(), SecretError> {
                Ok(())
            }
            async fn refresh(&self) -> Result<SecretValue, SecretError> {
                self.get().await
            }
        }

        let store = Arc::new(FakeStore);
        // Calling get_blocking from inside a #[tokio::test] runtime exercises
        // the Ok(_) branch of Handle::try_current() — the scoped-thread path.
        let v = get_blocking(store.as_ref()).unwrap();
        assert_eq!(v.as_bytes(), b"inside-runtime");
    }

    // ── json_navigate / extract_path / extract_path_field tests ──────────────
    //
    // Oracle: expected output is derived by manual inspection of the literal
    // JSON, not by calling the code under test.

    #[test]
    fn navigate_empty_path_returns_input() {
        // An empty path must return the original bytes unchanged.
        let input = br#"{"k":"v"}"#;
        let result = json_navigate(input, &[]).unwrap();
        assert_eq!(result, input);
    }

    #[test]
    fn navigate_single_key() {
        // Oracle: value of "data" is the sub-object {"key":"val"}.
        let input = br#"{"data":{"key":"val"}}"#;
        let result = json_navigate(input, &["data"]).unwrap();
        assert_eq!(result, br#"{"key":"val"}"#);
    }

    #[test]
    fn navigate_two_levels_vault_pattern() {
        // Vault KV v2 returns {"data":{"data":{...},"metadata":{...}}}.
        // Navigating ["data","data"] should return the inner secret object.
        let input = br#"{"data":{"data":{"password":"s3cr3t"},"metadata":{"version":3}}}"#;
        let result = json_navigate(input, &["data", "data"]).unwrap();
        assert_eq!(result, br#"{"password":"s3cr3t"}"#);
    }

    #[test]
    fn navigate_key_not_found() {
        let input = br#"{"a":"b"}"#;
        assert!(matches!(
            json_navigate(input, &["missing"]),
            Err(SecretError::DecodeFailed(_))
        ));
    }

    #[test]
    fn navigate_intermediate_not_object() {
        // "data" is a string, not an object — navigating into it must fail.
        let input = br#"{"data":"flat-string"}"#;
        assert!(matches!(
            json_navigate(input, &["data", "key"]),
            Err(SecretError::DecodeFailed(_))
        ));
    }

    #[test]
    fn navigate_key_with_escape_in_path() {
        // Key contains a JSON escape sequence; scan_string_key_b must decode it
        // to match the raw string supplied to json_navigate.
        // Oracle: the key `my\nkey` (backslash-n) decodes to a two-char string
        // "my" + newline + "key".  We navigate with the decoded form.
        let input = b"{\"my\\nkey\":\"found\"}";
        let result = json_navigate(input, &["my\nkey"]).unwrap();
        assert_eq!(result, b"\"found\"");
    }

    #[test]
    fn navigate_whitespace_around_value() {
        // Trailing whitespace on the returned slice must be trimmed.
        let input = br#"{"k":  42  }"#;
        let result = json_navigate(input, &["k"]).unwrap();
        assert_eq!(result, b"42");
    }

    #[test]
    fn navigate_empty_object_returns_not_found() {
        let input = br#"{}"#;
        assert!(matches!(
            json_navigate(input, &["k"]),
            Err(SecretError::DecodeFailed(_))
        ));
    }

    #[test]
    fn extract_path_vault_nested_object() {
        // extract_path(["data","data"]) should capture the inner object as bytes.
        let json = br#"{"data":{"data":{"token":"abc123"},"metadata":{}}}"#.to_vec();
        let sv = SecretValue::new(json);
        let inner = sv.extract_path(&["data", "data"]).unwrap();
        assert_eq!(inner.as_bytes(), br#"{"token":"abc123"}"#);
    }

    #[test]
    fn extract_path_field_vault_pattern() {
        // extract_path_field(["data","data"], "token") navigates to the inner
        // object and then extracts the string field "token".
        let json =
            br#"{"data":{"data":{"token":"s3cr3t","ttl":300},"metadata":{"version":1}}}"#.to_vec();
        let sv = SecretValue::new(json);
        let token = sv.extract_path_field(&["data", "data"], "token").unwrap();
        assert_eq!(token.as_bytes(), b"s3cr3t");
    }

    #[test]
    fn extract_path_missing_key_returns_decode_failed() {
        let json = br#"{"data":{"other":"val"}}"#.to_vec();
        let sv = SecretValue::new(json);
        assert!(matches!(
            sv.extract_path(&["data", "data"]),
            Err(SecretError::DecodeFailed(_))
        ));
    }

    #[test]
    fn extract_path_field_missing_field_returns_decode_failed() {
        let json = br#"{"data":{"data":{"a":"b"}}}"#.to_vec();
        let sv = SecretValue::new(json);
        assert!(matches!(
            sv.extract_path_field(&["data", "data"], "missing"),
            Err(SecretError::DecodeFailed(_))
        ));
    }

    // ── skip_number_b direct tests ────────────────────────────────────────────
    //
    // These tests exercise skip_number_b via the byte-level json_find_value_b
    // path (extract_path). The existing skip_number_* tests exercise only the
    // char-based path (extract_field). Both paths must be tested independently.
    //
    // Oracle: RFC 8259 §6 defines the JSON number grammar. Malformed numbers
    // are identified by the grammar, not by the implementation under test.

    #[test]
    fn skip_number_b_bare_decimal_rejected_via_navigate() {
        // {"n":1.,"k":"v"} — skip_number_b must reject 1. (no fractional digits)
        // when scanning past the non-target field "n" to reach "k".
        // RFC 8259: decimal-point must be followed by one or more digits.
        let json = br#"{"n":1.,"k":"v"}"#.to_vec();
        let sv = SecretValue::new(json);
        assert!(
            matches!(sv.extract_path(&["k"]), Err(SecretError::DecodeFailed(_))),
            "bare decimal point must be rejected by skip_number_b"
        );
    }

    #[test]
    fn skip_number_b_bare_exponent_rejected_via_navigate() {
        // {"n":1e,"k":"v"} — skip_number_b must reject 1e (no exponent digits).
        // RFC 8259: exponent marker must be followed by one or more digits.
        let json = br#"{"n":1e,"k":"v"}"#.to_vec();
        let sv = SecretValue::new(json);
        assert!(
            matches!(sv.extract_path(&["k"]), Err(SecretError::DecodeFailed(_))),
            "bare exponent must be rejected by skip_number_b"
        );
    }

    #[test]
    fn skip_number_b_signed_exponent_no_digits_rejected_via_navigate() {
        // {"n":1e+,"k":"v"} — exponent sign must be followed by digits.
        let json = br#"{"n":1e+,"k":"v"}"#.to_vec();
        let sv = SecretValue::new(json);
        assert!(
            matches!(sv.extract_path(&["k"]), Err(SecretError::DecodeFailed(_))),
            "signed exponent with no digits must be rejected by skip_number_b"
        );
    }

    #[test]
    fn skip_number_b_valid_number_allows_navigation() {
        // Sanity: a well-formed number in a non-target field must not block navigation.
        let json = br#"{"n":3.14e2,"k":"found"}"#.to_vec();
        let sv = SecretValue::new(json);
        let result = sv.extract_path(&["k"]).unwrap();
        assert_eq!(result.as_bytes(), b"\"found\"");
    }

    // RFC 8259 §6: a non-zero integer part must not have leading zeros.
    // Oracle: RFC 8259 §6 grammar — int = zero / (digit1-9 *DIGIT).
    // These mirror skip_number_leading_zero_* but exercise the byte-level
    // skip_number_b path (via extract_path / json_find_value_b).

    #[test]
    fn skip_number_b_leading_zero_rejected_via_navigate() {
        // 01 — leading zero in non-target field, invalid per RFC 8259.
        let json = br#"{"n":01,"k":"v"}"#.to_vec();
        let sv = SecretValue::new(json);
        assert!(
            matches!(sv.extract_path(&["k"]), Err(SecretError::DecodeFailed(_))),
            "leading zero must be rejected by skip_number_b"
        );
    }

    #[test]
    fn skip_number_b_negative_leading_zero_rejected_via_navigate() {
        // -01 — leading zero after minus, invalid per RFC 8259.
        let json = br#"{"n":-01,"k":"v"}"#.to_vec();
        let sv = SecretValue::new(json);
        assert!(
            matches!(sv.extract_path(&["k"]), Err(SecretError::DecodeFailed(_))),
            "-01 must be rejected by skip_number_b"
        );
    }

    #[test]
    fn skip_number_b_zero_alone_accepted_via_navigate() {
        // Bare 0 is valid per RFC 8259 (zero = %x30).
        let json = br#"{"n":0,"k":"v"}"#.to_vec();
        let sv = SecretValue::new(json);
        let result = sv.extract_path(&["k"]).unwrap();
        assert_eq!(result.as_bytes(), b"\"v\"");
    }

    // RFC 8259 §7: U+0000–U+001F must be escaped; skip_string_b must reject
    // bare control characters in skipped string values, consistent with
    // json_skip_string (char path).
    // Oracle: RFC 8259 §7 grammar — unescaped = %x20-21 / %x23-5B / %x5D-10FFFF.

    #[test]
    fn skip_string_b_control_char_in_skipped_value_rejected_via_navigate() {
        // U+0001 (SOH) in a non-target string value must cause DecodeFailed
        // even though the target field "k" is valid.
        let json = b"{\"other\":\"\x01bad\",\"k\":\"v\"}".to_vec();
        let sv = SecretValue::new(json);
        assert!(
            matches!(sv.extract_path(&["k"]), Err(SecretError::DecodeFailed(_))),
            "control char in skipped string value must be rejected by skip_string_b"
        );
    }

    #[test]
    fn skip_string_b_null_byte_in_skipped_value_rejected_via_navigate() {
        // U+0000 (NUL) in a non-target string value must also be rejected.
        let json = b"{\"other\":\"val\x00ue\",\"k\":\"v\"}".to_vec();
        let sv = SecretValue::new(json);
        assert!(
            matches!(sv.extract_path(&["k"]), Err(SecretError::DecodeFailed(_))),
            "NUL byte in skipped string value must be rejected by skip_string_b"
        );
    }

    #[test]
    fn skip_string_b_space_in_skipped_value_accepted_via_navigate() {
        // U+0020 (SPACE) is the first non-control char; must pass through.
        let json = br#"{"other":"val ue","k":"v"}"#.to_vec();
        let sv = SecretValue::new(json);
        let result = sv.extract_path(&["k"]).unwrap();
        assert_eq!(result.as_bytes(), b"\"v\"");
    }
}