synta-python 0.2.5

Python extension module for the synta ASN.1 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
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
//! Python bindings for PKIX types: [`PyCsr`], [`PyCrl`], [`PyOcspResponse`],
//! and PKCS#7 / PKCS#12 helper functions.

use std::sync::OnceLock;

use pyo3::prelude::*;
use pyo3::types::{PyBytes, PyList, PyString};

use synta::traits::Encode;
use synta::{Decoder, Encoding};
use synta_certificate::Time;

use super::cert::{pem_blocks_to_pyobject, pyobject_to_pem, PyCertificate};
use crate::crypto_keys::PyPrivateKey;
use crate::types::PyObjectIdentifier;

// ── Helpers for CSR / CRL (Name is decoded eagerly, not stored as RawDer) ─────

/// Re-encode a parsed `Name` to DER and format it as an RFC 4514 DN string.
fn name_to_dn_string(name: &synta_certificate::Name<'_>) -> String {
    let mut enc = synta::Encoder::new(synta::Encoding::Der);
    if name.encode(&mut enc).is_err() {
        return String::new();
    }
    synta_certificate::name::format_dn(&enc.finish().unwrap_or_default())
}

/// Re-encode a parsed `Name` to its DER bytes.
fn name_to_der_bytes(name: &synta_certificate::Name<'_>) -> Vec<u8> {
    let mut enc = synta::Encoder::new(synta::Encoding::Der);
    if name.encode(&mut enc).is_err() {
        return Vec::new();
    }
    enc.finish().unwrap_or_default()
}

/// Map an `OCSPResponseStatus` enum value to its RFC 6960 display name.
fn ocsp_status_str(status: synta_certificate::ocsp::OCSPResponseStatus) -> &'static str {
    use synta_certificate::ocsp::OCSPResponseStatus::*;
    match status {
        Successful => "successful",
        MalformedRequest => "malformedRequest",
        InternalError => "internalError",
        TryLater => "tryLater",
        SigRequired => "sigRequired",
        Unauthorized => "unauthorized",
    }
}

// ── PyCsr ─────────────────────────────────────────────────────────────────────

/// PKCS #10 Certificate Signing Request accessible from Python.
///
/// ```python
/// csr = CertificationRequest.from_der(open("req.der", "rb").read())
/// print(csr.subject)
/// print(csr.public_key_algorithm)
/// ```
#[pyclass(frozen, name = "CertificationRequest")]
pub struct PyCsr {
    pub(super) _data: Py<PyBytes>,
    pub(super) raw: &'static [u8],
    inner: OnceLock<Box<synta_certificate::csr::CertificationRequest<'static>>>,
    subject_cache: OnceLock<Py<PyString>>,
    subject_raw_der_cache: OnceLock<Py<PyBytes>>,
    signature_algorithm_cache: OnceLock<Py<PyString>>,
    signature_algorithm_oid_cache: OnceLock<Py<PyObjectIdentifier>>,
    signature_cache: OnceLock<Py<PyBytes>>,
    public_key_algorithm_cache: OnceLock<Py<PyString>>,
    public_key_algorithm_oid_cache: OnceLock<Py<PyObjectIdentifier>>,
    public_key_cache: OnceLock<Py<PyBytes>>,
    spki_der_cache: OnceLock<Py<PyBytes>>,
}

impl PyCsr {
    fn csr(&self) -> PyResult<&synta_certificate::csr::CertificationRequest<'static>> {
        if let Some(v) = self.inner.get() {
            return Ok(v.as_ref());
        }
        let mut decoder = Decoder::new(self.raw, Encoding::Der);
        let decoded = decoder.decode().map_err(|e| {
            pyo3::exceptions::PyValueError::new_err(format!(
                "CertificationRequest DER decode failed: {e}"
            ))
        })?;
        let _ = self.inner.set(Box::new(decoded));
        Ok(self.inner.get().unwrap().as_ref())
    }
}

#[pymethods]
impl PyCsr {
    /// Parse a DER-encoded PKCS #10 Certificate Signing Request.
    #[staticmethod]
    fn from_der(py: Python<'_>, data: Bound<'_, PyBytes>) -> PyResult<Self> {
        let py_bytes = data.unbind();
        // SAFETY: `py_bytes` holds a strong reference (Py<PyBytes>) that
        // keeps the Python bytes object alive for the lifetime of this struct.
        // CPython's bytes objects have a fixed-address, non-relocating payload
        // buffer (CPython has no moving GC).  The slice lifetime is extended
        // to 'static; the actual safety invariants are:
        //   (1) All reads of `raw` go through `&self`; no borrow of the struct
        //       can outlive the struct, so `raw` is never read after drop begins.
        //   (2) `raw: &'static [u8]` has no destructor (fat pointer, no heap
        //       allocation), so field drop order does not cause use-after-free.
        //   (3) `inner` contains only borrow-typed fields; dropping
        //       Box<CertificationRequest<'static>> does not read through the
        //       contained &'static slices (borrows have no destructors).
        // CPython-only: does not hold for PyPy or GraalPy.
        let raw: &'static [u8] = unsafe {
            let s = py_bytes.bind(py).as_bytes();
            std::slice::from_raw_parts(s.as_ptr(), s.len())
        };
        // Minimal structural scan: outer SEQUENCE tag + length.
        {
            let mut d = Decoder::new(raw, Encoding::Der);
            d.read_tag()
                .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("{e}")))?;
            d.read_length()
                .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("{e}")))?;
        }
        Ok(Self {
            _data: py_bytes,
            raw,
            inner: OnceLock::new(),
            subject_cache: OnceLock::new(),
            subject_raw_der_cache: OnceLock::new(),
            signature_algorithm_cache: OnceLock::new(),
            signature_algorithm_oid_cache: OnceLock::new(),
            signature_cache: OnceLock::new(),
            public_key_algorithm_cache: OnceLock::new(),
            public_key_algorithm_oid_cache: OnceLock::new(),
            public_key_cache: OnceLock::new(),
            spki_der_cache: OnceLock::new(),
        })
    }

    /// Parse a PEM-encoded PKCS #10 Certificate Signing Request.
    ///
    /// Returns a single :class:`CertificationRequest` for one PEM block, or a
    /// :class:`list` of :class:`CertificationRequest` objects when multiple
    /// blocks are present.  Raises :exc:`ValueError` if no PEM block is found.
    ///
    /// ```python
    /// csr = CertificationRequest.from_pem(open("csr.pem", "rb").read())
    /// print(csr.subject)
    /// ```
    #[staticmethod]
    fn from_pem<'py>(py: Python<'py>, data: Bound<'_, PyBytes>) -> PyResult<Bound<'py, PyAny>> {
        pem_blocks_to_pyobject(py, data.as_bytes(), |py, bytes| {
            let obj = Self::from_der(py, bytes)?;
            Ok(Py::new(py, obj)?.into_bound(py).into_any())
        })
    }

    /// Serialize one CSR or a list of CSRs to PEM format.
    ///
    /// ```python
    /// pem = CertificationRequest.to_pem(csr)
    /// pem = CertificationRequest.to_pem([csr1, csr2])
    /// ```
    #[staticmethod]
    fn to_pem<'py>(
        py: Python<'py>,
        obj_or_list: Bound<'_, PyAny>,
    ) -> PyResult<Bound<'py, PyBytes>> {
        pyobject_to_pem::<Self, _>(py, "CERTIFICATE REQUEST", &obj_or_list, |c| c.raw)
    }

    /// Subject distinguished name as a string.
    #[getter]
    fn subject<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyString>> {
        if let Some(cached) = self.subject_cache.get() {
            return Ok(cached.clone_ref(py).into_bound(py));
        }
        let s = name_to_dn_string(&self.csr()?.certification_request_info.subject);
        let py_str = PyString::new(py, &s).unbind();
        let _ = self.subject_cache.set(py_str.clone_ref(py));
        Ok(py_str.into_bound(py))
    }

    /// Raw DER bytes of the subject Name SEQUENCE.
    #[getter]
    fn subject_raw_der<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        if let Some(cached) = self.subject_raw_der_cache.get() {
            return Ok(cached.clone_ref(py).into_bound(py));
        }
        let bytes = name_to_der_bytes(&self.csr()?.certification_request_info.subject);
        let py_bytes = PyBytes::new(py, &bytes).unbind();
        let _ = self.subject_raw_der_cache.set(py_bytes.clone_ref(py));
        Ok(py_bytes.into_bound(py))
    }

    /// CSR version (0 = v1 per RFC 2986).
    #[getter]
    fn version(&self) -> PyResult<i64> {
        Ok(self
            .csr()?
            .certification_request_info
            .version
            .as_i64()
            .unwrap_or(0))
    }

    /// Signature algorithm name (e.g. "RSA", "ECDSA", "Ed25519").
    #[getter]
    fn signature_algorithm<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyString>> {
        if let Some(cached) = self.signature_algorithm_cache.get() {
            return Ok(cached.clone_ref(py).into_bound(py));
        }
        let oid = &self.csr()?.signature_algorithm.algorithm;
        let name = synta_certificate::identify_signature_algorithm(oid);
        let s = if name != "Other" {
            name.to_string()
        } else {
            oid.to_string()
        };
        let py_str = PyString::new(py, &s).unbind();
        let _ = self.signature_algorithm_cache.set(py_str.clone_ref(py));
        Ok(py_str.into_bound(py))
    }

    /// OID of the signature algorithm.
    #[getter]
    fn signature_algorithm_oid<'py>(
        &self,
        py: Python<'py>,
    ) -> PyResult<Bound<'py, PyObjectIdentifier>> {
        if let Some(cached) = self.signature_algorithm_oid_cache.get() {
            return Ok(cached.clone_ref(py).into_bound(py));
        }
        let obj = Py::new(
            py,
            PyObjectIdentifier::from_oid(self.csr()?.signature_algorithm.algorithm.clone()),
        )?;
        let _ = self.signature_algorithm_oid_cache.set(obj.clone_ref(py));
        Ok(obj.into_bound(py))
    }

    /// Raw signature bytes.
    #[getter]
    fn signature<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        if let Some(cached) = self.signature_cache.get() {
            return Ok(cached.clone_ref(py).into_bound(py));
        }
        let py_bytes = PyBytes::new(py, self.csr()?.signature.as_bytes()).unbind();
        let _ = self.signature_cache.set(py_bytes.clone_ref(py));
        Ok(py_bytes.into_bound(py))
    }

    /// Public-key algorithm name (e.g. "RSA", "ECDSA", "Ed25519").
    #[getter]
    fn public_key_algorithm<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyString>> {
        if let Some(cached) = self.public_key_algorithm_cache.get() {
            return Ok(cached.clone_ref(py).into_bound(py));
        }
        let oid = &self
            .csr()?
            .certification_request_info
            .subject_pkinfo
            .algorithm
            .algorithm;
        let s = synta_certificate::identify_public_key_algorithm(oid)
            .map(|s| s.to_string())
            .unwrap_or_else(|| oid.to_string());
        let py_str = PyString::new(py, &s).unbind();
        let _ = self.public_key_algorithm_cache.set(py_str.clone_ref(py));
        Ok(py_str.into_bound(py))
    }

    /// OID of the subject public-key algorithm.
    #[getter]
    fn public_key_algorithm_oid<'py>(
        &self,
        py: Python<'py>,
    ) -> PyResult<Bound<'py, PyObjectIdentifier>> {
        if let Some(cached) = self.public_key_algorithm_oid_cache.get() {
            return Ok(cached.clone_ref(py).into_bound(py));
        }
        let obj = Py::new(
            py,
            PyObjectIdentifier::from_oid(
                self.csr()?
                    .certification_request_info
                    .subject_pkinfo
                    .algorithm
                    .algorithm
                    .clone(),
            ),
        )?;
        let _ = self.public_key_algorithm_oid_cache.set(obj.clone_ref(py));
        Ok(obj.into_bound(py))
    }

    /// Raw subject public-key bytes.
    #[getter]
    fn public_key<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        if let Some(cached) = self.public_key_cache.get() {
            return Ok(cached.clone_ref(py).into_bound(py));
        }
        let py_bytes = PyBytes::new(
            py,
            self.csr()?
                .certification_request_info
                .subject_pkinfo
                .subject_public_key
                .as_bytes(),
        )
        .unbind();
        let _ = self.public_key_cache.set(py_bytes.clone_ref(py));
        Ok(py_bytes.into_bound(py))
    }

    /// DER encoding of the ``SubjectPublicKeyInfo`` SEQUENCE from this CSR.
    ///
    /// This is the same encoding that
    /// ``cryptography``'s ``public_bytes(Encoding.DER, PublicFormat.SubjectPublicKeyInfo)``
    /// produces.  Pass it directly to ``CertificateBuilder.public_key_der`` to
    /// copy the public key from a CSR into a new certificate without
    /// re-encoding.
    ///
    /// ```python,ignore
    /// csr = synta.CertificationRequest.from_pem(open("csr.pem", "rb").read())
    /// spki_der = csr.subject_public_key_info_der
    /// # Pass to a certificate builder:
    /// builder.public_key_der(spki_der)
    /// # Or load with cryptography:
    /// from cryptography.hazmat.primitives.serialization import load_der_public_key
    /// pub_key = load_der_public_key(spki_der)
    /// ```
    #[getter]
    fn subject_public_key_info_der<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        if let Some(cached) = self.spki_der_cache.get() {
            return Ok(cached.clone_ref(py).into_bound(py));
        }
        let spki = &self.csr()?.certification_request_info.subject_pkinfo;
        let bytes = spki
            .to_der()
            .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("SPKI encode: {e}")))?;
        let py_bytes = PyBytes::new(py, &bytes).unbind();
        let _ = self.spki_der_cache.set(py_bytes.clone_ref(py));
        Ok(py_bytes.into_bound(py))
    }

    /// Return the DER value bytes of the named extension from this CSR's
    /// ``extensionRequest`` attribute (OID ``1.2.840.113549.1.9.14``), or
    /// ``None`` if the CSR carries no such extension.
    ///
    /// ``oid`` may be a dotted-decimal string or a
    /// :class:`~synta.ObjectIdentifier`.  The value returned is the content of
    /// the ``extnValue`` OCTET STRING — the DER encoding of the extension value
    /// — without the outer OCTET STRING tag and length.  Returns ``None`` when
    /// the CSR has no ``extensionRequest`` attribute, when the attribute
    /// contains no extensions, or when the requested OID is absent.
    ///
    /// ```python,ignore
    /// SAN_OID = "2.5.29.17"
    /// san_der = csr.get_extension_value_der(SAN_OID)
    /// if san_der:
    ///     names = synta.parse_general_names(san_der)
    /// ```
    fn get_extension_value_der<'py>(
        &self,
        py: Python<'py>,
        oid: &Bound<'_, PyAny>,
    ) -> PyResult<Option<Bound<'py, PyBytes>>> {
        let target = super::oid_from_pyany(oid)?;
        let csr = self.csr()?;
        let attrs = match csr.certification_request_info.attributes.as_ref() {
            Some(a) => a,
            None => return Ok(None),
        };
        for attr in attrs.elements() {
            if attr.attr_type.components() != synta_certificate::oids::PKCS9_EXTENSION_REQUEST {
                continue;
            }
            // attr_values: SetOf<RawDer> — first element is the SEQUENCE OF Extension TLV
            let Some(raw) = attr.attr_values.elements().first() else {
                return Ok(None);
            };
            return Ok(synta_certificate::find_extension_value(
                raw.as_bytes(),
                target.components(),
            )
            .map(|v| PyBytes::new(py, v)));
        }
        Ok(None)
    }

    /// Return the Subject Alternative Names from this CSR's ``extensionRequest``
    /// attribute as a list of ``(tag_number, content_bytes)`` tuples.  Returns an
    /// empty list when the CSR carries no SAN extension.
    ///
    /// Returns raw tuples, not typed ``AnyGeneralName`` objects (unlike
    /// :meth:`~synta.Certificate.subject_alt_names`).  Use the tag-number
    /// constants from :mod:`synta.general_name` to interpret each entry.
    ///
    /// ```python,ignore
    /// import synta.general_name as gn
    /// for tag_num, content in csr.subject_alt_names():
    ///     if tag_num == gn.DNS_NAME:
    ///         print("DNS:", content.decode("ascii"))
    /// ```
    fn subject_alt_names<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyList>> {
        use pyo3::types::{PyBytes, PyList, PyTuple};
        let list = PyList::empty(py);
        let csr = self.csr()?;
        let attrs = match csr.certification_request_info.attributes.as_ref() {
            Some(a) => a,
            None => return Ok(list),
        };
        for attr in attrs.elements() {
            if attr.attr_type.components() != synta_certificate::oids::PKCS9_EXTENSION_REQUEST {
                continue;
            }
            let Some(raw) = attr.attr_values.elements().first() else {
                return Ok(list);
            };
            if let Some(san_bytes) = synta_certificate::find_extension_value(
                raw.as_bytes(),
                synta_certificate::oids::SUBJECT_ALT_NAME,
            ) {
                for (tag_num, content) in synta_certificate::parse_general_names(san_bytes) {
                    let tuple = PyTuple::new(
                        py,
                        [
                            tag_num.into_pyobject(py)?.into_any(),
                            PyBytes::new(py, &content).into_any(),
                        ],
                    )?;
                    list.append(tuple)?;
                }
            }
            break;
        }
        Ok(list)
    }

    /// Complete DER encoding of this CSR (the original bytes passed to ``from_der``).
    fn to_der<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        self._data.clone_ref(py).into_bound(py)
    }

    /// Verify the PKCS\#10 self-signature of this CSR.
    ///
    /// Checks that the ``signature`` field was produced over the DER encoding
    /// of ``CertificationRequestInfo`` by the key in ``subjectPKInfo``.
    ///
    /// :raises ValueError: if the signature is invalid or the algorithm is
    ///     unsupported.
    ///
    /// ```python,ignore
    /// csr = synta.CertificationRequest.from_pem(open("csr.pem", "rb").read())
    /// csr.verify_self_signature()   # raises ValueError if invalid
    /// ```
    fn verify_self_signature(&self) -> PyResult<()> {
        use synta_certificate::{default_signature_verifier, SignatureVerifier};

        let csr = self.csr()?;

        // Re-encode CertificationRequestInfo (the TBS).
        let tbs_der = csr.certification_request_info.to_der().map_err(|e| {
            pyo3::exceptions::PyValueError::new_err(format!("CSR info encode: {e}"))
        })?;

        // Re-encode signatureAlgorithm.
        let sig_alg_der = csr
            .signature_algorithm
            .to_der()
            .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("CSR alg encode: {e}")))?;

        // Re-encode the subject's own SubjectPublicKeyInfo.
        let spki_der = csr
            .certification_request_info
            .subject_pkinfo
            .to_der()
            .map_err(|e| {
                pyo3::exceptions::PyValueError::new_err(format!("CSR SPKI encode: {e}"))
            })?;

        // Verify the self-signature using the backend-agnostic verifier.
        default_signature_verifier()
            .verify_certificate_signature(
                &tbs_der,
                &sig_alg_der,
                csr.signature.as_bytes(),
                &spki_der,
            )
            .map_err(|e| {
                pyo3::exceptions::PyValueError::new_err(format!("CSR self-signature invalid: {e}"))
            })
    }

    fn __repr__(&self) -> PyResult<String> {
        Ok(format!(
            "CertificationRequest(subject={:?})",
            name_to_dn_string(&self.csr()?.certification_request_info.subject),
        ))
    }
}

impl PyCsr {
    /// Rust-internal constructor: parse DER bytes into a `PyCsr`.
    ///
    /// Mirrors `from_der` but is accessible from sibling Rust modules.
    pub(crate) fn new_from_der(py: Python<'_>, data: Bound<'_, PyBytes>) -> PyResult<Self> {
        Self::from_der(py, data)
    }
}

// ── PyCrl ─────────────────────────────────────────────────────────────────────

/// X.509 Certificate Revocation List accessible from Python.
///
/// ```python
/// crl = CertificateList.from_der(open("crl.der", "rb").read())
/// print(crl.issuer)
/// print(crl.revoked_count)
/// ```
#[pyclass(frozen, name = "CertificateList")]
pub struct PyCrl {
    pub(super) _data: Py<PyBytes>,
    pub(super) raw: &'static [u8],
    inner: OnceLock<Box<synta_certificate::crl::CertificateList<'static>>>,
    issuer_cache: OnceLock<Py<PyString>>,
    issuer_raw_der_cache: OnceLock<Py<PyBytes>>,
    this_update_cache: OnceLock<Py<PyString>>,
    next_update_cache: OnceLock<Option<Py<PyString>>>,
    signature_algorithm_cache: OnceLock<Py<PyString>>,
    signature_algorithm_oid_cache: OnceLock<Py<PyObjectIdentifier>>,
    signature_value_cache: OnceLock<Py<PyBytes>>,
}

impl PyCrl {
    fn crl(&self) -> PyResult<&synta_certificate::crl::CertificateList<'static>> {
        if let Some(v) = self.inner.get() {
            return Ok(v.as_ref());
        }
        let mut decoder = Decoder::new(self.raw, Encoding::Der);
        let decoded = decoder.decode().map_err(|e| {
            pyo3::exceptions::PyValueError::new_err(format!(
                "CertificateList DER decode failed: {e}"
            ))
        })?;
        let _ = self.inner.set(Box::new(decoded));
        Ok(self.inner.get().unwrap().as_ref())
    }
}

#[pymethods]
impl PyCrl {
    /// Parse a DER-encoded X.509 Certificate Revocation List.
    #[staticmethod]
    fn from_der(py: Python<'_>, data: Bound<'_, PyBytes>) -> PyResult<Self> {
        let py_bytes = data.unbind();
        // SAFETY: `py_bytes` holds a strong reference (Py<PyBytes>) that
        // keeps the Python bytes object alive for the lifetime of this struct.
        // CPython's bytes objects have a fixed-address, non-relocating payload
        // buffer (CPython has no moving GC).  The slice lifetime is extended
        // to 'static; the actual safety invariants are:
        //   (1) All reads of `raw` go through `&self`; no borrow of the struct
        //       can outlive the struct, so `raw` is never read after drop begins.
        //   (2) `raw: &'static [u8]` has no destructor (fat pointer, no heap
        //       allocation), so field drop order does not cause use-after-free.
        //   (3) `inner` contains only borrow-typed fields; dropping
        //       Box<CertificateList<'static>> does not read through the
        //       contained &'static slices (borrows have no destructors).
        // CPython-only: does not hold for PyPy or GraalPy.
        let raw: &'static [u8] = unsafe {
            let s = py_bytes.bind(py).as_bytes();
            std::slice::from_raw_parts(s.as_ptr(), s.len())
        };
        {
            let mut d = Decoder::new(raw, Encoding::Der);
            d.read_tag()
                .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("{e}")))?;
            d.read_length()
                .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("{e}")))?;
        }
        Ok(Self {
            _data: py_bytes,
            raw,
            inner: OnceLock::new(),
            issuer_cache: OnceLock::new(),
            issuer_raw_der_cache: OnceLock::new(),
            this_update_cache: OnceLock::new(),
            next_update_cache: OnceLock::new(),
            signature_algorithm_cache: OnceLock::new(),
            signature_algorithm_oid_cache: OnceLock::new(),
            signature_value_cache: OnceLock::new(),
        })
    }

    /// Parse a PEM-encoded X.509 Certificate Revocation List.
    ///
    /// Returns a single :class:`CertificateList` for one PEM block, or a
    /// :class:`list` of :class:`CertificateList` objects when multiple blocks
    /// are present.  Raises :exc:`ValueError` if no PEM block is found.
    ///
    /// ```python
    /// crl = CertificateList.from_pem(open("crl.pem", "rb").read())
    /// print(crl.issuer)
    /// ```
    #[staticmethod]
    fn from_pem<'py>(py: Python<'py>, data: Bound<'_, PyBytes>) -> PyResult<Bound<'py, PyAny>> {
        pem_blocks_to_pyobject(py, data.as_bytes(), |py, bytes| {
            let obj = Self::from_der(py, bytes)?;
            Ok(Py::new(py, obj)?.into_bound(py).into_any())
        })
    }

    /// Serialize one CRL or a list of CRLs to PEM format.
    ///
    /// ```python
    /// pem = CertificateList.to_pem(crl)
    /// pem = CertificateList.to_pem([crl1, crl2])
    /// ```
    #[staticmethod]
    fn to_pem<'py>(
        py: Python<'py>,
        obj_or_list: Bound<'_, PyAny>,
    ) -> PyResult<Bound<'py, PyBytes>> {
        pyobject_to_pem::<Self, _>(py, "X509 CRL", &obj_or_list, |c| c.raw)
    }

    /// CRL version field (1 = v2), or ``None`` if absent (implies v1).
    ///
    /// RFC 5280 §5.1.2.1: the ``version`` field is present only when the CRL
    /// is version 2.  For RFC 5280-compliant CRLs this value is always ``1``
    /// (the integer 1 encodes version 2).  Returns ``None`` for v1 CRLs.
    #[getter]
    fn version(&self) -> PyResult<Option<i64>> {
        Ok(self
            .crl()?
            .tbs_cert_list
            .version
            .as_ref()
            .and_then(|v| v.as_i64().ok()))
    }

    /// Issuer distinguished name as a string.
    #[getter]
    fn issuer<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyString>> {
        if let Some(cached) = self.issuer_cache.get() {
            return Ok(cached.clone_ref(py).into_bound(py));
        }
        let s = name_to_dn_string(&self.crl()?.tbs_cert_list.issuer);
        let py_str = PyString::new(py, &s).unbind();
        let _ = self.issuer_cache.set(py_str.clone_ref(py));
        Ok(py_str.into_bound(py))
    }

    /// Raw DER bytes of the issuer Name SEQUENCE.
    #[getter]
    fn issuer_raw_der<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        if let Some(cached) = self.issuer_raw_der_cache.get() {
            return Ok(cached.clone_ref(py).into_bound(py));
        }
        let bytes = name_to_der_bytes(&self.crl()?.tbs_cert_list.issuer);
        let py_bytes = PyBytes::new(py, &bytes).unbind();
        let _ = self.issuer_raw_der_cache.set(py_bytes.clone_ref(py));
        Ok(py_bytes.into_bound(py))
    }

    /// thisUpdate time as a string.
    #[getter]
    fn this_update<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyString>> {
        if let Some(cached) = self.this_update_cache.get() {
            return Ok(cached.clone_ref(py).into_bound(py));
        }
        let s = match &self.crl()?.tbs_cert_list.this_update {
            Time::UtcTime(t) => t.to_string(),
            Time::GeneralTime(t) => t.to_string(),
        };
        let py_str = PyString::new(py, &s).unbind();
        let _ = self.this_update_cache.set(py_str.clone_ref(py));
        Ok(py_str.into_bound(py))
    }

    /// nextUpdate time as a string, or ``None`` if absent.
    #[getter]
    fn next_update<'py>(&self, py: Python<'py>) -> PyResult<Option<Bound<'py, PyString>>> {
        if let Some(cached) = self.next_update_cache.get() {
            return Ok(cached.as_ref().map(|s| s.clone_ref(py).into_bound(py)));
        }
        let computed: Option<Bound<'py, PyString>> =
            self.crl()?.tbs_cert_list.next_update.as_ref().map(|t| {
                let s = match t {
                    Time::UtcTime(t) => t.to_string(),
                    Time::GeneralTime(t) => t.to_string(),
                };
                PyString::new(py, &s)
            });
        let to_store = computed.as_ref().map(|s| s.as_unbound().clone_ref(py));
        let _ = self.next_update_cache.set(to_store);
        Ok(computed)
    }

    /// Signature algorithm name (e.g. "RSA", "ECDSA").
    #[getter]
    fn signature_algorithm<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyString>> {
        if let Some(cached) = self.signature_algorithm_cache.get() {
            return Ok(cached.clone_ref(py).into_bound(py));
        }
        let oid = &self.crl()?.signature_algorithm.algorithm;
        let name = synta_certificate::identify_signature_algorithm(oid);
        let s = if name != "Other" {
            name.to_string()
        } else {
            oid.to_string()
        };
        let py_str = PyString::new(py, &s).unbind();
        let _ = self.signature_algorithm_cache.set(py_str.clone_ref(py));
        Ok(py_str.into_bound(py))
    }

    /// OID of the signature algorithm.
    #[getter]
    fn signature_algorithm_oid<'py>(
        &self,
        py: Python<'py>,
    ) -> PyResult<Bound<'py, PyObjectIdentifier>> {
        if let Some(cached) = self.signature_algorithm_oid_cache.get() {
            return Ok(cached.clone_ref(py).into_bound(py));
        }
        let obj = Py::new(
            py,
            PyObjectIdentifier::from_oid(self.crl()?.signature_algorithm.algorithm.clone()),
        )?;
        let _ = self.signature_algorithm_oid_cache.set(obj.clone_ref(py));
        Ok(obj.into_bound(py))
    }

    /// Raw signature bytes.
    #[getter]
    fn signature_value<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        if let Some(cached) = self.signature_value_cache.get() {
            return Ok(cached.clone_ref(py).into_bound(py));
        }
        let py_bytes = PyBytes::new(py, self.crl()?.signature_value.as_bytes()).unbind();
        let _ = self.signature_value_cache.set(py_bytes.clone_ref(py));
        Ok(py_bytes.into_bound(py))
    }

    /// CRL sequence number from the ``cRLNumber`` extension (OID ``2.5.29.20``),
    /// or ``None`` if the CRL carries no such extension.
    ///
    /// Returns an arbitrary-precision Python :class:`int`.
    ///
    /// ```python,ignore
    /// crl = synta.CertificateList.from_der(data)
    /// print("CRL number:", crl.crl_number)
    /// ```
    #[getter]
    fn crl_number<'py>(&self, py: Python<'py>) -> PyResult<Option<Bound<'py, PyAny>>> {
        let Some(n) = self.crl()?.crl_number() else {
            return Ok(None);
        };
        let py_int = if let Ok(v) = n.as_i64() {
            v.into_pyobject(py)?.into_any()
        } else if let Ok(v) = n.as_i128() {
            v.into_pyobject(py)?.into_any()
        } else {
            // Arbitrarily large CRL number — extremely uncommon but RFC-compliant.
            let bytes_obj = PyBytes::new(py, n.as_bytes());
            let kwargs = pyo3::types::PyDict::new(py);
            kwargs.set_item(pyo3::intern!(py, "signed"), false)?;
            py.get_type::<pyo3::types::PyInt>().call_method(
                pyo3::intern!(py, "from_bytes"),
                (bytes_obj, pyo3::intern!(py, "big")),
                Some(&kwargs),
            )?
        };
        Ok(Some(py_int))
    }

    /// Number of revoked certificates in this CRL (0 if no revoked entries).
    #[getter]
    fn revoked_count(&self) -> PyResult<usize> {
        Ok(self
            .crl()?
            .tbs_cert_list
            .revoked_certificates
            .as_ref()
            .map(|v| v.len())
            .unwrap_or(0))
    }

    /// Return the DER value bytes of the named CRL extension, or ``None`` if
    /// the CRL carries no such extension.
    ///
    /// ``oid`` may be a dotted-decimal string or a
    /// :class:`~synta.ObjectIdentifier`.  The value returned is the content of
    /// the ``extnValue`` OCTET STRING — the DER encoding of the extension value
    /// — without the outer OCTET STRING tag and length.
    ///
    /// ```python,ignore
    /// CRL_NUMBER_OID = "2.5.29.20"
    /// crl_num_der = crl.get_extension_value_der(CRL_NUMBER_OID)
    /// if crl_num_der:
    ///     num = int(synta.Decoder(crl_num_der, synta.Encoding.DER).decode_integer())
    ///     print("CRL Number:", num)
    /// ```
    fn get_extension_value_der<'py>(
        &self,
        py: Python<'py>,
        oid: &Bound<'_, PyAny>,
    ) -> PyResult<Option<Bound<'py, PyBytes>>> {
        let target = super::oid_from_pyany(oid)?;
        let exts = match self.crl()?.tbs_cert_list.crl_extensions.as_ref() {
            Some(e) => e,
            None => return Ok(None),
        };
        for ext in exts {
            if ext.extn_id == target {
                return Ok(Some(PyBytes::new(py, ext.extn_value.as_bytes())));
            }
        }
        Ok(None)
    }

    /// Complete DER encoding of this CRL (the original bytes passed to ``from_der``).
    fn to_der<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        self._data.clone_ref(py).into_bound(py)
    }

    /// Verify that this CRL was signed by ``issuer``.
    ///
    /// Checks that the CRL's ``issuer`` Name matches the certificate's
    /// ``subject`` Name, then verifies the outer signature against the
    /// issuer's public key.
    ///
    /// :raises ValueError: if the issuer name does not match or the signature
    ///     is invalid.
    ///
    /// ```python,ignore
    /// ca_cert = synta.Certificate.from_pem(open("ca.pem", "rb").read())
    /// crl = synta.CertificateList.from_der(open("crl.der", "rb").read())
    /// crl.verify_issued_by(ca_cert)   # raises ValueError if not valid
    /// ```
    fn verify_issued_by(&self, issuer: &super::cert::PyCertificate) -> PyResult<()> {
        use synta::traits::Encode;
        use synta_certificate::{default_signature_verifier, SignatureVerifier};

        let crl = self.crl()?;
        let issuer_cert = issuer.cert()?;

        // 1. Name check: CRL issuer (Name<'_>) must match issuer cert's subject (RawDer).
        let crl_issuer_der = name_to_der_bytes(&crl.tbs_cert_list.issuer);
        if crl_issuer_der.as_slice() != issuer_cert.tbs_certificate.subject.as_bytes() {
            return Err(pyo3::exceptions::PyValueError::new_err(
                "CRL issuer name does not match subject of provided certificate",
            ));
        }

        // 2. Re-encode TBSCertList for the verifier.
        let mut tbs_enc = synta::Encoder::new(synta::Encoding::Der);
        crl.tbs_cert_list
            .encode(&mut tbs_enc)
            .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("CRL TBS encode: {e}")))?;
        let tbs_der = tbs_enc
            .finish()
            .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("CRL TBS finish: {e}")))?;

        // 3. Re-encode outer signatureAlgorithm.
        let mut alg_enc = synta::Encoder::new(synta::Encoding::Der);
        crl.signature_algorithm
            .encode(&mut alg_enc)
            .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("CRL alg encode: {e}")))?;
        let sig_alg_der = alg_enc
            .finish()
            .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("CRL alg finish: {e}")))?;

        // 4. Re-encode issuer SPKI.
        let mut spki_enc = synta::Encoder::new(synta::Encoding::Der);
        issuer_cert
            .tbs_certificate
            .subject_public_key_info
            .encode(&mut spki_enc)
            .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("SPKI encode: {e}")))?;
        let spki_der = spki_enc
            .finish()
            .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("SPKI finish: {e}")))?;

        // 5. Verify using the backend-agnostic verifier.
        default_signature_verifier()
            .verify_certificate_signature(
                &tbs_der,
                &sig_alg_der,
                crl.signature_value.as_bytes(),
                &spki_der,
            )
            .map_err(|e| {
                pyo3::exceptions::PyValueError::new_err(format!("CRL signature invalid: {e}"))
            })
    }

    fn __repr__(&self) -> PyResult<String> {
        let crl = self.crl()?;
        Ok(format!(
            "CertificateList(issuer={:?}, revoked_count={})",
            name_to_dn_string(&crl.tbs_cert_list.issuer),
            crl.tbs_cert_list
                .revoked_certificates
                .as_ref()
                .map(|v| v.len())
                .unwrap_or(0),
        ))
    }
}

// ── PyOcspResponse ────────────────────────────────────────────────────────────

/// OCSP Response (RFC 6960) accessible from Python.
///
/// ```python
/// resp = OCSPResponse.from_der(open("resp.der", "rb").read())
/// print(resp.status)
/// if resp.response_bytes:
///     basic = resp.response_bytes  # DER of BasicOCSPResponse
/// ```
#[pyclass(frozen, name = "OCSPResponse")]
pub struct PyOcspResponse {
    pub(super) _data: Py<PyBytes>,
    pub(super) raw: &'static [u8],
    inner: OnceLock<Box<synta_certificate::ocsp::OCSPResponse<'static>>>,
    status_cache: OnceLock<Py<PyString>>,
    response_type_oid_cache: OnceLock<Option<Py<PyObjectIdentifier>>>,
    response_bytes_cache: OnceLock<Option<Py<PyBytes>>>,
}

impl PyOcspResponse {
    fn ocsp(&self) -> PyResult<&synta_certificate::ocsp::OCSPResponse<'static>> {
        if let Some(v) = self.inner.get() {
            return Ok(v.as_ref());
        }
        let mut decoder = Decoder::new(self.raw, Encoding::Der);
        let decoded = decoder.decode().map_err(|e| {
            pyo3::exceptions::PyValueError::new_err(format!("OCSPResponse DER decode failed: {e}"))
        })?;
        let _ = self.inner.set(Box::new(decoded));
        Ok(self.inner.get().unwrap().as_ref())
    }
}

#[pymethods]
impl PyOcspResponse {
    /// Parse a DER-encoded OCSP Response.
    #[staticmethod]
    fn from_der(py: Python<'_>, data: Bound<'_, PyBytes>) -> PyResult<Self> {
        let py_bytes = data.unbind();
        // SAFETY: `py_bytes` holds a strong reference (Py<PyBytes>) that
        // keeps the Python bytes object alive for the lifetime of this struct.
        // CPython's bytes objects have a fixed-address, non-relocating payload
        // buffer (CPython has no moving GC).  The slice lifetime is extended
        // to 'static; the actual safety invariants are:
        //   (1) All reads of `raw` go through `&self`; no borrow of the struct
        //       can outlive the struct, so `raw` is never read after drop begins.
        //   (2) `raw: &'static [u8]` has no destructor (fat pointer, no heap
        //       allocation), so field drop order does not cause use-after-free.
        //   (3) `inner` contains only borrow-typed fields; dropping
        //       Box<OCSPResponse<'static>> does not read through the contained
        //       &'static slices (borrows have no destructors).
        // CPython-only: does not hold for PyPy or GraalPy.
        let raw: &'static [u8] = unsafe {
            let s = py_bytes.bind(py).as_bytes();
            std::slice::from_raw_parts(s.as_ptr(), s.len())
        };
        {
            let mut d = Decoder::new(raw, Encoding::Der);
            d.read_tag()
                .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("{e}")))?;
            d.read_length()
                .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("{e}")))?;
        }
        Ok(Self {
            _data: py_bytes,
            raw,
            inner: OnceLock::new(),
            status_cache: OnceLock::new(),
            response_type_oid_cache: OnceLock::new(),
            response_bytes_cache: OnceLock::new(),
        })
    }

    /// Parse a PEM-encoded OCSP Response.
    ///
    /// Returns a single :class:`OCSPResponse` for one PEM block, or a
    /// :class:`list` of :class:`OCSPResponse` objects when multiple blocks are
    /// present.  Raises :exc:`ValueError` if no PEM block is found.
    ///
    /// ```python
    /// resp = OCSPResponse.from_pem(open("ocsp.pem", "rb").read())
    /// print(resp.status)
    /// ```
    #[staticmethod]
    fn from_pem<'py>(py: Python<'py>, data: Bound<'_, PyBytes>) -> PyResult<Bound<'py, PyAny>> {
        pem_blocks_to_pyobject(py, data.as_bytes(), |py, bytes| {
            let obj = Self::from_der(py, bytes)?;
            Ok(Py::new(py, obj)?.into_bound(py).into_any())
        })
    }

    /// Serialize one OCSP response or a list of them to PEM format.
    ///
    /// ```python
    /// pem = OCSPResponse.to_pem(resp)
    /// pem = OCSPResponse.to_pem([resp1, resp2])
    /// ```
    #[staticmethod]
    fn to_pem<'py>(
        py: Python<'py>,
        obj_or_list: Bound<'_, PyAny>,
    ) -> PyResult<Bound<'py, PyBytes>> {
        pyobject_to_pem::<Self, _>(py, "OCSP RESPONSE", &obj_or_list, |c| c.raw)
    }

    /// Response status string (e.g. ``"successful"``, ``"tryLater"``).
    #[getter]
    fn status<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyString>> {
        if let Some(cached) = self.status_cache.get() {
            return Ok(cached.clone_ref(py).into_bound(py));
        }
        let s = ocsp_status_str(self.ocsp()?.response_status);
        let py_str = PyString::new(py, s).unbind();
        let _ = self.status_cache.set(py_str.clone_ref(py));
        Ok(py_str.into_bound(py))
    }

    /// Dotted-decimal OID of the response type, or ``None`` for error responses
    /// that carry no ``responseBytes`` (e.g. ``tryLater``).
    ///
    /// For successful responses this is typically the id-pkix-ocsp-basic OID
    /// (``"1.3.6.1.5.5.7.48.1.1"``).
    #[getter]
    fn response_type_oid<'py>(
        &self,
        py: Python<'py>,
    ) -> PyResult<Option<Bound<'py, PyObjectIdentifier>>> {
        if let Some(cached) = self.response_type_oid_cache.get() {
            return Ok(cached.as_ref().map(|o| o.clone_ref(py).into_bound(py)));
        }
        let computed: Option<Py<PyObjectIdentifier>> = self
            .ocsp()?
            .response_bytes
            .as_ref()
            .map(|rb| Py::new(py, PyObjectIdentifier::from_oid(rb.response_type.clone())))
            .transpose()?;
        let _ = self
            .response_type_oid_cache
            .set(computed.as_ref().map(|o| o.clone_ref(py)));
        Ok(computed.map(|o| o.into_bound(py)))
    }

    /// Raw DER bytes of the embedded response (the OCTET STRING content of
    /// ``ResponseBytes``), or ``None`` for error responses.
    ///
    /// For id-pkix-ocsp-basic responses, these bytes are a DER-encoded
    /// ``BasicOCSPResponse``.
    #[getter]
    fn response_bytes<'py>(&self, py: Python<'py>) -> PyResult<Option<Bound<'py, PyBytes>>> {
        if let Some(cached) = self.response_bytes_cache.get() {
            return Ok(cached.as_ref().map(|b| b.clone_ref(py).into_bound(py)));
        }
        let computed: Option<Bound<'py, PyBytes>> = self
            .ocsp()?
            .response_bytes
            .as_ref()
            .map(|rb| PyBytes::new(py, rb.response.as_bytes()));
        let to_store = computed.as_ref().map(|b| b.as_unbound().clone_ref(py));
        let _ = self.response_bytes_cache.set(to_store);
        Ok(computed)
    }

    /// Complete DER encoding of this OCSP response (the original bytes passed to ``from_der``).
    fn to_der<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        self._data.clone_ref(py).into_bound(py)
    }

    /// Verify the signature of a ``BasicOCSPResponse`` using the responder's certificate.
    ///
    /// Decodes the embedded ``BasicOCSPResponse``, re-encodes ``ResponseData``
    /// as the TBS bytes, and verifies the outer signature against ``responder``'s
    /// public key.
    ///
    /// :param responder: the OCSP responder's certificate.
    /// :raises ValueError: if the response carries no ``responseBytes``, the
    ///     response type is not ``id-pkix-ocsp-basic``, or the signature is
    ///     invalid.
    ///
    /// ```python,ignore
    /// ca_cert = synta.Certificate.from_pem(open("ca.pem", "rb").read())
    /// resp = synta.OCSPResponse.from_der(open("resp.der", "rb").read())
    /// resp.verify_signature(ca_cert)   # raises ValueError if invalid
    /// ```
    fn verify_signature(&self, responder: &super::cert::PyCertificate) -> PyResult<()> {
        use synta_certificate::{default_signature_verifier, SignatureVerifier};

        let ocsp = self.ocsp()?;

        // 1. Get ResponseBytes — absent for error-status responses.
        let rb = ocsp.response_bytes.as_ref().ok_or_else(|| {
            pyo3::exceptions::PyValueError::new_err(
                "OCSP response carries no responseBytes (error status response)",
            )
        })?;

        // 2. Ensure the responseType is id-pkix-ocsp-basic.
        use synta_certificate::oids::ID_PKIX_OCSP_BASIC;
        if rb.response_type.components() != ID_PKIX_OCSP_BASIC {
            return Err(pyo3::exceptions::PyValueError::new_err(format!(
                "unsupported OCSP responseType: {}",
                rb.response_type,
            )));
        }

        // 3. Decode the OCTET STRING contents as BasicOCSPResponse.
        let basic_der = rb.response.as_bytes();
        let basic: synta_certificate::ocsp::BasicOCSPResponse<'_> = {
            let mut dec = Decoder::new(basic_der, Encoding::Der);
            dec.decode().map_err(|e| {
                pyo3::exceptions::PyValueError::new_err(format!(
                    "BasicOCSPResponse decode failed: {e}"
                ))
            })?
        };

        // 4. Re-encode ResponseData (TBS).
        let tbs_der = basic.tbs_response_data.to_der().map_err(|e| {
            pyo3::exceptions::PyValueError::new_err(format!("ResponseData encode: {e}"))
        })?;

        // 5. Re-encode BasicOCSPResponse signatureAlgorithm.
        let sig_alg_der = basic.signature_algorithm.to_der().map_err(|e| {
            pyo3::exceptions::PyValueError::new_err(format!("OCSP alg encode: {e}"))
        })?;

        // 6. Re-encode responder SPKI.
        let issuer_cert = responder.cert()?;
        let spki_der = issuer_cert
            .tbs_certificate
            .subject_public_key_info
            .to_der()
            .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("SPKI encode: {e}")))?;

        // 7. Verify using the backend-agnostic verifier.
        default_signature_verifier()
            .verify_certificate_signature(
                &tbs_der,
                &sig_alg_der,
                basic.signature.as_bytes(),
                &spki_der,
            )
            .map_err(|e| {
                pyo3::exceptions::PyValueError::new_err(format!("OCSP signature invalid: {e}"))
            })
    }

    fn __repr__(&self) -> PyResult<String> {
        Ok(format!(
            "OCSPResponse(status={})",
            ocsp_status_str(self.ocsp()?.response_status),
        ))
    }
}

// ── OCSPRequest / CertID ─────────────────────────────────────────────────────

type OcspRequest2024 = synta_certificate::ocsp_2024_88_types::OCSPRequest<'static>;

/// OCSP CertID — identifies a certificate by its issuer hashes and serial number.
#[pyclass(frozen, name = "CertID")]
pub struct PyCertID {
    hash_alg_oid: synta::ObjectIdentifier,
    issuer_name_hash: Vec<u8>,
    issuer_key_hash: Vec<u8>,
    serial: synta::Integer,
    hash_algorithm_oid_cache: OnceLock<Py<PyObjectIdentifier>>,
    serial_number_cache: OnceLock<Py<PyAny>>,
}

impl PyCertID {
    fn from_cert_id(c: &synta_certificate::ocsp_2024_88_types::CertID<'_>) -> Self {
        Self {
            hash_alg_oid: c.hash_algorithm.algorithm.clone(),
            issuer_name_hash: c.issuer_name_hash.as_bytes().to_vec(),
            issuer_key_hash: c.issuer_key_hash.as_bytes().to_vec(),
            serial: c.serial_number.clone(),
            hash_algorithm_oid_cache: OnceLock::new(),
            serial_number_cache: OnceLock::new(),
        }
    }
}

#[pymethods]
impl PyCertID {
    /// Dotted-decimal OID of the hash algorithm used to compute the issuer hashes.
    #[getter]
    fn hash_algorithm_oid<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyObjectIdentifier>> {
        if let Some(cached) = self.hash_algorithm_oid_cache.get() {
            return Ok(cached.clone_ref(py).into_bound(py));
        }
        let oid = Py::new(py, PyObjectIdentifier::from_oid(self.hash_alg_oid.clone()))?;
        let _ = self.hash_algorithm_oid_cache.set(oid.clone_ref(py));
        Ok(oid.into_bound(py))
    }

    /// Raw bytes of the issuer DN hash.
    #[getter]
    fn issuer_name_hash<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        PyBytes::new(py, &self.issuer_name_hash)
    }

    /// Raw bytes of the issuer public key hash.
    #[getter]
    fn issuer_key_hash<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        PyBytes::new(py, &self.issuer_key_hash)
    }

    /// Certificate serial number as a Python ``int``.
    #[getter]
    fn serial_number<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
        if let Some(cached) = self.serial_number_cache.get() {
            return Ok(cached.clone_ref(py).into_bound(py));
        }
        let py_int: Py<PyAny> = if let Ok(v) = self.serial.as_i64() {
            v.into_pyobject(py)?.into_any().unbind()
        } else if let Ok(v) = self.serial.as_i128() {
            v.into_pyobject(py)?.into_any().unbind()
        } else {
            let bytes_obj = PyBytes::new(py, self.serial.as_bytes());
            let kwargs = pyo3::types::PyDict::new(py);
            kwargs.set_item(pyo3::intern!(py, "signed"), true)?;
            py.get_type::<pyo3::types::PyInt>()
                .call_method(
                    pyo3::intern!(py, "from_bytes"),
                    (bytes_obj, pyo3::intern!(py, "big")),
                    Some(&kwargs),
                )
                .map(|r| r.unbind())?
        };
        let _ = self.serial_number_cache.set(py_int.clone_ref(py));
        Ok(py_int.into_bound(py))
    }

    fn __repr__(&self) -> String {
        format!(
            "CertID(hash_alg={}, serial=<{} bytes>)",
            self.hash_alg_oid,
            self.serial.as_bytes().len(),
        )
    }
}

/// Parsed OCSP Request (RFC 9654 / RFC 6960).
///
/// ```python,ignore
/// req = OCSPRequest.from_der(open("request.der", "rb").read())
/// for cert_id in req.request_list:
///     print(cert_id.serial_number)
/// ```
#[pyclass(frozen, name = "OCSPRequest")]
pub struct PyOcspRequest {
    pub(super) _data: Py<PyBytes>,
    pub(super) raw: &'static [u8],
    inner: OnceLock<Box<OcspRequest2024>>,
    request_list_cache: OnceLock<Py<PyList>>,
    requestor_name_cache: OnceLock<Option<Py<PyBytes>>>,
    request_extensions_cache: OnceLock<Option<Py<PyBytes>>>,
}

impl PyOcspRequest {
    fn req(&self) -> PyResult<&OcspRequest2024> {
        if let Some(v) = self.inner.get() {
            return Ok(v.as_ref());
        }
        let mut decoder = Decoder::new(self.raw, Encoding::Der);
        let decoded = decoder.decode::<OcspRequest2024>().map_err(|e| {
            pyo3::exceptions::PyValueError::new_err(format!("OCSPRequest DER decode failed: {e}"))
        })?;
        let _ = self.inner.set(Box::new(decoded));
        Ok(self.inner.get().unwrap().as_ref())
    }
}

#[pymethods]
impl PyOcspRequest {
    /// Parse a DER-encoded OCSP Request.
    #[staticmethod]
    fn from_der(py: Python<'_>, data: Bound<'_, PyBytes>) -> PyResult<Self> {
        let py_bytes = data.unbind();
        // SAFETY: `py_bytes` holds a strong Py<PyBytes> reference keeping the
        // Python bytes object alive for the lifetime of this struct.  CPython's
        // bytes objects have a fixed-address, non-relocating payload buffer
        // (CPython has no moving GC).  The slice lifetime is extended to
        // 'static; the safety invariants are:
        //   (1) All reads of `raw` go through `&self`; no borrow of the struct
        //       can outlive the struct, so `raw` is never read after drop begins.
        //   (2) `raw: &'static [u8]` has no destructor, so field drop order
        //       does not cause use-after-free.
        //   (3) `inner` contains only borrow-typed fields; dropping
        //       Box<OCSPRequest<'static>> does not read through the &'static
        //       slices (borrows have no destructors).
        // CPython-only: does not hold for PyPy or GraalPy.
        let raw: &'static [u8] = unsafe {
            let s = py_bytes.bind(py).as_bytes();
            std::slice::from_raw_parts(s.as_ptr(), s.len())
        };
        {
            let mut d = Decoder::new(raw, Encoding::Der);
            d.read_tag()
                .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("{e}")))?;
            d.read_length()
                .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("{e}")))?;
        }
        Ok(Self {
            _data: py_bytes,
            raw,
            inner: OnceLock::new(),
            request_list_cache: OnceLock::new(),
            requestor_name_cache: OnceLock::new(),
            request_extensions_cache: OnceLock::new(),
        })
    }

    /// Parse a PEM-encoded OCSP Request (``OCSP REQUEST`` block).
    #[staticmethod]
    fn from_pem<'py>(py: Python<'py>, data: Bound<'_, PyBytes>) -> PyResult<Bound<'py, PyAny>> {
        pem_blocks_to_pyobject(py, data.as_bytes(), |py, bytes| {
            let obj = Self::from_der(py, bytes)?;
            Ok(Py::new(py, obj)?.into_bound(py).into_any())
        })
    }

    /// Serialize one OCSP request or a list of them to PEM format.
    #[staticmethod]
    fn to_pem<'py>(
        py: Python<'py>,
        obj_or_list: Bound<'_, PyAny>,
    ) -> PyResult<Bound<'py, PyBytes>> {
        pyobject_to_pem::<Self, _>(py, "OCSP REQUEST", &obj_or_list, |c| c.raw)
    }

    /// Return the original DER bytes.
    fn to_der<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        PyBytes::new(py, self.raw)
    }

    /// List of :class:`CertID` entries — the certificates whose status is being queried.
    #[getter]
    fn request_list<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyList>> {
        if let Some(cached) = self.request_list_cache.get() {
            return Ok(cached.clone_ref(py).into_bound(py));
        }
        let req = self.req()?;
        let list = PyList::empty(py);
        for request in &req.tbs_request.request_list {
            let cert_id = PyCertID::from_cert_id(&request.req_cert);
            list.append(Py::new(py, cert_id)?)?;
        }
        let py_list = list.unbind();
        let _ = self.request_list_cache.set(py_list.clone_ref(py));
        Ok(py_list.into_bound(py))
    }

    /// DER bytes of the requestor ``GeneralName``, or ``None`` if absent.
    #[getter]
    fn requestor_name<'py>(&self, py: Python<'py>) -> PyResult<Option<Bound<'py, PyBytes>>> {
        if let Some(cached) = self.requestor_name_cache.get() {
            return Ok(cached.as_ref().map(|b| b.clone_ref(py).into_bound(py)));
        }
        let computed: Option<Bound<'py, PyBytes>> = self
            .req()?
            .tbs_request
            .requestor_name
            .as_ref()
            .map(|gn| -> PyResult<Bound<'py, PyBytes>> {
                let mut enc = synta::Encoder::new(synta::Encoding::Der);
                gn.encode(&mut enc)
                    .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("{e}")))?;
                let der = enc
                    .finish()
                    .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("{e}")))?;
                Ok(PyBytes::new(py, &der))
            })
            .transpose()?;
        let to_store = computed.as_ref().map(|b| b.as_unbound().clone_ref(py));
        let _ = self.requestor_name_cache.set(to_store);
        Ok(computed)
    }

    /// DER bytes of the request extensions ``SEQUENCE OF Extension``, or ``None``.
    #[getter]
    fn request_extensions<'py>(&self, py: Python<'py>) -> PyResult<Option<Bound<'py, PyBytes>>> {
        if let Some(cached) = self.request_extensions_cache.get() {
            return Ok(cached.as_ref().map(|b| b.clone_ref(py).into_bound(py)));
        }
        let computed: Option<Bound<'py, PyBytes>> = self
            .req()?
            .tbs_request
            .request_extensions
            .as_ref()
            .map(|exts| -> PyResult<Bound<'py, PyBytes>> {
                let mut enc = synta::Encoder::new(synta::Encoding::Der);
                exts.encode(&mut enc)
                    .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("{e}")))?;
                let der = enc
                    .finish()
                    .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("{e}")))?;
                Ok(PyBytes::new(py, &der))
            })
            .transpose()?;
        let to_store = computed.as_ref().map(|b| b.as_unbound().clone_ref(py));
        let _ = self.request_extensions_cache.set(to_store);
        Ok(computed)
    }

    fn __repr__(&self) -> PyResult<String> {
        Ok(format!(
            "OCSPRequest(requests={})",
            self.req()?.tbs_request.request_list.len(),
        ))
    }
}

// ── PKCS#7 / PKCS#12 free functions ─────────────────────────────────────────

/// Build a `PyList[Certificate]` from a `Vec<Vec<u8>>` of DER-encoded certs.
fn der_certs_to_pylist<'py>(
    py: Python<'py>,
    der_certs: Vec<Vec<u8>>,
) -> PyResult<Bound<'py, PyList>> {
    let list = PyList::empty(py);
    for der in der_certs {
        let py_bytes = PyBytes::new(py, &der);
        let cert = PyCertificate::new_from_der(py, py_bytes)?;
        list.append(Py::new(py, cert)?.into_bound(py))?;
    }
    Ok(list)
}

/// Extract X.509 certificates from a PKCS#7 SignedData blob (DER or BER).
///
/// Accepts raw DER or BER input; BER indefinite-length encodings (common in
/// PKCS#7 files produced by older tools) are handled transparently.  Returns
/// a list of :class:`Certificate` objects in document order.
///
/// Raises :exc:`ValueError` on any ASN.1 structural error or if the input
/// is not id-signedData.
///
/// ```python,ignore
/// data = open("bundle.p7b", "rb").read()
/// certs = synta.load_der_pkcs7_certificates(data)
/// for cert in certs:
///     print(cert.subject)
/// ```
#[pyfunction]
pub fn load_der_pkcs7_certificates<'py>(
    py: Python<'py>,
    data: &[u8],
) -> PyResult<Bound<'py, PyList>> {
    let der_certs = synta_certificate::certs_from_pkcs7(data)
        .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("{e}")))?;
    der_certs_to_pylist(py, der_certs)
}

/// Extract X.509 certificates from a PEM-encoded PKCS#7 SignedData blob.
///
/// Decodes PEM block(s) in ``data`` (any label is accepted: ``PKCS7``,
/// ``CMS``, ``CERTIFICATE``, etc.) then calls
/// :func:`load_der_pkcs7_certificates` on each DER payload.  All certificates
/// across all blocks are returned as a single flat list.
///
/// Raises :exc:`ValueError` if no PEM block is found or if any block fails
/// to parse as PKCS#7 SignedData.
///
/// ```python,ignore
/// data = open("bundle.pem", "rb").read()
/// certs = synta.load_pem_pkcs7_certificates(data)
/// for cert in certs:
///     print(cert.subject)
/// ```
#[pyfunction]
pub fn load_pem_pkcs7_certificates<'py>(
    py: Python<'py>,
    data: &[u8],
) -> PyResult<Bound<'py, PyList>> {
    let blocks = synta_certificate::pem_blocks(data);
    if blocks.is_empty() {
        return Err(pyo3::exceptions::PyValueError::new_err(
            "no PEM block found in input",
        ));
    }
    let mut all_certs: Vec<Vec<u8>> = Vec::new();
    for (_, der) in &blocks {
        let certs = synta_certificate::certs_from_pkcs7(der)
            .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("{e}")))?;
        all_certs.extend(certs);
    }
    der_certs_to_pylist(py, all_certs)
}

/// Extract X.509 certificates from a PKCS#12 archive.
///
/// Accepts raw DER or BER input; the encoding is detected automatically.
/// Returns a list of :class:`Certificate` objects in document order.
/// Non-certificate bag types (``keyBag``, ``pkcs8ShroudedKeyBag``,
/// ``crlBag``, ``secretBag``) are silently skipped.
///
/// ``password`` is the archive password as raw bytes (UTF-8 without a NUL
/// terminator).  Pass ``b""`` or omit the argument for password-less archives.
///
/// Encrypted bags are supported when the library is built with a crypto backend
/// (``openssl`` or ``nss`` Cargo feature).
///
/// ```python,ignore
/// data = open("archive.p12", "rb").read()
/// certs = synta.load_pkcs12_certificates(data, b"s3cr3t")
/// for cert in certs:
///     print(cert.subject)
/// ```
#[pyfunction]
#[pyo3(signature = (data, password = None))]
pub fn load_pkcs12_certificates<'py>(
    py: Python<'py>,
    data: &[u8],
    password: Option<&[u8]>,
) -> PyResult<Bound<'py, PyList>> {
    let pw = password.unwrap_or(b"");
    let der_certs =
        synta_certificate::certs_from_pkcs12(data, pw, &synta_certificate::DefaultCrypto)
            .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("{e}")))?;
    der_certs_to_pylist(py, der_certs)
}

/// Extract PKCS#8 private keys from a PKCS#12 archive.
///
/// Returns a :class:`list` of :class:`bytes` objects, one per private key
/// found in ``keyBag`` (unencrypted) and ``pkcs8ShroudedKeyBag`` (encrypted,
/// decrypted when a crypto backend is enabled and ``password`` is given)
/// entries.  Each element is a DER-encoded ``OneAsymmetricKey``
/// (PKCS#8) structure, suitable for passing to a cryptography library.
///
/// ``certBag``, ``crlBag``, ``secretBag`` and any unknown bag types are
/// silently skipped.
///
/// ```python,ignore
/// data = open("archive.p12", "rb").read()
/// keys = synta.load_pkcs12_keys(data, b"s3cr3t")
/// for key_der in keys:
///     from cryptography.hazmat.primitives.serialization import load_der_private_key
///     key = load_der_private_key(key_der, None)
/// ```
#[pyfunction]
#[pyo3(signature = (data, password = None))]
pub fn load_pkcs12_keys<'py>(
    py: Python<'py>,
    data: &[u8],
    password: Option<&[u8]>,
) -> PyResult<Bound<'py, PyList>> {
    let pw = password.unwrap_or(b"");
    let der_keys = synta_certificate::keys_from_pkcs12(data, pw, &synta_certificate::DefaultCrypto)
        .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("{e}")))?;
    let list = PyList::empty(py);
    for der in der_keys {
        list.append(PyBytes::new(py, &der))?;
    }
    Ok(list)
}

/// Extract both certificates and private keys from a PKCS#12 archive.
///
/// Returns a 2-tuple ``(certs, keys)`` where:
///
/// - ``certs`` is a :class:`list` of :class:`Certificate` objects.
/// - ``keys`` is a :class:`list` of :class:`bytes`, each a DER-encoded
///   PKCS#8 ``OneAsymmetricKey`` structure.
///
/// Encrypted bags are decrypted with ``password`` when a crypto backend is
/// available.  Pass ``b""`` or omit ``password`` for password-less archives.
///
/// Use :func:`load_pkcs12_certificates` if you only need certificates, or
/// :func:`load_pkcs12_keys` if you only need keys.
///
/// ```python,ignore
/// data = open("archive.p12", "rb").read()
/// certs, keys = synta.load_pkcs12(data, b"s3cr3t")
/// for cert in certs:
///     print(cert.subject)
/// for key_der in keys:
///     from cryptography.hazmat.primitives.serialization import load_der_private_key
///     key = load_der_private_key(key_der, None)
/// ```
#[pyfunction]
#[pyo3(signature = (data, password = None))]
pub fn load_pkcs12<'py>(
    py: Python<'py>,
    data: &[u8],
    password: Option<&[u8]>,
) -> PyResult<Bound<'py, pyo3::types::PyTuple>> {
    let pw = password.unwrap_or(b"");
    let pki = synta_certificate::pki_from_pkcs12(data, pw, &synta_certificate::DefaultCrypto)
        .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("{e}")))?;
    let certs = der_certs_to_pylist(py, pki.certs)?;
    let keys = PyList::empty(py);
    for der in pki.keys {
        keys.append(PyBytes::new(py, &der))?;
    }
    pyo3::types::PyTuple::new(py, [certs.into_any(), keys.into_any()])
}

/// Auto-detect the encoding of ``data`` and return every PKI object as a
/// ``(label, der_bytes)`` tuple, in document order.
///
/// Supported formats: PEM (any label), PKCS#7 / CMS SignedData (DER or BER),
/// PKCS#12 PFX (DER or BER), and raw DER.
///
/// **Labels:**
///
/// - PEM blocks whose payload is a PKCS#7 ``ContentInfo`` (detected by
///   structure, not label) are expanded: the embedded certificates are
///   extracted and each is returned as ``("CERTIFICATE", der)``.
/// - All other PEM block types pass through with their original label
///   (e.g. ``"CERTIFICATE"``, ``"PRIVATE KEY"``).  Malformed PEM blocks
///   (bad base64, truncated header) are silently skipped.
/// - Binary PKCS#7 and raw DER yield ``"CERTIFICATE"`` labels.
/// - Binary PKCS#12 yields ``"CERTIFICATE"`` for ``certBag`` entries and
///   ``"PRIVATE KEY"`` for ``keyBag`` / ``pkcs8ShroudedKeyBag`` entries.
///
/// **Decryption:**
///
/// ``password`` applies only to PKCS#12 archives.  When ``password`` is
/// given and a crypto backend is available, encrypted SafeBags are decrypted.
/// Otherwise encrypted bags are silently skipped; unencrypted certificates in
/// the same archive are still returned.
///
/// :raises ValueError: For any structural failure:
///
///   - A PKCS#7 block (binary or PEM-wrapped) has malformed DER, or its
///     ``contentType`` OID is not ``id-signedData``.
///   - The PKCS#12 input has a structural ASN.1 error.
///   - ``password`` was supplied and decryption of an encrypted SafeBag
///     failed (e.g. wrong password, unsupported cipher).
///   - The PKCS#12 authSafe uses an unsupported ``ContentInfo`` type.
///
/// :raises TypeError: If ``data`` is not :class:`bytes`, or ``password``
///   is not :class:`bytes` or ``None``.
///
/// ```python,ignore
/// data = open("bundle.p7b", "rb").read()
/// blocks = synta.read_pki_blocks(data)
/// for label, der in blocks:
///     print(f"{label}: {len(der)} bytes")
///
/// # PKCS#12 with encryption
/// data = open("archive.p12", "rb").read()
/// blocks = synta.read_pki_blocks(data, b"s3cr3t")
/// ```
#[pyfunction]
#[pyo3(signature = (data, password = None))]
pub fn read_pki_blocks<'py>(
    py: Python<'py>,
    data: &[u8],
    password: Option<&[u8]>,
) -> PyResult<Bound<'py, PyList>> {
    let pw = password.unwrap_or(b"");
    let blocks = if password.is_some() {
        synta_certificate::read_pki_blocks(
            data,
            pw,
            Some(&synta_certificate::DefaultCrypto as &dyn synta_certificate::PkiDecryptor),
        )
    } else {
        synta_certificate::read_pki_blocks(data, pw, None::<&dyn synta_certificate::PkiDecryptor>)
    };
    let blocks = blocks.map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("{e}")))?;
    let list = PyList::empty(py);
    for (label, der) in blocks {
        let tuple = pyo3::types::PyTuple::new(
            py,
            [
                PyString::new(py, &label).into_any(),
                PyBytes::new(py, &der).into_any(),
            ],
        )?;
        list.append(tuple)?;
    }
    Ok(list)
}

// ── X.509 encoding utilities ──────────────────────────────────────────────────

/// Encode a list of OIDs as a DER ``SEQUENCE OF OID`` (ExtendedKeyUsage value).
///
/// ``oids`` must be a :class:`list` of :class:`~synta.ObjectIdentifier` or
/// dotted-decimal ``str`` values.  Returns the complete DER bytes of the
/// ``SEQUENCE``, suitable for use as an X.509v3 Extended Key Usage extension
/// value.
///
/// Delegates to synta's ``Vec<ObjectIdentifier>`` encoder which matches the
/// generated ``ExtendedKeyUsage = Vec<KeyPurposeId>`` type from the X.509 schema.
///
/// ```python,ignore
/// eku_der = synta.encode_extended_key_usage([
///     "1.3.6.1.5.5.7.3.1",   # id-kp-serverAuth
///     "1.3.6.1.5.5.7.3.2",   # id-kp-clientAuth
/// ])
/// ```
#[pyfunction]
pub fn encode_extended_key_usage<'py>(
    py: Python<'py>,
    oids: &Bound<'_, PyList>,
) -> PyResult<Bound<'py, PyBytes>> {
    use synta::traits::Encode;
    let mut eku: Vec<synta::ObjectIdentifier> = Vec::with_capacity(oids.len());
    for item in oids.iter() {
        eku.push(super::oid_from_pyany(&item)?);
    }
    let mut enc = synta::Encoder::new(synta::Encoding::Der);
    eku.encode(&mut enc)
        .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("{e}")))?;
    let der = enc
        .finish()
        .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("{e}")))?;
    Ok(PyBytes::new(py, &der))
}

/// Encode a list of ``(tag_number, content_bytes)`` pairs as a DER
/// ``SEQUENCE OF GeneralName``.
///
/// This is the inverse of :func:`~synta.parse_general_names`: the input
/// format is identical to what that function returns.  Tag numbers follow
/// RFC 5280 §4.2.1.6; use the :mod:`synta.general_name` constants.
///
/// ``content_bytes`` must be the raw **value** bytes — without the outer
/// context-specific TLV — exactly as returned by
/// :func:`~synta.parse_general_names`.
///
/// Delegates to :func:`synta_certificate::encode_general_names` which uses the
/// generated :class:`GeneralName` enum's ``Encode`` implementation.
///
/// ```python,ignore
/// import synta.general_name as gn
///
/// san_der = synta.encode_subject_alt_names([
///     (gn.DNS_NAME,   b"example.com"),
///     (gn.IP_ADDRESS, b"\x7f\x00\x00\x01"),   # 127.0.0.1
/// ])
/// ```
#[pyfunction]
pub fn encode_subject_alt_names<'py>(
    py: Python<'py>,
    names: &Bound<'_, PyList>,
) -> PyResult<Bound<'py, PyBytes>> {
    // Collect owned (tag, bytes) first so we can create &[u8] references that
    // all share the same lifetime, satisfying Vec<GeneralName<'_>> constraints.
    let mut owned: Vec<(u32, Vec<u8>)> = Vec::with_capacity(names.len());
    for item in names.iter() {
        let tuple = item.cast::<pyo3::types::PyTuple>().map_err(|_| {
            pyo3::exceptions::PyTypeError::new_err(
                "each element must be a (tag_number, bytes) 2-tuple",
            )
        })?;
        if tuple.len() != 2 {
            return Err(pyo3::exceptions::PyTypeError::new_err(
                "each element must be a (tag_number, bytes) 2-tuple",
            ));
        }
        let tag_num: u32 = tuple.get_item(0)?.extract()?;
        let content: Vec<u8> = tuple.get_item(1)?.extract()?;
        owned.push((tag_num, content));
    }
    let entries: Vec<(u32, &[u8])> = owned.iter().map(|(t, v)| (*t, v.as_slice())).collect();
    let der = synta_certificate::encode_general_names(&entries).ok_or_else(|| {
        pyo3::exceptions::PyValueError::new_err(
            "failed to encode GeneralName entries (invalid content bytes or unsupported tag)",
        )
    })?;
    Ok(PyBytes::new(py, &der))
}

/// Compare two DER-encoded X.500 Names for byte-for-byte equality.
///
/// Returns ``True`` if and only if the two byte sequences are identical.
/// This is a strict comparison; RFC 5280 name matching rules (case-insensitive
/// string comparison, etc.) are **not** applied.
///
/// Useful for quickly checking whether issuer and subject names match without
/// decoding the full structure:
///
/// ```python,ignore
/// same = synta.name_der_equal(cert.issuer_raw_der, ca_cert.subject_raw_der)
/// ```
#[pyfunction]
pub fn name_der_equal(a: &[u8], b: &[u8]) -> bool {
    a == b
}

/// Build a DER-encoded PKCS#12 ``PFX`` archive.
///
/// Assembles a ``PFX`` from one or more certificates and an optional
/// DER-encoded PKCS#8 private key.  The archive is protected by ``password``
/// using PBES2 (PBKDF2 + the selected cipher) for key encryption and HMAC
/// (PBKDF2-derived key) for the integrity MAC.
///
/// :param certificates: sequence of :class:`~synta.Certificate` objects or
///     raw DER ``bytes``.  Both types may appear in the same list.
/// :param private_key: a :class:`~synta.PrivateKey` object or a DER-encoded
///     PKCS#8 ``OneAsymmetricKey`` ``bytes``, or ``None`` to omit.
/// :param password: archive password (``bytes``), or ``None`` for a
///     password-less archive.
/// :param cipher: symmetric cipher for private-key encryption.  One of
///     ``"aes128"`` or ``"aes256"`` (default).
/// :param mac_algorithm: HMAC algorithm for the integrity MAC and PBKDF2 PRF.
///     One of ``"sha256"`` (default), ``"sha384"``, or ``"sha512"``.
/// :returns: DER-encoded ``PFX`` archive bytes.
/// :raises TypeError: if any element of ``certificates`` is neither a
///     :class:`~synta.Certificate` nor ``bytes``, or if ``private_key`` is
///     not a :class:`~synta.PrivateKey` nor ``bytes``.
/// :raises ValueError: if no certificates or key are supplied, if an unknown
///     cipher or MAC algorithm name is given, or if encryption fails.
///
/// ```python,ignore
/// # Certificate and PrivateKey objects — no .to_der() call needed
/// pfx = synta.create_pkcs12(
///     [cert, ca_cert],
///     private_key=key,
///     password=b"s3cr3t",
/// )
///
/// # Custom cipher and MAC algorithm
/// pfx = synta.create_pkcs12(
///     [cert],
///     private_key=key,
///     password=b"pass",
///     cipher="aes128",
///     mac_algorithm="sha384",
/// )
///
/// # Raw DER bytes also accepted for both
/// pfx = synta.create_pkcs12([cert.to_der()], private_key=key.to_der())
///
/// with open("out.p12", "wb") as f:
///     f.write(pfx)
/// ```
#[pyfunction]
#[pyo3(signature = (certificates, private_key = None, password = None, cipher = None, mac_algorithm = None))]
pub fn create_pkcs12<'py>(
    py: Python<'py>,
    certificates: &Bound<'_, PyList>,
    private_key: Option<Bound<'_, PyAny>>,
    password: Option<&[u8]>,
    cipher: Option<&str>,
    mac_algorithm: Option<&str>,
) -> PyResult<Bound<'py, PyBytes>> {
    use pyo3::exceptions::PyValueError;
    use synta_certificate::{
        OpensslPkcs12Encryptor, Pkcs12Builder, Pkcs12Cipher, Pkcs12Config, Pkcs12HmacAlgorithm,
    };

    let pkcs12_cipher = match cipher.unwrap_or("aes256") {
        "aes128" => Pkcs12Cipher::Aes128Cbc,
        "aes256" => Pkcs12Cipher::Aes256Cbc,
        "3des" => {
            return Err(PyValueError::new_err(
                "cipher '3des' is not supported; use 'aes128' or 'aes256'",
            ))
        }
        other => {
            return Err(PyValueError::new_err(format!(
                "unknown cipher: {other}; use 'aes128' or 'aes256'"
            )))
        }
    };
    let pkcs12_mac = match mac_algorithm.unwrap_or("sha256") {
        "sha256" => Pkcs12HmacAlgorithm::Sha256,
        "sha384" => Pkcs12HmacAlgorithm::Sha384,
        "sha512" => Pkcs12HmacAlgorithm::Sha512,
        "sha1" => {
            return Err(PyValueError::new_err(
                "mac_algorithm 'sha1' is not supported; use 'sha256', 'sha384', or 'sha512'",
            ))
        }
        other => {
            return Err(PyValueError::new_err(format!(
                "unknown mac_algorithm: {other}; use 'sha256', 'sha384', or 'sha512'"
            )))
        }
    };
    let config = Pkcs12Config {
        cipher: pkcs12_cipher,
        encryption_prf: pkcs12_mac,
        mac_algorithm: pkcs12_mac,
        ..Pkcs12Config::default()
    };
    let encryptor = OpensslPkcs12Encryptor::with_config(config);

    let password = password.unwrap_or(b"");
    let mut builder = Pkcs12Builder::new();
    for item in certificates.iter() {
        if let Ok(py_cert) = item.cast::<PyCertificate>() {
            // Zero-copy: raw is &'static [u8] backed by the PyBytes in _data.
            // Pkcs12Builder::certificate() copies into Vec<u8> immediately, so
            // the borrow does not outlive this loop iteration.
            builder = builder.certificate(py_cert.get().raw);
        } else if let Ok(py_bytes) = item.cast::<PyBytes>() {
            builder = builder.certificate(py_bytes.as_bytes());
        } else {
            return Err(pyo3::exceptions::PyTypeError::new_err(
                "certificates must be synta.Certificate or bytes",
            ));
        }
    }
    if let Some(key_arg) = private_key {
        if let Ok(py_key) = key_arg.cast::<PyPrivateKey>() {
            // PyPrivateKey stores PKCS#8 DER internally; retrieve it directly.
            let key_der = py_key
                .get()
                .inner
                .to_der()
                .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("{e}")))?;
            builder = builder.private_key(&key_der);
        } else if let Ok(py_bytes) = key_arg.cast::<PyBytes>() {
            builder = builder.private_key(py_bytes.as_bytes());
        } else {
            return Err(pyo3::exceptions::PyTypeError::new_err(
                "private_key must be synta.PrivateKey or bytes",
            ));
        }
    }

    let pfx_der = builder
        .build(password, &encryptor)
        .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("{e}")))?;

    Ok(PyBytes::new(py, &pfx_der))
}

// ── PyCertificateListBuilder helpers ─────────────────────────────────────────

/// Convert a Python `datetime.datetime` (must be timezone-aware) to a
/// GeneralizedTime string in `"YYYYMMDDHHmmssZ"` format accepted by the
/// string-based `CertificateListBuilder` setters.
///
/// Uses `datetime.timestamp()` to obtain a Unix timestamp and delegates to
/// [`synta::GeneralizedTime::from_unix`] for the calendar conversion.
fn py_dt_to_gen_time_str(dt: &Bound<'_, PyAny>) -> PyResult<String> {
    if dt.getattr("tzinfo")?.is_none() {
        return Err(pyo3::exceptions::PyValueError::new_err(
            "datetime must be timezone-aware (e.g. datetime.timezone.utc)",
        ));
    }
    let ts: f64 = dt.call_method0("timestamp")?.extract()?;
    let secs = ts.floor() as i64;
    let gt = synta::GeneralizedTime::from_unix(secs).ok_or_else(|| {
        pyo3::exceptions::PyValueError::new_err("datetime out of valid ASN.1 year range 1–9999")
    })?;
    Ok(gt.to_string())
}

// ── PyCertificateListBuilder ──────────────────────────────────────────────────

/// Fluent builder for a DER-encoded X.509 CRL (RFC 5280 §5).
///
/// Chain setters to configure the CRL, then call :meth:`build` to obtain the
/// DER-encoded ``TBSCertList`` SEQUENCE.  Sign the TBS externally and call the
/// static :meth:`assemble` to produce the final ``CertificateList``.
///
/// ```python,ignore
/// import synta
///
/// name_der = synta.NameBuilder().common_name("Test CA").build()
/// alg_der  = bytes.fromhex("300d06092a864886f70d01010b0500")  # sha256WithRSAEncryption
/// tbs = (
///     synta.CertificateListBuilder()
///     .issuer(name_der)
///     .signature_algorithm(alg_der)
///     .this_update("20240101120000Z")
///     .next_update("20240201120000Z")
///     .revoke(bytes([1]), "20231201000000Z", 1)  # keyCompromise
///     .build()
/// )
/// # sign tbs externally, then:
/// crl_der = synta.CertificateListBuilder.assemble(tbs, alg_der, sig_bytes)
/// ```
#[pyclass(name = "CertificateListBuilder")]
pub struct PyCertificateListBuilder {
    inner: synta_certificate::CertificateListBuilder,
}

#[pymethods]
impl PyCertificateListBuilder {
    /// Create a new, empty ``CertificateListBuilder``.
    #[new]
    fn new() -> Self {
        Self {
            inner: synta_certificate::CertificateListBuilder::new(),
        }
    }

    /// Set the issuer ``Name`` from pre-encoded DER bytes.
    fn issuer<'py>(slf: Bound<'py, Self>, name_der: &[u8]) -> Bound<'py, Self> {
        let mut guard = slf.borrow_mut();
        let old = std::mem::replace(
            &mut guard.inner,
            synta_certificate::CertificateListBuilder::new(),
        );
        guard.inner = old.issuer(name_der);
        drop(guard);
        slf
    }

    /// Set the ``thisUpdate`` time (``"YYYYMMDDHHmmssZ"`` or ``"YYMMDDHHmmssZ"``).
    fn this_update<'py>(slf: Bound<'py, Self>, time: &str) -> Bound<'py, Self> {
        let mut guard = slf.borrow_mut();
        let old = std::mem::replace(
            &mut guard.inner,
            synta_certificate::CertificateListBuilder::new(),
        );
        guard.inner = old.this_update(time);
        drop(guard);
        slf
    }

    /// Set the optional ``nextUpdate`` time (same format as :meth:`this_update`).
    fn next_update<'py>(slf: Bound<'py, Self>, time: &str) -> Bound<'py, Self> {
        let mut guard = slf.borrow_mut();
        let old = std::mem::replace(
            &mut guard.inner,
            synta_certificate::CertificateListBuilder::new(),
        );
        guard.inner = old.next_update(time);
        drop(guard);
        slf
    }

    /// Add a revoked certificate entry.
    ///
    /// ``serial`` is the big-endian DER INTEGER value bytes of the certificate
    /// serial number.  ``revocation_date`` uses the same time format as
    /// :meth:`this_update`.  ``reason`` is an optional CRL reason code integer
    /// (0=unspecified, 1=keyCompromise, 2=cACompromise, …, 10=aACompromise).
    fn revoke<'py>(
        slf: Bound<'py, Self>,
        serial: &[u8],
        revocation_date: &str,
        reason: Option<u8>,
    ) -> Bound<'py, Self> {
        let mut guard = slf.borrow_mut();
        let old = std::mem::replace(
            &mut guard.inner,
            synta_certificate::CertificateListBuilder::new(),
        );
        guard.inner = old.revoke(serial, revocation_date, reason);
        drop(guard);
        slf
    }

    /// Set the ``thisUpdate`` time from a timezone-aware
    /// :class:`datetime.datetime`.
    ///
    /// Converts the datetime to a Unix timestamp and formats it as
    /// ``"YYYYMMDDHHmmssZ"`` (GeneralizedTime).
    ///
    /// :raises ValueError: if ``dt`` is naive (no tzinfo) or out of range.
    fn this_update_utc<'py>(
        slf: Bound<'py, Self>,
        dt: &Bound<'_, PyAny>,
    ) -> PyResult<Bound<'py, Self>> {
        let time_str = py_dt_to_gen_time_str(dt)?;
        let mut guard = slf.borrow_mut();
        let old = std::mem::replace(
            &mut guard.inner,
            synta_certificate::CertificateListBuilder::new(),
        );
        guard.inner = old.this_update(&time_str);
        drop(guard);
        Ok(slf)
    }

    /// Set the optional ``nextUpdate`` time from a timezone-aware
    /// :class:`datetime.datetime`.
    ///
    /// :raises ValueError: if ``dt`` is naive (no tzinfo) or out of range.
    fn next_update_utc<'py>(
        slf: Bound<'py, Self>,
        dt: &Bound<'_, PyAny>,
    ) -> PyResult<Bound<'py, Self>> {
        let time_str = py_dt_to_gen_time_str(dt)?;
        let mut guard = slf.borrow_mut();
        let old = std::mem::replace(
            &mut guard.inner,
            synta_certificate::CertificateListBuilder::new(),
        );
        guard.inner = old.next_update(&time_str);
        drop(guard);
        Ok(slf)
    }

    /// Add a revoked certificate entry using a timezone-aware
    /// :class:`datetime.datetime` for the revocation time.
    ///
    /// ``serial`` is the big-endian DER INTEGER value bytes of the certificate
    /// serial number.  ``reason`` is an optional CRL reason code integer
    /// (0=unspecified, 1=keyCompromise, 2=cACompromise, …, 10=aACompromise).
    ///
    /// :raises ValueError: if ``revocation_dt`` is naive (no tzinfo) or out of range.
    fn revoke_utc<'py>(
        slf: Bound<'py, Self>,
        serial: &[u8],
        revocation_dt: &Bound<'_, PyAny>,
        reason: Option<u8>,
    ) -> PyResult<Bound<'py, Self>> {
        let time_str = py_dt_to_gen_time_str(revocation_dt)?;
        let mut guard = slf.borrow_mut();
        let old = std::mem::replace(
            &mut guard.inner,
            synta_certificate::CertificateListBuilder::new(),
        );
        guard.inner = old.revoke(serial, &time_str, reason);
        drop(guard);
        Ok(slf)
    }

    /// Set the signature ``AlgorithmIdentifier`` DER for ``TBSCertList.signature``.
    ///
    /// Must be a complete ``AlgorithmIdentifier`` SEQUENCE TLV.
    fn signature_algorithm<'py>(slf: Bound<'py, Self>, alg_der: &[u8]) -> Bound<'py, Self> {
        let mut guard = slf.borrow_mut();
        let old = std::mem::replace(
            &mut guard.inner,
            synta_certificate::CertificateListBuilder::new(),
        );
        guard.inner = old.signature_algorithm(alg_der);
        drop(guard);
        slf
    }

    /// Add a CRL-level extension.
    ///
    /// ``oid`` is the dotted-decimal OID string (e.g. ``"2.5.29.20"`` for
    /// CRL Number).  ``critical`` marks the extension as critical.
    /// ``value_der`` is the raw DER of the extension value (the OCTET STRING
    /// wrapper is added automatically).
    ///
    /// :raises ValueError: if ``oid`` is not a valid dotted-decimal OID string.
    fn add_extension<'py>(
        slf: Bound<'py, Self>,
        oid: Bound<'_, pyo3::PyAny>,
        critical: bool,
        value_der: &[u8],
    ) -> PyResult<Bound<'py, Self>> {
        use std::str::FromStr;
        let parsed_oid: synta::ObjectIdentifier = if let Ok(s) = oid.extract::<String>() {
            synta::ObjectIdentifier::from_str(&s)
                .map_err(|_| pyo3::exceptions::PyValueError::new_err(format!("invalid OID: {s}")))?
        } else if let Ok(o) = oid.extract::<pyo3::PyRef<'_, PyObjectIdentifier>>() {
            o.inner.clone()
        } else {
            return Err(pyo3::exceptions::PyTypeError::new_err(
                "oid must be a str or ObjectIdentifier",
            ));
        };
        let mut guard = slf.borrow_mut();
        let old = std::mem::replace(
            &mut guard.inner,
            synta_certificate::CertificateListBuilder::new(),
        );
        guard.inner = old.add_crl_extension(parsed_oid.components(), critical, value_der);
        drop(guard);
        Ok(slf)
    }

    /// Build the DER-encoded ``TBSCertList`` SEQUENCE.
    ///
    /// Required fields: ``issuer``, ``this_update``, ``signature_algorithm``.
    ///
    /// :raises ValueError: if any required field is absent or encoding fails.
    fn build<'py>(&mut self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        let inner = std::mem::replace(
            &mut self.inner,
            synta_certificate::CertificateListBuilder::new(),
        );
        let der = inner
            .build()
            .map_err(pyo3::exceptions::PyValueError::new_err)?;
        Ok(PyBytes::new(py, &der))
    }

    /// Assemble a DER-encoded ``CertificateList`` from its three components.
    ///
    /// ``tbs_der`` is the ``TBSCertList`` from :meth:`build`.
    /// ``sig_alg_der`` is the outer ``AlgorithmIdentifier`` SEQUENCE TLV.
    /// ``signature`` is the raw signature bytes (BIT STRING value; unused-bits byte
    /// is added automatically).
    ///
    /// :raises ValueError: if DER encoding fails.
    #[staticmethod]
    fn assemble<'py>(
        py: Python<'py>,
        tbs_der: &[u8],
        sig_alg_der: &[u8],
        signature: &[u8],
    ) -> PyResult<Bound<'py, PyBytes>> {
        let der =
            synta_certificate::CertificateListBuilder::assemble(tbs_der, sig_alg_der, signature)
                .map_err(pyo3::exceptions::PyValueError::new_err)?;
        Ok(PyBytes::new(py, &der))
    }

    fn __repr__(&self) -> String {
        "CertificateListBuilder()".to_string()
    }
}

// ── OCSPResponseBuilder ───────────────────────────────────────────────────────

/// Parameters for a single OCSP response entry.
///
/// Pass an instance to :meth:`OCSPResponseBuilder.add_response`.
///
/// ```python,ignore
/// resp = synta.OCSPSingleResponse(
///     hash_algorithm_der=sha1_alg_der,
///     issuer_name_hash=name_hash,
///     issuer_key_hash=key_hash,
///     serial=serial_bytes,
///     status=0,
///     this_update="20240101120000Z",
///     next_update="20240201120000Z",  # optional
/// )
/// ```
#[pyclass(frozen, name = "OCSPSingleResponse")]
pub struct PyOCSPSingleResponse {
    pub(crate) hash_algorithm_der: Vec<u8>,
    pub(crate) issuer_name_hash: Vec<u8>,
    pub(crate) issuer_key_hash: Vec<u8>,
    pub(crate) serial: Vec<u8>,
    pub(crate) status: u8,
    pub(crate) this_update: String,
    pub(crate) next_update: Option<String>,
}

#[pymethods]
impl PyOCSPSingleResponse {
    /// Create an ``OCSPSingleResponse`` entry.
    ///
    /// :param hash_algorithm_der: DER-encoded ``AlgorithmIdentifier`` SEQUENCE TLV used to
    ///     hash the issuer name and key.
    /// :param issuer_name_hash: hash of the issuer ``Name`` DER encoding.
    /// :param issuer_key_hash: hash of the issuer public key BIT STRING value.
    /// :param serial: big-endian serial number bytes of the certificate being checked.
    /// :param status: revocation status integer — ``0`` = good, ``1`` = revoked, ``2`` = unknown.
    /// :param this_update: ``GeneralizedTime`` string (e.g. ``"20240101120000Z"``).
    /// :param next_update: optional ``GeneralizedTime`` string for the next update time.
    #[new]
    #[pyo3(signature = (hash_algorithm_der, issuer_name_hash, issuer_key_hash, serial, status, this_update, next_update=None))]
    fn new(
        hash_algorithm_der: &[u8],
        issuer_name_hash: &[u8],
        issuer_key_hash: &[u8],
        serial: &[u8],
        status: u8,
        this_update: &str,
        next_update: Option<&str>,
    ) -> Self {
        Self {
            hash_algorithm_der: hash_algorithm_der.to_vec(),
            issuer_name_hash: issuer_name_hash.to_vec(),
            issuer_key_hash: issuer_key_hash.to_vec(),
            serial: serial.to_vec(),
            status,
            this_update: this_update.to_owned(),
            next_update: next_update.map(str::to_owned),
        }
    }
}

/// Python-facing wrapper for [`synta_certificate::OCSPResponseBuilder`].
///
/// Builds a DER-encoded ``ResponseData`` (RFC 6960) for external signing.
/// After signing, call :meth:`assemble` to produce the complete
/// ``OCSPResponse`` DER blob.
///
/// ```python,ignore
/// import synta
///
/// resp = synta.OCSPSingleResponse(
///     hash_algorithm_der=sha1_alg_der,
///     issuer_name_hash=name_hash,
///     issuer_key_hash=key_hash,
///     serial=serial_bytes,
///     status=0,  # good
///     this_update="20240101120000Z",
///     next_update="20240201120000Z",
/// )
/// tbs = (
///     synta.OCSPResponseBuilder()
///     .responder_key_hash(key_hash_bytes)
///     .produced_at("20240101120000Z")
///     .add_response(resp)
///     .build_tbs()
/// )
/// ocsp_der = synta.OCSPResponseBuilder.assemble(tbs, sig_alg_der, sig_bytes)
/// ```
#[pyclass(name = "OCSPResponseBuilder")]
pub struct PyOCSPResponseBuilder {
    inner: synta_certificate::OCSPResponseBuilder,
}

#[pymethods]
impl PyOCSPResponseBuilder {
    /// Create a new, empty ``OCSPResponseBuilder``.
    #[new]
    fn new() -> Self {
        Self {
            inner: synta_certificate::OCSPResponseBuilder::new(),
        }
    }

    /// Set ``responderID byName`` from a pre-encoded DER Name SEQUENCE TLV.
    ///
    /// :param name_der: DER-encoded ``Name`` SEQUENCE bytes.
    /// :raises ValueError: if ``name_der`` is not a valid Name.
    fn responder_name<'py>(slf: Bound<'py, Self>, name_der: &[u8]) -> Bound<'py, Self> {
        let mut guard = slf.borrow_mut();
        let old = std::mem::replace(
            &mut guard.inner,
            synta_certificate::OCSPResponseBuilder::new(),
        );
        guard.inner = old.responder_name(name_der);
        drop(guard);
        slf
    }

    /// Set ``responderID byKey`` from the raw key-hash bytes.
    ///
    /// ``key_hash`` is the raw hash bytes without any TLV wrapper — typically
    /// the SHA-1 hash of the issuer's ``subjectPublicKey`` BIT STRING value.
    ///
    /// :param key_hash: raw SHA-1 key-hash bytes.
    fn responder_key_hash<'py>(slf: Bound<'py, Self>, key_hash: &[u8]) -> Bound<'py, Self> {
        let mut guard = slf.borrow_mut();
        let old = std::mem::replace(
            &mut guard.inner,
            synta_certificate::OCSPResponseBuilder::new(),
        );
        guard.inner = old.responder_key_hash(key_hash);
        drop(guard);
        slf
    }

    /// Set ``producedAt`` GeneralizedTime.
    ///
    /// :param time: time string in ``YYYYMMDDHHmmssZ`` format.
    /// :raises ValueError: if the time string is malformed (deferred to :meth:`build_tbs`).
    fn produced_at<'py>(slf: Bound<'py, Self>, time: &str) -> Bound<'py, Self> {
        let mut guard = slf.borrow_mut();
        let old = std::mem::replace(
            &mut guard.inner,
            synta_certificate::OCSPResponseBuilder::new(),
        );
        guard.inner = old.produced_at(time);
        drop(guard);
        slf
    }

    /// Add a ``SingleResponse`` entry.
    ///
    /// :param response: an :class:`OCSPSingleResponse` instance.
    /// :raises ValueError: if any parameter is invalid (deferred to :meth:`build_tbs`).
    fn add_response<'py>(
        slf: Bound<'py, Self>,
        response: &PyOCSPSingleResponse,
    ) -> Bound<'py, Self> {
        let mut guard = slf.borrow_mut();
        let old = std::mem::replace(
            &mut guard.inner,
            synta_certificate::OCSPResponseBuilder::new(),
        );
        guard.inner = old.add_response(synta_certificate::SingleResponseSpec {
            hash_algorithm_der: &response.hash_algorithm_der,
            issuer_name_hash: &response.issuer_name_hash,
            issuer_key_hash: &response.issuer_key_hash,
            serial: &response.serial,
            status: response.status,
            this_update: &response.this_update,
            next_update: response.next_update.as_deref(),
        });
        drop(guard);
        slf
    }

    /// Build the DER-encoded ``ResponseData`` SEQUENCE.
    ///
    /// :returns: DER bytes of the ``ResponseData``.
    /// :raises ValueError: if any required field is absent or encoding fails.
    fn build_tbs<'py>(&mut self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        let inner = std::mem::replace(
            &mut self.inner,
            synta_certificate::OCSPResponseBuilder::new(),
        );
        let der = inner
            .build_tbs()
            .map_err(pyo3::exceptions::PyValueError::new_err)?;
        Ok(PyBytes::new(py, &der))
    }

    /// Assemble a complete DER-encoded ``OCSPResponse``.
    ///
    /// :param tbs_der: ``ResponseData`` bytes from :meth:`build_tbs`.
    /// :param sig_alg_der: outer ``AlgorithmIdentifier`` SEQUENCE TLV.
    /// :param signature: raw signature bytes (BIT STRING value).
    /// :raises ValueError: if DER encoding fails.
    #[staticmethod]
    fn assemble<'py>(
        py: Python<'py>,
        tbs_der: &[u8],
        sig_alg_der: &[u8],
        signature: &[u8],
    ) -> PyResult<Bound<'py, PyBytes>> {
        let der = synta_certificate::OCSPResponseBuilder::assemble(tbs_der, sig_alg_der, signature)
            .map_err(pyo3::exceptions::PyValueError::new_err)?;
        Ok(PyBytes::new(py, &der))
    }

    fn __repr__(&self) -> String {
        "OCSPResponseBuilder()".to_string()
    }
}

// ── OCSPRequestBuilder ────────────────────────────────────────────────────────

/// Parameters for a single OCSP request entry (one certificate to check).
///
/// Pass an instance to :meth:`OCSPRequestBuilder.add_request`.
///
/// ```python,ignore
/// spec = synta.OCSPCertIDSpec(
///     hash_algorithm_der=sha1_alg_der,
///     issuer_name_hash=name_hash,
///     issuer_key_hash=key_hash,
///     serial=serial_bytes,
/// )
/// ```
#[pyclass(frozen, name = "OCSPCertIDSpec")]
pub struct PyOCSPCertIDSpec {
    pub(crate) hash_algorithm_der: Vec<u8>,
    pub(crate) issuer_name_hash: Vec<u8>,
    pub(crate) issuer_key_hash: Vec<u8>,
    pub(crate) serial: Vec<u8>,
}

#[pymethods]
impl PyOCSPCertIDSpec {
    /// Create an ``OCSPCertIDSpec`` entry.
    ///
    /// :param hash_algorithm_der: DER-encoded ``AlgorithmIdentifier`` SEQUENCE TLV used to
    ///     hash the issuer name and key.
    /// :param issuer_name_hash: hash of the issuer ``Name`` DER encoding.
    /// :param issuer_key_hash: hash of the issuer public key BIT STRING value.
    /// :param serial: big-endian serial number bytes of the certificate being checked.
    #[new]
    fn new(
        hash_algorithm_der: &[u8],
        issuer_name_hash: &[u8],
        issuer_key_hash: &[u8],
        serial: &[u8],
    ) -> Self {
        Self {
            hash_algorithm_der: hash_algorithm_der.to_vec(),
            issuer_name_hash: issuer_name_hash.to_vec(),
            issuer_key_hash: issuer_key_hash.to_vec(),
            serial: serial.to_vec(),
        }
    }
}

/// Python-facing wrapper for [`synta_certificate::OCSPRequestBuilder`].
///
/// Builds a DER-encoded ``OCSPRequest`` (RFC 6960) for direct submission to an
/// OCSP responder (unsigned) or for external signing.  The unsigned form is
/// produced by :meth:`build_tbs`.  For signed requests, use
/// :meth:`build_tbs_inner` to obtain the inner ``TBSRequest`` bytes for
/// signing, then call :meth:`assemble` to produce the complete signed
/// ``OCSPRequest``.
///
/// ```python,ignore
/// import synta
///
/// spec = synta.OCSPCertIDSpec(
///     hash_algorithm_der=sha1_alg_der,
///     issuer_name_hash=name_hash,
///     issuer_key_hash=key_hash,
///     serial=serial_bytes,
/// )
/// # Unsigned request (most common):
/// ocsp_der = (
///     synta.OCSPRequestBuilder()
///     .add_request(spec)
///     .build_tbs()
/// )
/// # Signed request:
/// tbs_inner = synta.OCSPRequestBuilder().add_request(spec).build_tbs_inner()
/// ocsp_der = synta.OCSPRequestBuilder.assemble(tbs_inner, sig_alg_der, sig_bytes)
/// ```
#[pyclass(name = "OCSPRequestBuilder")]
pub struct PyOCSPRequestBuilder {
    inner: synta_certificate::OCSPRequestBuilder,
    built: bool,
}

#[pymethods]
impl PyOCSPRequestBuilder {
    /// Create a new, empty ``OCSPRequestBuilder``.
    #[new]
    fn new() -> Self {
        Self {
            inner: synta_certificate::OCSPRequestBuilder::new(),
            built: false,
        }
    }

    /// Set the optional ``requestorName`` from a pre-encoded DER ``GeneralName`` TLV.
    ///
    /// :param name_der: DER-encoded ``GeneralName`` TLV bytes.
    /// :raises ValueError: if ``name_der`` is not a valid ``GeneralName`` (deferred to
    ///     :meth:`build_tbs`).
    fn requestor_name<'py>(slf: Bound<'py, Self>, name_der: &[u8]) -> Bound<'py, Self> {
        let mut guard = slf.borrow_mut();
        let old = std::mem::replace(
            &mut guard.inner,
            synta_certificate::OCSPRequestBuilder::new(),
        );
        guard.inner = old.requestor_name(name_der);
        drop(guard);
        slf
    }

    /// Add a ``Request`` entry (one certificate whose status is being queried).
    ///
    /// :param spec: an :class:`OCSPCertIDSpec` instance.
    /// :raises ValueError: if any parameter is invalid (deferred to :meth:`build_tbs`).
    fn add_request<'py>(slf: Bound<'py, Self>, spec: &PyOCSPCertIDSpec) -> Bound<'py, Self> {
        let mut guard = slf.borrow_mut();
        let old = std::mem::replace(
            &mut guard.inner,
            synta_certificate::OCSPRequestBuilder::new(),
        );
        guard.inner = old.add_request(synta_certificate::CertIDSpec {
            hash_algorithm_der: &spec.hash_algorithm_der,
            issuer_name_hash: &spec.issuer_name_hash,
            issuer_key_hash: &spec.issuer_key_hash,
            serial: &spec.serial,
        });
        drop(guard);
        slf
    }

    /// Build the complete DER-encoded unsigned ``OCSPRequest`` SEQUENCE.
    ///
    /// The returned bytes are a valid ``OCSPRequest`` (with the inner
    /// ``TBSRequest`` and no optional signature) and can be submitted directly
    /// to an OCSP responder.
    ///
    /// :returns: DER bytes of the complete unsigned ``OCSPRequest``.
    /// :raises ValueError: if no request entry was added, or if encoding fails.
    fn build_tbs<'py>(&mut self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        if self.built {
            return Err(pyo3::exceptions::PyValueError::new_err(
                "build_tbs already called on this OCSPRequestBuilder",
            ));
        }
        self.built = true;
        let inner = std::mem::replace(
            &mut self.inner,
            synta_certificate::OCSPRequestBuilder::new(),
        );
        let der = inner
            .build_tbs()
            .map_err(pyo3::exceptions::PyValueError::new_err)?;
        Ok(PyBytes::new(py, &der))
    }

    /// Build the DER-encoded inner ``TBSRequest`` SEQUENCE for signing.
    ///
    /// These bytes are intended to be signed externally.  After signing, pass
    /// them to :meth:`assemble` along with the signature to produce the
    /// complete signed ``OCSPRequest``.
    ///
    /// :returns: DER bytes of the inner ``TBSRequest``.
    /// :raises ValueError: if no request entry was added, or if encoding fails.
    fn build_tbs_inner<'py>(&mut self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        if self.built {
            return Err(pyo3::exceptions::PyValueError::new_err(
                "build_tbs_inner already called on this OCSPRequestBuilder",
            ));
        }
        self.built = true;
        let inner = std::mem::replace(
            &mut self.inner,
            synta_certificate::OCSPRequestBuilder::new(),
        );
        let der = inner
            .build_tbs_inner()
            .map_err(pyo3::exceptions::PyValueError::new_err)?;
        Ok(PyBytes::new(py, &der))
    }

    /// Assemble a complete DER-encoded signed ``OCSPRequest``.
    ///
    /// :param tbs_der: inner ``TBSRequest`` bytes from :meth:`build_tbs_inner`.
    /// :param sig_alg_der: outer ``AlgorithmIdentifier`` SEQUENCE TLV.
    /// :param signature: raw signature bytes (BIT STRING value).
    /// :raises ValueError: if DER encoding fails.
    #[staticmethod]
    fn assemble<'py>(
        py: Python<'py>,
        tbs_der: &[u8],
        sig_alg_der: &[u8],
        signature: &[u8],
    ) -> PyResult<Bound<'py, PyBytes>> {
        let der = synta_certificate::OCSPRequestBuilder::assemble(tbs_der, sig_alg_der, signature)
            .map_err(pyo3::exceptions::PyValueError::new_err)?;
        Ok(PyBytes::new(py, &der))
    }

    fn __repr__(&self) -> String {
        "OCSPRequestBuilder()".to_string()
    }
}