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
//! Python binding for [`PyCertificate`] (X.509 Certificate).
use std::sync::OnceLock;
use pyo3::prelude::*;
use pyo3::types::{PyBytes, PyList, PyString};
use pyo3::PyClass;
use synta::traits::Encode;
use synta::{Decoder, Encoding};
use synta_certificate::{Certificate, PolicyQualifierInfo, Time};
use crate::types::PyObjectIdentifier;
use super::oid_from_pyany;
/// Re-encode an ASN.1 `Element` to DER bytes, returning `None` for a missing
/// optional field. Used by the algorithm-parameter getters.
fn encode_element_opt<'py>(
py: Python<'py>,
elem: Option<&synta::Element<'_>>,
) -> PyResult<Option<Bound<'py, PyBytes>>> {
match elem {
None => Ok(None),
Some(e) => {
let mut encoder = synta::Encoder::new(Encoding::Der);
e.encode(&mut encoder)
.map_err(|err| pyo3::exceptions::PyValueError::new_err(format!("{err}")))?;
let bytes = encoder
.finish()
.map_err(|err| pyo3::exceptions::PyValueError::new_err(format!("{err}")))?;
Ok(Some(PyBytes::new(py, &bytes)))
}
}
}
/// Decode a raw DER Name SEQUENCE and format it as an RFC 4514-style string.
fn decode_name_debug(raw: &[u8]) -> String {
synta_certificate::name::format_dn(raw)
}
/// Shared implementation for every `from_pem` static method.
///
/// Decodes all PEM blocks in `data` and constructs a Python object for each
/// by calling `make_obj(py, der_bytes)`. The closure is responsible for
/// parsing the DER bytes and wrapping the result as a `Bound<'py, PyAny>`;
/// this lets the caller use concrete types (with their full `Py::new` bounds)
/// without any generic `PyClass` constraint here.
///
/// Returns a single object for one block, a `list` for multiple blocks, and
/// raises `ValueError` when no block is found.
pub(super) fn pem_blocks_to_pyobject<'py, F>(
py: Python<'py>,
data: &[u8],
make_obj: F,
) -> PyResult<Bound<'py, PyAny>>
where
F: for<'a> Fn(Python<'py>, Bound<'a, PyBytes>) -> PyResult<Bound<'py, PyAny>>,
{
let blocks = synta_certificate::pem_blocks(data);
match blocks.len() {
0 => Err(pyo3::exceptions::PyValueError::new_err(
"no PEM block found in input",
)),
1 => make_obj(py, PyBytes::new(py, &blocks[0].1)),
_ => {
let list = PyList::empty(py);
for (_, der) in &blocks {
list.append(make_obj(py, PyBytes::new(py, der))?)?;
}
Ok(list.into_any())
}
}
}
/// Shared implementation for every `to_pem` static method.
///
/// Accepts either a single Python object of type `T` or a `list` of them,
/// serialises each to a PEM block labelled `label`, and returns the
/// concatenated bytes. The `get_der` closure extracts the raw DER bytes from
/// a Rust reference to `T`.
///
/// Using a closure (rather than a trait method) avoids requiring `T: PyClass`
/// with internal PyO3 initialiser bounds while still letting the caller use
/// concrete types.
pub(super) fn pyobject_to_pem<'py, T, D>(
py: Python<'py>,
label: &str,
obj_or_list: &Bound<'_, PyAny>,
get_der: D,
) -> PyResult<Bound<'py, PyBytes>>
where
T: PyClass,
D: for<'r> Fn(&'r T) -> &'r [u8],
{
let mut pem: Vec<u8> = Vec::new();
if let Ok(list) = obj_or_list.cast::<PyList>() {
for item in list.iter() {
let bound_t = item.cast::<T>().map_err(|_| {
pyo3::exceptions::PyTypeError::new_err(format!(
"list items must be {label} objects"
))
})?;
let borrow = bound_t.borrow();
pem.extend_from_slice(&synta_certificate::der_to_pem(label, get_der(&borrow)));
}
} else {
let bound_t = obj_or_list.cast::<T>().map_err(|_| {
pyo3::exceptions::PyTypeError::new_err(format!(
"expected a {label} object or list[{label}]"
))
})?;
let borrow = bound_t.borrow();
pem.extend_from_slice(&synta_certificate::der_to_pem(label, get_der(&borrow)));
}
Ok(PyBytes::new(py, &pem))
}
/// A single policy qualifier from the CertificatePolicies extension.
///
/// Corresponds to `PolicyQualifierInfo` in RFC 5280:
///
/// ```asn1
/// PolicyQualifierInfo ::= SEQUENCE {
/// policyQualifierId PolicyQualifierId,
/// qualifier ANY DEFINED BY policyQualifierId }
/// ```
///
/// The ``qualifier_value`` bytes are the complete DER TLV of the ``qualifier``
/// field. For ``id-qt-cps`` (OID ``1.3.6.1.5.5.7.2.1``) this encodes an
/// IA5String containing the CPS URI. For ``id-qt-unotice``
/// (``1.3.6.1.5.5.7.2.2``) it encodes a ``UserNotice`` SEQUENCE.
#[pyclass(frozen, name = "PolicyQualifier", module = "synta")]
pub struct PyPolicyQualifier {
pub qualifier_oid: synta::ObjectIdentifier,
pub qualifier_value: Vec<u8>,
}
#[pymethods]
impl PyPolicyQualifier {
/// OID identifying the qualifier type.
///
/// Common values:
///
/// - ``1.3.6.1.5.5.7.2.1`` — CPS pointer (URI string)
/// - ``1.3.6.1.5.5.7.2.2`` — user notice
#[getter]
fn qualifier_oid<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyObjectIdentifier>> {
Py::new(py, PyObjectIdentifier::from_oid(self.qualifier_oid.clone()))
.map(|p| p.into_bound(py))
}
/// Raw DER bytes of the qualifier value (tag + length + value).
///
/// For a CPS qualifier (OID ``1.3.6.1.5.5.7.2.1``) this is an IA5String
/// encoding of the CPS URI. Decode with:
///
/// ```python,ignore
/// synta.Decoder(data, synta.Encoding.DER).decode_ia5_string()
/// ```
#[getter]
fn qualifier_value<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
PyBytes::new(py, &self.qualifier_value)
}
fn __repr__(&self) -> String {
format!("PolicyQualifier(qualifier_oid={})", self.qualifier_oid)
}
}
/// A single ``PolicyInformation`` entry from the CertificatePolicies extension.
///
/// Corresponds to ``PolicyInformation`` in RFC 5280:
///
/// ```asn1
/// PolicyInformation ::= SEQUENCE {
/// policyIdentifier CertPolicyId,
/// policyQualifiers PolicyQualifiers OPTIONAL }
/// ```
#[pyclass(frozen, name = "PolicyInformation", module = "synta")]
pub struct PyPolicyInformation {
pub policy_oid: synta::ObjectIdentifier,
pub qualifiers: Vec<(synta::ObjectIdentifier, Vec<u8>)>,
}
#[pymethods]
impl PyPolicyInformation {
/// The certificate policy OID.
#[getter]
fn policy_oid<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyObjectIdentifier>> {
Py::new(py, PyObjectIdentifier::from_oid(self.policy_oid.clone())).map(|p| p.into_bound(py))
}
/// List of :class:`PolicyQualifier` entries (empty when ``policyQualifiers`` is absent).
#[getter]
fn qualifiers<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyList>> {
let list = PyList::empty(py);
for (qoid, qval) in &self.qualifiers {
let pq = Py::new(
py,
PyPolicyQualifier {
qualifier_oid: qoid.clone(),
qualifier_value: qval.clone(),
},
)?;
list.append(pq.into_bound(py))?;
}
Ok(list)
}
fn __repr__(&self) -> String {
format!("PolicyInformation(policy_oid={})", self.policy_oid)
}
}
/// X.509 Certificate accessible from Python.
///
/// Example (inside a Python extension that called `register_module`):
///
/// ```python
/// cert = Certificate.from_der(open("cert.der", "rb").read())
/// print(cert.subject)
/// ```
#[pyclass(frozen, name = "Certificate")]
pub struct PyCertificate {
// Holds a strong reference to the Python bytes object that backs the
// DER data. The CPython refcount prevents the underlying bytes buffer
// from being freed for the full lifetime of this struct. After the
// struct is collected by Python's GC, `_data` drops (in Rust's
// declaration order) and decrements the refcount; by that point no
// Rust code can hold a borrow of this struct, so no read of `raw`
// can occur through `&self` after drop begins.
pub(super) _data: Py<PyBytes>,
// Raw slice pointing into `_data`'s buffer. SAFETY: valid as long as
// `_data` is alive; CPython bytes objects have a fixed-address buffer
// that is never relocated. Stored here so the OnceLock init closure in
// `cert()` can access the bytes without requiring a GIL token.
pub(super) raw: &'static [u8],
// Full decoded certificate, heap-allocated and initialised lazily on first
// field access. `Box` keeps the 568-byte `Certificate` off the struct so
// that `PyCertificate` stays within CPython's 512-byte `pymalloc`
// threshold (after adding the Python object header). Allocating through
// pymalloc instead of the system allocator is roughly 3× faster, which is
// measurable at parse-only speeds. The full recursive decode is deferred
// so that parse-only workloads pay only the shallow envelope-scan cost.
inner: OnceLock<Box<Certificate<'static>>>,
// Byte range within `_data` covering the complete TBSCertificate TLV.
tbs_range: std::ops::Range<usize>,
// Lazily-computed Python objects. Each field is initialised on first
// Python access and returned via clone_ref on every subsequent call,
// avoiding repeated allocation and PyO3 string construction.
issuer_cache: OnceLock<Py<PyString>>,
subject_cache: OnceLock<Py<PyString>>,
signature_algorithm_cache: OnceLock<Py<PyString>>,
not_before_cache: OnceLock<Py<PyString>>,
not_after_cache: OnceLock<Py<PyString>>,
public_key_algorithm_cache: OnceLock<Py<PyString>>,
serial_number_cache: OnceLock<Py<PyAny>>,
signature_value_cache: OnceLock<Py<PyBytes>>,
public_key_cache: OnceLock<Py<PyBytes>>,
tbs_bytes_cache: OnceLock<Py<PyBytes>>,
signature_algorithm_oid_cache: OnceLock<Py<PyObjectIdentifier>>,
public_key_algorithm_oid_cache: OnceLock<Py<PyObjectIdentifier>>,
signature_algorithm_der_cache: OnceLock<Py<PyBytes>>,
signature_algorithm_params_cache: OnceLock<Option<Py<PyBytes>>>,
public_key_algorithm_params_cache: OnceLock<Option<Py<PyBytes>>>,
extensions_der_cache: OnceLock<Option<Py<PyBytes>>>,
issuer_raw_der_cache: OnceLock<Py<PyBytes>>,
subject_raw_der_cache: OnceLock<Py<PyBytes>>,
not_before_utc_cache: OnceLock<Py<PyAny>>,
not_after_utc_cache: OnceLock<Py<PyAny>>,
spki_der_cache: OnceLock<Py<PyBytes>>,
}
impl PyCertificate {
/// Return the fully-decoded certificate, triggering a full recursive
/// `Certificate::decode()` on the first call.
///
/// The result is cached in `inner` so subsequent calls are a single
/// atomic load. Returns `Err(PyValueError)` if the full decode fails
/// (e.g. malformed inner content that passed the shallow envelope scan
/// in `from_der`). Unlike a panic, this surfaces as a catchable Python
/// `ValueError` rather than an uncatchable `PanicException`.
pub(super) fn cert(&self) -> PyResult<&Certificate<'static>> {
if let Some(v) = self.inner.get() {
return Ok(v.as_ref());
}
let mut decoder = Decoder::new(self.raw, Encoding::Der);
let decoded = decoder.decode().map_err(|e| {
pyo3::exceptions::PyValueError::new_err(format!("Certificate DER decode failed: {e}"))
})?;
let _ = self.inner.set(Box::new(decoded));
Ok(self.inner.get().unwrap().as_ref())
}
}
#[pymethods]
impl PyCertificate {
/// Parse a DER-encoded X.509 certificate.
#[staticmethod]
fn from_der(py: Python<'_>, data: Bound<'_, PyBytes>) -> PyResult<Self> {
// Store the Python bytes object directly — no copy of the DER data.
let py_bytes = data.unbind();
// SAFETY: `py_bytes` holds a strong reference (Py<PyBytes>) that
// keeps the Python bytes object alive for the lifetime of this struct.
// CPython's bytes objects have a fixed-address, non-relocating payload
// buffer (CPython has no moving GC for bytes objects). The slice
// lifetime is extended to 'static; the actual safety invariants are:
// (1) All reads of `raw` go through `&self` (a borrow of the struct).
// No borrow of the struct can outlive the struct, so `raw` is
// never read after the struct begins dropping.
// (2) `raw: &'static [u8]` has no destructor (it is a fat pointer
// with no heap allocation), so Rust dropping `_data` before `raw`
// (fields drop in declaration order) does not cause a
// use-after-free during the drop sequence itself.
// (3) `inner` contains `Certificate<'static>` references into the
// buffer; dropping `Box<Certificate<'static>>` frees the box
// allocation but does not read through the contained &'static
// slices (borrows have no destructors in Rust).
// CPython-only: this pattern does not hold for PyPy or GraalPy,
// which may relocate or compact heap objects.
let raw: &'static [u8] = unsafe {
let s = py_bytes.bind(py).as_bytes();
std::slice::from_raw_parts(s.as_ptr(), s.len())
};
// Shallow structural scan: validate the Certificate SEQUENCE envelope
// and locate the TBSCertificate TLV range. This is ~4 decoder
// operations — roughly 10× faster than a full Certificate::decode().
// The full decode is deferred to the first field access via `cert()`.
//
// Certificate ::= SEQUENCE {
// tbsCertificate TBSCertificate, -- child 0: SEQUENCE
// signatureAlgorithm AlgorithmIdentifier, -- child 1: SEQUENCE
// signature BIT STRING -- child 2
// }
let tbs_range = {
let mut d = Decoder::new(raw, Encoding::Der);
// Outer Certificate SEQUENCE tag + length.
d.read_tag()
.map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("{e}")))?;
d.read_length()
.map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("{e}")))?;
// TBSCertificate: record the full TLV range (tag + length + content).
let tbs_start = d.position();
d.read_tag()
.map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("{e}")))?;
let tbs_len = d
.read_length()
.map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("{e}")))?;
let tbs_content_len = tbs_len
.definite()
.map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("{e}")))?;
tbs_start..(d.position() + tbs_content_len)
};
Ok(Self {
_data: py_bytes,
raw,
inner: OnceLock::new(),
tbs_range,
issuer_cache: OnceLock::new(),
subject_cache: OnceLock::new(),
signature_algorithm_cache: OnceLock::new(),
not_before_cache: OnceLock::new(),
not_after_cache: OnceLock::new(),
public_key_algorithm_cache: OnceLock::new(),
serial_number_cache: OnceLock::new(),
signature_value_cache: OnceLock::new(),
public_key_cache: OnceLock::new(),
tbs_bytes_cache: OnceLock::new(),
signature_algorithm_oid_cache: OnceLock::new(),
public_key_algorithm_oid_cache: OnceLock::new(),
signature_algorithm_der_cache: OnceLock::new(),
signature_algorithm_params_cache: OnceLock::new(),
public_key_algorithm_params_cache: OnceLock::new(),
extensions_der_cache: OnceLock::new(),
issuer_raw_der_cache: OnceLock::new(),
subject_raw_der_cache: OnceLock::new(),
not_before_utc_cache: OnceLock::new(),
not_after_utc_cache: OnceLock::new(),
spki_der_cache: OnceLock::new(),
})
}
/// Parse a DER-encoded X.509 certificate and perform a full RFC 5280 decode immediately.
///
/// Unlike :meth:`from_der`, which performs only a shallow 4-operation
/// envelope scan and defers the full :class:`Certificate` decode to the
/// first field access, this method triggers the complete recursive
/// ``Certificate::decode()`` at construction time.
///
/// Use this when you need all fields to be available without any
/// lazy-decode latency on the first getter call, or when benchmarking the
/// true full-parse cost that is comparable to Criterion's ``rust_typed``
/// numbers.
///
/// ```python
/// # Full parse happens here — no deferred work on first field access.
/// cert = Certificate.full_from_der(der)
/// print(cert.issuer) # warm path only
/// ```
#[staticmethod]
fn full_from_der(py: Python<'_>, data: Bound<'_, PyBytes>) -> PyResult<Self> {
let cert = Self::from_der(py, data)?;
// Prime the OnceLock: runs the full Certificate::decode() now.
cert.cert()?;
Ok(cert)
}
/// Parse a PEM-encoded X.509 certificate.
///
/// Strips the ``-----BEGIN CERTIFICATE-----`` / ``-----END CERTIFICATE-----``
/// boundary lines, decodes the base64 body, and calls :meth:`from_der`.
/// No external dependencies are required — the decoder is implemented in
/// pure Rust inside ``synta-certificate``.
///
/// Returns a single :class:`Certificate` when the input contains exactly
/// one PEM block. When multiple blocks are present (e.g. a certificate
/// chain file), returns a :class:`list` of :class:`Certificate` objects in
/// the order they appear. Raises :exc:`ValueError` if no PEM block is
/// found.
///
/// ```python
/// # Single certificate — returns Certificate directly.
/// cert = Certificate.from_pem(open("cert.pem", "rb").read())
/// print(cert.subject)
///
/// # Certificate chain — returns list[Certificate].
/// chain = Certificate.from_pem(open("chain.pem", "rb").read())
/// for cert in chain:
/// print(cert.subject)
/// ```
#[staticmethod]
fn from_pem<'py>(py: Python<'py>, data: Bound<'_, PyBytes>) -> PyResult<Bound<'py, PyAny>> {
pem_blocks_to_pyobject(py, data.as_bytes(), |py, bytes| {
let obj = Self::from_der(py, bytes)?;
Ok(Py::new(py, obj)?.into_bound(py).into_any())
})
}
/// Convert to a ``cryptography.x509.Certificate`` (PyCA) object.
///
/// Passes the original DER bytes directly to
/// ``cryptography.x509.load_der_x509_certificate``; no re-encoding is
/// performed. Requires the ``cryptography`` package to be installed.
///
/// ```python
/// synta_cert = synta.Certificate.from_der(der)
/// pyca_cert = synta_cert.to_pyca()
/// # Full cryptographic operations are now available via PyCA:
/// pyca_cert.public_key().verify(signature, message, ...)
/// ```
fn to_pyca<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
let m = py.import("cryptography.x509").map_err(|_| {
pyo3::exceptions::PyImportError::new_err(
"the 'cryptography' package is required; install it with: pip install cryptography",
)
})?;
m.call_method1(
"load_der_x509_certificate",
(self._data.clone_ref(py).into_bound(py),),
)
}
/// Construct a ``Certificate`` from a ``cryptography.x509.Certificate``.
///
/// Serialises the PyCA certificate to DER via
/// ``cert.public_bytes(Encoding.DER)`` and parses the result with
/// :meth:`from_der`. Requires the ``cryptography`` package to be
/// installed.
///
/// **Fast path** — if the object exposes a ``_synta_der_bytes`` attribute
/// whose value is a ``bytes`` object, that buffer is used directly and
/// the ``public_bytes()`` call is skipped entirely. Wrapper classes that
/// already hold the raw DER (e.g. an ``IPACertificate`` loaded from LDAP)
/// can opt in by setting the attribute at construction time:
///
/// ```python
/// class IPACertificate:
/// def __init__(self, der: bytes):
/// self._synta_der_bytes = der # enables fast path
/// self._pyca = x509.load_der_x509_certificate(der)
///
/// # Zero re-encoding cost — DER is read from _synta_der_bytes directly:
/// synta_cert = synta.Certificate.from_pyca(ipa_cert)
/// ```
///
/// Without the attribute the standard path is used:
///
/// ```python
/// pyca_cert = cryptography.x509.load_pem_x509_certificate(pem)
/// synta_cert = synta.Certificate.from_pyca(pyca_cert)
/// ```
#[staticmethod]
fn from_pyca(py: Python<'_>, pyca_cert: Bound<'_, PyAny>) -> PyResult<Self> {
// Optional fast path: if the caller has cached raw DER bytes on the
// object under the `_synta_der_bytes` attribute, use that directly to
// avoid the re-encoding cost of `public_bytes(Encoding.DER)`. This
// lets wrappers like FreeIPA's `IPACertificate` opt in by setting
// `self._synta_der_bytes = der` at construction time.
if let Ok(attr) = pyca_cert.getattr("_synta_der_bytes") {
if let Ok(der_bytes) = attr.cast_into::<PyBytes>() {
return Self::from_der(py, der_bytes);
}
}
let ser = py
.import("cryptography.hazmat.primitives.serialization")
.map_err(|_| {
pyo3::exceptions::PyImportError::new_err(
"the 'cryptography' package is required; install it with: pip install cryptography",
)
})?;
let der_bytes: Bound<'_, PyBytes> = pyca_cert
.call_method1("public_bytes", (ser.getattr("Encoding")?.getattr("DER")?,))?
.cast_into()?;
Self::from_der(py, der_bytes)
}
/// Serialize one certificate or a list of certificates to PEM format.
///
/// The mirror of :meth:`from_pem`: accepts either a single
/// :class:`Certificate` or a :class:`list` of them, and returns a
/// :class:`bytes` value containing one or more
/// ``-----BEGIN CERTIFICATE-----`` blocks concatenated in order.
///
/// ```python
/// # Single certificate:
/// pem = Certificate.to_pem(cert)
/// open("cert.pem", "wb").write(pem)
///
/// # Certificate chain:
/// pem = Certificate.to_pem([leaf, intermediate, root])
/// open("chain.pem", "wb").write(pem)
/// ```
#[staticmethod]
fn to_pem<'py>(
py: Python<'py>,
obj_or_list: Bound<'_, PyAny>,
) -> PyResult<Bound<'py, PyBytes>> {
pyobject_to_pem::<Self, _>(py, "CERTIFICATE", &obj_or_list, |c| c.raw)
}
/// Serial number as a Python int.
///
/// Returns a native Python `int` regardless of size (X.509 serials can be
/// up to 20 bytes / 160 bits per RFC 5280). The Python object is created
/// once and cached; subsequent accesses return a reference to the same object.
#[getter]
fn serial_number<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
// `get_or_try_init` is not stable on `OnceLock`, so build the value
// outside the lock if the cache is empty, then store it.
if let Some(cached) = self.serial_number_cache.get() {
return Ok(cached.clone_ref(py).into_bound(py));
}
let serial = &self.cert()?.tbs_certificate.serial_number;
let py_int: Py<PyAny> = if let Ok(v) = serial.as_u64() {
// Fast path: fits in u64 (covers traditional short serials).
// Use unsigned to match RFC 5280 §4.1.2.2 (serials are positive).
v.into_pyobject(py)?.into_any().unbind()
} else if let Ok(v) = serial.as_u128() {
// Fits in u128 after stripping any DER leading 0x00 byte.
// Covers 128-bit RSNv3 random serials correctly encoded with a
// leading 0x00 (17 bytes total) and 127-bit serials (16 bytes).
v.into_pyobject(py)?.into_any().unbind()
} else if let Ok(v) = serial.as_i64() {
// Fallback for small negative serials (technically invalid per
// RFC 5280 but be lenient when decoding).
v.into_pyobject(py)?.into_any().unbind()
} else if let Ok(v) = serial.as_i128() {
// Fallback: 16-byte signed value.
v.into_pyobject(py)?.into_any().unbind()
} else {
// Large serial (17–20 bytes): call int.from_bytes() directly.
// Using call_method avoids the parse+compile overhead of py.eval()
// on every cold-path invocation. `signed` is keyword-only in
// Python's int.from_bytes signature, so it must go in kwargs.
// Use signed=False: RFC 5280 §4.1.2.2 requires positive serials,
// and a leading 0x00 in correctly-encoded values is already
// stripped before reaching this branch.
let bytes_obj = PyBytes::new(py, serial.as_bytes());
let kwargs = pyo3::types::PyDict::new(py);
kwargs.set_item(pyo3::intern!(py, "signed"), false)?;
py.get_type::<pyo3::types::PyInt>()
.call_method(
pyo3::intern!(py, "from_bytes"),
(bytes_obj, pyo3::intern!(py, "big")),
Some(&kwargs),
)
.map(|r| r.unbind())?
};
// Ignore a racing writer; both produce the same value.
let _ = self.serial_number_cache.set(py_int.clone_ref(py));
Ok(py_int.into_bound(py))
}
/// Issuer distinguished name as a string.
#[getter]
fn issuer<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyString>> {
if let Some(cached) = self.issuer_cache.get() {
return Ok(cached.clone_ref(py).into_bound(py));
}
let s = decode_name_debug(self.cert()?.tbs_certificate.issuer.as_bytes());
let py_str = PyString::new(py, &s).unbind();
let _ = self.issuer_cache.set(py_str.clone_ref(py));
Ok(py_str.into_bound(py))
}
/// Subject distinguished name as a string.
#[getter]
fn subject<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyString>> {
if let Some(cached) = self.subject_cache.get() {
return Ok(cached.clone_ref(py).into_bound(py));
}
let s = decode_name_debug(self.cert()?.tbs_certificate.subject.as_bytes());
let py_str = PyString::new(py, &s).unbind();
let _ = self.subject_cache.set(py_str.clone_ref(py));
Ok(py_str.into_bound(py))
}
/// Signature algorithm name (e.g. "RSA", "ECDSA", "Ed25519", "ML-DSA-65"),
/// or the dotted OID notation for unrecognized algorithms.
#[getter]
fn signature_algorithm<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyString>> {
if let Some(cached) = self.signature_algorithm_cache.get() {
return Ok(cached.clone_ref(py).into_bound(py));
}
let oid = &self.cert()?.signature_algorithm.algorithm;
let name = synta_certificate::identify_signature_algorithm(oid);
let s = if name != "Other" {
name.to_string()
} else {
oid.to_string()
};
let py_str = PyString::new(py, &s).unbind();
let _ = self.signature_algorithm_cache.set(py_str.clone_ref(py));
Ok(py_str.into_bound(py))
}
/// Raw signature bytes.
///
/// The `bytes` object is created once on first access and the same Python
/// object is returned (by reference) on every subsequent call,
/// avoiding repeated allocation and PyO3 string construction.
#[getter]
fn signature_value<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
if let Some(cached) = self.signature_value_cache.get() {
return Ok(cached.clone_ref(py).into_bound(py));
}
let py_bytes = PyBytes::new(py, self.cert()?.signature_value.as_bytes()).unbind();
let _ = self.signature_value_cache.set(py_bytes.clone_ref(py));
Ok(py_bytes.into_bound(py))
}
/// notBefore time as a string.
#[getter]
fn not_before<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyString>> {
if let Some(cached) = self.not_before_cache.get() {
return Ok(cached.clone_ref(py).into_bound(py));
}
let s = match &self.cert()?.tbs_certificate.validity.not_before {
Time::UtcTime(t) => t.to_string(),
Time::GeneralTime(t) => t.to_string(),
};
let py_str = PyString::new(py, &s).unbind();
let _ = self.not_before_cache.set(py_str.clone_ref(py));
Ok(py_str.into_bound(py))
}
/// notAfter time as a string.
#[getter]
fn not_after<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyString>> {
if let Some(cached) = self.not_after_cache.get() {
return Ok(cached.clone_ref(py).into_bound(py));
}
let s = match &self.cert()?.tbs_certificate.validity.not_after {
Time::UtcTime(t) => t.to_string(),
Time::GeneralTime(t) => t.to_string(),
};
let py_str = PyString::new(py, &s).unbind();
let _ = self.not_after_cache.set(py_str.clone_ref(py));
Ok(py_str.into_bound(py))
}
/// Subject public-key algorithm name (e.g. "RSA", "ECDSA", "Ed25519", "ML-DSA-65"),
/// or the dotted OID notation for unrecognized algorithms.
#[getter]
fn public_key_algorithm<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyString>> {
if let Some(cached) = self.public_key_algorithm_cache.get() {
return Ok(cached.clone_ref(py).into_bound(py));
}
let oid = &self
.cert()?
.tbs_certificate
.subject_public_key_info
.algorithm
.algorithm;
let s = synta_certificate::identify_public_key_algorithm(oid)
.map(|s| s.to_string())
.unwrap_or_else(|| oid.to_string());
let py_str = PyString::new(py, &s).unbind();
let _ = self.public_key_algorithm_cache.set(py_str.clone_ref(py));
Ok(py_str.into_bound(py))
}
/// Raw subject public-key bytes.
///
/// The `bytes` object is created once on first access and the same Python
/// object is returned (by reference) on every subsequent call,
/// avoiding repeated allocation and PyO3 string construction.
#[getter]
fn public_key<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
if let Some(cached) = self.public_key_cache.get() {
return Ok(cached.clone_ref(py).into_bound(py));
}
let py_bytes = PyBytes::new(
py,
self.cert()?
.tbs_certificate
.subject_public_key_info
.subject_public_key
.as_bytes(),
)
.unbind();
let _ = self.public_key_cache.set(py_bytes.clone_ref(py));
Ok(py_bytes.into_bound(py))
}
/// Version field (0 = v1, 1 = v2, 2 = v3), or None if absent.
#[getter]
fn version(&self) -> PyResult<Option<i64>> {
Ok(self
.cert()?
.tbs_certificate
.version
.as_ref()
.and_then(|v| v.as_i64().ok()))
}
/// Complete DER encoding of this certificate (the original bytes passed to
/// ``from_der``).
fn to_der<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
self._data.clone_ref(py).into_bound(py)
}
/// Raw DER bytes of the TBSCertificate structure (the bytes that were
/// signed by the issuer's key).
#[getter]
fn tbs_bytes<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
self.tbs_bytes_cache
.get_or_init(|| {
let data = self._data.bind(py).as_bytes();
PyBytes::new(py, &data[self.tbs_range.clone()]).unbind()
})
.clone_ref(py)
.into_bound(py)
}
/// OID of the signature algorithm
/// (e.g. ``ObjectIdentifier("1.2.840.113549.1.1.11")`` for sha256WithRSAEncryption).
///
/// Unlike ``signature_algorithm``, this always returns the machine-readable
/// OID, even for algorithms that synta does not recognise by name.
#[getter]
fn signature_algorithm_oid<'py>(
&self,
py: Python<'py>,
) -> PyResult<Bound<'py, PyObjectIdentifier>> {
if let Some(cached) = self.signature_algorithm_oid_cache.get() {
return Ok(cached.clone_ref(py).into_bound(py));
}
let obj = Py::new(
py,
PyObjectIdentifier::from_oid(self.cert()?.signature_algorithm.algorithm.clone()),
)?;
let _ = self.signature_algorithm_oid_cache.set(obj.clone_ref(py));
Ok(obj.into_bound(py))
}
/// Raw DER bytes of the signature algorithm parameters, or ``None`` if
/// the AlgorithmIdentifier has no parameters field (e.g. Ed25519).
#[getter]
fn signature_algorithm_params<'py>(
&self,
py: Python<'py>,
) -> PyResult<Option<Bound<'py, PyBytes>>> {
if let Some(cached) = self.signature_algorithm_params_cache.get() {
return Ok(cached.as_ref().map(|b| b.clone_ref(py).into_bound(py)));
}
let computed =
encode_element_opt(py, self.cert()?.signature_algorithm.parameters.as_ref())?;
let to_store = computed.as_ref().map(|b| b.as_unbound().clone_ref(py));
let _ = self.signature_algorithm_params_cache.set(to_store);
Ok(computed)
}
/// DER-encoded ``AlgorithmIdentifier`` SEQUENCE from the certificate's outer
/// ``signatureAlgorithm`` field.
///
/// This is the raw DER form of the field — suitable for passing directly to
/// :meth:`PublicKey.verify_certificate_signature` without any re-encoding.
///
/// ```python,ignore
/// pub = synta.PublicKey.from_der(issuer_cert.public_key)
/// pub.verify_certificate_signature(
/// cert.tbs_certificate_der,
/// cert.signature_algorithm_der,
/// cert.signature_value,
/// )
/// ```
#[getter]
fn signature_algorithm_der<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
if let Some(cached) = self.signature_algorithm_der_cache.get() {
return Ok(cached.clone_ref(py).into_bound(py));
}
let ranges = synta_certificate::cert_byte_ranges(self.raw).ok_or_else(|| {
pyo3::exceptions::PyValueError::new_err("certificate DER structure is invalid")
})?;
let py_bytes = PyBytes::new(py, &self.raw[ranges.signature_algorithm]).unbind();
let _ = self
.signature_algorithm_der_cache
.set(py_bytes.clone_ref(py));
Ok(py_bytes.into_bound(py))
}
/// OID of the subject public-key algorithm
/// (e.g. ``ObjectIdentifier("1.2.840.10045.2.1")`` for id-ecPublicKey).
#[getter]
fn public_key_algorithm_oid<'py>(
&self,
py: Python<'py>,
) -> PyResult<Bound<'py, PyObjectIdentifier>> {
if let Some(cached) = self.public_key_algorithm_oid_cache.get() {
return Ok(cached.clone_ref(py).into_bound(py));
}
let obj = Py::new(
py,
PyObjectIdentifier::from_oid(
self.cert()?
.tbs_certificate
.subject_public_key_info
.algorithm
.algorithm
.clone(),
),
)?;
let _ = self.public_key_algorithm_oid_cache.set(obj.clone_ref(py));
Ok(obj.into_bound(py))
}
/// Raw DER bytes of the public-key algorithm parameters, or ``None``.
///
/// For EC keys this is an OID naming the curve (e.g. secp256r1).
/// For RSA and Ed25519 this is typically ``None`` or a NULL element.
#[getter]
fn public_key_algorithm_params<'py>(
&self,
py: Python<'py>,
) -> PyResult<Option<Bound<'py, PyBytes>>> {
if let Some(cached) = self.public_key_algorithm_params_cache.get() {
return Ok(cached.as_ref().map(|b| b.clone_ref(py).into_bound(py)));
}
let computed = encode_element_opt(
py,
self.cert()?
.tbs_certificate
.subject_public_key_info
.algorithm
.parameters
.as_ref(),
)?;
let to_store = computed.as_ref().map(|b| b.as_unbound().clone_ref(py));
let _ = self.public_key_algorithm_params_cache.set(to_store);
Ok(computed)
}
/// Raw DER bytes of the extensions SEQUENCE OF, or ``None`` for v1/v2
/// certificates that carry no extensions.
///
/// The returned bytes begin with the SEQUENCE tag (``0x30``) and contain
/// the full SEQUENCE OF Extension encoding. Pass them to a ``Decoder``
/// to iterate the individual extensions:
///
/// ```python
/// ext_der = cert.extensions_der
/// if ext_der:
/// dec = synta.Decoder(ext_der, synta.Encoding.DER)
/// exts_dec = dec.decode_sequence()
/// while not exts_dec.is_empty():
/// ext_tlv = exts_dec.decode_raw_tlv()
/// ```
#[getter]
fn extensions_der<'py>(&self, py: Python<'py>) -> PyResult<Option<Bound<'py, PyBytes>>> {
if let Some(cached) = self.extensions_der_cache.get() {
return Ok(cached.as_ref().map(|b| b.clone_ref(py).into_bound(py)));
}
let computed = self
.cert()?
.tbs_certificate
.extensions
.as_ref()
.map(|raw: &synta::RawDer<'_>| PyBytes::new(py, raw.as_bytes()));
let to_store = computed.as_ref().map(|b| b.as_unbound().clone_ref(py));
let _ = self.extensions_der_cache.set(to_store);
Ok(computed)
}
/// Return the DER content of a named extension's value, or ``None``.
///
/// Searches the certificate's extension list for an extension whose
/// ``extnID`` equals *oid* (dotted-decimal notation, e.g.
/// ``"2.5.29.17"`` for SubjectAltName). When found, the bytes inside
/// the ``extnValue`` OCTET STRING — the DER-encoded extension-specific
/// structure — are returned. Returns ``None`` when the certificate
/// carries no extensions or the named OID is absent.
///
/// Example — parse SubjectAltName:
///
/// ```python
/// san_der = cert.get_extension_value_der("2.5.29.17")
/// if san_der:
/// dec = synta.Decoder(san_der, synta.Encoding.DER)
/// san_seq = dec.decode_sequence()
/// while not san_seq.is_empty():
/// tag_num, tag_class, _ = san_seq.peek_tag()
/// child = san_seq.decode_implicit_tag(tag_num, tag_class)
/// if tag_num == 2: # dNSName
/// print(child.remaining_bytes().decode("ascii"))
/// ```
fn get_extension_value_der<'py>(
&self,
py: Python<'py>,
oid: &Bound<'_, PyAny>,
) -> PyResult<Option<Bound<'py, PyBytes>>> {
let target = oid_from_pyany(oid)?;
let raw = match self.cert()?.tbs_certificate.extensions.as_ref() {
Some(r) => r,
None => return Ok(None),
};
for ext in &synta_certificate::decode_extensions(raw.as_bytes()) {
if ext.extn_id == target {
return Ok(Some(PyBytes::new(py, ext.extn_value.as_bytes())));
}
}
Ok(None)
}
/// Return the Subject Alternative Names of this certificate as typed objects.
///
/// Combines looking up the SAN extension (OID ``2.5.29.17``) and parsing
/// its ``GeneralName`` entries into a single call. Returns a
/// :class:`list` of typed :mod:`synta.general_name` objects in document
/// order; returns an empty list when the certificate carries no SAN
/// extension.
///
/// Each element is one of:
///
/// - :class:`~synta.general_name.OtherName` — tag 0
/// - :class:`~synta.general_name.RFC822Name` — tag 1 (e-mail address)
/// - :class:`~synta.general_name.DNSName` — tag 2
/// - :class:`~synta.general_name.X400Address` — tag 3 (raw DER)
/// - :class:`~synta.general_name.DirectoryName` — tag 4
/// - :class:`~synta.general_name.EDIPartyName` — tag 5 (raw DER)
/// - :class:`~synta.general_name.UniformResourceIdentifier` — tag 6
/// - :class:`~synta.general_name.IPAddress` — tag 7
/// - :class:`~synta.general_name.RegisteredID` — tag 8
///
/// ```python,ignore
/// import ipaddress
/// import synta.general_name as gn
///
/// for name in cert.subject_alt_names():
/// if isinstance(name, gn.DNSName):
/// print("DNS:", name.value)
/// elif isinstance(name, gn.IPAddress):
/// print("IP:", ipaddress.ip_address(name.address))
/// elif isinstance(name, gn.RFC822Name):
/// print("email:", name.value)
/// elif isinstance(name, gn.DirectoryName):
/// attrs = synta.parse_name_attrs(name.name_der)
/// print("DirName:", attrs)
/// elif isinstance(name, gn.UniformResourceIdentifier):
/// print("URI:", name.value)
/// ```
fn subject_alt_names<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyList>> {
use super::general_name::decode_general_names_to_py;
use synta_certificate::find_extension_value;
let cert = self.cert()?;
let raw = match cert.tbs_certificate.extensions.as_ref() {
Some(r) => r,
None => return Ok(PyList::empty(py)),
};
let san_bytes =
match find_extension_value(raw.as_bytes(), synta_certificate::oids::SUBJECT_ALT_NAME) {
Some(b) => b,
None => return Ok(PyList::empty(py)),
};
decode_general_names_to_py(py, san_bytes)
}
/// Return the GeneralNames from any extension that encodes a
/// ``SEQUENCE OF GeneralName``, identified by OID.
///
/// Looks up the extension with the given *oid* and decodes its value as a
/// ``SEQUENCE OF GeneralName``. Suitable for SAN (``2.5.29.17``), IAN
/// (``2.5.29.18``), or any private extension that uses the same format.
///
/// Returns a :class:`list` of typed :mod:`synta.general_name` objects, or
/// an empty list when the extension is absent or cannot be decoded.
///
/// ```python,ignore
/// import synta
/// import synta.general_name as gn
///
/// cert = synta.Certificate.from_der(der)
/// # Decode the Issuer Alternative Names extension:
/// for name in cert.general_names("2.5.29.18"):
/// if isinstance(name, gn.DirectoryName):
/// print(synta.parse_name_attrs(name.name_der))
/// ```
fn general_names<'py>(
&self,
py: Python<'py>,
oid: &Bound<'_, PyAny>,
) -> PyResult<Bound<'py, PyList>> {
use super::general_name::decode_general_names_to_py;
use super::oid_from_pyany;
use synta_certificate::find_extension_value;
let target = oid_from_pyany(oid)?;
let cert = self.cert()?;
let raw = match cert.tbs_certificate.extensions.as_ref() {
Some(r) => r,
None => return Ok(PyList::empty(py)),
};
let ext_bytes = match find_extension_value(raw.as_bytes(), target.components()) {
Some(b) => b,
None => return Ok(PyList::empty(py)),
};
decode_general_names_to_py(py, ext_bytes)
}
/// Return the CertificatePolicies entries from the extension (OID ``2.5.29.32``).
///
/// Decodes the ``CertificatePolicies`` extension value
/// (``SEQUENCE OF PolicyInformation``) and returns a list of
/// :class:`PolicyInformation` objects, each containing the policy OID and
/// any ``policyQualifiers``.
///
/// Returns an empty list when the extension is absent or cannot be parsed.
///
/// ```python,ignore
/// import synta
/// cert = synta.Certificate.from_der(der)
/// for pi in cert.certificate_policies():
/// print(str(pi.policy_oid)) # e.g. "1.3.6.1.4.1.311.21.8...."
/// for q in pi.qualifiers:
/// print(str(q.qualifier_oid))
/// ```
fn certificate_policies<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyList>> {
let list = PyList::empty(py);
let cert = self.cert()?;
let ext_raw = match cert.tbs_certificate.extensions.as_ref() {
Some(r) => r,
None => return Ok(list),
};
let ext_value_bytes = synta_certificate::find_extension_value(
ext_raw.as_bytes(),
synta_certificate::oids::CERTIFICATE_POLICIES,
);
let ext_bytes = match ext_value_bytes {
Some(b) => b,
None => return Ok(list),
};
// Decode using the code-generated PolicyInformation<'a> type.
let mut decoder = synta::Decoder::new(ext_bytes, synta::Encoding::Der);
let infos: Vec<synta_certificate::PolicyInformation<'_>> = match decoder.decode() {
Ok(v) => v,
Err(_) => return Ok(list),
};
for pi in infos {
let qualifiers = pi
.policy_qualifiers
.unwrap_or_default()
.into_iter()
.filter_map(|qi: PolicyQualifierInfo<'_>| {
let mut enc = synta::Encoder::new(synta::Encoding::Der);
qi.qualifier.encode(&mut enc).ok()?;
let qval = enc.finish().ok()?;
Some((qi.policy_qualifier_id, qval))
})
.collect();
let py_pi = Py::new(
py,
PyPolicyInformation {
policy_oid: pi.policy_identifier,
qualifiers,
},
)?;
list.append(py_pi.into_bound(py))?;
}
Ok(list)
}
/// Raw DER bytes of the issuer Name SEQUENCE.
#[getter]
fn issuer_raw_der<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
if let Some(cached) = self.issuer_raw_der_cache.get() {
return Ok(cached.clone_ref(py).into_bound(py));
}
let py_bytes = PyBytes::new(py, self.cert()?.tbs_certificate.issuer.as_bytes()).unbind();
let _ = self.issuer_raw_der_cache.set(py_bytes.clone_ref(py));
Ok(py_bytes.into_bound(py))
}
/// Raw DER bytes of the subject Name SEQUENCE.
#[getter]
fn subject_raw_der<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
if let Some(cached) = self.subject_raw_der_cache.get() {
return Ok(cached.clone_ref(py).into_bound(py));
}
let py_bytes = PyBytes::new(py, self.cert()?.tbs_certificate.subject.as_bytes()).unbind();
let _ = self.subject_raw_der_cache.set(py_bytes.clone_ref(py));
Ok(py_bytes.into_bound(py))
}
/// notBefore time as a UTC-aware ``datetime.datetime``.
///
/// Equivalent to ``cert.not_valid_before.replace(tzinfo=datetime.timezone.utc)``
/// from the ``cryptography`` library. Derives the value from the parsed
/// ASN.1 ``Time`` field (``UTCTime`` or ``GeneralizedTime``) without calling
/// any Python date-parsing code.
///
/// ```python,ignore
/// import datetime
/// cert = synta.Certificate.from_der(der)
/// dt = cert.not_before_utc
/// print(dt.isoformat()) # e.g. "2023-01-01T00:00:00+00:00"
/// print(dt.tzinfo) # datetime.timezone.utc
/// ```
#[getter]
fn not_before_utc<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
if let Some(cached) = self.not_before_utc_cache.get() {
return Ok(cached.clone_ref(py).into_bound(py));
}
let unix_secs = synta_x509_verification::certificate::time_to_unix(
&self.cert()?.tbs_certificate.validity.not_before,
)
.ok_or_else(|| {
pyo3::exceptions::PyValueError::new_err("notBefore date is structurally invalid")
})?;
let datetime_mod = py.import("datetime")?;
let utc = datetime_mod.getattr("timezone")?.getattr("utc")?;
let dt = datetime_mod
.getattr("datetime")?
.call_method1("fromtimestamp", (unix_secs, &utc))?
.unbind();
let _ = self.not_before_utc_cache.set(dt.clone_ref(py));
Ok(dt.into_bound(py))
}
/// notAfter time as a UTC-aware ``datetime.datetime``.
///
/// Equivalent to ``cert.not_valid_after.replace(tzinfo=datetime.timezone.utc)``
/// from the ``cryptography`` library. Derives the value from the parsed
/// ASN.1 ``Time`` field (``UTCTime`` or ``GeneralizedTime``) without calling
/// any Python date-parsing code.
///
/// ```python,ignore
/// import datetime
/// cert = synta.Certificate.from_der(der)
/// dt = cert.not_after_utc
/// print(dt.isoformat()) # e.g. "2033-01-01T00:00:00+00:00"
/// print(dt.tzinfo) # datetime.timezone.utc
/// ```
#[getter]
fn not_after_utc<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
if let Some(cached) = self.not_after_utc_cache.get() {
return Ok(cached.clone_ref(py).into_bound(py));
}
let unix_secs = synta_x509_verification::certificate::time_to_unix(
&self.cert()?.tbs_certificate.validity.not_after,
)
.ok_or_else(|| {
pyo3::exceptions::PyValueError::new_err("notAfter date is structurally invalid")
})?;
let datetime_mod = py.import("datetime")?;
let utc = datetime_mod.getattr("timezone")?.getattr("utc")?;
let dt = datetime_mod
.getattr("datetime")?
.call_method1("fromtimestamp", (unix_secs, &utc))?
.unbind();
let _ = self.not_after_utc_cache.set(dt.clone_ref(py));
Ok(dt.into_bound(py))
}
/// Hash algorithm name component of the certificate's outer signature algorithm.
///
/// Returns the lowercase hash algorithm name (e.g. ``"sha256"``, ``"sha1"``,
/// ``"sha384"``) implied by the signature algorithm OID. Returns ``None``
/// for algorithms that do not use a traditional hash (Ed25519, Ed448,
/// ML-DSA, etc.).
///
/// For RSASSA-PSS the hash is encoded in the parameters field, which is not
/// inspected here; ``"sha256"`` is returned as a conservative default.
///
/// ```python,ignore
/// cert = synta.Certificate.from_der(der)
/// hash_name = cert.signature_hash_algorithm_name
/// if hash_name:
/// print(hash_name) # e.g. "sha256"
/// else:
/// print("no hash (e.g. Ed25519)")
/// ```
#[getter]
fn signature_hash_algorithm_name(&self) -> PyResult<Option<&'static str>> {
use synta_certificate::oids;
let oid = &self.cert()?.signature_algorithm.algorithm;
let c = oid.components();
// RSA PKCS#1 v1.5 variants (1.2.840.113549.1.1.*)
if c == oids::SHA1_WITH_RSA {
return Ok(Some("sha1"));
}
if c == oids::SHA256_WITH_RSA {
return Ok(Some("sha256"));
}
if c == oids::SHA384_WITH_RSA {
return Ok(Some("sha384"));
}
if c == oids::SHA512_WITH_RSA {
return Ok(Some("sha512"));
}
// RSA-PSS (hash is in params; return sha256 as safe default)
if c == oids::RSASSA_PSS {
return Ok(Some("sha256"));
}
// ECDSA variants
if c == oids::ECDSA_WITH_SHA1 {
return Ok(Some("sha1"));
}
if c == oids::ECDSA_WITH_SHA256 {
return Ok(Some("sha256"));
}
if c == oids::ECDSA_WITH_SHA384 {
return Ok(Some("sha384"));
}
if c == oids::ECDSA_WITH_SHA512 {
return Ok(Some("sha512"));
}
// Ed25519, Ed448, ML-DSA-*, SLH-DSA-* and everything else: no hash
Ok(None)
}
/// Complete DER encoding of the SubjectPublicKeyInfo SEQUENCE.
///
/// Returns the full ``SubjectPublicKeyInfo`` SEQUENCE TLV as ``bytes``,
/// including the algorithm identifier and the BIT STRING carrying the
/// actual public key. This is the DER encoding that
/// ``cryptography``'s ``public_bytes(Encoding.DER, PublicFormat.SubjectPublicKeyInfo)``
/// produces.
///
/// ```python,ignore
/// cert = synta.Certificate.from_der(der)
/// spki_der = cert.subject_public_key_info_der
/// # Load the public key with cryptography:
/// from cryptography.hazmat.primitives.serialization import load_der_public_key
/// pub_key = load_der_public_key(spki_der)
/// ```
#[getter]
fn subject_public_key_info_der<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
if let Some(cached) = self.spki_der_cache.get() {
return Ok(cached.clone_ref(py).into_bound(py));
}
let spki = &self.cert()?.tbs_certificate.subject_public_key_info;
let mut enc = synta::Encoder::new(synta::Encoding::Der);
spki.encode(&mut enc)
.map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("{e}")))?;
let bytes = enc
.finish()
.map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("{e}")))?;
let py_bytes = PyBytes::new(py, &bytes).unbind();
let _ = self.spki_der_cache.set(py_bytes.clone_ref(py));
Ok(py_bytes.into_bound(py))
}
/// Raw DER bytes of the ``TBSCertificate`` structure — the bytes that
/// were signed by the issuer's key.
///
/// This is the DER encoding of the full ``TBSCertificate`` SEQUENCE TLV,
/// suitable for signature verification or as the input to a hash function.
/// Equivalent to ``cryptography``'s ``cert.tbs_certificate_bytes``.
///
/// ```python,ignore
/// cert = synta.Certificate.from_der(der)
/// tbs = cert.tbs_certificate_der
/// # Verify signature manually:
/// import synta.crypto
/// digest = synta.digest("sha256", tbs)
/// ```
#[getter]
fn tbs_certificate_der<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
self.tbs_bytes(py)
}
/// Verify that this certificate was directly issued by ``issuer``.
///
/// Checks two things:
///
/// 1. The ``issuer`` field of this certificate's TBS matches the
/// ``subject`` field of the provided issuer certificate (byte-exact
/// DER comparison).
/// 2. The certificate's signature is valid under the issuer's public key.
///
/// Raises :exc:`ValueError` if either check fails. This is the synta
/// equivalent of ``cryptography``'s
/// ``cert.verify_directly_issued_by(issuer)``.
///
/// ```python,ignore
/// root = synta.Certificate.from_pem(open("root.pem", "rb").read())
/// leaf = synta.Certificate.from_pem(open("leaf.pem", "rb").read())
/// leaf.verify_issued_by(root) # raises ValueError if not valid
/// ```
fn verify_issued_by(&self, issuer: &PyCertificate) -> PyResult<()> {
use synta_certificate::{cert_byte_ranges, default_signature_verifier, SignatureVerifier};
// 1. Name check: our issuer Name must byte-equal their subject Name.
let cert = self.cert()?;
let issuer_cert = issuer.cert()?;
if cert.tbs_certificate.issuer.as_bytes() != issuer_cert.tbs_certificate.subject.as_bytes()
{
return Err(pyo3::exceptions::PyValueError::new_err(
"issuer name does not match subject of provided certificate",
));
}
// 2. Locate byte ranges within each cert's DER without re-encoding.
let my_ranges = cert_byte_ranges(self.raw).ok_or_else(|| {
pyo3::exceptions::PyValueError::new_err(
"failed to locate byte ranges in certificate DER",
)
})?;
let issuer_ranges = cert_byte_ranges(issuer.raw).ok_or_else(|| {
pyo3::exceptions::PyValueError::new_err(
"failed to locate byte ranges in issuer certificate DER",
)
})?;
// 3. Signature bits (raw bytes, no unused-bits prefix).
let signature_bits = cert.signature_value.as_bytes();
// 4. Verify using the backend-agnostic verifier.
default_signature_verifier()
.verify_certificate_signature(
&self.raw[my_ranges.tbs],
&self.raw[my_ranges.signature_algorithm],
signature_bits,
&issuer.raw[issuer_ranges.subject_public_key_info],
)
.map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("{e}")))?;
Ok(())
}
/// Compute a hash fingerprint of the complete certificate DER.
///
/// ``algorithm`` must be one of ``"sha1"``, ``"sha224"``, ``"sha256"``,
/// ``"sha384"``, ``"sha512"``, or ``"md5"``. Raises :exc:`ValueError` for
/// unknown algorithm names.
///
/// ```python,ignore
/// cert = synta.Certificate.from_der(der)
/// fp = cert.fingerprint("sha256")
/// print(fp.hex()) # e.g. "3a2b1c..."
/// ```
fn fingerprint<'py>(&self, py: Python<'py>, algorithm: &str) -> PyResult<Bound<'py, PyBytes>> {
use synta_certificate::{default_data_hasher, DataHasher};
let digest = default_data_hasher()
.hash_data(algorithm, self.raw)
.map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("{e}")))?;
Ok(PyBytes::new(py, &digest))
}
fn __repr__(&self) -> PyResult<String> {
let cert = self.cert()?;
let serial = &cert.tbs_certificate.serial_number;
let serial_str = if let Ok(v) = serial.as_i64() {
v.to_string()
} else {
format!("<{} bytes>", serial.as_bytes().len())
};
Ok(format!(
"Certificate(subject={:?}, serial={})",
decode_name_debug(cert.tbs_certificate.subject.as_bytes()),
serial_str,
))
}
}
impl PyCertificate {
/// Parse a DER-encoded X.509 certificate (internal helper visible to sibling modules).
///
/// This is the same logic as the `#[staticmethod] from_der` exposed to Python but
/// accessible from Rust sibling modules via `pub(super)` visibility.
pub(crate) fn new_from_der(py: Python<'_>, data: Bound<'_, PyBytes>) -> PyResult<Self> {
Self::from_der(py, data)
}
}