synta-python 0.2.1

Python extension module for the synta ASN.1 library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
//! Python bindings for X.509 extension DER value builders.
//!
//! Registers the ``synta.ext`` submodule with low-level DER-encoding helpers
//! for the most common X.509 v3 extension values.  Each function returns the
//! raw DER bytes of the extension's ``extnValue`` — the content inside the
//! OCTET STRING wrapper.
//!
//! ## Key identifier method constants
//!
//! Pass these to ``subject_key_identifier`` and ``authority_key_identifier``
//! as the ``method`` argument:
//!
//! | Constant | Value | Specification |
//! |----------|-------|---------------|
//! | `KEYID_RFC5280` | 0 | SHA-1 of BIT STRING value of subjectPublicKey (RFC 5280 §4.2.1.2) |
//! | `KEYID_RFC7093M1` | 1 | SHA-256 of BIT STRING value, truncated to 160 bits (RFC 7093 §2 m1) |
//! | `KEYID_RFC7093M2` | 2 | SHA-384 of BIT STRING value, truncated to 160 bits (RFC 7093 §2 m2) |
//! | `KEYID_RFC7093M3` | 3 | SHA-512 of BIT STRING value, truncated to 160 bits (RFC 7093 §2 m3) |
//! | `KEYID_RFC7093M4` | 4 | SHA-256 of full SubjectPublicKeyInfo DER (RFC 7093 §2 m4) |
//!
//! ## Key usage bitmask constants
//!
//! ``KU_*`` constants are ready-to-OR bitmasks for ``key_usage``:
//!
//! | Constant | Mask | Named bit (RFC 5280 §4.2.1.3) |
//! |----------|------|-------------------------------|
//! | `KU_DIGITAL_SIGNATURE` | 0x001 | `digitalSignature` |
//! | `KU_NON_REPUDIATION` | 0x002 | `contentCommitment` |
//! | `KU_KEY_ENCIPHERMENT` | 0x004 | `keyEncipherment` |
//! | `KU_DATA_ENCIPHERMENT` | 0x008 | `dataEncipherment` |
//! | `KU_KEY_AGREEMENT` | 0x010 | `keyAgreement` |
//! | `KU_KEY_CERT_SIGN` | 0x020 | `keyCertSign` |
//! | `KU_CRL_SIGN` | 0x040 | `cRLSign` |
//! | `KU_ENCIPHER_ONLY` | 0x080 | `encipherOnly` |
//! | `KU_DECIPHER_ONLY` | 0x100 | `decipherOnly` |
//!
//! ## Fluent builder classes
//!
//! Four builder classes accumulate entries and produce DER on ``.build()``:
//!
//! | Class | Short alias | Extension | OID |
//! |-------|-------------|-----------|-----|
//! | ``SubjectAlternativeNameBuilder`` | ``SAN`` | Subject Alternative Name | 2.5.29.17 |
//! | ``AuthorityInformationAccessBuilder`` | ``AIA`` | Authority Information Access | 1.3.6.1.5.5.7.1.1 |
//! | ``ExtendedKeyUsageBuilder`` | ``EKU`` | Extended Key Usage | 2.5.29.37 |
//! | ``NameConstraintsBuilder`` | ``NC`` | Name Constraints | 2.5.29.30 |

use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
use pyo3::types::PyBytes;

use synta_certificate::{
    default_key_id_hasher, encode_authority_key_identifier, encode_basic_constraints,
    encode_key_usage, encode_subject_key_identifier, AuthorityInformationAccessBuilder,
    CRLDistributionPointsBuilder, CertificatePoliciesBuilder, ExtendedKeyUsageBuilder,
    IssuerAlternativeNameBuilder, IssuingDistributionPointBuilder, KeyIdMethod,
    NameConstraintsBuilder, SubjectAlternativeNameBuilder,
};

// ── Key identifier method constants ──────────────────────────────────────────

/// RFC 5280 §4.2.1.2: SHA-1 of the BIT STRING value of ``subjectPublicKey``.
pub const KEYID_RFC5280: u8 = 0;

/// RFC 7093 §2 method 1: SHA-256 of BIT STRING value, truncated to 160 bits.
pub const KEYID_RFC7093M1: u8 = 1;

/// RFC 7093 §2 method 2: SHA-384 of BIT STRING value, truncated to 160 bits.
pub const KEYID_RFC7093M2: u8 = 2;

/// RFC 7093 §2 method 3: SHA-512 of BIT STRING value, truncated to 160 bits.
pub const KEYID_RFC7093M3: u8 = 3;

/// RFC 7093 §2 method 4: SHA-256 of the full ``SubjectPublicKeyInfo`` DER encoding.
pub const KEYID_RFC7093M4: u8 = 4;

// ── Key usage bitmask constants ───────────────────────────────────────────────

/// ``digitalSignature`` (bit 0) — RFC 5280 §4.2.1.3.
pub const KU_DIGITAL_SIGNATURE: u16 = 1 << 0;
/// ``contentCommitment`` / ``nonRepudiation`` (bit 1) — RFC 5280 §4.2.1.3.
pub const KU_NON_REPUDIATION: u16 = 1 << 1;
/// ``keyEncipherment`` (bit 2) — RFC 5280 §4.2.1.3.
pub const KU_KEY_ENCIPHERMENT: u16 = 1 << 2;
/// ``dataEncipherment`` (bit 3) — RFC 5280 §4.2.1.3.
pub const KU_DATA_ENCIPHERMENT: u16 = 1 << 3;
/// ``keyAgreement`` (bit 4) — RFC 5280 §4.2.1.3.
pub const KU_KEY_AGREEMENT: u16 = 1 << 4;
/// ``keyCertSign`` (bit 5) — RFC 5280 §4.2.1.3.
pub const KU_KEY_CERT_SIGN: u16 = 1 << 5;
/// ``cRLSign`` (bit 6) — RFC 5280 §4.2.1.3.
pub const KU_CRL_SIGN: u16 = 1 << 6;
/// ``encipherOnly`` (bit 7) — RFC 5280 §4.2.1.3; only meaningful when keyAgreement is set.
pub const KU_ENCIPHER_ONLY: u16 = 1 << 7;
/// ``decipherOnly`` (bit 8) — RFC 5280 §4.2.1.3; only meaningful when keyAgreement is set.
pub const KU_DECIPHER_ONLY: u16 = 1 << 8;

// ── Internal helper ───────────────────────────────────────────────────────────

/// Convert a Python-level ``KEYID_*`` integer constant to a [`KeyIdMethod`].
///
/// Accepts the five method codes exported as module-level constants:
/// `KEYID_RFC5280` (0), `KEYID_RFC7093M1` (1), `KEYID_RFC7093M2` (2),
/// `KEYID_RFC7093M3` (3), `KEYID_RFC7093M4` (4).
///
/// Returns `Err(ValueError)` with a descriptive message for any other value.
fn method_from_int(m: u8) -> PyResult<KeyIdMethod> {
    match m {
        KEYID_RFC5280 => Ok(KeyIdMethod::Rfc5280Sha1),
        KEYID_RFC7093M1 => Ok(KeyIdMethod::Rfc7093Method1Sha256),
        KEYID_RFC7093M2 => Ok(KeyIdMethod::Rfc7093Method2Sha384),
        KEYID_RFC7093M3 => Ok(KeyIdMethod::Rfc7093Method3Sha512),
        KEYID_RFC7093M4 => Ok(KeyIdMethod::Rfc7093Method4 {
            algorithm_oid: synta_certificate::ID_SHA256.to_vec(),
        }),
        other => Err(PyValueError::new_err(format!(
            "unknown key identifier method {other}: \
             use KEYID_RFC5280, KEYID_RFC7093M1, KEYID_RFC7093M2, \
             KEYID_RFC7093M3, or KEYID_RFC7093M4"
        ))),
    }
}

// ── Python functions ──────────────────────────────────────────────────────────

/// Encode a ``BasicConstraints`` extension value (OID 2.5.29.19).
///
/// Returns the DER bytes of the ``BasicConstraints`` SEQUENCE for use as the
/// extension ``extnValue`` (inside the OCTET STRING wrapper):
///
/// ```text
/// BasicConstraints ::= SEQUENCE {
///     cA                  BOOLEAN DEFAULT FALSE,
///     pathLenConstraint   INTEGER (0..MAX) OPTIONAL }
/// ```
///
/// When ``ca`` is ``False`` the ``cA`` field is omitted (DER DEFAULT-FALSE
/// rule).  ``path_length`` is silently ignored when ``ca`` is ``False``.
///
/// ```python,ignore
/// import synta.ext as ext
///
/// # End-entity certificate: empty SEQUENCE (30 00)
/// ee_bc = ext.basic_constraints()
/// assert ee_bc == bytes([0x30, 0x00])
///
/// # CA with no path-length constraint (30 03 01 01 ff)
/// ca_bc = ext.basic_constraints(ca=True)
///
/// # CA with pathLen = 0 (30 06 01 01 ff 02 01 00)
/// ca_pl0 = ext.basic_constraints(ca=True, path_length=0)
/// ```
#[pyfunction]
#[pyo3(signature = (ca = false, path_length = None))]
fn basic_constraints<'py>(
    py: Python<'py>,
    ca: bool,
    path_length: Option<u64>,
) -> PyResult<Bound<'py, PyBytes>> {
    let der = encode_basic_constraints(ca, path_length)
        .ok_or_else(|| PyValueError::new_err("BasicConstraints DER encoding failed"))?;
    Ok(PyBytes::new(py, &der))
}

/// Encode a ``CRLNumber`` extension value (OID 2.5.29.20, RFC 5280 §5.2.1).
///
/// Returns the bare DER-encoded ``INTEGER`` — the content that goes inside the
/// OCTET STRING wrapper in the ``Extension`` SEQUENCE.  Pass the result
/// directly to ``CertificateListBuilder.add_extension``:
///
/// ```python,ignore
/// import synta.ext as ext
///
/// der = ext.crl_number(42)
/// # → b'\x02\x01\x2a'
///
/// # Zero is encoded as a single content byte of 0x00:
/// der = ext.crl_number(0)
/// # → b'\x02\x01\x00'
/// ```
///
/// ``n`` must be a non-negative integer that fits in a ``u64``.  Raises
/// :exc:`ValueError` if ``n`` is negative or too large.
#[pyfunction]
fn crl_number<'py>(py: Python<'py>, n: u64) -> PyResult<Bound<'py, PyBytes>> {
    // Build the big-endian two's-complement encoding for a non-negative u64.
    // Strip leading zero bytes, but keep at least one byte.
    // Prepend a 0x00 padding byte if the high bit of the first content byte
    // would be set (which would make the value appear negative in two's complement).
    let be_bytes = n.to_be_bytes(); // 8 bytes, big-endian
    let first_nonzero = be_bytes.iter().position(|&b| b != 0).unwrap_or(7);
    let content = &be_bytes[first_nonzero..];
    // content is now the minimal non-zero prefix; for n=0 this is &[0x00] because
    // first_nonzero is 7, so content = &be_bytes[7..] = &[0x00].
    let needs_pad = content[0] & 0x80 != 0;
    let content_len = content.len() + usize::from(needs_pad);

    // Encode the length — for u64 the maximum content is 9 bytes (pad + 8), which
    // fits in a single-byte DER length field (max 127 for short form).
    let mut der = Vec::with_capacity(2 + content_len);
    der.push(0x02u8); // INTEGER tag
    der.push(content_len as u8); // length (always fits in one byte for u64)
    if needs_pad {
        der.push(0x00u8);
    }
    der.extend_from_slice(content);
    Ok(PyBytes::new(py, &der))
}

/// Encode a ``KeyUsage`` extension value (OID 2.5.29.15).
///
/// ``bits`` is an integer bitmask formed by OR-ing the ``KU_*`` constants
/// exported from this module.  Returns the DER BIT STRING value.
///
/// ```python,ignore
/// import synta.ext as ext
///
/// # digitalSignature only → 03 02 07 80
/// ku = ext.key_usage(ext.KU_DIGITAL_SIGNATURE)
///
/// # keyCertSign | cRLSign → 03 02 01 06
/// ku = ext.key_usage(ext.KU_KEY_CERT_SIGN | ext.KU_CRL_SIGN)
///
/// # Typical CA key usage
/// ku = ext.key_usage(
///     ext.KU_KEY_CERT_SIGN | ext.KU_CRL_SIGN | ext.KU_DIGITAL_SIGNATURE
/// )
/// ```
#[pyfunction]
fn key_usage<'py>(py: Python<'py>, bits: u16) -> PyResult<Bound<'py, PyBytes>> {
    let der = encode_key_usage(bits)
        .ok_or_else(|| PyValueError::new_err("KeyUsage DER encoding failed"))?;
    Ok(PyBytes::new(py, &der))
}

/// Encode a ``SubjectKeyIdentifier`` extension value (OID 2.5.29.14).
///
/// Decodes ``spki_der`` as a DER ``SubjectPublicKeyInfo`` and computes the
/// key identifier according to ``method`` (one of the ``KEYID_*`` constants
/// from this module).
///
/// Methods other than ``KEYID_RFC7093M4`` hash the BIT STRING value of
/// ``subjectPublicKey`` (the key bytes, without the unused-bits octet).
/// ``KEYID_RFC7093M4`` hashes the full ``SubjectPublicKeyInfo`` DER encoding.
///
/// Returns the DER OCTET STRING value, or raises :exc:`ValueError` if
/// ``spki_der`` cannot be decoded or if hashing fails.
///
/// ```python,ignore
/// import synta.ext as ext
///
/// # RFC 5280 default (SHA-1 of subjectPublicKey BIT STRING value)
/// ski_der = ext.subject_key_identifier(cert.subject_public_key_info_der)
///
/// # RFC 7093 method 1 (SHA-256 of BIT STRING value, truncated to 160 bits)
/// ski_der = ext.subject_key_identifier(
///     cert.subject_public_key_info_der,
///     method=ext.KEYID_RFC7093M1,
/// )
/// ```
#[pyfunction]
#[pyo3(signature = (spki_der, method = KEYID_RFC5280))]
fn subject_key_identifier<'py>(
    py: Python<'py>,
    spki_der: &[u8],
    method: u8,
) -> PyResult<Bound<'py, PyBytes>> {
    let m = method_from_int(method)?;
    encode_subject_key_identifier(spki_der, m, &default_key_id_hasher())
        .map(|v| PyBytes::new(py, &v))
        .ok_or_else(|| {
            PyValueError::new_err(
                "failed to encode SubjectKeyIdentifier: \
                 invalid SubjectPublicKeyInfo DER or hash error",
            )
        })
}

/// Encode an ``AuthorityKeyIdentifier`` extension value (OID 2.5.29.35).
///
/// Computes the key identifier from the issuer's ``SubjectPublicKeyInfo``
/// using the same input selection and hash rules as
/// :func:`subject_key_identifier`.  Sets only the ``keyIdentifier [0]``
/// field; ``authorityCertIssuer`` and ``authorityCertSerialNumber`` are not
/// included.
///
/// Returns the DER bytes of the ``AuthorityKeyIdentifier`` SEQUENCE, or
/// raises :exc:`ValueError` on error.
///
/// ```python,ignore
/// import synta.ext as ext
///
/// # RFC 5280 default (SHA-1 of issuer subjectPublicKey BIT STRING value)
/// aki_der = ext.authority_key_identifier(ca_cert.subject_public_key_info_der)
///
/// # RFC 7093 method 1 (SHA-256 of BIT STRING value, truncated to 160 bits)
/// aki_der = ext.authority_key_identifier(
///     ca_cert.subject_public_key_info_der,
///     method=ext.KEYID_RFC7093M1,
/// )
/// ```
#[pyfunction]
#[pyo3(signature = (issuer_spki_der, method = KEYID_RFC5280))]
fn authority_key_identifier<'py>(
    py: Python<'py>,
    issuer_spki_der: &[u8],
    method: u8,
) -> PyResult<Bound<'py, PyBytes>> {
    let m = method_from_int(method)?;
    encode_authority_key_identifier(issuer_spki_der, m, &default_key_id_hasher())
        .map(|v| PyBytes::new(py, &v))
        .ok_or_else(|| {
            PyValueError::new_err(
                "failed to encode AuthorityKeyIdentifier: \
                 invalid SubjectPublicKeyInfo DER or hash error",
            )
        })
}

// ── SubjectAlternativeNameBuilder ─────────────────────────────────────────────

/// Fluent builder for a ``SubjectAltName`` extension value (OID 2.5.29.17).
///
/// Accumulate :class:`GeneralName` entries with the fluent methods, then call
/// :meth:`build` to obtain the DER bytes of the ``GeneralNames`` SEQUENCE —
/// the content that goes inside the OCTET STRING wrapper in the ``Extension``
/// SEQUENCE.
///
/// The class is also available as the short alias ``synta.ext.SAN``.
///
/// ```python,ignore
/// import synta.ext as ext
///
/// san = ext.SAN() \
///     .dns_name("www.example.com") \
///     .dns_name("example.com") \
///     .rfc822_name("admin@example.com") \
///     .ip_address(b"\xc0\xa8\x01\x01") \
///     .build()
/// ```
#[pyclass(name = "SubjectAlternativeNameBuilder")]
pub struct PySubjectAlternativeNameBuilder {
    inner: SubjectAlternativeNameBuilder,
    built: bool,
}

#[pymethods]
impl PySubjectAlternativeNameBuilder {
    #[new]
    fn new() -> Self {
        Self {
            inner: SubjectAlternativeNameBuilder::new(),
            built: false,
        }
    }

    /// Add a ``dNSName [2]`` GeneralName.
    fn dns_name<'py>(slf: Bound<'py, Self>, name: &str) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, SubjectAlternativeNameBuilder::new());
            guard.inner = old.dns_name(name);
        }
        slf
    }

    /// Add an ``rfc822Name [1]`` GeneralName (email address).
    fn rfc822_name<'py>(slf: Bound<'py, Self>, email: &str) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, SubjectAlternativeNameBuilder::new());
            guard.inner = old.rfc822_name(email);
        }
        slf
    }

    /// Add a ``uniformResourceIdentifier [6]`` GeneralName (URI).
    fn uri<'py>(slf: Bound<'py, Self>, uri: &str) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, SubjectAlternativeNameBuilder::new());
            guard.inner = old.uri(uri);
        }
        slf
    }

    /// Add an ``iPAddress [7]`` GeneralName.
    ///
    /// Pass 4 bytes for IPv4 or 16 bytes for IPv6.
    fn ip_address<'py>(slf: Bound<'py, Self>, addr: &[u8]) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, SubjectAlternativeNameBuilder::new());
            guard.inner = old.ip_address(addr);
        }
        slf
    }

    /// Add a ``directoryName [4]`` GeneralName (EXPLICIT wrapper).
    ///
    /// ``name_der`` is the complete DER TLV bytes of the ``Name`` SEQUENCE
    /// (e.g. from :meth:`synta.NameBuilder.build`).  Silently ignored if
    /// ``name_der`` cannot be decoded.
    fn directory_name<'py>(slf: Bound<'py, Self>, name_der: &[u8]) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, SubjectAlternativeNameBuilder::new());
            guard.inner = old.directory_name(name_der);
        }
        slf
    }

    /// Add a ``registeredID [8]`` GeneralName.
    ///
    /// ``oid_comps`` is the list of arc components of the OID (e.g.
    /// ``[1, 3, 6, 1, 5, 5, 7, 3, 1]`` for id-kp-serverAuth).
    fn registered_id<'py>(
        slf: Bound<'py, Self>,
        oid_comps: Vec<u32>,
    ) -> PyResult<Bound<'py, Self>> {
        let oid = synta::ObjectIdentifier::new(&oid_comps)
            .map_err(|e| PyValueError::new_err(format!("invalid OID: {e}")))?;
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, SubjectAlternativeNameBuilder::new());
            guard.inner = old.registered_id(oid);
        }
        Ok(slf)
    }

    /// Add an ``otherName [0]`` GeneralName.
    ///
    /// ``other_name_der`` is the complete DER TLV bytes of the ``OtherName``
    /// SEQUENCE: ``SEQUENCE { type-id OBJECT IDENTIFIER, value [0] EXPLICIT ANY }``.
    ///
    /// Raises :exc:`ValueError` if ``other_name_der`` cannot be decoded as a
    /// valid ``OtherName`` structure.
    fn other_name<'py>(slf: Bound<'py, Self>, other_name_der: &[u8]) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, SubjectAlternativeNameBuilder::new());
            guard.inner = old.other_name(other_name_der);
        }
        slf
    }

    /// Build the DER-encoded ``GeneralNames`` SEQUENCE.
    ///
    /// Returns ``bytes``.  Returns ``b'\\x30\\x00'`` (empty SEQUENCE) if no
    /// entries have been added.  Raises :exc:`ValueError` if any entry failed
    /// DER encoding or if ``build()`` is called more than once on the same
    /// builder instance.
    fn build<'py>(&mut self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        if self.built {
            return Err(PyValueError::new_err(
                "SubjectAlternativeNameBuilder.build() has already been called; \
                 create a new builder instance",
            ));
        }
        self.built = true;
        let builder = std::mem::replace(&mut self.inner, SubjectAlternativeNameBuilder::new());
        let der = builder.build().map_err(PyValueError::new_err)?;
        Ok(PyBytes::new(py, &der))
    }
}

// ── AuthorityInformationAccessBuilder ─────────────────────────────────────────

/// Fluent builder for an ``AuthorityInfoAccessSyntax`` extension value
/// (OID 1.3.6.1.5.5.7.1.1, Authority Information Access, RFC 5280 §4.2.2.1).
///
/// Add OCSP and/or CA Issuers URIs with the fluent methods, then call
/// :meth:`build` to obtain the DER bytes of the ``AuthorityInfoAccessSyntax``
/// SEQUENCE — the content that goes inside the OCTET STRING wrapper.
///
/// The class is also available as the short alias ``synta.ext.AIA``.
///
/// ```python,ignore
/// import synta.ext as ext
///
/// aia = ext.AIA() \
///     .ocsp("http://ocsp.example.com") \
///     .ca_issuers("http://ca.example.com/ca.crt") \
///     .build()
/// ```
#[pyclass(name = "AuthorityInformationAccessBuilder")]
pub struct PyAuthorityInformationAccessBuilder {
    inner: AuthorityInformationAccessBuilder,
    built: bool,
}

#[pymethods]
impl PyAuthorityInformationAccessBuilder {
    #[new]
    fn new() -> Self {
        Self {
            inner: AuthorityInformationAccessBuilder::new(),
            built: false,
        }
    }

    /// Add an OCSP responder URI (``id-ad-ocsp``, 1.3.6.1.5.5.7.48.1).
    fn ocsp<'py>(slf: Bound<'py, Self>, uri: &str) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, AuthorityInformationAccessBuilder::new());
            guard.inner = old.ocsp(uri);
        }
        slf
    }

    /// Add a CA Issuers URI (``id-ad-caIssuers``, 1.3.6.1.5.5.7.48.2).
    fn ca_issuers<'py>(slf: Bound<'py, Self>, uri: &str) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, AuthorityInformationAccessBuilder::new());
            guard.inner = old.ca_issuers(uri);
        }
        slf
    }

    /// Build the DER-encoded ``AuthorityInfoAccessSyntax`` SEQUENCE.
    ///
    /// Returns ``bytes``.  Returns ``b'\\x30\\x00'`` (empty SEQUENCE) if no
    /// entries have been added.  Raises :exc:`ValueError` if any entry failed
    /// DER encoding or if ``build()`` is called more than once on the same
    /// builder instance.
    fn build<'py>(&mut self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        if self.built {
            return Err(PyValueError::new_err(
                "AuthorityInformationAccessBuilder.build() has already been called; \
                 create a new builder instance",
            ));
        }
        self.built = true;
        let builder = std::mem::replace(&mut self.inner, AuthorityInformationAccessBuilder::new());
        let der = builder.build().map_err(PyValueError::new_err)?;
        Ok(PyBytes::new(py, &der))
    }
}

// ── ExtendedKeyUsageBuilder ───────────────────────────────────────────────────

/// Fluent builder for an ``ExtKeyUsageSyntax`` extension value
/// (OID 2.5.29.37, Extended Key Usage, RFC 5280 §4.2.1.12).
///
/// Add well-known key purpose OIDs with the convenience methods or custom OIDs
/// via :meth:`add_oid`, then call :meth:`build` to obtain the DER bytes of the
/// ``ExtKeyUsageSyntax`` SEQUENCE.
///
/// The class is also available as the short alias ``synta.ext.EKU``.
///
/// ```python,ignore
/// import synta.ext as ext
///
/// # Typical TLS server certificate EKU
/// eku = ext.EKU().server_auth().client_auth().build()
///
/// # Custom OID
/// eku = ext.EKU().add_oid([1, 3, 6, 1, 5, 5, 7, 3, 1]).build()
/// ```
#[pyclass(name = "ExtendedKeyUsageBuilder")]
pub struct PyExtendedKeyUsageBuilder {
    inner: ExtendedKeyUsageBuilder,
    built: bool,
}

#[pymethods]
impl PyExtendedKeyUsageBuilder {
    #[new]
    fn new() -> Self {
        Self {
            inner: ExtendedKeyUsageBuilder::new(),
            built: false,
        }
    }

    /// Add ``id-kp-serverAuth`` (1.3.6.1.5.5.7.3.1).
    fn server_auth<'py>(slf: Bound<'py, Self>) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, ExtendedKeyUsageBuilder::new());
            guard.inner = old.server_auth();
        }
        slf
    }

    /// Add ``id-kp-clientAuth`` (1.3.6.1.5.5.7.3.2).
    fn client_auth<'py>(slf: Bound<'py, Self>) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, ExtendedKeyUsageBuilder::new());
            guard.inner = old.client_auth();
        }
        slf
    }

    /// Add ``id-kp-codeSigning`` (1.3.6.1.5.5.7.3.3).
    fn code_signing<'py>(slf: Bound<'py, Self>) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, ExtendedKeyUsageBuilder::new());
            guard.inner = old.code_signing();
        }
        slf
    }

    /// Add ``id-kp-emailProtection`` (1.3.6.1.5.5.7.3.4).
    fn email_protection<'py>(slf: Bound<'py, Self>) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, ExtendedKeyUsageBuilder::new());
            guard.inner = old.email_protection();
        }
        slf
    }

    /// Add ``id-kp-timeStamping`` (1.3.6.1.5.5.7.3.8).
    fn time_stamping<'py>(slf: Bound<'py, Self>) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, ExtendedKeyUsageBuilder::new());
            guard.inner = old.time_stamping();
        }
        slf
    }

    /// Add ``id-kp-OCSPSigning`` (1.3.6.1.5.5.7.3.9).
    fn ocsp_signing<'py>(slf: Bound<'py, Self>) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, ExtendedKeyUsageBuilder::new());
            guard.inner = old.ocsp_signing();
        }
        slf
    }

    /// Add a custom key purpose OID by component list.
    ///
    /// ``comps`` is a list of integers forming the OID arc, e.g.
    /// ``[1, 3, 6, 1, 5, 5, 7, 3, 1]`` for ``id-kp-serverAuth``.
    fn add_oid<'py>(slf: Bound<'py, Self>, comps: Vec<u32>) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, ExtendedKeyUsageBuilder::new());
            guard.inner = old.add_oid(&comps);
        }
        slf
    }

    /// Build the DER-encoded ``ExtKeyUsageSyntax`` SEQUENCE.
    ///
    /// Returns ``bytes``.  Returns ``b'\\x30\\x00'`` (empty SEQUENCE) if no
    /// OIDs have been added.  Raises :exc:`ValueError` if any OID was invalid
    /// or if ``build()`` is called more than once on the same builder instance.
    fn build<'py>(&mut self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        if self.built {
            return Err(PyValueError::new_err(
                "ExtendedKeyUsageBuilder.build() has already been called; \
                 create a new builder instance",
            ));
        }
        self.built = true;
        let builder = std::mem::replace(&mut self.inner, ExtendedKeyUsageBuilder::new());
        let der = builder.build().map_err(PyValueError::new_err)?;
        Ok(PyBytes::new(py, &der))
    }
}

// ── NameConstraintsBuilder ────────────────────────────────────────────────────

/// Fluent builder for a ``NameConstraints`` extension value (OID 2.5.29.30,
/// RFC 5280 §4.2.1.10).
///
/// The ``NameConstraints`` extension restricts the namespace within which all
/// subject names in certificates issued by a CA must fall.  Names in
/// ``permittedSubtrees`` are allowed; names in ``excludedSubtrees`` are
/// forbidden.  When present in a CA certificate this extension MUST be marked
/// critical.
///
/// Add permitted and excluded subtrees using the typed methods, then call
/// :meth:`build` to obtain the DER bytes of the ``NameConstraints`` SEQUENCE —
/// the content that goes inside the OCTET STRING wrapper in the ``Extension``
/// SEQUENCE.
///
/// The class is also available as the short alias ``synta.ext.NC``.
///
/// **DNS name conventions:** prefix the domain with a leading dot (e.g.
/// ``".example.com"``) to constrain the entire subtree rooted at
/// ``example.com``; omit the dot to constrain only that exact host.
///
/// **IP address constraints:** pass address bytes concatenated with mask bytes
/// — 8 bytes for IPv4 (e.g. ``b"\\xc0\\xa8\\x00\\x00\\xff\\xff\\x00\\x00"``
/// for ``192.168.0.0/16``) or 32 bytes for IPv6.
///
/// ```python,ignore
/// import synta.ext as ext
///
/// # Permit example.com DNS subtree and a private IP range;
/// # exclude a known-bad subdomain.
/// nc = ext.NC() \
///     .permit_dns(".example.com") \
///     .permit_rfc822(".example.com") \
///     .permit_ip(b"\x0a\x00\x00\x00\xff\x00\x00\x00") \
///     .exclude_dns(".evil.com") \
///     .build()
/// ```
#[pyclass(name = "NameConstraintsBuilder")]
pub struct PyNameConstraintsBuilder {
    inner: NameConstraintsBuilder,
    built: bool,
}

#[pymethods]
impl PyNameConstraintsBuilder {
    #[new]
    fn new() -> Self {
        Self {
            inner: NameConstraintsBuilder::new(),
            built: false,
        }
    }

    /// Add a DNS name constraint to the permitted subtrees.
    ///
    /// Use a leading dot (e.g. ``".example.com"``) to constrain an entire
    /// domain subtree; omit the dot (e.g. ``"host.example.com"``) to
    /// constrain only that exact host name.
    fn permit_dns<'py>(slf: Bound<'py, Self>, dns: &str) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, NameConstraintsBuilder::new());
            guard.inner = old.permit_dns(dns);
        }
        slf
    }

    /// Add an RFC 822 (email) domain constraint to the permitted subtrees.
    ///
    /// Pass a bare domain (e.g. ``"example.com"``) to permit all addresses
    /// in that domain, or a full address (e.g. ``"user@example.com"``) to
    /// permit only that specific mailbox.
    fn permit_rfc822<'py>(slf: Bound<'py, Self>, email: &str) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, NameConstraintsBuilder::new());
            guard.inner = old.permit_rfc822(email);
        }
        slf
    }

    /// Add a URI scheme constraint to the permitted subtrees.
    ///
    /// Per RFC 5280 §4.2.1.10, the constraint value is a host name or
    /// dot-prefixed domain (e.g. ``".example.com"``), not a full URI.
    fn permit_uri<'py>(slf: Bound<'py, Self>, uri: &str) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, NameConstraintsBuilder::new());
            guard.inner = old.permit_uri(uri);
        }
        slf
    }

    /// Add an IP prefix to the permitted subtrees.
    ///
    /// Pass 8 bytes for IPv4 (4-byte address + 4-byte mask) or 32 bytes for
    /// IPv6 (16-byte address + 16-byte mask), as required by RFC 5280 §4.2.1.10.
    fn permit_ip<'py>(slf: Bound<'py, Self>, addr_and_mask: &[u8]) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, NameConstraintsBuilder::new());
            guard.inner = old.permit_ip(addr_and_mask);
        }
        slf
    }

    /// Add a directory name constraint to the permitted subtrees.
    ///
    /// ``name_der`` is the complete DER TLV bytes of an X.509 ``Name``
    /// SEQUENCE (e.g. from :meth:`synta.NameBuilder.build`).  The constraint
    /// is encoded as a ``directoryName [4]`` ``GeneralName`` inside a
    /// ``GeneralSubtree``.
    fn permit_directory_name<'py>(slf: Bound<'py, Self>, name_der: &[u8]) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, NameConstraintsBuilder::new());
            guard.inner = old.permit_directory_name(name_der);
        }
        slf
    }

    /// Add a DNS name constraint to the excluded subtrees.
    ///
    /// Use a leading dot (e.g. ``".evil.com"``) to exclude the entire
    /// subtree rooted at ``evil.com``; omit the dot to exclude only that
    /// exact host name.
    fn exclude_dns<'py>(slf: Bound<'py, Self>, dns: &str) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, NameConstraintsBuilder::new());
            guard.inner = old.exclude_dns(dns);
        }
        slf
    }

    /// Add an RFC 822 (email) domain constraint to the excluded subtrees.
    ///
    /// Pass a bare domain (e.g. ``"evil.com"``) to exclude all addresses in
    /// that domain, or a full address (e.g. ``"user@evil.com"``) to exclude
    /// only that specific mailbox.
    fn exclude_rfc822<'py>(slf: Bound<'py, Self>, email: &str) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, NameConstraintsBuilder::new());
            guard.inner = old.exclude_rfc822(email);
        }
        slf
    }

    /// Add a URI scheme constraint to the excluded subtrees.
    ///
    /// Per RFC 5280 §4.2.1.10, the constraint value is a host name or
    /// dot-prefixed domain, not a full URI.
    fn exclude_uri<'py>(slf: Bound<'py, Self>, uri: &str) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, NameConstraintsBuilder::new());
            guard.inner = old.exclude_uri(uri);
        }
        slf
    }

    /// Add an IP prefix to the excluded subtrees.
    ///
    /// Pass 8 bytes for IPv4 (4-byte address + 4-byte mask) or 32 bytes for
    /// IPv6 (16-byte address + 16-byte mask), as required by RFC 5280 §4.2.1.10.
    fn exclude_ip<'py>(slf: Bound<'py, Self>, addr_and_mask: &[u8]) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, NameConstraintsBuilder::new());
            guard.inner = old.exclude_ip(addr_and_mask);
        }
        slf
    }

    /// Add a directory name constraint to the excluded subtrees.
    ///
    /// ``name_der`` is the complete DER TLV bytes of an X.509 ``Name``
    /// SEQUENCE (e.g. from :meth:`synta.NameBuilder.build`).  The constraint
    /// is encoded as a ``directoryName [4]`` ``GeneralName`` inside a
    /// ``GeneralSubtree``.
    fn exclude_directory_name<'py>(slf: Bound<'py, Self>, name_der: &[u8]) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, NameConstraintsBuilder::new());
            guard.inner = old.exclude_directory_name(name_der);
        }
        slf
    }

    /// Build the DER-encoded ``NameConstraints`` SEQUENCE.
    ///
    /// Returns the DER bytes of the outer ``NameConstraints`` SEQUENCE (tag
    /// ``30``), ready to be placed inside the ``extnValue`` OCTET STRING of
    /// an ``Extension``.  If neither permitted nor excluded subtrees have been
    /// added, the result is an empty SEQUENCE (``b'\\x30\\x00'``).
    ///
    /// Permitted subtrees appear as ``[0] IMPLICIT`` (tag ``A0``); excluded
    /// subtrees as ``[1] IMPLICIT`` (tag ``A1``), as required by
    /// RFC 5280 §4.2.1.10.
    ///
    /// Raises :exc:`ValueError` if any entry failed DER encoding or if
    /// ``build()`` is called more than once on the same builder instance.
    fn build<'py>(&mut self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        if self.built {
            return Err(PyValueError::new_err(
                "NameConstraintsBuilder.build() has already been called; \
                 create a new builder instance",
            ));
        }
        self.built = true;
        let builder = std::mem::replace(&mut self.inner, NameConstraintsBuilder::new());
        let der = builder.build().map_err(PyValueError::new_err)?;
        Ok(PyBytes::new(py, &der))
    }
}

// ── CRLDistributionPointsBuilder ─────────────────────────────────────────────

/// Fluent builder for a ``CRLDistributionPoints`` extension value (OID 2.5.29.31).
///
/// Add distribution point entries with the fluent methods, then call
/// :meth:`build` to obtain the DER bytes of the ``CRLDistributionPoints``
/// SEQUENCE OF — the content that goes inside the OCTET STRING wrapper in the
/// ``Extension`` SEQUENCE.
///
/// The class is also available as the short alias ``synta.ext.CDP``.
///
/// ```python,ignore
/// import synta.ext as ext
///
/// cdp = ext.CDP() \
///     .full_name_uri("http://crl.example.com/ca.crl") \
///     .build()
/// ```
#[pyclass(name = "CRLDistributionPointsBuilder")]
pub struct PyCRLDistributionPointsBuilder {
    inner: CRLDistributionPointsBuilder,
    built: bool,
}

#[pymethods]
impl PyCRLDistributionPointsBuilder {
    #[new]
    fn new() -> Self {
        Self {
            inner: CRLDistributionPointsBuilder::new(),
            built: false,
        }
    }

    /// Add a distribution point with a URI as the full name.
    ///
    /// ``uri`` is an ASCII URI string (e.g. ``"http://crl.example.com/ca.crl"``).
    fn full_name_uri<'py>(slf: Bound<'py, Self>, uri: &str) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, CRLDistributionPointsBuilder::new());
            guard.inner = old.full_name_uri(uri);
        }
        slf
    }

    /// Add a distribution point with a DNS name as the full name.
    fn full_name_dns<'py>(slf: Bound<'py, Self>, dns: &str) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, CRLDistributionPointsBuilder::new());
            guard.inner = old.full_name_dns(dns);
        }
        slf
    }

    /// Add a distribution point with a directory name as the full name.
    ///
    /// ``name_der`` is the complete DER TLV bytes of an X.509 ``Name`` SEQUENCE
    /// (e.g. from :meth:`synta.NameBuilder.build`).
    fn full_name_directory<'py>(slf: Bound<'py, Self>, name_der: &[u8]) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, CRLDistributionPointsBuilder::new());
            guard.inner = old.full_name_directory(name_der);
        }
        slf
    }

    /// Build the DER-encoded ``CRLDistributionPoints`` SEQUENCE OF.
    ///
    /// Returns ``bytes``.  Returns ``b'\\x30\\x00'`` (empty SEQUENCE) if no
    /// entries have been added.  Raises :exc:`ValueError` if any entry failed
    /// DER encoding or if ``build()`` is called more than once on the same
    /// builder instance.
    fn build<'py>(&mut self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        if self.built {
            return Err(PyValueError::new_err(
                "CRLDistributionPointsBuilder.build() has already been called; \
                 create a new builder instance",
            ));
        }
        self.built = true;
        let builder = std::mem::replace(&mut self.inner, CRLDistributionPointsBuilder::new());
        let der = builder.build().map_err(PyValueError::new_err)?;
        Ok(PyBytes::new(py, &der))
    }
}

// ── IssuerAlternativeNameBuilder ──────────────────────────────────────────────

/// Fluent builder for an ``IssuerAltName`` extension value (OID 2.5.29.18).
///
/// Accumulate :class:`GeneralName` entries with the fluent methods, then call
/// :meth:`build` to obtain the DER bytes of the ``GeneralNames`` SEQUENCE —
/// the content that goes inside the OCTET STRING wrapper in the ``Extension``
/// SEQUENCE.
///
/// The encoding is identical to :class:`SubjectAlternativeNameBuilder` (OID
/// 2.5.29.17) but uses the Issuer Alternative Name OID (2.5.29.18) instead.
/// Note: ``otherName`` is not supported by this builder.
///
/// The class is also available as the short alias ``synta.ext.IAN``.
///
/// ```python,ignore
/// import synta.ext as ext
///
/// ian = ext.IAN() \
///     .rfc822_name("ca@example.com") \
///     .uri("http://www.example.com") \
///     .build()
/// ```
#[pyclass(name = "IssuerAlternativeNameBuilder")]
pub struct PyIssuerAlternativeNameBuilder {
    inner: IssuerAlternativeNameBuilder,
    built: bool,
}

#[pymethods]
impl PyIssuerAlternativeNameBuilder {
    #[new]
    fn new() -> Self {
        Self {
            inner: IssuerAlternativeNameBuilder::new(),
            built: false,
        }
    }

    /// Add a ``dNSName [2]`` GeneralName.
    fn dns_name<'py>(slf: Bound<'py, Self>, name: &str) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, IssuerAlternativeNameBuilder::new());
            guard.inner = old.dns_name(name);
        }
        slf
    }

    /// Add an ``rfc822Name [1]`` GeneralName (email address).
    fn rfc822_name<'py>(slf: Bound<'py, Self>, email: &str) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, IssuerAlternativeNameBuilder::new());
            guard.inner = old.rfc822_name(email);
        }
        slf
    }

    /// Add a ``uniformResourceIdentifier [6]`` GeneralName (URI).
    fn uri<'py>(slf: Bound<'py, Self>, uri: &str) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, IssuerAlternativeNameBuilder::new());
            guard.inner = old.uri(uri);
        }
        slf
    }

    /// Add an ``iPAddress [7]`` GeneralName.
    ///
    /// Pass 4 bytes for IPv4 or 16 bytes for IPv6.
    fn ip_address<'py>(slf: Bound<'py, Self>, addr: &[u8]) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, IssuerAlternativeNameBuilder::new());
            guard.inner = old.ip_address(addr);
        }
        slf
    }

    /// Add a ``directoryName [4]`` GeneralName (EXPLICIT wrapper).
    ///
    /// ``name_der`` is the complete DER TLV bytes of the ``Name`` SEQUENCE
    /// (e.g. from :meth:`synta.NameBuilder.build`).  Silently ignored if
    /// ``name_der`` cannot be decoded.
    fn directory_name<'py>(slf: Bound<'py, Self>, name_der: &[u8]) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, IssuerAlternativeNameBuilder::new());
            guard.inner = old.directory_name(name_der);
        }
        slf
    }

    /// Add a ``registeredID [8]`` GeneralName.
    ///
    /// ``oid_comps`` is the list of arc components of the OID (e.g.
    /// ``[1, 3, 6, 1, 5, 5, 7, 3, 1]`` for id-kp-serverAuth).
    fn registered_id<'py>(
        slf: Bound<'py, Self>,
        oid_comps: Vec<u32>,
    ) -> PyResult<Bound<'py, Self>> {
        let oid = synta::ObjectIdentifier::new(&oid_comps)
            .map_err(|e| PyValueError::new_err(format!("invalid OID: {e}")))?;
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, IssuerAlternativeNameBuilder::new());
            guard.inner = old.registered_id(oid);
        }
        Ok(slf)
    }

    /// Build the DER-encoded ``GeneralNames`` SEQUENCE.
    ///
    /// Returns ``bytes``.  Returns ``b'\\x30\\x00'`` (empty SEQUENCE) if no
    /// entries have been added.  Raises :exc:`ValueError` if any entry failed
    /// DER encoding or if ``build()`` is called more than once on the same
    /// builder instance.
    fn build<'py>(&mut self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        if self.built {
            return Err(PyValueError::new_err(
                "IssuerAlternativeNameBuilder.build() has already been called; \
                 create a new builder instance",
            ));
        }
        self.built = true;
        let builder = std::mem::replace(&mut self.inner, IssuerAlternativeNameBuilder::new());
        let der = builder.build().map_err(PyValueError::new_err)?;
        Ok(PyBytes::new(py, &der))
    }
}

// ── IssuingDistributionPointBuilder ───────────────────────────────────────────

/// Fluent builder for an ``IssuingDistributionPoint`` extension value
/// (OID 2.5.29.28, RFC 5280 §5.2.5).
///
/// The ``IssuingDistributionPoint`` extension identifies the CRL distribution
/// point and scope for a particular CRL.  Configure the distribution point and
/// the boolean flags with the fluent methods, then call :meth:`build` to obtain
/// the DER bytes — the content that goes inside the OCTET STRING wrapper in the
/// ``Extension`` SEQUENCE.
///
/// The class is also available as the short alias ``synta.ext.IDP``.
///
/// ```python,ignore
/// import synta.ext as ext
///
/// idp = ext.IDP() \
///     .full_name_uri("http://crl.example.com/ca.crl") \
///     .only_contains_user_certs(True) \
///     .build()
/// ```
#[pyclass(name = "IssuingDistributionPointBuilder")]
pub struct PyIssuingDistributionPointBuilder {
    inner: IssuingDistributionPointBuilder,
    built: bool,
}

#[pymethods]
impl PyIssuingDistributionPointBuilder {
    #[new]
    fn new() -> Self {
        Self {
            inner: IssuingDistributionPointBuilder::new(),
            built: false,
        }
    }

    /// Set the distribution point to a URI full name.
    ///
    /// ``uri`` is an ASCII URI string (e.g. ``"http://crl.example.com/ca.crl"``).
    fn full_name_uri<'py>(slf: Bound<'py, Self>, uri: &str) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, IssuingDistributionPointBuilder::new());
            guard.inner = old.full_name_uri(uri);
        }
        slf
    }

    /// Set the distribution point to a DNS name full name.
    fn full_name_dns<'py>(slf: Bound<'py, Self>, dns: &str) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, IssuingDistributionPointBuilder::new());
            guard.inner = old.full_name_dns(dns);
        }
        slf
    }

    /// Set the ``onlyContainsUserCerts`` flag.
    ///
    /// When ``True``, the CRL only contains end-entity certificate revocations.
    fn only_contains_user_certs<'py>(slf: Bound<'py, Self>, val: bool) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, IssuingDistributionPointBuilder::new());
            guard.inner = old.only_contains_user_certs(val);
        }
        slf
    }

    /// Set the ``onlyContainsCACerts`` flag.
    ///
    /// When ``True``, the CRL only contains CA certificate revocations.
    fn only_contains_cacerts<'py>(slf: Bound<'py, Self>, val: bool) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, IssuingDistributionPointBuilder::new());
            guard.inner = old.only_contains_cacerts(val);
        }
        slf
    }

    /// Set the ``indirectCRL`` flag.
    ///
    /// When ``True``, the CRL may contain revocations for certificates issued
    /// by CAs other than the CRL issuer.
    fn indirect_crl<'py>(slf: Bound<'py, Self>, val: bool) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, IssuingDistributionPointBuilder::new());
            guard.inner = old.indirect_crl(val);
        }
        slf
    }

    /// Set the ``onlyContainsAttributeCerts`` flag.
    ///
    /// When ``True``, the CRL only contains attribute certificate revocations.
    fn only_contains_attribute_certs<'py>(slf: Bound<'py, Self>, val: bool) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, IssuingDistributionPointBuilder::new());
            guard.inner = old.only_contains_attribute_certs(val);
        }
        slf
    }

    /// Build the DER-encoded ``IssuingDistributionPoint`` SEQUENCE.
    ///
    /// Returns ``bytes``.  Raises :exc:`ValueError` if any entry failed DER
    /// encoding or if ``build()`` is called more than once on the same builder
    /// instance.
    fn build<'py>(&mut self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        if self.built {
            return Err(PyValueError::new_err(
                "IssuingDistributionPointBuilder.build() has already been called; \
                 create a new builder instance",
            ));
        }
        self.built = true;
        let builder = std::mem::replace(&mut self.inner, IssuingDistributionPointBuilder::new());
        let der = builder.build().map_err(PyValueError::new_err)?;
        Ok(PyBytes::new(py, &der))
    }
}

// ── CertificatePoliciesBuilder ────────────────────────────────────────────────

/// Fluent builder for a ``CertificatePolicies`` extension value (OID 2.5.29.32,
/// RFC 5280 §4.2.1.4).
///
/// Add policy entries with optional CPS URI qualifiers using the fluent methods,
/// then call :meth:`build` to obtain the DER bytes of the
/// ``CertificatePolicies`` SEQUENCE OF — the content that goes inside the OCTET
/// STRING wrapper in the ``Extension`` SEQUENCE.
///
/// The class is also available as the short alias ``synta.ext.CP``.
///
/// ```python,ignore
/// import synta.ext as ext
///
/// cp = ext.CP() \
///     .add_policy([2, 23, 140, 1, 2, 1]) \
///     .add_policy_cps([2, 23, 140, 1, 2, 2], "https://example.com/cps") \
///     .build()
/// ```
#[pyclass(name = "CertificatePoliciesBuilder")]
pub struct PyCertificatePoliciesBuilder {
    inner: CertificatePoliciesBuilder,
    built: bool,
}

#[pymethods]
impl PyCertificatePoliciesBuilder {
    #[new]
    fn new() -> Self {
        Self {
            inner: CertificatePoliciesBuilder::new(),
            built: false,
        }
    }

    /// Add a policy identified by OID arc components, with no qualifiers.
    ///
    /// ``oid_comps`` is the list of integer arc components of the policy OID
    /// (e.g. ``[2, 23, 140, 1, 2, 1]`` for
    /// ``2.23.140.1.2.1`` / ``baseline-requirements-domain-validated``).
    fn add_policy<'py>(slf: Bound<'py, Self>, oid_comps: Vec<u32>) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, CertificatePoliciesBuilder::new());
            guard.inner = old.add_policy(&oid_comps);
        }
        slf
    }

    /// Add a policy with a CPS URI qualifier (``id-qt-cps``, 1.3.6.1.5.5.7.2.1).
    ///
    /// ``oid_comps`` is the list of integer arc components of the policy OID.
    /// ``cps_uri`` must be an ASCII URI string pointing to the Certification
    /// Practice Statement for this policy.
    fn add_policy_cps<'py>(
        slf: Bound<'py, Self>,
        oid_comps: Vec<u32>,
        cps_uri: &str,
    ) -> Bound<'py, Self> {
        {
            let mut guard = slf.borrow_mut();
            let old = std::mem::replace(&mut guard.inner, CertificatePoliciesBuilder::new());
            guard.inner = old.add_policy_cps(&oid_comps, cps_uri);
        }
        slf
    }

    /// Build the DER-encoded ``CertificatePolicies`` SEQUENCE OF.
    ///
    /// Returns ``bytes``.  Returns ``b'\\x30\\x00'`` (empty SEQUENCE) if no
    /// policies have been added.  Raises :exc:`ValueError` if any policy OID
    /// was invalid, the CPS URI contained non-ASCII characters, any entry
    /// failed DER encoding, or if ``build()`` is called more than once on the
    /// same builder instance.
    fn build<'py>(&mut self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        if self.built {
            return Err(PyValueError::new_err(
                "CertificatePoliciesBuilder.build() has already been called; \
                 create a new builder instance",
            ));
        }
        self.built = true;
        let builder = std::mem::replace(&mut self.inner, CertificatePoliciesBuilder::new());
        let der = builder.build().map_err(PyValueError::new_err)?;
        Ok(PyBytes::new(py, &der))
    }
}

// ── Module registration ───────────────────────────────────────────────────────

/// Register the ``synta.ext`` submodule.
///
/// Exposes DER builders for common X.509 v3 extension values together with
/// ``KEYID_*`` key-identifier method constants (RFC 5280 / RFC 7093) and
/// ``KU_*`` key-usage bitmask constants (RFC 5280 §4.2.1.3).
pub fn register_ext_module(parent: &Bound<'_, PyModule>) -> PyResult<()> {
    let py = parent.py();
    let m = PyModule::new(py, "ext")?;

    // Key identifier method constants (RFC 5280 / RFC 7093)
    m.add("KEYID_RFC5280", KEYID_RFC5280)?;
    m.add("KEYID_RFC7093M1", KEYID_RFC7093M1)?;
    m.add("KEYID_RFC7093M2", KEYID_RFC7093M2)?;
    m.add("KEYID_RFC7093M3", KEYID_RFC7093M3)?;
    m.add("KEYID_RFC7093M4", KEYID_RFC7093M4)?;

    // Key usage bitmask constants — OR these together and pass to key_usage()
    m.add("KU_DIGITAL_SIGNATURE", KU_DIGITAL_SIGNATURE)?;
    m.add("KU_NON_REPUDIATION", KU_NON_REPUDIATION)?;
    m.add("KU_KEY_ENCIPHERMENT", KU_KEY_ENCIPHERMENT)?;
    m.add("KU_DATA_ENCIPHERMENT", KU_DATA_ENCIPHERMENT)?;
    m.add("KU_KEY_AGREEMENT", KU_KEY_AGREEMENT)?;
    m.add("KU_KEY_CERT_SIGN", KU_KEY_CERT_SIGN)?;
    m.add("KU_CRL_SIGN", KU_CRL_SIGN)?;
    m.add("KU_ENCIPHER_ONLY", KU_ENCIPHER_ONLY)?;
    m.add("KU_DECIPHER_ONLY", KU_DECIPHER_ONLY)?;

    // Extension builder functions
    m.add_function(wrap_pyfunction!(basic_constraints, &m)?)?;
    m.add_function(wrap_pyfunction!(crl_number, &m)?)?;
    m.add_function(wrap_pyfunction!(key_usage, &m)?)?;
    m.add_function(wrap_pyfunction!(subject_key_identifier, &m)?)?;
    m.add_function(wrap_pyfunction!(authority_key_identifier, &m)?)?;

    // Fluent builder classes
    m.add_class::<PySubjectAlternativeNameBuilder>()?;
    m.add_class::<PyAuthorityInformationAccessBuilder>()?;
    m.add_class::<PyExtendedKeyUsageBuilder>()?;
    m.add_class::<PyNameConstraintsBuilder>()?;
    m.add_class::<PyCRLDistributionPointsBuilder>()?;
    m.add_class::<PyIssuerAlternativeNameBuilder>()?;
    m.add_class::<PyIssuingDistributionPointBuilder>()?;
    m.add_class::<PyCertificatePoliciesBuilder>()?;

    // Short aliases for the builder classes
    m.add("SAN", m.getattr("SubjectAlternativeNameBuilder")?)?;
    m.add("AIA", m.getattr("AuthorityInformationAccessBuilder")?)?;
    m.add("EKU", m.getattr("ExtendedKeyUsageBuilder")?)?;
    m.add("NC", m.getattr("NameConstraintsBuilder")?)?;
    m.add("CDP", m.getattr("CRLDistributionPointsBuilder")?)?;
    m.add("IAN", m.getattr("IssuerAlternativeNameBuilder")?)?;
    m.add("IDP", m.getattr("IssuingDistributionPointBuilder")?)?;
    m.add("CP", m.getattr("CertificatePoliciesBuilder")?)?;

    crate::install_submodule(
        parent,
        &m,
        "synta.ext",
        Some(
            "X.509 v3 extension value DER builders: basic_constraints, crl_number, key_usage, \
             subject_key_identifier, authority_key_identifier; \
             SubjectAlternativeNameBuilder (alias: SAN), \
             AuthorityInformationAccessBuilder (alias: AIA), \
             ExtendedKeyUsageBuilder (alias: EKU), \
             NameConstraintsBuilder (alias: NC), \
             CRLDistributionPointsBuilder (alias: CDP), \
             IssuerAlternativeNameBuilder (alias: IAN), \
             IssuingDistributionPointBuilder (alias: IDP), \
             CertificatePoliciesBuilder (alias: CP); \
             KEYID_* method constants (RFC 5280 §4.2.1.2 / RFC 7093); \
             KU_* key-usage bitmask constants (RFC 5280 §4.2.1.3).",
        ),
    )
}