native-ossl 0.1.1

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
//! 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;

// ── 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)
    }

    /// 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
        }
    }

    /// 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)
    }

    /// 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) })
    }

    /// 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,
            })
        }
    }

    /// 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,
            })
        }
    }

    /// 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 }
    }

    /// 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
    }
}

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

/// 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 ────────────────────────────────────────────────────────

    // 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());
    }
}