synta-certificate 0.2.2

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

use synta::tag::TAG_SEQUENCE;
use synta::traits::Decode;
use synta::{Encoder, Encoding, Tag, ToDer};

use crate::crypto::{KeyIdHasher, KeyIdMethod};
use crate::{
    AccessDescription, AuthorityKeyIdentifier, BasicConstraints, DistributionPoint,
    DistributionPointName, GeneralNameSpec, GeneralSubtree, IssuingDistributionPoint,
    PolicyInformation, PolicyQualifierInfo, SubjectPublicKeyInfo, KEY_USAGE_DECIPHER_ONLY,
};

/// Encode a `BasicConstraints` extension value (OID 2.5.29.19).
///
/// Returns the DER bytes of the `BasicConstraints` SEQUENCE:
///
/// ```text
/// BasicConstraints ::= SEQUENCE {
///     cA                  BOOLEAN DEFAULT FALSE,
///     pathLenConstraint   INTEGER (0..MAX) OPTIONAL }
/// ```
///
/// Uses the generated [`BasicConstraints`] type's `Encode` implementation.
/// When `ca` is `false` the `cA` field is omitted (DER DEFAULT-FALSE rule).
///
/// Returns `None` on DER encoding error (which cannot happen for well-formed
/// inputs in practice), or `Some(der)` with the encoded SEQUENCE.
///
/// # Example
///
/// ```
/// use synta_certificate::encode_basic_constraints;
///
/// // End-entity certificate: empty SEQUENCE (30 00)
/// let ee = encode_basic_constraints(false, None).unwrap();
/// assert_eq!(ee, &[0x30, 0x00]);
///
/// // CA with no path-length constraint: cA = TRUE (30 03 01 01 ff)
/// let ca = encode_basic_constraints(true, None).unwrap();
/// assert_eq!(ca, &[0x30, 0x03, 0x01, 0x01, 0xff]);
///
/// // CA with pathLen = 0
/// let ca_pl0 = encode_basic_constraints(true, Some(0)).unwrap();
/// assert_eq!(ca_pl0, &[0x30, 0x06, 0x01, 0x01, 0xff, 0x02, 0x01, 0x00]);
/// ```
pub fn encode_basic_constraints(ca: bool, path_length: Option<u64>) -> Option<Vec<u8>> {
    use synta::{Boolean, Integer};

    let bc = BasicConstraints {
        // DEFAULT FALSE: omit cA field in DER when false
        c_a: if ca { Some(Boolean(true)) } else { None },
        path_len_constraint: path_length.map(|n| Integer::from(n as i64)),
    };
    bc.to_der().ok()
}

/// Encode a `KeyUsage` extension value (OID 2.5.29.15).
///
/// `bits` is a bitmask where bit `n` corresponds to the `KEY_USAGE_*`
/// constants exported from this crate:
///
/// | Bit | Constant | Named bit |
/// |-----|----------|-----------|
/// | 0 | `KEY_USAGE_DIGITAL_SIGNATURE` | `digitalSignature` |
/// | 1 | `KEY_USAGE_NON_REPUDIATION` | `contentCommitment` |
/// | 2 | `KEY_USAGE_KEY_ENCIPHERMENT` | `keyEncipherment` |
/// | 3 | `KEY_USAGE_DATA_ENCIPHERMENT` | `dataEncipherment` |
/// | 4 | `KEY_USAGE_KEY_AGREEMENT` | `keyAgreement` |
/// | 5 | `KEY_USAGE_KEY_CERT_SIGN` | `keyCertSign` |
/// | 6 | `KEY_USAGE_C_RLSIGN` | `cRLSign` |
/// | 7 | `KEY_USAGE_ENCIPHER_ONLY` | `encipherOnly` |
/// | 8 | `KEY_USAGE_DECIPHER_ONLY` | `decipherOnly` |
///
/// The BIT STRING is encoded in minimal DER form: trailing zero-bits are
/// trimmed by adjusting `unused_bits` accordingly.
///
/// Uses [`synta::BitString`] (the same underlying type as the generated
/// `KeyUsage` alias) for encoding.
///
/// Returns `None` on encoding error (which cannot happen for valid bit values
/// in practice), or `Some(der)` containing the encoded BIT STRING.
///
/// # Example
///
/// ```
/// use synta_certificate::{
///     encode_key_usage,
///     KEY_USAGE_DIGITAL_SIGNATURE, KEY_USAGE_KEY_CERT_SIGN, KEY_USAGE_C_RLSIGN,
/// };
///
/// // digitalSignature only โ†’ 03 02 07 80
/// let ku = encode_key_usage(1 << KEY_USAGE_DIGITAL_SIGNATURE).unwrap();
/// assert_eq!(ku, &[0x03, 0x02, 0x07, 0x80]);
///
/// // keyCertSign | cRLSign โ†’ 03 02 01 06
/// let ku = encode_key_usage(
///     (1 << KEY_USAGE_KEY_CERT_SIGN) | (1 << KEY_USAGE_C_RLSIGN)
/// ).unwrap();
/// assert_eq!(ku, &[0x03, 0x02, 0x01, 0x06]);
/// ```
pub fn encode_key_usage(bits: u16) -> Option<Vec<u8>> {
    // Map named-bit positions 0โ€“7 to the DER byte representation.
    // Named-bit n occupies bit-position 7-(n%8) within byte n/8 (MSB-first).
    // For the 8 bits that all fall in byte 0: reverse_bits() of the lower
    // byte achieves the correct layout in one operation.
    let b0 = (bits as u8).reverse_bits();

    // Bit 8 (decipherOnly) falls in the MSB of a second byte.
    let has_decipher_only = (bits >> KEY_USAGE_DECIPHER_ONLY) & 1 != 0;

    let (bytes, unused_bits) = if has_decipher_only {
        // Two bytes: b0 holds bits 0โ€“7; 0x80 places bit 8 at byte-1 MSB.
        (vec![b0, 0x80u8], 7u8)
    } else if b0 == 0 {
        // No bits set โ€” encode as empty BIT STRING (03 01 00 in DER).
        (vec![], 0u8)
    } else {
        // DER requires unused_bits == number of trailing zero bits.
        let trailing = b0.trailing_zeros() as u8;
        (vec![b0], trailing)
    };

    let bs = synta::BitString::new(bytes, unused_bits).ok()?;
    bs.to_der().ok()
}

/// 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`:
///
/// - All methods except [`Rfc7093Method4`][KeyIdMethod::Rfc7093Method4] hash
///   the raw BIT STRING value of `subjectPublicKey` (i.e. the key bytes
///   without the unused-bits octet).
/// - [`Rfc7093Method4`][KeyIdMethod::Rfc7093Method4] hashes the full
///   `SubjectPublicKeyInfo` DER encoding.
///
/// Returns a DER `OCTET STRING` value containing the computed identifier,
/// or `None` if `spki_der` cannot be decoded or if the hasher fails.
///
/// # Example (RFC 5280 default)
///
/// ```rust,ignore
/// use synta_certificate::{encode_subject_key_identifier, KeyIdMethod, OpensslKeyIdHasher};
///
/// let ski_der = encode_subject_key_identifier(
///     &spki_der,
///     KeyIdMethod::Rfc5280Sha1,
///     &OpensslKeyIdHasher,
/// );
/// ```
pub fn encode_subject_key_identifier<H: KeyIdHasher>(
    spki_der: &[u8],
    method: KeyIdMethod,
    hasher: &H,
) -> Option<Vec<u8>> {
    let mut dec = synta::Decoder::new(spki_der, synta::Encoding::Der);
    let spki: SubjectPublicKeyInfo<'_> = dec.decode().ok()?;

    // Select input data per method (RFC 7093 ยง2 m4 uses the full SPKI DER).
    let hash_input: &[u8] = if method.uses_full_spki_der() {
        spki_der
    } else {
        spki.subject_public_key.as_bytes()
    };

    let raw_hash = hasher.hash(method.algorithm_oid(), hash_input).ok()?;
    let key_id = method.apply_output_length(raw_hash);

    let os = synta::OctetString::new(key_id);
    os.to_der().ok()
}

/// Encode an `AuthorityKeyIdentifier` extension value (OID 2.5.29.35).
///
/// Sets only the `keyIdentifier [0]` field.  The key identifier is computed
/// from the issuer's `SubjectPublicKeyInfo` using the same input and hash
/// rules as [`encode_subject_key_identifier`]:
///
/// - Methods other than [`Rfc7093Method4`][KeyIdMethod::Rfc7093Method4] hash
///   the BIT STRING value of `subjectPublicKey`.
/// - [`Rfc7093Method4`][KeyIdMethod::Rfc7093Method4] hashes the full
///   `SubjectPublicKeyInfo` DER encoding.
///
/// Returns the DER bytes of the `AuthorityKeyIdentifier` SEQUENCE, or `None`
/// if `issuer_spki_der` cannot be decoded or if the hasher fails.
///
/// Uses the generated [`AuthorityKeyIdentifier`] type's `Encode`
/// implementation.
///
/// # Example (RFC 5280 default)
///
/// ```rust,ignore
/// use synta_certificate::{encode_authority_key_identifier, KeyIdMethod, OpensslKeyIdHasher};
///
/// let aki_der = encode_authority_key_identifier(
///     &ca_spki_der,
///     KeyIdMethod::Rfc5280Sha1,
///     &OpensslKeyIdHasher,
/// );
/// ```
pub fn encode_authority_key_identifier<H: KeyIdHasher>(
    issuer_spki_der: &[u8],
    method: KeyIdMethod,
    hasher: &H,
) -> Option<Vec<u8>> {
    use synta::OctetStringRef;

    let mut dec = synta::Decoder::new(issuer_spki_der, synta::Encoding::Der);
    let spki: SubjectPublicKeyInfo<'_> = dec.decode().ok()?;

    let hash_input: &[u8] = if method.uses_full_spki_der() {
        issuer_spki_der
    } else {
        spki.subject_public_key.as_bytes()
    };

    let raw_hash = hasher.hash(method.algorithm_oid(), hash_input).ok()?;
    let key_id = method.apply_output_length(raw_hash);

    let aki = AuthorityKeyIdentifier {
        key_identifier: Some(OctetStringRef::new(&key_id)),
        authority_cert_issuer: None,
        authority_cert_serial_number: None,
    };
    aki.to_der().ok()
}

// โ”€โ”€ Internal helpers โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

/// Wrap `content` bytes in a DER SEQUENCE TLV and return the result.
pub(crate) fn encode_sequence(content: Vec<u8>) -> Vec<u8> {
    let mut enc = Encoder::new(Encoding::Der);
    let _ = enc.start_constructed_no_guard(Tag::universal_constructed(TAG_SEQUENCE));
    enc.write_bytes(&content);
    let _ = enc.end_constructed();
    enc.finish().unwrap_or_default()
}

// โ”€โ”€ SubjectAlternativeNameBuilder โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

/// Fluent builder for a `SubjectAltName` extension value (OID 2.5.29.17).
///
/// Add [`crate::GeneralName`] entries with the fluent methods, then call
/// [`build`][Self::build] to obtain the DER bytes of the `GeneralNames`
/// SEQUENCE โ€” the content that goes inside the OCTET STRING wrapper in the
/// `Extension` SEQUENCE.
///
/// # Example
///
/// ```rust,ignore
/// use synta_certificate::SubjectAlternativeNameBuilder;
///
/// let san_der = SubjectAlternativeNameBuilder::new()
///     .dns_name("www.example.com")
///     .dns_name("example.com")
///     .rfc822_name("admin@example.com")
///     .ip_address(&[192, 168, 1, 1])
///     .build()
///     .unwrap();
/// ```
#[derive(Debug, Default)]
pub struct SubjectAlternativeNameBuilder {
    /// Pre-encoded `GeneralName` TLVs accumulated as raw DER bytes.
    encoded: Vec<u8>,
    /// First encoding error encountered; set by `push()`.
    error: Option<String>,
}

impl SubjectAlternativeNameBuilder {
    /// Create a new, empty `SubjectAlternativeNameBuilder`.
    pub fn new() -> Self {
        Self::default()
    }

    /// Encode a [`GeneralNameSpec`] and append its DER TLV bytes to the buffer.
    ///
    /// Records the first encoding error in `self.error`; subsequent pushes
    /// are skipped once an error has been recorded.
    pub fn push(&mut self, spec: GeneralNameSpec) {
        if self.error.is_some() {
            return;
        }
        let gn = match spec.to_general_name() {
            Ok(gn) => gn,
            Err(e) => {
                self.error = Some(format!("GeneralName error: {e}"));
                return;
            }
        };
        match gn.to_der() {
            Ok(bytes) => self.encoded.extend_from_slice(&bytes),
            Err(e) => self.error = Some(format!("GeneralName DER encoding failed: {e}")),
        }
    }

    /// Add a `dNSName [2]` GeneralName.
    pub fn dns_name(mut self, name: &str) -> Self {
        self.push(GeneralNameSpec::dns(name));
        self
    }

    /// Add an `rfc822Name [1]` GeneralName (email address).
    pub fn rfc822_name(mut self, email: &str) -> Self {
        self.push(GeneralNameSpec::rfc822(email));
        self
    }

    /// Add a `uniformResourceIdentifier [6]` GeneralName (URI).
    pub fn uri(mut self, uri: &str) -> Self {
        self.push(GeneralNameSpec::uri(uri));
        self
    }

    /// Add an `iPAddress [7]` GeneralName.
    ///
    /// Pass 4 bytes for IPv4 or 16 bytes for IPv6.
    pub fn ip_address(mut self, addr: &[u8]) -> Self {
        self.push(GeneralNameSpec::ip_address(addr));
        self
    }

    /// Add a `directoryName [4]` GeneralName (EXPLICIT wrapper).
    ///
    /// `name_der` is the complete DER TLV bytes of the `Name` SEQUENCE, such
    /// as those returned by [`NameBuilder::build`][crate::NameBuilder::build].
    pub fn directory_name(mut self, name_der: &[u8]) -> Self {
        self.push(GeneralNameSpec::directory_name(name_der));
        self
    }

    /// Add a `registeredID [8]` GeneralName.
    pub fn registered_id(mut self, oid: synta::ObjectIdentifier) -> Self {
        self.push(GeneralNameSpec::registered_id(oid));
        self
    }

    /// 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 }`.
    ///
    /// The bytes are decoded and re-encoded as a `GeneralName::OtherName` TLV.
    /// On decoding failure the error is recorded and subsequent `push` calls are skipped.
    pub fn other_name(mut self, other_name_der: &[u8]) -> Self {
        if self.error.is_some() {
            return self;
        }
        let mut dec = synta::Decoder::new(other_name_der, synta::Encoding::Der);
        match crate::OtherName::decode(&mut dec) {
            Ok(on) => {
                let gn = crate::GeneralName::OtherName(on);
                match gn.to_der() {
                    Ok(bytes) => self.encoded.extend_from_slice(&bytes),
                    Err(e) => self.error = Some(format!("OtherName DER re-encoding failed: {e}")),
                }
            }
            Err(e) => {
                self.error = Some(format!("OtherName DER decode failed: {e}"));
            }
        }
        self
    }

    /// Build the DER-encoded `GeneralNames` SEQUENCE.
    ///
    /// Returns an empty `SEQUENCE` (`30 00`) if no entries have been added.
    /// Returns `Err` if any entry could not be DER-encoded.
    pub fn build(self) -> Result<Vec<u8>, String> {
        if let Some(e) = self.error {
            return Err(e);
        }
        Ok(encode_sequence(self.encoded))
    }
}

// โ”€โ”€ 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
/// [`build`][Self::build] to obtain the DER bytes of the
/// `AuthorityInfoAccessSyntax` SEQUENCE โ€” the content that goes inside the
/// OCTET STRING wrapper in the `Extension` SEQUENCE.
///
/// # Example
///
/// ```rust,ignore
/// use synta_certificate::AuthorityInformationAccessBuilder;
///
/// let aia_der = AuthorityInformationAccessBuilder::new()
///     .ocsp("http://ocsp.example.com")
///     .ca_issuers("http://ca.example.com/ca.crt")
///     .build()
///     .unwrap();
/// ```
#[derive(Debug, Default)]
pub struct AuthorityInformationAccessBuilder {
    /// Pre-encoded `AccessDescription` TLVs accumulated as raw DER bytes.
    encoded: Vec<u8>,
    /// First encoding error encountered; set by `push()` or `push_uri()`.
    error: Option<String>,
}

impl AuthorityInformationAccessBuilder {
    /// Create a new, empty `AuthorityInformationAccessBuilder`.
    pub fn new() -> Self {
        Self::default()
    }

    /// Encode an `AccessDescription` and append its TLV bytes.
    ///
    /// Records the first encoding error in `self.error`.
    fn push(&mut self, desc: AccessDescription<'_>) {
        if self.error.is_some() {
            return;
        }
        match desc.to_der() {
            Ok(bytes) => self.encoded.extend_from_slice(&bytes),
            Err(e) => self.error = Some(format!("AccessDescription DER encoding failed: {e}")),
        }
    }

    fn push_uri(&mut self, method_oid: &[u32], uri: &str) {
        if self.error.is_some() {
            return;
        }
        let access_method = match synta::ObjectIdentifier::new(method_oid) {
            Ok(oid) => oid,
            Err(e) => {
                self.error = Some(format!("invalid access method OID: {e}"));
                return;
            }
        };
        let spec = GeneralNameSpec::uri(uri);
        let access_location = match spec.to_general_name() {
            Ok(gn) => gn,
            Err(e) => {
                self.error = Some(format!("URI GeneralName error: {e}"));
                return;
            }
        };
        self.push(AccessDescription {
            access_method,
            access_location,
        });
    }

    /// Add an OCSP responder URI (`id-ad-ocsp`, 1.3.6.1.5.5.7.48.1).
    pub fn ocsp(mut self, uri: &str) -> Self {
        self.push_uri(crate::ID_AD_OCSP, uri);
        self
    }

    /// Add a CA Issuers URI (`id-ad-caIssuers`, 1.3.6.1.5.5.7.48.2).
    pub fn ca_issuers(mut self, uri: &str) -> Self {
        self.push_uri(crate::ID_AD_CA_ISSUERS, uri);
        self
    }

    /// Build the DER-encoded `AuthorityInfoAccessSyntax` SEQUENCE.
    ///
    /// Returns an empty `SEQUENCE` (`30 00`) if no entries have been added.
    /// Returns `Err` if any entry could not be DER-encoded.
    pub fn build(self) -> Result<Vec<u8>, String> {
        if let Some(e) = self.error {
            return Err(e);
        }
        Ok(encode_sequence(self.encoded))
    }
}

// โ”€โ”€ 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 [`add_oid`][Self::add_oid], then call [`build`][Self::build] to obtain
/// the DER bytes of the `ExtKeyUsageSyntax` SEQUENCE โ€” the content that goes
/// inside the OCTET STRING wrapper in the `Extension` SEQUENCE.
///
/// # Example
///
/// ```rust,ignore
/// use synta_certificate::ExtendedKeyUsageBuilder;
///
/// // Typical TLS server certificate EKU
/// let eku_der = ExtendedKeyUsageBuilder::new()
///     .server_auth()
///     .client_auth()
///     .build()
///     .unwrap();
/// ```
#[derive(Debug, Default)]
pub struct ExtendedKeyUsageBuilder {
    /// Pre-encoded `KeyPurposeId` (OID) TLVs accumulated as raw DER bytes.
    encoded: Vec<u8>,
    /// First encoding error encountered; set by `add_oid()`.
    error: Option<String>,
}

impl ExtendedKeyUsageBuilder {
    /// Create a new, empty `ExtendedKeyUsageBuilder`.
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a key purpose OID by component slice.
    ///
    /// Use this for custom EKU OIDs not covered by the convenience methods.
    /// The well-known constants are in [`crate::oids`].
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use synta_certificate::{ExtendedKeyUsageBuilder, oids};
    ///
    /// let eku_der = ExtendedKeyUsageBuilder::new()
    ///     .add_oid(oids::KP_SERVER_AUTH)
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn add_oid(mut self, comps: &[u32]) -> Self {
        if self.error.is_some() {
            return self;
        }
        let oid = match synta::ObjectIdentifier::new(comps) {
            Ok(oid) => oid,
            Err(e) => {
                self.error = Some(format!("invalid EKU OID: {e}"));
                return self;
            }
        };
        match oid.to_der() {
            Ok(bytes) => self.encoded.extend_from_slice(&bytes),
            Err(e) => self.error = Some(format!("OID DER encoding failed: {e}")),
        }
        self
    }

    /// Add `id-kp-serverAuth` (1.3.6.1.5.5.7.3.1).
    pub fn server_auth(self) -> Self {
        self.add_oid(crate::ID_KP_SERVER_AUTH)
    }

    /// Add `id-kp-clientAuth` (1.3.6.1.5.5.7.3.2).
    pub fn client_auth(self) -> Self {
        self.add_oid(crate::ID_KP_CLIENT_AUTH)
    }

    /// Add `id-kp-codeSigning` (1.3.6.1.5.5.7.3.3).
    pub fn code_signing(self) -> Self {
        self.add_oid(crate::ID_KP_CODE_SIGNING)
    }

    /// Add `id-kp-emailProtection` (1.3.6.1.5.5.7.3.4).
    pub fn email_protection(self) -> Self {
        self.add_oid(crate::ID_KP_EMAIL_PROTECTION)
    }

    /// Add `id-kp-timeStamping` (1.3.6.1.5.5.7.3.8).
    pub fn time_stamping(self) -> Self {
        self.add_oid(crate::ID_KP_TIME_STAMPING)
    }

    /// Add `id-kp-OCSPSigning` (1.3.6.1.5.5.7.3.9).
    pub fn ocsp_signing(self) -> Self {
        self.add_oid(crate::ID_KP_OCSPSIGNING)
    }

    /// Build the DER-encoded `ExtKeyUsageSyntax` SEQUENCE.
    ///
    /// Returns an empty `SEQUENCE` (`30 00`) if no OIDs have been added.
    /// Returns `Err` if any OID could not be constructed or DER-encoded.
    pub fn build(self) -> Result<Vec<u8>, String> {
        if let Some(e) = self.error {
            return Err(e);
        }
        Ok(encode_sequence(self.encoded))
    }
}

// โ”€โ”€ IssuerAlternativeNameBuilder โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

/// Fluent builder for an `IssuerAltName` extension value (OID 2.5.29.18).
///
/// The encoding is identical to [`SubjectAlternativeNameBuilder`] โ€” a
/// `GeneralNames` SEQUENCE โ€” but the OID differs (2.5.29.18 vs 2.5.29.17).
/// Add entries with the fluent methods, then call [`build`][Self::build].
///
/// # Example
///
/// ```rust,ignore
/// use synta_certificate::IssuerAlternativeNameBuilder;
///
/// let ian_der = IssuerAlternativeNameBuilder::new()
///     .rfc822_name("ca@example.com")
///     .uri("http://www.example.com")
///     .build()
///     .unwrap();
/// ```
#[derive(Debug, Default)]
pub struct IssuerAlternativeNameBuilder {
    /// Pre-encoded `GeneralName` TLVs accumulated as raw DER bytes.
    encoded: Vec<u8>,
    /// First encoding error encountered; set by `push()`.
    error: Option<String>,
}

impl IssuerAlternativeNameBuilder {
    /// Create a new, empty `IssuerAlternativeNameBuilder`.
    pub fn new() -> Self {
        Self::default()
    }

    /// Encode a [`GeneralNameSpec`] and append its DER TLV bytes to the buffer.
    ///
    /// Records the first encoding error in `self.error`.
    pub fn push(&mut self, spec: GeneralNameSpec) {
        if self.error.is_some() {
            return;
        }
        let gn = match spec.to_general_name() {
            Ok(gn) => gn,
            Err(e) => {
                self.error = Some(format!("GeneralName error: {e}"));
                return;
            }
        };
        match gn.to_der() {
            Ok(bytes) => self.encoded.extend_from_slice(&bytes),
            Err(e) => {
                self.error = Some(format!("GeneralName DER encoding failed: {e}"));
            }
        }
    }

    /// Add a DNS name entry.
    pub fn dns_name(mut self, name: &str) -> Self {
        self.push(GeneralNameSpec::dns(name));
        self
    }

    /// Add an RFC 822 (email) name entry.
    pub fn rfc822_name(mut self, email: &str) -> Self {
        self.push(GeneralNameSpec::rfc822(email));
        self
    }

    /// Add a URI entry.
    pub fn uri(mut self, uri: &str) -> Self {
        self.push(GeneralNameSpec::uri(uri));
        self
    }

    /// Add an IP address entry (4 bytes for IPv4, 16 bytes for IPv6).
    pub fn ip_address(mut self, addr: &[u8]) -> Self {
        self.push(GeneralNameSpec::ip_address(addr));
        self
    }

    /// Add a directory name entry (DER-encoded `Name` SEQUENCE bytes).
    pub fn directory_name(mut self, name_der: &[u8]) -> Self {
        self.push(GeneralNameSpec::directory_name(name_der));
        self
    }

    /// Add a registered OID entry.
    pub fn registered_id(mut self, oid: synta::ObjectIdentifier) -> Self {
        self.push(GeneralNameSpec::registered_id(oid));
        self
    }

    /// Build the DER-encoded `IssuerAltName` value (a `GeneralNames` SEQUENCE).
    ///
    /// Returns `Err` if any entry could not be DER-encoded.
    pub fn build(self) -> Result<Vec<u8>, String> {
        if let Some(e) = self.error {
            return Err(e);
        }
        Ok(encode_sequence(self.encoded))
    }
}

// โ”€โ”€ 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 the
/// `permittedSubtrees` field are allowed; names in the `excludedSubtrees`
/// field are forbidden.  When present, this extension MUST be marked critical.
///
/// ```text
/// NameConstraints ::= SEQUENCE {
///     permittedSubtrees   [0] GeneralSubtrees OPTIONAL,
///     excludedSubtrees    [1] GeneralSubtrees OPTIONAL }
///
/// GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
///
/// GeneralSubtree ::= SEQUENCE {
///     base                GeneralName,
///     minimum  [0]        BaseDistance DEFAULT 0,
///     maximum  [1]        BaseDistance OPTIONAL }
/// ```
///
/// Add permitted and excluded subtrees using the typed methods, then call
/// [`build`][Self::build] to obtain the DER bytes of the outer `NameConstraints`
/// SEQUENCE โ€” the content that goes inside the OCTET STRING wrapper in the
/// `Extension` SEQUENCE.
///
/// The permitted and excluded lists are encoded as
/// `[0] IMPLICIT GeneralSubtrees` and `[1] IMPLICIT GeneralSubtrees`
/// respectively.  Each [`GeneralSubtree`] is encoded with `minimum` and
/// `maximum` absent (i.e. the DEFAULT values `0` and absent, per RFC 5280).
///
/// **DNS name conventions (RFC 5280 ยง4.2.1.10):** a constraint of `".example.com"`
/// applies to any subdomain of `example.com` (e.g. `www.example.com`), while
/// `"example.com"` constrains only that exact host name.
///
/// **IP address constraints:** supply `addr ++ mask` concatenated โ€” 8 bytes for
/// IPv4 (4-byte address followed by 4-byte mask, e.g. `[192,168,0,0,255,255,0,0]`)
/// or 32 bytes for IPv6 (16-byte address followed by 16-byte mask).
///
/// # Example
///
/// ```rust,ignore
/// use synta_certificate::NameConstraintsBuilder;
///
/// // Permit the example.com DNS subtree and a specific IP range;
/// // exclude a known-bad subdomain.
/// let nc_der = NameConstraintsBuilder::new()
///     .permit_dns(".example.com")
///     .permit_ip(&[10, 0, 0, 0, 255, 0, 0, 0])   // 10.0.0.0/8
///     .exclude_dns(".evil.com")
///     .build()
///     .unwrap();
/// ```
#[derive(Debug, Default)]
pub struct NameConstraintsBuilder {
    /// Pre-encoded `GeneralSubtree` TLVs for permitted subtrees.
    permitted_bytes: Vec<u8>,
    /// Pre-encoded `GeneralSubtree` TLVs for excluded subtrees.
    excluded_bytes: Vec<u8>,
    /// First encoding error encountered.
    error: Option<String>,
}

impl NameConstraintsBuilder {
    /// Create a new, empty `NameConstraintsBuilder`.
    pub fn new() -> Self {
        Self::default()
    }

    /// Encode a `GeneralSubtree { base: gn, minimum: None, maximum: None }` and
    /// append to the given buffer.  Records the first error in `self.error`.
    fn push_subtree(&mut self, spec: GeneralNameSpec, buf: &mut Vec<u8>) {
        if self.error.is_some() {
            return;
        }
        let gn = match spec.to_general_name() {
            Ok(gn) => gn,
            Err(e) => {
                self.error = Some(format!("GeneralName error: {e}"));
                return;
            }
        };
        let subtree = GeneralSubtree {
            base: gn,
            minimum: None,
            maximum: None,
        };
        match subtree.to_der() {
            Ok(bytes) => buf.extend_from_slice(&bytes),
            Err(e) => {
                self.error = Some(format!("GeneralSubtree DER encoding failed: {e}"));
            }
        }
    }

    /// Add a DNS name constraint to the permitted subtrees.
    ///
    /// Use a leading dot (e.g. `".example.com"`) to constrain the entire
    /// subtree rooted at `example.com`.  A value without a leading dot
    /// (e.g. `"host.example.com"`) constrains only that exact host name.
    pub fn permit_dns(mut self, dns: &str) -> Self {
        let mut buf = std::mem::take(&mut self.permitted_bytes);
        self.push_subtree(GeneralNameSpec::dns(dns), &mut buf);
        self.permitted_bytes = buf;
        self
    }

    /// 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 address.
    pub fn permit_rfc822(mut self, email: &str) -> Self {
        let mut buf = std::mem::take(&mut self.permitted_bytes);
        self.push_subtree(GeneralNameSpec::rfc822(email), &mut buf);
        self.permitted_bytes = buf;
        self
    }

    /// Add a URI scheme constraint to the permitted subtrees.
    ///
    /// The URI value is encoded as a `uniformResourceIdentifier [6]`
    /// `GeneralName`.  Per RFC 5280 ยง4.2.1.10, a URI constraint specifies
    /// a host name (optionally with a leading dot for subtree matching),
    /// not a full URI.  Example: `"example.com"` or `".example.com"`.
    pub fn permit_uri(mut self, uri: &str) -> Self {
        let mut buf = std::mem::take(&mut self.permitted_bytes);
        self.push_subtree(GeneralNameSpec::uri(uri), &mut buf);
        self.permitted_bytes = buf;
        self
    }

    /// Add an IP address range constraint to the permitted subtrees.
    ///
    /// `addr_and_mask` must be the address bytes immediately followed by the
    /// mask bytes โ€” 8 bytes for IPv4 (e.g. `[192,168,0,0, 255,255,0,0]` for
    /// `192.168.0.0/16`) or 32 bytes for IPv6.  The encoding follows
    /// RFC 5280 ยง4.2.1.10 (a `SEQUENCE { iPAddress [7] OCTET STRING }`
    /// where the OCTET STRING contains address||mask).
    pub fn permit_ip(mut self, addr_and_mask: &[u8]) -> Self {
        let mut buf = std::mem::take(&mut self.permitted_bytes);
        self.push_subtree(GeneralNameSpec::ip_address(addr_and_mask), &mut buf);
        self.permitted_bytes = buf;
        self
    }

    /// Add a directory name constraint to the permitted subtrees.
    ///
    /// `name_der` is the complete DER TLV bytes of an X.509 `Name` SEQUENCE,
    /// such as those returned by `NameBuilder::build()`.  The constraint
    /// is encoded as a `directoryName [4]` `GeneralName` inside a
    /// `GeneralSubtree`.
    pub fn permit_directory_name(mut self, name_der: &[u8]) -> Self {
        let mut buf = std::mem::take(&mut self.permitted_bytes);
        self.push_subtree(GeneralNameSpec::directory_name(name_der), &mut buf);
        self.permitted_bytes = buf;
        self
    }

    /// 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`.  A value without a leading dot excludes only
    /// that exact host name.
    pub fn exclude_dns(mut self, dns: &str) -> Self {
        let mut buf = std::mem::take(&mut self.excluded_bytes);
        self.push_subtree(GeneralNameSpec::dns(dns), &mut buf);
        self.excluded_bytes = buf;
        self
    }

    /// 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 address.
    pub fn exclude_rfc822(mut self, email: &str) -> Self {
        let mut buf = std::mem::take(&mut self.excluded_bytes);
        self.push_subtree(GeneralNameSpec::rfc822(email), &mut buf);
        self.excluded_bytes = buf;
        self
    }

    /// Add a URI scheme constraint to the excluded subtrees.
    ///
    /// The value is encoded as a `uniformResourceIdentifier [6]` `GeneralName`.
    /// Per RFC 5280 ยง4.2.1.10, the constraint value is a host name or
    /// dot-prefixed domain, not a full URI.
    pub fn exclude_uri(mut self, uri: &str) -> Self {
        let mut buf = std::mem::take(&mut self.excluded_bytes);
        self.push_subtree(GeneralNameSpec::uri(uri), &mut buf);
        self.excluded_bytes = buf;
        self
    }

    /// Add an IP address range constraint to the excluded subtrees.
    ///
    /// `addr_and_mask` must be the address bytes immediately followed by the
    /// mask bytes โ€” 8 bytes for IPv4 (e.g. `[10,0,0,0, 255,0,0,0]` for
    /// `10.0.0.0/8`) or 32 bytes for IPv6.  Follows the same encoding as
    /// [`permit_ip`][Self::permit_ip].
    pub fn exclude_ip(mut self, addr_and_mask: &[u8]) -> Self {
        let mut buf = std::mem::take(&mut self.excluded_bytes);
        self.push_subtree(GeneralNameSpec::ip_address(addr_and_mask), &mut buf);
        self.excluded_bytes = buf;
        self
    }

    /// Add a directory name constraint to the excluded subtrees.
    ///
    /// `name_der` is the complete DER TLV bytes of an X.509 `Name` SEQUENCE.
    /// The constraint is encoded as a `directoryName [4]` `GeneralName`
    /// inside a `GeneralSubtree`.  See also [`permit_directory_name`][Self::permit_directory_name].
    pub fn exclude_directory_name(mut self, name_der: &[u8]) -> Self {
        let mut buf = std::mem::take(&mut self.excluded_bytes);
        self.push_subtree(GeneralNameSpec::directory_name(name_der), &mut buf);
        self.excluded_bytes = buf;
        self
    }

    /// 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 (`30 00`).
    ///
    /// The permitted subtrees, if any, are wrapped in `[0] IMPLICIT` (tag
    /// `A0`); excluded subtrees in `[1] IMPLICIT` (tag `A1`), following
    /// RFC 5280 ยง4.2.1.10.
    ///
    /// Returns `Err(String)` if any entry failed DER encoding; the error
    /// message describes the first failure encountered.
    pub fn build(self) -> Result<Vec<u8>, String> {
        if let Some(e) = self.error {
            return Err(e);
        }

        // Wrap pre-encoded `GeneralSubtree` TLVs in an IMPLICIT CONSTRUCTED
        // context tag.  The SEQUENCE OF tag (0x30) is replaced by [N] keeping
        // the CONSTRUCTED bit: A0 for [0], A1 for [1].
        let wrap_implicit = |tag_byte: u8, content: Vec<u8>| -> Vec<u8> {
            let mut out = Vec::with_capacity(content.len() + 4);
            out.push(tag_byte);
            let len = content.len();
            if len < 128 {
                out.push(len as u8);
            } else if len < 256 {
                out.push(0x81);
                out.push(len as u8);
            } else if len < 65536 {
                out.push(0x82);
                out.push((len >> 8) as u8);
                out.push((len & 0xFF) as u8);
            } else {
                out.push(0x83);
                out.push((len >> 16) as u8);
                out.push((len >> 8) as u8);
                out.push((len & 0xFF) as u8);
            }
            out.extend_from_slice(&content);
            out
        };

        let mut content = Vec::new();
        if !self.permitted_bytes.is_empty() {
            content.extend_from_slice(&wrap_implicit(0xA0, self.permitted_bytes));
        }
        if !self.excluded_bytes.is_empty() {
            content.extend_from_slice(&wrap_implicit(0xA1, self.excluded_bytes));
        }
        Ok(encode_sequence(content))
    }
}

// โ”€โ”€ CRLDistributionPointsBuilder โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

/// Fluent builder for a `CRLDistributionPoints` extension value (OID 2.5.29.31).
///
/// Add distribution point entries with the fluent methods, then call
/// [`build`][Self::build] to obtain the DER bytes of the
/// `CRLDistributionPoints` SEQUENCE OF โ€” the content that goes inside the
/// OCTET STRING wrapper in the `Extension` SEQUENCE.
///
/// Each entry is encoded as a [`DistributionPoint`] SEQUENCE using the
/// generated type's `Encode` implementation.
///
/// # Example
///
/// ```rust,ignore
/// use synta_certificate::CRLDistributionPointsBuilder;
///
/// let cdp_der = CRLDistributionPointsBuilder::new()
///     .full_name_uri("http://crl.example.com/ca.crl")
///     .build()
///     .unwrap();
/// ```
#[derive(Debug, Default)]
pub struct CRLDistributionPointsBuilder {
    /// Pre-encoded `DistributionPoint` TLVs accumulated as raw DER bytes.
    encoded: Vec<u8>,
    /// First encoding error encountered.
    error: Option<String>,
}

impl CRLDistributionPointsBuilder {
    /// Create a new, empty `CRLDistributionPointsBuilder`.
    pub fn new() -> Self {
        Self::default()
    }

    /// Encode a `DistributionPoint` with a `fullName` containing a single
    /// `GeneralName` and append the TLV bytes to the buffer.
    fn push_full_name(&mut self, spec: GeneralNameSpec) {
        if self.error.is_some() {
            return;
        }
        let gn = match spec.to_general_name() {
            Ok(gn) => gn,
            Err(e) => {
                self.error = Some(format!("GeneralName error: {e}"));
                return;
            }
        };
        let dp = DistributionPoint {
            distribution_point: Some(DistributionPointName::FullName(vec![gn])),
            reasons: None,
            c_rlissuer: None,
        };
        match dp.to_der() {
            Ok(bytes) => self.encoded.extend_from_slice(&bytes),
            Err(e) => {
                self.error = Some(format!("DistributionPoint DER encoding failed: {e}"));
            }
        }
    }

    /// Add a distribution point with a URI as the full name.
    pub fn full_name_uri(mut self, uri: &str) -> Self {
        self.push_full_name(GeneralNameSpec::uri(uri));
        self
    }

    /// Add a distribution point with a DNS name as the full name.
    pub fn full_name_dns(mut self, dns: &str) -> Self {
        self.push_full_name(GeneralNameSpec::dns(dns));
        self
    }

    /// Add a distribution point with a directory name as the full name
    /// (DER-encoded `Name` SEQUENCE bytes).
    pub fn full_name_directory(mut self, name_der: &[u8]) -> Self {
        self.push_full_name(GeneralNameSpec::directory_name(name_der));
        self
    }

    /// Build the DER-encoded `CRLDistributionPoints` SEQUENCE OF.
    ///
    /// Returns an empty `SEQUENCE` (`30 00`) if no entries have been added.
    /// Returns `Err` if any entry could not be DER-encoded.
    pub fn build(self) -> Result<Vec<u8>, String> {
        if let Some(e) = self.error {
            return Err(e);
        }
        Ok(encode_sequence(self.encoded))
    }
}

// โ”€โ”€ IssuingDistributionPointBuilder โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

/// Fluent builder for an `IssuingDistributionPoint` extension value
/// (OID 2.5.29.28, RFC 5280 Section 5.2.5).
///
/// Set the optional distribution point name and/or the boolean flags, then
/// call [`build`][Self::build] to obtain the DER bytes of the
/// `IssuingDistributionPoint` SEQUENCE โ€” the content that goes inside the
/// OCTET STRING wrapper in the `Extension` SEQUENCE.
///
/// All boolean flags default to `false` (omitted in DER per DEFAULT FALSE
/// semantics).  The distribution point is optional.
///
/// Uses the generated [`IssuingDistributionPoint`] type with
/// IMPLICIT-tagged BOOLEAN fields (as specified in RFC 5280).
///
/// # Example
///
/// ```rust,ignore
/// use synta_certificate::IssuingDistributionPointBuilder;
///
/// let idp_der = IssuingDistributionPointBuilder::new()
///     .full_name_uri("http://crl.example.com/ca.crl")
///     .only_contains_user_certs(true)
///     .build()
///     .unwrap();
/// ```
#[derive(Debug, Default)]
pub struct IssuingDistributionPointBuilder {
    /// Pre-encoded `DistributionPointName` DER bytes, if set.
    distribution_point: Option<Vec<u8>>,
    /// `onlyContainsUserCerts` boolean flag.
    only_contains_user_certs: bool,
    /// `onlyContainsCACerts` boolean flag.
    only_contains_cacerts: bool,
    /// `indirectCRL` boolean flag.
    indirect_crl: bool,
    /// `onlyContainsAttributeCerts` boolean flag.
    only_contains_attribute_certs: bool,
    /// First encoding error encountered.
    error: Option<String>,
}

impl IssuingDistributionPointBuilder {
    /// Create a new `IssuingDistributionPointBuilder` with all fields absent/false.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the distribution point to a URI full name.
    pub fn full_name_uri(mut self, uri: &str) -> Self {
        if self.error.is_some() {
            return self;
        }
        let spec = GeneralNameSpec::uri(uri);
        let gn = match spec.to_general_name() {
            Ok(gn) => gn,
            Err(e) => {
                self.error = Some(format!("GeneralName error: {e}"));
                return self;
            }
        };
        let dpn = DistributionPointName::FullName(vec![gn]);
        match dpn.to_der() {
            Ok(bytes) => self.distribution_point = Some(bytes),
            Err(e) => {
                self.error = Some(format!("DistributionPointName DER encoding failed: {e}"));
            }
        }
        self
    }

    /// Set the distribution point to a DNS name full name.
    pub fn full_name_dns(mut self, dns: &str) -> Self {
        if self.error.is_some() {
            return self;
        }
        let spec = GeneralNameSpec::dns(dns);
        let gn = match spec.to_general_name() {
            Ok(gn) => gn,
            Err(e) => {
                self.error = Some(format!("GeneralName error: {e}"));
                return self;
            }
        };
        let dpn = DistributionPointName::FullName(vec![gn]);
        match dpn.to_der() {
            Ok(bytes) => self.distribution_point = Some(bytes),
            Err(e) => {
                self.error = Some(format!("DistributionPointName DER encoding failed: {e}"));
            }
        }
        self
    }

    /// Set `onlyContainsUserCerts`.
    pub fn only_contains_user_certs(mut self, val: bool) -> Self {
        self.only_contains_user_certs = val;
        self
    }

    /// Set `onlyContainsCACerts`.
    pub fn only_contains_cacerts(mut self, val: bool) -> Self {
        self.only_contains_cacerts = val;
        self
    }

    /// Set `indirectCRL`.
    pub fn indirect_crl(mut self, val: bool) -> Self {
        self.indirect_crl = val;
        self
    }

    /// Set `onlyContainsAttributeCerts`.
    pub fn only_contains_attribute_certs(mut self, val: bool) -> Self {
        self.only_contains_attribute_certs = val;
        self
    }

    /// Build the DER-encoded `IssuingDistributionPoint` SEQUENCE.
    ///
    /// Returns `Err` if the distribution point could not be re-decoded or
    /// DER encoding of the final structure fails.
    pub fn build(self) -> Result<Vec<u8>, String> {
        if let Some(e) = self.error {
            return Err(e);
        }

        // Decode the pre-encoded DistributionPointName bytes (if any) back into
        // the generated type so we can pass it to IssuingDistributionPoint.
        // Both decode and encode happen before `dp_bytes` is dropped.
        let dp_bytes = self.distribution_point;
        let distribution_point = if let Some(ref bytes) = dp_bytes {
            let dp_name = synta::Decoder::new(bytes, synta::Encoding::Der)
                .decode::<DistributionPointName<'_>>()
                .map_err(|e| format!("DistributionPointName re-decode failed: {e}"))?;
            Some(dp_name)
        } else {
            None
        };

        let idp = IssuingDistributionPoint {
            distribution_point,
            only_contains_user_certs: self
                .only_contains_user_certs
                .then_some(synta::Boolean(true)),
            only_contains_cacerts: self.only_contains_cacerts.then_some(synta::Boolean(true)),
            only_some_reasons: None,
            indirect_crl: self.indirect_crl.then_some(synta::Boolean(true)),
            only_contains_attribute_certs: self
                .only_contains_attribute_certs
                .then_some(synta::Boolean(true)),
        };

        idp.to_der()
            .map_err(|e| format!("IssuingDistributionPoint DER encoding failed: {e}"))
    }
}

// โ”€โ”€ CertificatePoliciesBuilder โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

/// Fluent builder for a `CertificatePolicies` extension value (OID 2.5.29.32).
///
/// Add policy entries (with or without a CPS URI qualifier) using the fluent
/// methods, then call [`build`][Self::build] to obtain the DER bytes of the
/// `CertificatePolicies` SEQUENCE OF โ€” the content that goes inside the
/// OCTET STRING wrapper in the `Extension` SEQUENCE.
///
/// Each [`PolicyInformation`] is encoded immediately using the generated
/// type's `Encode` implementation.
///
/// # Example
///
/// ```rust,ignore
/// use synta_certificate::{CertificatePoliciesBuilder, oids};
///
/// let cp_der = CertificatePoliciesBuilder::new()
///     .add_policy(oids::PKIX_CE_ANY_POLICY)
///     .add_policy_cps(&[2, 23, 140, 1, 2, 1], "https://example.com/cps")
///     .build()
///     .unwrap();
/// ```
#[derive(Debug, Default)]
pub struct CertificatePoliciesBuilder {
    /// Pre-encoded `PolicyInformation` TLVs accumulated as raw DER bytes.
    encoded: Vec<u8>,
    /// First encoding error encountered.
    error: Option<String>,
}

impl CertificatePoliciesBuilder {
    /// Create a new, empty `CertificatePoliciesBuilder`.
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a policy identified by `policy_oid` with no qualifiers.
    pub fn add_policy(mut self, policy_oid: &[u32]) -> Self {
        if self.error.is_some() {
            return self;
        }
        let policy_identifier = match synta::ObjectIdentifier::new(policy_oid) {
            Ok(oid) => oid,
            Err(e) => {
                self.error = Some(format!("invalid policy OID: {e}"));
                return self;
            }
        };
        let pi = PolicyInformation {
            policy_identifier,
            policy_qualifiers: None,
        };
        match pi.to_der() {
            Ok(bytes) => self.encoded.extend_from_slice(&bytes),
            Err(e) => self.error = Some(format!("PolicyInformation DER encoding failed: {e}")),
        }
        self
    }

    /// Add a policy with a CPS URI qualifier (`id-qt-cps`, 1.3.6.1.5.5.7.2.1).
    ///
    /// `cps_uri` must be ASCII; returns an error via [`build`][Self::build]
    /// if it contains non-ASCII characters.
    pub fn add_policy_cps(mut self, policy_oid: &[u32], cps_uri: &str) -> Self {
        if self.error.is_some() {
            return self;
        }
        let policy_identifier = match synta::ObjectIdentifier::new(policy_oid) {
            Ok(oid) => oid,
            Err(e) => {
                self.error = Some(format!("invalid policy OID: {e}"));
                return self;
            }
        };
        // id-qt-cps = 1.3.6.1.5.5.7.2.1
        let cps_oid = synta::ObjectIdentifier::new(&[1, 3, 6, 1, 5, 5, 7, 2, 1])
            .expect("id-qt-cps is a valid OID");
        let uri_ref = match synta::IA5StringRef::new(cps_uri) {
            Ok(r) => r,
            Err(e) => {
                self.error = Some(format!("CPS URI contains non-ASCII characters: {e}"));
                return self;
            }
        };
        // Construct PolicyQualifierInfo within this scope so that the IA5StringRef
        // lifetime (bound to cps_uri) stays live until after encode().
        let pqi = PolicyQualifierInfo {
            policy_qualifier_id: cps_oid,
            qualifier: synta::Element::IA5String(uri_ref),
        };
        let pi = PolicyInformation {
            policy_identifier,
            policy_qualifiers: Some(vec![pqi]),
        };
        match pi.to_der() {
            Ok(bytes) => self.encoded.extend_from_slice(&bytes),
            Err(e) => self.error = Some(format!("PolicyInformation DER encoding failed: {e}")),
        }
        self
    }

    /// Build the DER-encoded `CertificatePolicies` SEQUENCE OF.
    ///
    /// Returns an empty `SEQUENCE` (`30 00`) if no policies have been added.
    /// Returns `Err` if any entry could not be DER-encoded.
    pub fn build(self) -> Result<Vec<u8>, String> {
        if let Some(e) = self.error {
            return Err(e);
        }
        Ok(encode_sequence(self.encoded))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// RFC 5280 ยง4.2.1.13 requires two IMPLICIT context tags for a fullName CDP:
    ///
    ///   30 ??          -- CRLDistributionPoints SEQUENCE OF
    ///     30 ??        -- DistributionPoint SEQUENCE
    ///       A0 ??      -- distributionPoint [0] EXPLICIT (targets CHOICE โ†’ forced EXPLICIT)
    ///         A0 ??    -- fullName [0] IMPLICIT (replaces GeneralNames SEQUENCE 0x30 tag)
    ///           86 ??  -- [6] uniformResourceIdentifier
    ///
    /// OpenSSL 3.x rejects certificates where the inner A0 is a plain 0x30 SEQUENCE.
    #[test]
    fn cdp_full_name_uri_correct_implicit_tagging() {
        let uri = "http://crl.example.com/ca.crl";
        let cdp = CRLDistributionPointsBuilder::new()
            .full_name_uri(uri)
            .build()
            .expect("CDP build must succeed");

        // Byte layout:
        //   0: 0x30 (CRLDistributionPoints SEQUENCE)
        //   2: 0x30 (DistributionPoint SEQUENCE)
        //   4: 0xA0 (distributionPoint [0] EXPLICIT โ€” outer A0)
        //   6: 0xA0 (fullName [0] IMPLICIT โ€” inner A0, NOT 0x30 SEQUENCE)
        //   8: 0x86 ([6] uniformResourceIdentifier)
        assert_eq!(cdp[0], 0x30, "outer SEQUENCE tag");
        assert_eq!(cdp[2], 0x30, "DistributionPoint SEQUENCE tag");
        assert_eq!(cdp[4], 0xA0, "distributionPoint [0] must be A0 (EXPLICIT)");
        assert_eq!(
            cdp[6], 0xA0,
            "fullName [0] IMPLICIT must be A0 (not 0x30 SEQUENCE), got 0x{:02x}",
            cdp[6]
        );
        assert_eq!(cdp[8], 0x86, "[6] uniformResourceIdentifier tag");
        let uri_len = cdp[9] as usize;
        assert_eq!(&cdp[10..10 + uri_len], uri.as_bytes());
    }

    /// Round-trip: build a CDP, decode it with the generated DistributionPoint type,
    /// and verify the URI survives.
    #[cfg(feature = "derive")]
    #[test]
    fn cdp_full_name_uri_roundtrip() {
        use crate::{DistributionPoint, DistributionPointName, GeneralName};

        let uri = "http://crl.example.com/ca.crl";
        let cdp_der = CRLDistributionPointsBuilder::new()
            .full_name_uri(uri)
            .build()
            .expect("CDP build must succeed");

        // Decode the outer SEQUENCE OF (skip 2-byte wrapper)
        let inner = &cdp_der[2..];
        let mut dec = synta::Decoder::new(inner, synta::Encoding::Der);
        let dp: DistributionPoint<'_> = dec.decode().expect("DistributionPoint must decode");

        let names = match dp
            .distribution_point
            .expect("distributionPoint must be present")
        {
            DistributionPointName::FullName(names) => names,
            other => panic!("expected FullName, got {:?}", other),
        };
        assert_eq!(names.len(), 1);
        match &names[0] {
            GeneralName::UniformResourceIdentifier(s) => {
                assert_eq!(s.as_str(), uri);
            }
            other => panic!("expected URI GeneralName, got {:?}", other),
        }
    }
}