native-ossl 0.1.3

Native Rust idiomatic bindings to OpenSSL
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
//! X.509 certificate — reading, inspecting, and building.
//!
//! # Types
//!
//! | Type              | Owned / Borrowed | Description                          |
//! |-------------------|-----------------|--------------------------------------|
//! | [`X509`]          | Owned (Arc-like) | Certificate, Clone via `up_ref`      |
//! | [`X509Name`]      | Borrowed `'cert` | Subject or issuer distinguished name |
//! | [`X509NameEntry`] | Borrowed `'name` | One RDN entry (e.g. CN, O, C)       |
//! | [`X509Extension`] | Borrowed `'cert` | One certificate extension            |
//! | [`X509NameOwned`] | Owned            | Mutable name for certificate builder |
//! | [`X509Builder`]   | Owned builder    | Constructs a new X.509 certificate   |

use crate::bio::{MemBio, MemBioBuf};
use crate::error::ErrorStack;
use native_ossl_sys as sys;
use std::ffi::CStr;
use std::marker::PhantomData;
use std::sync::Arc;

// ── BrokenDownTime — structured calendar time ────────────────────────────────

/// A calendar date and time in UTC, as returned by [`X509::not_before_tm`] and
/// [`X509::not_after_tm`].
///
/// All fields are in natural units (year is the full Gregorian year; month is
/// 1–12; all time fields are 0-based).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BrokenDownTime {
    /// Full Gregorian year (e.g. 2026).
    pub year: i32,
    /// Month, 1–12.
    pub month: u8,
    /// Day of the month, 1–31.
    pub day: u8,
    /// Hour, 0–23.
    pub hour: u8,
    /// Minute, 0–59.
    pub minute: u8,
    /// Second, 0–60 (60 is possible for leap seconds).
    pub second: u8,
}

// ── SignatureInfo — certificate signature algorithm metadata ──────────────────

/// Decoded signature algorithm metadata from an [`X509`] certificate.
///
/// Returned by [`X509::signature_info`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SignatureInfo {
    /// NID of the digest algorithm used in the signature.
    ///
    /// `0` (`NID_undef`) for algorithms that do not use a separate
    /// pre-hash step, such as Ed25519 and ML-DSA.
    pub md_nid: i32,
    /// NID of the public-key algorithm used in the signature.
    pub pk_nid: i32,
    /// Estimated security strength in bits (e.g. 128 for AES-128-equivalent).
    pub security_bits: i32,
}

// ── X509 — owned certificate ──────────────────────────────────────────────────

/// An X.509 certificate (`X509*`).
///
/// Cloneable via `EVP_X509_up_ref`; wrapping in `Arc<X509>` is safe.
pub struct X509 {
    ptr: *mut sys::X509,
}

// SAFETY: `X509*` is reference-counted.
unsafe impl Send for X509 {}
unsafe impl Sync for X509 {}

impl Clone for X509 {
    fn clone(&self) -> Self {
        unsafe { sys::X509_up_ref(self.ptr) };
        X509 { ptr: self.ptr }
    }
}

impl Drop for X509 {
    fn drop(&mut self) {
        unsafe { sys::X509_free(self.ptr) };
    }
}

impl X509 {
    /// Construct from a raw, owned `X509*`.
    ///
    /// # Safety
    ///
    /// `ptr` must be a valid, non-null `X509*` whose ownership is being transferred.
    pub(crate) unsafe fn from_ptr(ptr: *mut sys::X509) -> Self {
        X509 { ptr }
    }

    /// Load a certificate from PEM bytes.
    ///
    /// # Errors
    pub fn from_pem(pem: &[u8]) -> Result<Self, ErrorStack> {
        let bio = MemBioBuf::new(pem)?;
        let ptr = unsafe {
            sys::PEM_read_bio_X509(
                bio.as_ptr(),
                std::ptr::null_mut(),
                None,
                std::ptr::null_mut(),
            )
        };
        if ptr.is_null() {
            return Err(ErrorStack::drain());
        }
        Ok(unsafe { Self::from_ptr(ptr) })
    }

    /// Load a certificate from PEM bytes, accepting a library context for API
    /// symmetry with other `from_pem_in` methods.
    ///
    /// OpenSSL 3.5 does not expose a libctx-aware `PEM_read_bio_X509_ex`
    /// variant, so this calls the standard `PEM_read_bio_X509`.  The `ctx`
    /// parameter is accepted but unused.  Certificate parsing itself does not
    /// require provider dispatch; provider-bound operations use the context
    /// stored in the key extracted from the certificate.
    ///
    /// # Errors
    pub fn from_pem_in(_ctx: &Arc<crate::lib_ctx::LibCtx>, pem: &[u8]) -> Result<Self, ErrorStack> {
        Self::from_pem(pem)
    }

    /// Create a new, empty `X509` object bound to the given library context.
    ///
    /// Use this instead of the implicit-context `X509Builder::new` when you need
    /// the certificate to be associated with a FIPS-isolated or otherwise
    /// explicit `LibCtx`.  The `propq` (property query) argument is `NULL`,
    /// meaning default provider properties are used.
    ///
    /// # Errors
    ///
    /// Returns `Err` if OpenSSL cannot allocate the certificate structure.
    pub fn new_in(ctx: &Arc<crate::lib_ctx::LibCtx>) -> Result<Self, ErrorStack> {
        // SAFETY:
        // - ctx.as_ptr() is non-null (LibCtx constructor invariant)
        // - propq is null → use default algorithm properties
        let ptr = unsafe { sys::X509_new_ex(ctx.as_ptr(), std::ptr::null()) };
        if ptr.is_null() {
            return Err(ErrorStack::drain());
        }
        Ok(unsafe { Self::from_ptr(ptr) })
    }

    /// Load a certificate from DER bytes.
    ///
    /// Zero-copy: parses from the caller's slice without an intermediate buffer.
    ///
    /// # Errors
    ///
    /// Returns `Err` if the DER is malformed, or if `der.len()` exceeds `i64::MAX`.
    pub fn from_der(der: &[u8]) -> Result<Self, ErrorStack> {
        let mut der_ptr = der.as_ptr();
        let len = i64::try_from(der.len()).map_err(|_| ErrorStack::drain())?;
        let ptr =
            unsafe { sys::d2i_X509(std::ptr::null_mut(), std::ptr::addr_of_mut!(der_ptr), len) };
        if ptr.is_null() {
            return Err(ErrorStack::drain());
        }
        Ok(unsafe { Self::from_ptr(ptr) })
    }

    /// Serialise to PEM.
    ///
    /// # Errors
    pub fn to_pem(&self) -> Result<Vec<u8>, ErrorStack> {
        let mut bio = MemBio::new()?;
        crate::ossl_call!(sys::PEM_write_bio_X509(bio.as_ptr(), self.ptr))?;
        Ok(bio.into_vec())
    }

    /// Serialise to DER.
    ///
    /// Zero-copy: writes into a freshly allocated `Vec<u8>` without going
    /// through an OpenSSL-owned buffer.
    ///
    /// # Errors
    pub fn to_der(&self) -> Result<Vec<u8>, ErrorStack> {
        let len = unsafe { sys::i2d_X509(self.ptr, std::ptr::null_mut()) };
        if len < 0 {
            return Err(ErrorStack::drain());
        }
        let mut buf = vec![0u8; usize::try_from(len).unwrap_or(0)];
        let mut out_ptr = buf.as_mut_ptr();
        let written = unsafe { sys::i2d_X509(self.ptr, std::ptr::addr_of_mut!(out_ptr)) };
        if written < 0 {
            return Err(ErrorStack::drain());
        }
        buf.truncate(usize::try_from(written).unwrap_or(0));
        Ok(buf)
    }

    /// Subject distinguished name (borrowed).
    #[must_use]
    pub fn subject_name(&self) -> X509Name<'_> {
        // get0: does not increment ref count; valid while self is alive.
        // OpenSSL 4.x made this return `*const`; cast is safe — we never
        // mutate through the borrowed pointer.
        let ptr = unsafe { sys::X509_get_subject_name(self.ptr) }.cast();
        X509Name {
            ptr,
            _owner: PhantomData,
        }
    }

    /// Issuer distinguished name (borrowed).
    #[must_use]
    pub fn issuer_name(&self) -> X509Name<'_> {
        let ptr = unsafe { sys::X509_get_issuer_name(self.ptr) }.cast();
        X509Name {
            ptr,
            _owner: PhantomData,
        }
    }

    /// Serial number as a signed 64-bit integer.
    ///
    /// Returns `None` if the serial number is too large to fit in `i64`.
    #[must_use]
    pub fn serial_number(&self) -> Option<i64> {
        let ai = unsafe { sys::X509_get0_serialNumber(self.ptr) };
        if ai.is_null() {
            return None;
        }
        let mut n: i64 = 0;
        let rc = unsafe { sys::ASN1_INTEGER_get_int64(std::ptr::addr_of_mut!(n), ai) };
        if rc == 1 {
            Some(n)
        } else {
            None
        }
    }

    /// Serial number as a big-endian byte slice.
    ///
    /// Complementary to [`Self::serial_number`] for serials that exceed `i64::MAX`.
    /// The bytes are the raw content octets of the DER `INTEGER`, not including
    /// the tag or length.
    ///
    /// Returns `None` if the serial field is absent.
    #[must_use]
    pub fn serial_number_bytes(&self) -> Option<Vec<u8>> {
        // SAFETY:
        // - self.ptr is non-null (constructor invariant)
        // - X509_get_serialNumber returns a pointer embedded in the X509 object;
        //   it is valid for as long as self is alive
        // - &self ensures the certificate is not mutated while we read the field
        let ai = unsafe { sys::X509_get_serialNumber(self.ptr) };
        if ai.is_null() {
            return None;
        }
        // SAFETY: ai is non-null (checked above) and lives for the duration of
        // &self; ASN1_INTEGER is typedef'd to ASN1_STRING in OpenSSL, so the
        // cast to *const ASN1_STRING is safe.
        Some(unsafe { asn1_string_data(ai.cast()) }.to_vec())
    }

    /// Validity `notBefore` as a human-readable UTC string.
    ///
    /// The format is `"Mmm DD HH:MM:SS YYYY GMT"` (OpenSSL default).
    /// Returns `None` if the field is absent or cannot be printed.
    #[must_use]
    pub fn not_before_str(&self) -> Option<String> {
        let t = unsafe { sys::X509_get0_notBefore(self.ptr) };
        asn1_time_to_str(t)
    }

    /// Validity `notAfter` as a human-readable UTC string.
    ///
    /// Returns `None` if the field is absent or cannot be printed.
    #[must_use]
    pub fn not_after_str(&self) -> Option<String> {
        let t = unsafe { sys::X509_get0_notAfter(self.ptr) };
        asn1_time_to_str(t)
    }

    /// Validity `notBefore` as a structured [`BrokenDownTime`] in UTC.
    ///
    /// Returns `None` if the field is absent or cannot be parsed.
    #[must_use]
    pub fn not_before_tm(&self) -> Option<BrokenDownTime> {
        // SAFETY:
        // - self.ptr is non-null (constructor invariant)
        // - X509_get0_notBefore returns a pointer embedded in the X509; valid while &self lives
        // - &self ensures no concurrent mutation
        let t = unsafe { sys::X509_get0_notBefore(self.ptr) };
        asn1_time_to_broken_down(t)
    }

    /// Validity `notAfter` as a structured [`BrokenDownTime`] in UTC.
    ///
    /// Returns `None` if the field is absent or cannot be parsed.
    #[must_use]
    pub fn not_after_tm(&self) -> Option<BrokenDownTime> {
        // SAFETY: same as not_before_tm
        let t = unsafe { sys::X509_get0_notAfter(self.ptr) };
        asn1_time_to_broken_down(t)
    }

    /// Returns `true` if the current time is within `[notBefore, notAfter]`.
    #[must_use]
    pub fn is_valid_now(&self) -> bool {
        let nb = unsafe { sys::X509_get0_notBefore(self.ptr) };
        let na = unsafe { sys::X509_get0_notAfter(self.ptr) };
        // X509_cmp_time(t, NULL) < 0 → t < now; > 0 → t > now.
        unsafe {
            sys::X509_cmp_time(nb, std::ptr::null_mut()) <= 0
                && sys::X509_cmp_time(na, std::ptr::null_mut()) >= 0
        }
    }

    /// Extract the public key (owned `Pkey<Public>`).
    ///
    /// Calls `X509_get_pubkey` — the returned key is independently reference-counted.
    ///
    /// # Errors
    pub fn public_key(&self) -> Result<crate::pkey::Pkey<crate::pkey::Public>, ErrorStack> {
        let ptr = unsafe { sys::X509_get_pubkey(self.ptr) };
        if ptr.is_null() {
            return Err(ErrorStack::drain());
        }
        Ok(unsafe { crate::pkey::Pkey::from_ptr(ptr) })
    }

    /// Check whether the certificate's public key uses the named algorithm.
    ///
    /// Uses `X509_get0_pubkey` — no reference-count increment.  Call
    /// [`Self::public_key`] if you need an owned [`crate::pkey::Pkey`] handle.
    ///
    /// Returns `false` if the certificate has no public key or if the algorithm
    /// name does not match.
    #[must_use]
    pub fn public_key_is_a(&self, alg: &CStr) -> bool {
        // SAFETY:
        // - self.ptr is non-null (constructor invariant)
        // - X509_get0_pubkey returns a borrowed pointer valid while &self holds;
        //   we do not store it and do not outlive this call
        // - &self ensures no concurrent mutation of the certificate
        let pkey = unsafe { sys::X509_get0_pubkey(self.ptr) };
        if pkey.is_null() {
            return false;
        }
        // SAFETY: pkey is non-null (checked above); alg.as_ptr() is valid for
        // the duration of this call (CStr invariant)
        unsafe { sys::EVP_PKEY_is_a(pkey, alg.as_ptr()) == 1 }
    }

    /// Bit size of the certificate's public key.
    ///
    /// Uses `X509_get0_pubkey` — no reference-count increment.
    ///
    /// Returns `None` if the certificate has no public key.
    #[must_use]
    pub fn public_key_bits(&self) -> Option<u32> {
        // SAFETY:
        // - self.ptr is non-null (constructor invariant)
        // - X509_get0_pubkey returns a borrowed pointer valid while &self holds
        // - &self ensures no concurrent mutation of the certificate
        let pkey = unsafe { sys::X509_get0_pubkey(self.ptr) };
        if pkey.is_null() {
            return None;
        }
        // SAFETY: pkey is non-null (checked above)
        u32::try_from(unsafe { sys::EVP_PKEY_get_bits(pkey) }).ok()
    }

    /// Inspect the signature algorithm used in this certificate.
    ///
    /// Calls `X509_get_signature_info` to decode the signature algorithm fields
    /// embedded in the certificate's `signatureAlgorithm` and `signature`
    /// structures.
    ///
    /// `md_nid` is `0` (`NID_undef`) for algorithms that have no separate
    /// pre-hash step, such as Ed25519 and ML-DSA (post-quantum lattice signatures
    /// defined in FIPS 204).  Always check for `0` before using `md_nid` as a
    /// digest identifier.
    ///
    /// # Errors
    ///
    /// Returns `Err` if OpenSSL cannot decode the signature algorithm (e.g. the
    /// certificate's signature field is absent or uses an unrecognised OID).
    pub fn signature_info(&self) -> Result<SignatureInfo, ErrorStack> {
        let mut md_nid: std::ffi::c_int = 0;
        let mut pk_nid: std::ffi::c_int = 0;
        let mut security_bits: std::ffi::c_int = 0;
        // SAFETY:
        // - self.ptr is non-null (constructor invariant)
        // - md_nid, pk_nid, security_bits are local stack variables; we pass
        //   their addresses which are valid for the duration of this call
        // - flags is null_mut(): we do not need the X509_SIG_INFO_TLS /
        //   X509_SIG_INFO_VALID flags; OpenSSL accepts NULL for any out-param
        // - &self ensures the certificate is not mutated concurrently
        let rc = unsafe {
            sys::X509_get_signature_info(
                self.ptr,
                &raw mut md_nid,
                &raw mut pk_nid,
                &raw mut security_bits,
                std::ptr::null_mut(),
            )
        };
        if rc != 1 {
            return Err(ErrorStack::drain());
        }
        Ok(SignatureInfo {
            md_nid,
            pk_nid,
            security_bits,
        })
    }

    /// Verify this certificate was signed by `key`.
    ///
    /// Returns `Ok(true)` if the signature is valid, `Ok(false)` if not, or
    /// `Err` on a fatal error.
    ///
    /// # Errors
    pub fn verify(&self, key: &crate::pkey::Pkey<crate::pkey::Public>) -> Result<bool, ErrorStack> {
        match unsafe { sys::X509_verify(self.ptr, key.as_ptr()) } {
            1 => Ok(true),
            0 => Ok(false),
            _ => Err(ErrorStack::drain()),
        }
    }

    /// Returns `true` if the certificate is self-signed.
    #[must_use]
    pub fn is_self_signed(&self) -> bool {
        // verify_signature=0 → only check name match, not signature itself.
        unsafe { sys::X509_self_signed(self.ptr, 0) == 1 }
    }

    /// Number of extensions in this certificate.
    #[must_use]
    pub fn extension_count(&self) -> usize {
        let n = unsafe { sys::X509_get_ext_count(self.ptr) };
        usize::try_from(n).unwrap_or(0)
    }

    /// Access extension by index (0-based).
    ///
    /// Returns `None` if `idx` is out of range.
    #[must_use]
    pub fn extension(&self, idx: usize) -> Option<X509Extension<'_>> {
        let idx_i32 = i32::try_from(idx).ok()?;
        // OpenSSL 4.x returns *const; cast is safe — borrowed, never mutated.
        let ptr = unsafe { sys::X509_get_ext(self.ptr, idx_i32) }.cast::<sys::X509_EXTENSION>();
        if ptr.is_null() {
            None
        } else {
            Some(X509Extension {
                ptr,
                _owner: PhantomData,
            })
        }
    }

    /// Find the first extension with the given NID.
    ///
    /// Returns `None` if no such extension exists.
    #[must_use]
    pub fn extension_by_nid(&self, nid: i32) -> Option<X509Extension<'_>> {
        let idx = unsafe { sys::X509_get_ext_by_NID(self.ptr, nid, -1) };
        if idx < 0 {
            return None;
        }
        let ptr = unsafe { sys::X509_get_ext(self.ptr, idx) }.cast::<sys::X509_EXTENSION>();
        if ptr.is_null() {
            None
        } else {
            Some(X509Extension {
                ptr,
                _owner: PhantomData,
            })
        }
    }

    /// Return the DER-encoded value of the first extension with the given NID.
    ///
    /// Returns `None` if the extension is not present.  The returned byte slice
    /// is borrowed from the certificate's internal storage — zero-copy, no
    /// allocation — and is valid for `'self`'s lifetime.
    ///
    /// To iterate all extensions or access criticality flags, use
    /// [`Self::extension_by_nid`] or [`Self::extension`] instead.
    #[must_use]
    pub fn extension_der(&self, nid: i32) -> Option<&[u8]> {
        // SAFETY: self.ptr is non-null (constructor invariant)
        let idx = unsafe { sys::X509_get_ext_by_NID(self.ptr, nid, -1) };
        if idx < 0 {
            return None;
        }
        // SAFETY: idx is a valid extension index returned by X509_get_ext_by_NID
        let ext = unsafe { sys::X509_get_ext(self.ptr, idx) };
        if ext.is_null() {
            return None;
        }
        // SAFETY: ext is non-null; X509_EXTENSION_get_data returns data borrowed
        // from ext, which itself is borrowed from self
        let data = unsafe { sys::X509_EXTENSION_get_data(ext) };
        if data.is_null() {
            return Some(&[]);
        }
        // SAFETY: data is a valid ASN1_OCTET_STRING; cast to ASN1_STRING is safe
        // because ASN1_OCTET_STRING is typedef'd to ASN1_STRING in OpenSSL
        Some(unsafe { asn1_string_data(data.cast()) })
    }

    /// Raw `X509*` pointer valid for the lifetime of `self`.
    #[must_use]
    #[allow(dead_code)] // used by ssl module added in the next phase
    pub(crate) fn as_ptr(&self) -> *mut sys::X509 {
        self.ptr
    }
}

// ── X509Name — borrowed distinguished name ────────────────────────────────────

/// A borrowed distinguished name (`X509_NAME*`) tied to its owning `X509`.
pub struct X509Name<'cert> {
    ptr: *mut sys::X509_NAME,
    _owner: PhantomData<&'cert X509>,
}

impl X509Name<'_> {
    /// Number of entries (RDN components) in the name.
    #[must_use]
    pub fn entry_count(&self) -> usize {
        usize::try_from(unsafe { sys::X509_NAME_entry_count(self.ptr) }).unwrap_or(0)
    }

    /// Access an entry by index (0-based).
    #[must_use]
    pub fn entry(&self, idx: usize) -> Option<X509NameEntry<'_>> {
        let idx_i32 = i32::try_from(idx).ok()?;
        // OpenSSL 4.x returns *const; cast is safe — borrowed, never mutated.
        let ptr =
            unsafe { sys::X509_NAME_get_entry(self.ptr, idx_i32) }.cast::<sys::X509_NAME_ENTRY>();
        if ptr.is_null() {
            None
        } else {
            Some(X509NameEntry {
                ptr,
                _owner: PhantomData,
            })
        }
    }

    /// Return a one-line string representation of this distinguished name.
    ///
    /// Produces the legacy `/CN=.../O=.../C=...` slash-separated format via
    /// `X509_NAME_oneline`.  Useful for logging and debugging, but **not
    /// recommended** for structured access — use [`Self::entry`] or
    /// [`Self::to_string`] (which honours RFC 2253 / RFC 4514 flags) instead.
    ///
    /// Returns `None` if OpenSSL fails to allocate the string.
    #[must_use]
    pub fn to_oneline(&self) -> Option<String> {
        // SAFETY:
        // - self.ptr is non-null (constructor invariant)
        // - passing NULL + 0 causes OpenSSL to heap-allocate the result; we
        //   take ownership and must free it with OPENSSL_free
        let ptr = unsafe { sys::X509_NAME_oneline(self.ptr, std::ptr::null_mut(), 0) };
        if ptr.is_null() {
            return None;
        }
        // SAFETY: ptr is a valid NUL-terminated C string allocated by OpenSSL
        let s = unsafe { std::ffi::CStr::from_ptr(ptr) }
            .to_string_lossy()
            .into_owned();
        // SAFETY: ptr was allocated by OpenSSL; CRYPTO_free is the underlying
        // implementation of the OPENSSL_free macro (OPENSSL_free is a C macro
        // and cannot be bound directly — CRYPTO_free is the actual function)
        unsafe { sys::CRYPTO_free(ptr.cast(), c"x509.rs".as_ptr(), 0) };
        Some(s)
    }

    /// Format the entire name as a single-line string.
    ///
    /// Uses `X509_NAME_print_ex` with `XN_FLAG_COMPAT` (traditional
    /// `/CN=.../O=.../` format).  Returns `None` on error.
    #[must_use]
    pub fn to_string(&self) -> Option<String> {
        let mut bio = MemBio::new().ok()?;
        // flags = 0 → XN_FLAG_COMPAT (old /CN=…/O=… format).
        let n = unsafe { sys::X509_NAME_print_ex(bio.as_ptr(), self.ptr, 0, 0) };
        if n < 0 {
            return None;
        }
        String::from_utf8(bio.into_vec()).ok()
    }
}

// ── X509NameEntry — one RDN component ────────────────────────────────────────

/// A borrowed entry within an [`X509Name`].
pub struct X509NameEntry<'name> {
    ptr: *mut sys::X509_NAME_ENTRY,
    _owner: PhantomData<&'name ()>,
}

impl X509NameEntry<'_> {
    /// NID of this field (e.g. `NID_commonName = 13`).
    #[must_use]
    pub fn nid(&self) -> i32 {
        let obj = unsafe { sys::X509_NAME_ENTRY_get_object(self.ptr) };
        unsafe { sys::OBJ_obj2nid(obj) }
    }

    /// Raw DER-encoded value bytes of this entry.
    ///
    /// The slice is valid as long as the owning certificate is alive.
    #[must_use]
    pub fn data(&self) -> &[u8] {
        let asn1 = unsafe { sys::X509_NAME_ENTRY_get_data(self.ptr) };
        if asn1.is_null() {
            return &[];
        }
        // SAFETY: asn1 is valid for 'name (guaranteed by self._owner PhantomData).
        unsafe { asn1_string_data(asn1) }
    }
}

// ── X509Extension — borrowed extension ───────────────────────────────────────

/// A borrowed extension within an [`X509`] certificate.
pub struct X509Extension<'cert> {
    ptr: *mut sys::X509_EXTENSION,
    _owner: PhantomData<&'cert X509>,
}

impl X509Extension<'_> {
    /// NID of this extension (e.g. `NID_subject_key_identifier`).
    #[must_use]
    pub fn nid(&self) -> i32 {
        let obj = unsafe { sys::X509_EXTENSION_get_object(self.ptr) };
        unsafe { sys::OBJ_obj2nid(obj) }
    }

    /// Returns `true` if this extension is marked critical.
    #[must_use]
    pub fn is_critical(&self) -> bool {
        unsafe { sys::X509_EXTENSION_get_critical(self.ptr) == 1 }
    }

    /// Raw DER-encoded value bytes.
    ///
    /// The slice is valid as long as the owning certificate is alive.
    #[must_use]
    pub fn data(&self) -> &[u8] {
        let asn1 = unsafe { sys::X509_EXTENSION_get_data(self.ptr) };
        if asn1.is_null() {
            return &[];
        }
        // SAFETY: asn1 is valid for 'cert (guaranteed by self._owner PhantomData).
        // ASN1_OCTET_STRING is typedef'd to ASN1_STRING — cast is safe.
        unsafe { asn1_string_data(asn1.cast()) }
    }
}

// ── X509NameOwned — mutable name for the builder ─────────────────────────────

/// An owned, mutable distinguished name (`X509_NAME*`).
///
/// Pass to [`X509Builder::set_subject_name`] / [`X509Builder::set_issuer_name`].
pub struct X509NameOwned {
    ptr: *mut sys::X509_NAME,
}

impl X509NameOwned {
    /// Create an empty distinguished name.
    ///
    /// # Errors
    pub fn new() -> Result<Self, ErrorStack> {
        let ptr = unsafe { sys::X509_NAME_new() };
        if ptr.is_null() {
            return Err(ErrorStack::drain());
        }
        Ok(X509NameOwned { ptr })
    }

    /// Append a field entry by short name (e.g. `c"CN"`, `c"O"`, `c"C"`).
    ///
    /// `value` is the UTF-8 field value.
    ///
    /// # Panics
    ///
    /// # Errors
    ///
    /// Returns `Err` if the field cannot be added, or if `value.len()` exceeds `i32::MAX`.
    pub fn add_entry_by_txt(&mut self, field: &CStr, value: &[u8]) -> Result<(), ErrorStack> {
        let len = i32::try_from(value.len()).map_err(|_| ErrorStack::drain())?;
        // MBSTRING_UTF8 = 0x1000 → encode value as UTF-8.
        let rc = unsafe {
            sys::X509_NAME_add_entry_by_txt(
                self.ptr,
                field.as_ptr(),
                0x1000, // MBSTRING_UTF8
                value.as_ptr(),
                len,
                -1, // append
                0,
            )
        };
        if rc != 1 {
            return Err(ErrorStack::drain());
        }
        Ok(())
    }
}

impl Drop for X509NameOwned {
    fn drop(&mut self) {
        unsafe { sys::X509_NAME_free(self.ptr) };
    }
}

// ── X509Builder — certificate builder ────────────────────────────────────────

/// Builder for a new X.509 certificate.
///
/// ```ignore
/// let mut name = X509NameOwned::new()?;
/// name.add_entry_by_txt(c"CN", b"example.com")?;
///
/// let cert = X509Builder::new()?
///     .set_version(2)?                    // X.509v3
///     .set_serial_number(1)?
///     .set_not_before_offset(0)?          // valid from now
///     .set_not_after_offset(365 * 86400)? // valid for 1 year
///     .set_subject_name(&name)?
///     .set_issuer_name(&name)?            // self-signed
///     .set_public_key(&pub_key)?
///     .sign(&priv_key, None)?             // None → no digest (Ed25519)
///     .build();
/// ```
pub struct X509Builder {
    ptr: *mut sys::X509,
}

impl X509Builder {
    /// Allocate a new, empty `X509` structure.
    ///
    /// # Errors
    pub fn new() -> Result<Self, ErrorStack> {
        let ptr = unsafe { sys::X509_new() };
        if ptr.is_null() {
            return Err(ErrorStack::drain());
        }
        Ok(X509Builder { ptr })
    }

    /// Set the X.509 version (0 = v1, 1 = v2, 2 = v3).
    ///
    /// # Errors
    pub fn set_version(self, version: i64) -> Result<Self, ErrorStack> {
        crate::ossl_call!(sys::X509_set_version(self.ptr, version))?;
        Ok(self)
    }

    /// Set the serial number.
    ///
    /// # Errors
    pub fn set_serial_number(self, n: i64) -> Result<Self, ErrorStack> {
        let ai = unsafe { sys::ASN1_INTEGER_new() };
        if ai.is_null() {
            return Err(ErrorStack::drain());
        }
        crate::ossl_call!(sys::ASN1_INTEGER_set_int64(ai, n)).map_err(|e| {
            unsafe { sys::ASN1_INTEGER_free(ai) };
            e
        })?;
        let rc = unsafe { sys::X509_set_serialNumber(self.ptr, ai) };
        unsafe { sys::ASN1_INTEGER_free(ai) };
        if rc != 1 {
            return Err(ErrorStack::drain());
        }
        Ok(self)
    }

    /// Set `notBefore` to `now + offset_secs`.
    ///
    /// # Errors
    pub fn set_not_before_offset(self, offset_secs: i64) -> Result<Self, ErrorStack> {
        let t = unsafe { sys::X509_getm_notBefore(self.ptr) };
        if unsafe { sys::X509_gmtime_adj(t, offset_secs) }.is_null() {
            return Err(ErrorStack::drain());
        }
        Ok(self)
    }

    /// Set `notAfter` to `now + offset_secs`.
    ///
    /// # Errors
    pub fn set_not_after_offset(self, offset_secs: i64) -> Result<Self, ErrorStack> {
        let t = unsafe { sys::X509_getm_notAfter(self.ptr) };
        if unsafe { sys::X509_gmtime_adj(t, offset_secs) }.is_null() {
            return Err(ErrorStack::drain());
        }
        Ok(self)
    }

    /// Set the subject distinguished name.
    ///
    /// # Errors
    pub fn set_subject_name(self, name: &X509NameOwned) -> Result<Self, ErrorStack> {
        crate::ossl_call!(sys::X509_set_subject_name(self.ptr, name.ptr))?;
        Ok(self)
    }

    /// Set the issuer distinguished name.
    ///
    /// # Errors
    pub fn set_issuer_name(self, name: &X509NameOwned) -> Result<Self, ErrorStack> {
        crate::ossl_call!(sys::X509_set_issuer_name(self.ptr, name.ptr))?;
        Ok(self)
    }

    /// Set the public key.
    ///
    /// # Errors
    pub fn set_public_key<T: crate::pkey::HasPublic>(
        self,
        key: &crate::pkey::Pkey<T>,
    ) -> Result<Self, ErrorStack> {
        crate::ossl_call!(sys::X509_set_pubkey(self.ptr, key.as_ptr()))?;
        Ok(self)
    }

    /// Sign the certificate.
    ///
    /// Pass `digest = None` for one-shot algorithms such as Ed25519.
    /// For ECDSA or RSA, pass the appropriate digest (e.g. SHA-256).
    ///
    /// # Errors
    pub fn sign(
        self,
        key: &crate::pkey::Pkey<crate::pkey::Private>,
        digest: Option<&crate::digest::DigestAlg>,
    ) -> Result<Self, ErrorStack> {
        let md_ptr = digest.map_or(std::ptr::null(), crate::digest::DigestAlg::as_ptr);
        // X509_sign returns the signature length (> 0) on success.
        let rc = unsafe { sys::X509_sign(self.ptr, key.as_ptr(), md_ptr) };
        if rc <= 0 {
            return Err(ErrorStack::drain());
        }
        Ok(self)
    }

    /// Finalise and return the certificate.
    #[must_use]
    pub fn build(self) -> X509 {
        let ptr = self.ptr;
        std::mem::forget(self);
        X509 { ptr }
    }
}

impl Drop for X509Builder {
    fn drop(&mut self) {
        unsafe { sys::X509_free(self.ptr) };
    }
}

// ── X509Store — trust store ────────────────────────────────────────────────────

/// An OpenSSL certificate trust store (`X509_STORE*`).
///
/// Cloneable via `X509_STORE_up_ref`; wrapping in `Arc<X509Store>` is safe.
pub struct X509Store {
    ptr: *mut sys::X509_STORE,
}

unsafe impl Send for X509Store {}
unsafe impl Sync for X509Store {}

impl Clone for X509Store {
    fn clone(&self) -> Self {
        unsafe { sys::X509_STORE_up_ref(self.ptr) };
        X509Store { ptr: self.ptr }
    }
}

impl Drop for X509Store {
    fn drop(&mut self) {
        unsafe { sys::X509_STORE_free(self.ptr) };
    }
}

impl X509Store {
    /// Create an empty trust store.
    ///
    /// # Errors
    pub fn new() -> Result<Self, ErrorStack> {
        let ptr = unsafe { sys::X509_STORE_new() };
        if ptr.is_null() {
            return Err(ErrorStack::drain());
        }
        Ok(X509Store { ptr })
    }

    /// Add a trusted certificate to the store.
    ///
    /// The certificate's reference count is incremented internally.
    ///
    /// # Errors
    pub fn add_cert(&mut self, cert: &X509) -> Result<(), ErrorStack> {
        let rc = unsafe { sys::X509_STORE_add_cert(self.ptr, cert.ptr) };
        if rc != 1 {
            return Err(ErrorStack::drain());
        }
        Ok(())
    }

    /// Add a CRL to the store.
    ///
    /// # Errors
    pub fn add_crl(&mut self, crl: &X509Crl) -> Result<(), ErrorStack> {
        let rc = unsafe { sys::X509_STORE_add_crl(self.ptr, crl.ptr) };
        if rc != 1 {
            return Err(ErrorStack::drain());
        }
        Ok(())
    }

    /// Set verification flags (e.g. `X509_V_FLAG_CRL_CHECK`).
    ///
    /// # Errors
    pub fn set_flags(&mut self, flags: u64) -> Result<(), ErrorStack> {
        let rc = unsafe { sys::X509_STORE_set_flags(self.ptr, flags) };
        if rc != 1 {
            return Err(ErrorStack::drain());
        }
        Ok(())
    }

    /// Return the raw `X509_STORE*` pointer.
    #[must_use]
    pub(crate) fn as_ptr(&self) -> *mut sys::X509_STORE {
        self.ptr
    }
}

// ── X509StoreCtx — verification context ──────────────────────────────────────

/// A chain-verification context (`X509_STORE_CTX*`).
///
/// Create with [`X509StoreCtx::new`], initialise with [`X509StoreCtx::init`],
/// then call [`X509StoreCtx::verify`].
pub struct X509StoreCtx {
    ptr: *mut sys::X509_STORE_CTX,
}

impl Drop for X509StoreCtx {
    fn drop(&mut self) {
        unsafe { sys::X509_STORE_CTX_free(self.ptr) };
    }
}

unsafe impl Send for X509StoreCtx {}

impl X509StoreCtx {
    /// Allocate a new, uninitialised verification context.
    ///
    /// # Errors
    pub fn new() -> Result<Self, ErrorStack> {
        let ptr = unsafe { sys::X509_STORE_CTX_new() };
        if ptr.is_null() {
            return Err(ErrorStack::drain());
        }
        Ok(X509StoreCtx { ptr })
    }

    /// Initialise the context for verifying `cert` against `store`.
    ///
    /// Call this before [`Self::verify`].
    ///
    /// # Errors
    pub fn init(&mut self, store: &X509Store, cert: &X509) -> Result<(), ErrorStack> {
        let rc = unsafe {
            sys::X509_STORE_CTX_init(self.ptr, store.ptr, cert.ptr, std::ptr::null_mut())
        };
        if rc != 1 {
            return Err(ErrorStack::drain());
        }
        Ok(())
    }

    /// Verify the certificate chain.
    ///
    /// Returns `Ok(true)` if the chain is valid, `Ok(false)` if not (call
    /// [`Self::error`] to retrieve the error code), or `Err` on a fatal error.
    ///
    /// # Errors
    pub fn verify(&mut self) -> Result<bool, ErrorStack> {
        match unsafe { sys::X509_verify_cert(self.ptr) } {
            1 => Ok(true),
            0 => Ok(false),
            _ => Err(ErrorStack::drain()),
        }
    }

    /// OpenSSL verification error code after a failed [`Self::verify`].
    ///
    /// Returns 0 (`X509_V_OK`) if no error occurred.  See `<openssl/x509_vfy.h>`
    /// for the full list of `X509_V_ERR_*` constants.
    #[must_use]
    pub fn error(&self) -> i32 {
        unsafe { sys::X509_STORE_CTX_get_error(self.ptr) }
    }

    /// Collect the verified chain into a `Vec<X509>`.
    ///
    /// Only meaningful after a successful [`Self::verify`].  Returns an empty
    /// `Vec` if the chain is not available.
    #[must_use]
    // i < n where n came from OPENSSL_sk_num (i32), so the i as i32 cast is safe.
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    pub fn chain(&self) -> Vec<X509> {
        let stack = unsafe { sys::X509_STORE_CTX_get0_chain(self.ptr) };
        if stack.is_null() {
            return Vec::new();
        }
        let n = unsafe { sys::OPENSSL_sk_num(stack.cast::<sys::OPENSSL_STACK>()) };
        let n = usize::try_from(n).unwrap_or(0);
        let mut out = Vec::with_capacity(n);
        for i in 0..n {
            let raw =
                unsafe { sys::OPENSSL_sk_value(stack.cast::<sys::OPENSSL_STACK>(), i as i32) };
            if raw.is_null() {
                continue;
            }
            // up_ref so each X509 in the Vec has its own reference.
            let cert_ptr = raw.cast::<sys::X509>();
            unsafe { sys::X509_up_ref(cert_ptr) };
            out.push(X509 { ptr: cert_ptr });
        }
        out
    }
}

// ── X509Crl — certificate revocation list ─────────────────────────────────────

/// An X.509 certificate revocation list (`X509_CRL*`).
///
/// Cloneable via `X509_CRL_up_ref`.
pub struct X509Crl {
    ptr: *mut sys::X509_CRL,
}

unsafe impl Send for X509Crl {}
unsafe impl Sync for X509Crl {}

impl Clone for X509Crl {
    fn clone(&self) -> Self {
        unsafe { sys::X509_CRL_up_ref(self.ptr) };
        X509Crl { ptr: self.ptr }
    }
}

impl Drop for X509Crl {
    fn drop(&mut self) {
        unsafe { sys::X509_CRL_free(self.ptr) };
    }
}

impl X509Crl {
    /// Construct from a raw, owned `X509_CRL*`.
    ///
    /// # Safety
    ///
    /// `ptr` must be a valid, non-null `X509_CRL*` whose ownership is transferred.
    pub(crate) unsafe fn from_ptr(ptr: *mut sys::X509_CRL) -> Self {
        X509Crl { ptr }
    }

    /// Allocate a new, empty `X509_CRL` structure.
    ///
    /// The returned CRL has no fields set. Use this when constructing a CRL
    /// programmatically before populating its fields via the OpenSSL API.
    ///
    /// # Errors
    ///
    /// Returns `Err` if OpenSSL cannot allocate the structure.
    pub fn new() -> Result<Self, ErrorStack> {
        // SAFETY:
        // - X509_CRL_new() takes no arguments and returns a new heap allocation
        // - the returned pointer is non-null on success; null on allocation failure
        // - ownership is fully transferred to this X509Crl value
        let ptr = unsafe { sys::X509_CRL_new() };
        if ptr.is_null() {
            return Err(ErrorStack::drain());
        }
        Ok(unsafe { Self::from_ptr(ptr) })
    }

    /// Allocate a new, empty `X509_CRL` structure bound to a library context.
    ///
    /// Equivalent to `X509_CRL_new_ex(ctx, NULL)`. The CRL will use providers
    /// from `ctx` for any cryptographic operations performed on it.
    ///
    /// # Errors
    ///
    /// Returns `Err` if OpenSSL cannot allocate the structure.
    pub fn new_in(ctx: &std::sync::Arc<crate::lib_ctx::LibCtx>) -> Result<Self, ErrorStack> {
        // SAFETY:
        // - ctx.as_ptr() is non-null (LibCtx invariant)
        // - propq is NULL, which is valid (no property query)
        // - the returned pointer is non-null on success; null on allocation failure
        // - ownership is fully transferred to this X509Crl value
        // - ctx borrow covers the duration of this call; no aliasing of the OSSL_LIB_CTX*
        let ptr = unsafe { sys::X509_CRL_new_ex(ctx.as_ptr(), std::ptr::null()) };
        if ptr.is_null() {
            return Err(ErrorStack::drain());
        }
        Ok(unsafe { Self::from_ptr(ptr) })
    }

    /// Load a CRL from PEM bytes.
    ///
    /// # Errors
    pub fn from_pem(pem: &[u8]) -> Result<Self, ErrorStack> {
        let bio = MemBioBuf::new(pem)?;
        let ptr = unsafe {
            sys::PEM_read_bio_X509_CRL(
                bio.as_ptr(),
                std::ptr::null_mut(),
                None,
                std::ptr::null_mut(),
            )
        };
        if ptr.is_null() {
            return Err(ErrorStack::drain());
        }
        Ok(unsafe { Self::from_ptr(ptr) })
    }

    /// Load a CRL from DER bytes.
    ///
    /// # Errors
    pub fn from_der(der: &[u8]) -> Result<Self, ErrorStack> {
        let bio = MemBioBuf::new(der)?;
        let ptr = unsafe { sys::d2i_X509_CRL_bio(bio.as_ptr(), std::ptr::null_mut()) };
        if ptr.is_null() {
            return Err(ErrorStack::drain());
        }
        Ok(unsafe { Self::from_ptr(ptr) })
    }

    /// Serialise the CRL to PEM.
    ///
    /// # Errors
    pub fn to_pem(&self) -> Result<Vec<u8>, ErrorStack> {
        let mut bio = MemBio::new()?;
        let rc = unsafe { sys::PEM_write_bio_X509_CRL(bio.as_ptr(), self.ptr) };
        if rc != 1 {
            return Err(ErrorStack::drain());
        }
        Ok(bio.into_vec())
    }

    /// Serialise the CRL to DER.
    ///
    /// # Errors
    pub fn to_der(&self) -> Result<Vec<u8>, ErrorStack> {
        let mut bio = MemBio::new()?;
        let rc = unsafe { sys::i2d_X509_CRL_bio(bio.as_ptr(), self.ptr) };
        if rc != 1 {
            return Err(ErrorStack::drain());
        }
        Ok(bio.into_vec())
    }

    /// Issuer distinguished name (borrowed).
    #[must_use]
    pub fn issuer_name(&self) -> X509Name<'_> {
        let ptr = unsafe { sys::X509_CRL_get_issuer(self.ptr) };
        X509Name {
            ptr: ptr.cast(),
            _owner: PhantomData,
        }
    }

    /// `thisUpdate` field as a human-readable string.
    #[must_use]
    pub fn last_update_str(&self) -> Option<String> {
        let t = unsafe { sys::X509_CRL_get0_lastUpdate(self.ptr) };
        asn1_time_to_str(t)
    }

    /// `nextUpdate` field as a human-readable string.
    #[must_use]
    pub fn next_update_str(&self) -> Option<String> {
        let t = unsafe { sys::X509_CRL_get0_nextUpdate(self.ptr) };
        asn1_time_to_str(t)
    }

    /// Verify this CRL was signed by `key`.
    ///
    /// Returns `Ok(true)` if valid, `Ok(false)` if not.
    ///
    /// # Errors
    pub fn verify(&self, key: &crate::pkey::Pkey<crate::pkey::Public>) -> Result<bool, ErrorStack> {
        match unsafe { sys::X509_CRL_verify(self.ptr, key.as_ptr()) } {
            1 => Ok(true),
            0 => Ok(false),
            _ => Err(ErrorStack::drain()),
        }
    }

    /// Raw `X509_CRL*` pointer for use by internal APIs.
    #[must_use]
    #[allow(dead_code)]
    pub(crate) fn as_ptr(&self) -> *mut sys::X509_CRL {
        self.ptr
    }
}

// ── NID ↔ name free functions ────────────────────────────────────────────────

/// Look up a NID by its short name (e.g. `c"sha256"`, `c"rsaEncryption"`).
///
/// Returns `None` if the name is not in OpenSSL's object table.
#[must_use]
pub fn nid_from_short_name(sn: &CStr) -> Option<i32> {
    // SAFETY:
    // - sn.as_ptr() is valid, non-null, and NUL-terminated for the duration of
    //   this call (CStr invariant)
    // - OBJ_sn2nid performs a read-only table lookup; it does not retain the pointer
    // - no mutable global state is accessed
    let nid = unsafe { sys::OBJ_sn2nid(sn.as_ptr()) };
    if nid == 0 {
        None
    } else {
        Some(nid)
    }
}

/// Look up a NID by OID text or short name.
///
/// Accepts dotted decimal (e.g. `c"2.16.840.1.101.3.4.2.1"`) or a short name
/// (e.g. `c"sha256"`).
///
/// Returns `None` if the string is not recognised by OpenSSL.
#[must_use]
pub fn nid_from_text(s: &CStr) -> Option<i32> {
    // SAFETY:
    // - s.as_ptr() is valid, non-null, and NUL-terminated for the duration of
    //   this call (CStr invariant)
    // - OBJ_txt2nid performs a read-only table lookup; it does not retain the pointer
    // - no mutable global state is accessed
    let nid = unsafe { sys::OBJ_txt2nid(s.as_ptr()) };
    if nid == 0 {
        None
    } else {
        Some(nid)
    }
}

/// Look up the short name for a NID (e.g. `13` → `"CN"`, `672` → `"SHA256"`).
///
/// Returns `None` if the NID is not in OpenSSL's object table.
///
/// The returned string points to OpenSSL's static object table; its lifetime
/// is `'static` and no allocation is performed.
///
/// Use this together with [`crate::pkey::Pkey::is_a`] to perform provider-aware key-type
/// comparison: `pkey.is_a(nid_to_short_name(pknid)?)`.
#[must_use]
pub fn nid_to_short_name(nid: i32) -> Option<&'static CStr> {
    // SAFETY:
    // - nid is a plain integer; no pointer arguments
    // - OBJ_nid2sn returns a pointer into OpenSSL's static OBJ table, valid
    //   for the lifetime of the process ('static); it never allocates
    // - no mutable state is accessed; this is a read-only table lookup
    let ptr = unsafe { sys::OBJ_nid2sn(nid) };
    if ptr.is_null() {
        return None;
    }
    // SAFETY: ptr is non-null (checked above) and points to a NUL-terminated
    // string in OpenSSL's static object table
    Some(unsafe { CStr::from_ptr(ptr) })
}

/// Look up the long name for a NID (e.g. `13` → `"commonName"`).
///
/// Returns `None` if the NID is not in OpenSSL's object table.
///
/// The returned string points to OpenSSL's static object table; its lifetime
/// is `'static` and no allocation is performed.
#[must_use]
pub fn nid_to_long_name(nid: i32) -> Option<&'static CStr> {
    // SAFETY: same as nid_to_short_name — plain integer argument, result
    // points to static storage in OpenSSL's OBJ table
    let ptr = unsafe { sys::OBJ_nid2ln(nid) };
    if ptr.is_null() {
        return None;
    }
    // SAFETY: ptr is non-null (checked above) and points to a NUL-terminated
    // string in OpenSSL's static object table
    Some(unsafe { CStr::from_ptr(ptr) })
}

// ── Private helpers ───────────────────────────────────────────────────────────

/// Convert an `ASN1_TIME*` to a [`BrokenDownTime`] via `ASN1_TIME_to_tm`.
fn asn1_time_to_broken_down(t: *const sys::ASN1_TIME) -> Option<BrokenDownTime> {
    if t.is_null() {
        return None;
    }
    // SAFETY:
    // - t is non-null (checked above) and valid for the duration of this call
    // - tm is zero-initialised; ASN1_TIME_to_tm fills all relevant fields
    // - no mutable aliasing: t comes from a &self borrow at call sites
    let mut tm = unsafe { std::mem::zeroed::<sys::tm>() };
    let rc = unsafe { sys::ASN1_TIME_to_tm(t, &raw mut tm) };
    if rc != 1 {
        return None;
    }
    Some(BrokenDownTime {
        year: tm.tm_year + 1900,
        month: u8::try_from(tm.tm_mon + 1).unwrap_or(0),
        day: u8::try_from(tm.tm_mday).unwrap_or(0),
        hour: u8::try_from(tm.tm_hour).unwrap_or(0),
        minute: u8::try_from(tm.tm_min).unwrap_or(0),
        second: u8::try_from(tm.tm_sec).unwrap_or(0),
    })
}

/// Convert an `ASN1_TIME*` to a human-readable string via `ASN1_TIME_print`.
fn asn1_time_to_str(t: *const sys::ASN1_TIME) -> Option<String> {
    if t.is_null() {
        return None;
    }
    let mut bio = MemBio::new().ok()?;
    let rc = unsafe { sys::ASN1_TIME_print(bio.as_ptr(), t) };
    if rc != 1 {
        return None;
    }
    String::from_utf8(bio.into_vec()).ok()
}

/// Extract the raw data bytes from an `ASN1_STRING*`.
///
/// # Safety
///
/// `asn1` must be a valid, non-null pointer for at least the duration of
/// lifetime `'a`.  The caller is responsible for ensuring the returned slice
/// does not outlive the owning ASN1 object.  Call sites bind the true lifetime
/// through their own `&self` borrow and `PhantomData` fields.
unsafe fn asn1_string_data<'a>(asn1: *const sys::ASN1_STRING) -> &'a [u8] {
    let len = usize::try_from(sys::ASN1_STRING_length(asn1)).unwrap_or(0);
    let ptr = sys::ASN1_STRING_get0_data(asn1);
    if ptr.is_null() || len == 0 {
        return &[];
    }
    // SAFETY: ptr is valid for `len` bytes; lifetime 'a is upheld by the caller.
    std::slice::from_raw_parts(ptr, len)
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::pkey::{KeygenCtx, Pkey, Private, Public};

    /// Build a self-signed Ed25519 certificate and run all read operations.
    fn make_self_signed() -> (X509, Pkey<Private>, Pkey<Public>) {
        let mut kgen = KeygenCtx::new(c"ED25519").unwrap();
        let priv_key = kgen.generate().unwrap();
        let pub_key = Pkey::<Public>::from(priv_key.clone());

        let mut name = X509NameOwned::new().unwrap();
        name.add_entry_by_txt(c"CN", b"Test Cert").unwrap();
        name.add_entry_by_txt(c"O", b"Example Org").unwrap();

        let cert = X509Builder::new()
            .unwrap()
            .set_version(2)
            .unwrap()
            .set_serial_number(1)
            .unwrap()
            .set_not_before_offset(0)
            .unwrap()
            .set_not_after_offset(365 * 86400)
            .unwrap()
            .set_subject_name(&name)
            .unwrap()
            .set_issuer_name(&name)
            .unwrap()
            .set_public_key(&pub_key)
            .unwrap()
            .sign(&priv_key, None)
            .unwrap()
            .build();

        (cert, priv_key, pub_key)
    }

    #[test]
    fn build_and_verify_self_signed() {
        let (cert, _, pub_key) = make_self_signed();
        assert!(cert.verify(&pub_key).unwrap());
        assert!(cert.is_self_signed());
    }

    #[test]
    fn pem_round_trip() {
        let (cert, _, _) = make_self_signed();
        let pem = cert.to_pem().unwrap();
        assert!(pem.starts_with(b"-----BEGIN CERTIFICATE-----"));

        let cert2 = X509::from_pem(&pem).unwrap();
        // Both should verify with the same key.
        assert_eq!(cert.to_der().unwrap(), cert2.to_der().unwrap());
    }

    #[test]
    fn der_round_trip() {
        let (cert, _, _) = make_self_signed();
        let der = cert.to_der().unwrap();
        assert!(!der.is_empty());

        let cert2 = X509::from_der(&der).unwrap();
        assert_eq!(cert2.to_der().unwrap(), der);
    }

    #[test]
    fn subject_name_entries() {
        let (cert, _, _) = make_self_signed();
        let name = cert.subject_name();

        assert_eq!(name.entry_count(), 2);

        // First entry: CN (NID 13)
        let e0 = name.entry(0).unwrap();
        assert_eq!(e0.nid(), 13); // NID_commonName
        assert!(!e0.data().is_empty());

        // to_string should include both components.
        let s = name.to_string().unwrap();
        assert!(s.contains("Test Cert") || s.contains("CN=Test Cert"));
    }

    #[test]
    fn serial_number() {
        let (cert, _, _) = make_self_signed();
        assert_eq!(cert.serial_number(), Some(1));
    }

    #[test]
    fn validity_strings_present() {
        let (cert, _, _) = make_self_signed();
        let nb = cert.not_before_str().unwrap();
        let na = cert.not_after_str().unwrap();
        // Both should contain "GMT" as OpenSSL uses UTC.
        assert!(nb.contains("GMT"), "not_before_str = {nb:?}");
        assert!(na.contains("GMT"), "not_after_str  = {na:?}");
    }

    #[test]
    fn is_valid_now() {
        let (cert, _, _) = make_self_signed();
        assert!(cert.is_valid_now());
    }

    #[test]
    fn public_key_extraction() {
        let (cert, _, pub_key) = make_self_signed();
        let extracted = cert.public_key().unwrap();
        // Both keys should verify the same signature.
        assert!(extracted.is_a(c"ED25519"));
        assert_eq!(pub_key.bits(), extracted.bits());
    }

    #[test]
    fn clone_cert() {
        let (cert, _, pub_key) = make_self_signed();
        let cert2 = cert.clone();
        // Both references should share the same content.
        assert_eq!(cert.to_der().unwrap(), cert2.to_der().unwrap());
        assert!(cert2.verify(&pub_key).unwrap());
    }

    #[test]
    fn verify_fails_with_wrong_key() {
        let (cert, _, _) = make_self_signed();
        // Generate a fresh, unrelated key pair.
        let mut kgen = KeygenCtx::new(c"ED25519").unwrap();
        let other_priv = kgen.generate().unwrap();
        let other_pub = Pkey::<Public>::from(other_priv);

        // cert was not signed by other_pub → should return Ok(false).
        assert!(!cert.verify(&other_pub).unwrap());
    }

    // ── X509Store / X509StoreCtx tests ──────────────────────────────────────

    #[test]
    fn x509_store_add_cert_and_verify() {
        let (cert, _, _) = make_self_signed();

        let mut store = X509Store::new().unwrap();
        store.add_cert(&cert).unwrap();

        let mut ctx = X509StoreCtx::new().unwrap();
        ctx.init(&store, &cert).unwrap();
        // Self-signed cert trusted by its own store → should verify.
        assert!(ctx.verify().unwrap());
    }

    #[test]
    fn x509_store_verify_untrusted_fails() {
        let (cert, _, _) = make_self_signed();
        // Empty store (nothing trusted).
        let store = X509Store::new().unwrap();

        let mut ctx = X509StoreCtx::new().unwrap();
        ctx.init(&store, &cert).unwrap();
        assert!(!ctx.verify().unwrap());
        // Error code must be non-zero.
        assert_ne!(ctx.error(), 0);
    }

    #[test]
    fn x509_store_ctx_chain_populated_after_verify() {
        let (cert, _, _) = make_self_signed();
        let mut store = X509Store::new().unwrap();
        store.add_cert(&cert).unwrap();

        let mut ctx = X509StoreCtx::new().unwrap();
        ctx.init(&store, &cert).unwrap();
        assert!(ctx.verify().unwrap());

        let chain = ctx.chain();
        assert!(
            !chain.is_empty(),
            "verified chain should contain at least the leaf"
        );
    }

    // ── X509Crl tests ────────────────────────────────────────────────────────

    #[test]
    fn x509crl_new_roundtrip() {
        // Allocate an empty CRL and verify it can be DER-serialised without panic.
        // (The DER of an empty/incomplete CRL may fail to encode a valid structure,
        // so we only assert that the call itself does not panic or crash.)
        let crl = X509Crl::new().expect("X509_CRL_new should succeed");
        // The CRL has no fields set; to_der may return Err (invalid ASN.1 state),
        // but must not panic or abort.
        let _result = crl.to_der();
        drop(crl);
    }

    #[test]
    fn x509crl_new_in_roundtrip() {
        use std::sync::Arc;
        let ctx = Arc::new(crate::lib_ctx::LibCtx::new().expect("LibCtx::new should succeed"));
        let crl = X509Crl::new_in(&ctx).expect("X509_CRL_new_ex should succeed");
        let _result = crl.to_der();
        drop(crl);
    }

    // A minimal CRL signed by an RSA/SHA-256 CA (generated via the openssl CLI).
    const TEST_CRL_PEM: &[u8] = b"\
-----BEGIN X509 CRL-----\n\
MIIBVjBAMA0GCSqGSIb3DQEBCwUAMBExDzANBgNVBAMMBlJTQSBDQRcNMjYwNDE1\n\
MTUwNDEzWhcNMjYwNTE1MTUwNDEzWjANBgkqhkiG9w0BAQsFAAOCAQEAi209u0hh\n\
Vz42YaqLplQwBoYCjtjETenl4xXRNcFOYU6Y+FmR66XNGkl9HbPClrz3hRMnbBYr\n\
OQJfWQOKS9lS0zpEI4qtlH/H1JBNGwiY32HMqf5HULn0w0ARvmoXR4NzsCecK22G\n\
gN61k5FCCpPY8HztsuoHMHAQ65W1WfBiTWu8ZH0nCCU0CA4MSaPZUiNt8/mJZzTG\n\
UwTGcZ/hcHQMpocBX40nE7ta5opcIpjG+q2uiCWhXwoqmYsLvdJ+Obw20bLirMHt\n\
UsmESTw5G+vcRCudoiSw89Z/jzsYq8yuFhRzF9kA/RtqCoQ+ylQSSH5hxzW2+bPd\n\
QPHivSGDiUhH6Q==\n\
-----END X509 CRL-----\n";

    #[test]
    fn crl_pem_round_trip() {
        let crl = X509Crl::from_pem(TEST_CRL_PEM).unwrap();
        // issuer_name should be non-empty (RSA CA)
        let issuer = crl.issuer_name();
        assert!(issuer.entry_count() > 0);
        // last_update and next_update are present.
        assert!(crl.last_update_str().is_some());
        assert!(crl.next_update_str().is_some());
        // to_pem produces a valid CRL PEM.
        let pem = crl.to_pem().unwrap();
        assert!(pem.starts_with(b"-----BEGIN X509 CRL-----"));
    }

    #[test]
    fn crl_der_round_trip() {
        let crl = X509Crl::from_pem(TEST_CRL_PEM).unwrap();
        let der = crl.to_der().unwrap();
        assert!(!der.is_empty());
        let crl2 = X509Crl::from_der(&der).unwrap();
        assert_eq!(crl2.to_der().unwrap(), der);
    }

    #[test]
    fn crl_clone() {
        let crl = X509Crl::from_pem(TEST_CRL_PEM).unwrap();
        let crl2 = crl.clone();
        assert_eq!(crl.to_der().unwrap(), crl2.to_der().unwrap());
    }

    // ── nid_from_short_name / nid_from_text tests ────────────────────────────

    #[test]
    fn x509_nid_from_short_name_known() {
        // OBJ_sn2nid is case-sensitive; "SHA256" is the registered short name,
        // not "sha256" (lowercase).  CN has stable NID 13 across all versions.
        let nid = nid_from_short_name(c"SHA256");
        assert!(nid.is_some(), "SHA256 should be a known short name");
        assert_eq!(nid_from_short_name(c"CN"), Some(13));
    }

    #[test]
    fn x509_nid_from_short_name_unknown() {
        assert_eq!(nid_from_short_name(c"not-a-real-algorithm-xyz"), None);
    }

    #[test]
    fn x509_nid_from_text_dotted_oid() {
        // 2.5.4.3 is commonName — NID 13.
        assert_eq!(nid_from_text(c"2.5.4.3"), Some(13));
    }

    #[test]
    fn x509_nid_from_text_short_name() {
        // OBJ_txt2nid accepts short names; use uppercase which OBJ_sn2nid also
        // recognises (OBJ_sn2nid is case-sensitive, lowercase "sha256" has no entry).
        let via_sn = nid_from_short_name(c"SHA256");
        let via_txt = nid_from_text(c"SHA256");
        assert_eq!(
            via_sn, via_txt,
            "short-name lookup must agree between OBJ_sn2nid and OBJ_txt2nid"
        );
    }

    #[test]
    fn x509_nid_from_text_unknown() {
        assert_eq!(nid_from_text(c"9.9.9.9.9.9.9.9"), None);
    }

    // ── serial_number_bytes tests ────────────────────────────────────────────

    #[test]
    fn x509_serial_number_bytes_small_serial() {
        let (cert, _, _) = make_self_signed();
        // set_serial_number(1) → bytes should be [0x01].
        let bytes = cert.serial_number_bytes().unwrap();
        assert!(!bytes.is_empty());
        assert_eq!(*bytes.last().unwrap(), 1u8);
    }

    #[test]
    fn x509_serial_number_bytes_consistent_with_serial_number() {
        let (cert, _, _) = make_self_signed();
        let bytes = cert.serial_number_bytes().unwrap();
        let n = cert.serial_number().unwrap();
        // For small positives: the big-endian bytes equal the i64 value.
        let be = n.to_be_bytes();
        // strip leading zeros to match OpenSSL's minimal encoding
        let start = be.iter().position(|&b| b != 0).unwrap_or(7);
        assert_eq!(bytes, &be[start..]);
    }

    // ── not_before_tm / not_after_tm tests ──────────────────────────────────

    #[test]
    fn x509_not_before_tm_is_some() {
        let (cert, _, _) = make_self_signed();
        let tm = cert.not_before_tm().expect("notBefore must be parseable");
        // The self-signed cert was built with set_not_before_offset(0) (≈ now).
        assert!(tm.year >= 2026, "year must be 2026 or later");
        assert!((1..=12).contains(&tm.month));
        assert!((1..=31).contains(&tm.day));
    }

    #[test]
    fn x509_not_after_tm_one_year_after_not_before() {
        let (cert, _, _) = make_self_signed();
        let nb = cert.not_before_tm().unwrap();
        let na = cert.not_after_tm().unwrap();
        // The cert has a 365-day validity window.  After wrapping at year boundary
        // the notAfter year is either the same or one more than notBefore.
        let year_diff = na.year - nb.year;
        assert!(year_diff == 0 || year_diff == 1, "year diff must be 0 or 1");
    }

    #[test]
    fn x509_not_before_tm_consistent_with_not_before_str() {
        let (cert, _, _) = make_self_signed();
        // Both methods must succeed on the same certificate.
        assert!(cert.not_before_tm().is_some());
        assert!(cert.not_before_str().is_some());
    }

    // ── public_key_is_a / public_key_bits tests ──────────────────────────────

    #[test]
    fn x509_public_key_is_a_ed25519() {
        let (cert, _, _) = make_self_signed();
        assert!(cert.public_key_is_a(c"ED25519"));
        assert!(!cert.public_key_is_a(c"RSA"));
    }

    #[test]
    fn x509_public_key_bits_ed25519() {
        let (cert, _, _) = make_self_signed();
        // Ed25519 keys are 255 bits / 32 bytes; OpenSSL reports 253 or 256 bits
        // depending on version — just check it's non-zero.
        let bits = cert.public_key_bits().unwrap();
        assert!(bits > 0, "Ed25519 key must report non-zero bit size");
    }

    #[test]
    fn x509_public_key_bits_agrees_with_public_key_method() {
        let (cert, _, _) = make_self_signed();
        let owned_bits = cert.public_key().unwrap().bits();
        let borrow_bits = cert.public_key_bits().unwrap();
        assert_eq!(owned_bits, borrow_bits);
    }

    // ── nid_to_short_name / nid_to_long_name tests ───────────────────────────

    #[test]
    fn nid_to_short_name_known_nid() {
        // NID 13 is "CN" (commonName) in all OpenSSL versions.
        let sn = nid_to_short_name(13).expect("NID 13 must be known");
        assert_eq!(sn.to_bytes(), b"CN");
    }

    #[test]
    fn nid_to_long_name_known_nid() {
        let ln = nid_to_long_name(13).expect("NID 13 must be known");
        assert_eq!(ln.to_bytes(), b"commonName");
    }

    #[test]
    fn nid_to_short_name_unknown_nid() {
        // A very large NID that is guaranteed not to be in the table.
        assert!(nid_to_short_name(i32::MAX).is_none());
    }

    #[test]
    fn nid_to_long_name_unknown_nid() {
        assert!(nid_to_long_name(i32::MAX).is_none());
    }

    #[test]
    fn nid_to_short_name_sha256() {
        // SHA-256 has NID 672 in OpenSSL; short name is "SHA256".
        let sn = nid_to_short_name(672).expect("NID 672 (SHA256) must be known");
        assert_eq!(sn.to_bytes(), b"SHA256");
    }

    // ── X509Name::to_oneline tests ───────────────────────────────────────────

    #[test]
    fn x509_name_oneline_returns_string() {
        let (cert, _, _) = make_self_signed();
        let name = cert.subject_name();
        let s = name
            .to_oneline()
            .expect("to_oneline must return Some for a non-empty name");
        // The legacy format includes "CN=" for the commonName entry.
        assert!(
            s.contains("CN="),
            "to_oneline output should contain CN=: {s:?}"
        );
    }

    // ── X509::new_in tests ───────────────────────────────────────────────────

    #[test]
    fn x509_new_in_lib_ctx() {
        use crate::lib_ctx::LibCtx;
        let ctx = Arc::new(LibCtx::new().expect("LibCtx::new must succeed"));
        let cert = X509::new_in(&ctx);
        assert!(
            cert.is_ok(),
            "X509::new_in must succeed with a valid LibCtx"
        );
    }

    // ── X509::extension_der tests ────────────────────────────────────────────

    #[test]
    fn x509_extension_der_absent_nid_returns_none() {
        let (cert, _, _) = make_self_signed();
        // NID 85 = subjectAltName; our simple self-signed cert has no SAN.
        let result = cert.extension_der(85);
        assert!(
            result.is_none(),
            "extension_der must return None for absent extension"
        );
    }

    #[test]
    fn x509_extension_der_present_returns_some() {
        // Build a cert that has at least one extension: subjectKeyIdentifier (NID 82).
        // We rely on extension_count() to confirm at least one extension was found.
        let (cert, _, _) = make_self_signed();
        // The basic self-signed cert may or may not carry extensions depending on the
        // builder; use extension_count to find a valid NID and then call extension_der.
        let count = cert.extension_count();
        if count > 0 {
            let ext = cert
                .extension(0)
                .expect("extension(0) must be Some when count > 0");
            let nid = ext.nid();
            let der = cert
                .extension_der(nid)
                .expect("extension_der must return Some for a NID that exists in the cert");
            // The DER bytes for the value must match X509Extension::data().
            assert_eq!(
                der,
                ext.data(),
                "extension_der bytes must match X509Extension::data"
            );
        }
        // If count == 0, the test trivially passes: no extensions to check.
    }
}

#[cfg(test)]
mod signature_info_tests {
    use super::*;
    use crate::pkey::{KeygenCtx, Pkey, Private, Public};

    fn make_ed25519_cert() -> (X509, Pkey<Private>, Pkey<Public>) {
        let mut kgen = KeygenCtx::new(c"ED25519").unwrap();
        let priv_key = kgen.generate().unwrap();
        let pub_key = Pkey::<Public>::from(priv_key.clone());

        let mut name = X509NameOwned::new().unwrap();
        name.add_entry_by_txt(c"CN", b"Ed25519 Sig Info Test")
            .unwrap();

        let cert = X509Builder::new()
            .unwrap()
            .set_version(2)
            .unwrap()
            .set_serial_number(42)
            .unwrap()
            .set_not_before_offset(0)
            .unwrap()
            .set_not_after_offset(365 * 86400)
            .unwrap()
            .set_subject_name(&name)
            .unwrap()
            .set_issuer_name(&name)
            .unwrap()
            .set_public_key(&pub_key)
            .unwrap()
            .sign(&priv_key, None)
            .unwrap()
            .build();

        (cert, priv_key, pub_key)
    }

    /// Ed25519 is a "pre-hash-free" (one-shot) algorithm: the digest NID is
    /// `NID_undef` (0) because there is no separate hashing step.
    /// The public-key NID must correspond to "ED25519" in OpenSSL's OBJ table.
    #[test]
    fn x509_signature_info_ed25519() {
        let (cert, _, _) = make_ed25519_cert();
        let info = cert
            .signature_info()
            .expect("signature_info must succeed for a signed cert");

        // Ed25519 uses no separate digest — md_nid must be NID_undef (0).
        assert_eq!(
            info.md_nid, 0,
            "Ed25519 md_nid must be 0 (NID_undef); got {}",
            info.md_nid
        );

        // pk_nid must be non-zero and must map to the "ED25519" short name.
        assert_ne!(info.pk_nid, 0, "Ed25519 pk_nid must not be NID_undef");
        let sn = nid_to_short_name(info.pk_nid)
            .expect("Ed25519 pk_nid must have a short name in OpenSSL's OBJ table");
        assert_eq!(
            sn.to_bytes(),
            b"ED25519",
            "pk_nid short name must be ED25519; got {sn:?}"
        );

        // Security bits for Ed25519 are 128.
        assert_eq!(
            info.security_bits, 128,
            "Ed25519 security bits must be 128; got {}",
            info.security_bits
        );
    }
}