synta-python 0.3.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
//! Python bindings for RFC 9810 Certificate Management Protocol (CMP) types.
//!
//! Exposes ``CMPMessage`` (wrapping ``PKIMessage``) as a Python class and
//! installs MAC algorithm and key-purpose OID constants into the ``synta.cmp``
//! submodule.

use std::sync::OnceLock;

use pyo3::prelude::*;
use pyo3::types::{PyBytes, PyString};

use synta::{Decoder, Encoding};

use crate::error::SyntaErr;
use crate::types::PyObjectIdentifier;

// ── helpers ───────────────────────────────────────────────────────────────────

/// Map a `PKIBody` variant to its CMP message-type name (lowercase, per RFC 9810).
fn body_type_name(body: &synta_certificate::cmp_types::PKIBody<'_>) -> &'static str {
    use synta_certificate::cmp_types::PKIBody::*;
    match body {
        Ir(_) => "ir",
        Ip(_) => "ip",
        Cr(_) => "cr",
        Cp(_) => "cp",
        P10cr(_) => "p10cr",
        Popdecc(_) => "popdecc",
        Popdecr(_) => "popdecr",
        Kur(_) => "kur",
        Kup(_) => "kup",
        Krr(_) => "krr",
        Krp(_) => "krp",
        Rr(_) => "rr",
        Rp(_) => "rp",
        Ccr(_) => "ccr",
        Ccp(_) => "ccp",
        Ckuann(_) => "ckuann",
        Cann(_) => "cann",
        Rann(_) => "rann",
        Crlann(_) => "crlann",
        Pkiconf(_) => "pkiconf",
        Nested(_) => "nested",
        Genm(_) => "genm",
        Genp(_) => "genp",
        Error(_) => "error",
        CertConf(_) => "certConf",
        PollReq(_) => "pollReq",
        PollRep(_) => "pollRep",
    }
}

/// Extract raw body DER from a `PKIBody` variant.  Returns `None` for
/// the `pkiconf` (NULL) arm; returns the `RawDer` bytes for all others.
fn body_raw_der(body: &synta_certificate::cmp_types::PKIBody<'_>) -> Option<Vec<u8>> {
    use synta_certificate::cmp_types::PKIBody::*;
    match body {
        Pkiconf(_) => None,
        Ir(r) | Ip(r) | Cr(r) | Cp(r) | P10cr(r) | Popdecc(r) | Popdecr(r) | Kur(r) | Kup(r)
        | Krr(r) | Krp(r) | Rr(r) | Rp(r) | Ccr(r) | Ccp(r) | Ckuann(r) | Cann(r) | Rann(r)
        | Crlann(r) | Nested(r) | Genm(r) | Genp(r) | Error(r) | CertConf(r) | PollReq(r)
        | PollRep(r) => Some(r.as_bytes().to_vec()),
    }
}

// ── PyCMPMessage ──────────────────────────────────────────────────────────────

/// A CMP ``PKIMessage`` (RFC 9810 §5.1).
///
/// ``PKIMessage`` is the top-level CMP envelope, carrying a ``PKIHeader``
/// (metadata: pvno, sender, recipient, timestamps, nonces, …) and a
/// ``PKIBody`` (the message payload: IR, IP, CR, CP, RR, RP, …).
///
/// The ``body_type`` property names the active ``PKIBody`` arm in lowercase
/// (``"ir"``, ``"ip"``, ``"cr"``, ``"cp"``, ``"pkiconf"``, …).  For all arms
/// except ``pkiconf``, ``body_der`` returns the raw DER bytes of the body
/// content for further decoding with a ``synta.Decoder``.
///
/// ```python,ignore
/// import synta.cmp as cmp
///
/// msg = cmp.CMPMessage.from_der(open("cmp.der", "rb").read())
/// print(msg.pvno, msg.body_type)
/// if msg.body_type == "ir":
///     # body_der contains the DER of CertReqMessages
///     import synta.crmf as crmf
///     reqs = crmf.CertReqMessages.from_der(msg.body_der)
///     for req in reqs:
///         print(req.cert_req_id, req.popo_type)
/// ```
#[pyclass(frozen, name = "CMPMessage")]
pub struct PyCMPMessage {
    _data: Py<PyBytes>,
    raw: &'static [u8],
    inner: OnceLock<Box<synta_certificate::cmp_types::PKIMessage<'static>>>,
    // Field caches
    pvno_cache: OnceLock<i64>,
    body_type_cache: OnceLock<&'static str>,
    body_der_cache: OnceLock<Option<Py<PyBytes>>>,
    sender_der_cache: OnceLock<Py<PyBytes>>,
    recipient_der_cache: OnceLock<Py<PyBytes>>,
    transaction_id_cache: OnceLock<Option<Py<PyBytes>>>,
    sender_nonce_cache: OnceLock<Option<Py<PyBytes>>>,
    recip_nonce_cache: OnceLock<Option<Py<PyBytes>>>,
    protection_alg_oid_cache: OnceLock<Option<Py<PyObjectIdentifier>>>,
    message_time_cache: OnceLock<Option<Py<PyString>>>,
}

impl PyCMPMessage {
    fn msg(&self) -> PyResult<&synta_certificate::cmp_types::PKIMessage<'static>> {
        if let Some(v) = self.inner.get() {
            return Ok(v.as_ref());
        }
        let mut dec = Decoder::new(self.raw, Encoding::Der);
        let decoded = dec
            .decode::<synta_certificate::cmp_types::PKIMessage<'static>>()
            .map_err(SyntaErr)?;
        let _ = self.inner.set(Box::new(decoded));
        Ok(self.inner.get().unwrap().as_ref())
    }
}

#[pymethods]
impl PyCMPMessage {
    /// Parse a DER-encoded ``PKIMessage`` SEQUENCE.
    ///
    /// :param data: DER bytes of the ``PKIMessage``.
    /// :raises ValueError: if the bytes cannot be decoded.
    #[staticmethod]
    fn from_der(py: Python<'_>, data: Bound<'_, PyBytes>) -> PyResult<Self> {
        let py_bytes = data.unbind();
        {
            let raw = py_bytes.as_bytes(py);
            Decoder::new(raw, Encoding::Der)
                .decode::<synta_certificate::cmp_types::PKIMessage<'_>>()
                .map_err(SyntaErr)?;
        }
        let raw: &'static [u8] = unsafe {
            let s = py_bytes.bind(py).as_bytes();
            std::slice::from_raw_parts(s.as_ptr(), s.len())
        };
        Ok(Self {
            _data: py_bytes,
            raw,
            inner: OnceLock::new(),
            pvno_cache: OnceLock::new(),
            body_type_cache: OnceLock::new(),
            body_der_cache: OnceLock::new(),
            sender_der_cache: OnceLock::new(),
            recipient_der_cache: OnceLock::new(),
            transaction_id_cache: OnceLock::new(),
            sender_nonce_cache: OnceLock::new(),
            recip_nonce_cache: OnceLock::new(),
            protection_alg_oid_cache: OnceLock::new(),
            message_time_cache: OnceLock::new(),
        })
    }

    /// Return the DER encoding of this ``PKIMessage``.
    fn to_der<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        Ok(PyBytes::new(py, &self.msg()?.to_der().map_err(SyntaErr)?))
    }

    /// CMP protocol version number (``pvno`` field; ``2`` for CMP v2/v3).
    #[getter]
    fn pvno(&self) -> PyResult<i64> {
        if let Some(v) = self.pvno_cache.get() {
            return Ok(*v);
        }
        let v = self.msg()?.header.pvno.as_i64().unwrap_or(2);
        let _ = self.pvno_cache.set(v);
        Ok(v)
    }

    /// Name of the active ``PKIBody`` arm in lowercase (e.g. ``"ir"``, ``"ip"``,
    /// ``"cr"``, ``"cp"``, ``"rr"``, ``"rp"``, ``"pkiconf"``).
    #[getter]
    fn body_type(&self) -> PyResult<&'static str> {
        if let Some(v) = self.body_type_cache.get() {
            return Ok(v);
        }
        let name = body_type_name(&self.msg()?.body);
        let _ = self.body_type_cache.set(name);
        Ok(name)
    }

    /// Raw DER bytes of the ``PKIBody`` content, or ``None`` for ``pkiconf``
    /// (which carries a NULL value and has no further content to decode).
    ///
    /// For ``"ir"``, ``"cr"`` etc., these bytes are a ``CertReqMessages``
    /// SEQUENCE OF that can be decoded with ``synta.crmf.CertReqMessages.from_der``.
    #[getter]
    fn body_der<'py>(&self, py: Python<'py>) -> PyResult<Option<Bound<'py, PyBytes>>> {
        if let Some(cached) = self.body_der_cache.get() {
            return Ok(cached.as_ref().map(|b| b.clone_ref(py).into_bound(py)));
        }
        let der = body_raw_der(&self.msg()?.body);
        let py_opt = der
            .as_deref()
            .map(|b| PyBytes::new(py, b).as_unbound().clone_ref(py));
        let _ = self.body_der_cache.set(py_opt);
        Ok(self
            .body_der_cache
            .get()
            .unwrap()
            .as_ref()
            .map(|b| b.clone_ref(py).into_bound(py)))
    }

    /// Raw DER bytes of the ``sender`` ``GeneralName`` field.
    #[getter]
    fn sender_der<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        if let Some(c) = self.sender_der_cache.get() {
            return Ok(c.clone_ref(py).into_bound(py));
        }
        let der = self.msg()?.header.sender.to_der().map_err(SyntaErr)?;
        let b = PyBytes::new(py, &der);
        let _ = self.sender_der_cache.set(b.as_unbound().clone_ref(py));
        Ok(b)
    }

    /// Raw DER bytes of the ``recipient`` ``GeneralName`` field.
    #[getter]
    fn recipient_der<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        if let Some(c) = self.recipient_der_cache.get() {
            return Ok(c.clone_ref(py).into_bound(py));
        }
        let der = self.msg()?.header.recipient.to_der().map_err(SyntaErr)?;
        let b = PyBytes::new(py, &der);
        let _ = self.recipient_der_cache.set(b.as_unbound().clone_ref(py));
        Ok(b)
    }

    /// ``transactionID`` bytes, or ``None`` if not present.
    #[getter]
    fn transaction_id<'py>(&self, py: Python<'py>) -> PyResult<Option<Bound<'py, PyBytes>>> {
        if let Some(cached) = self.transaction_id_cache.get() {
            return Ok(cached.as_ref().map(|b| b.clone_ref(py).into_bound(py)));
        }
        let opt = self
            .msg()?
            .header
            .transaction_id
            .as_ref()
            .map(|o| PyBytes::new(py, o.as_bytes()).as_unbound().clone_ref(py));
        let _ = self.transaction_id_cache.set(opt);
        Ok(self
            .transaction_id_cache
            .get()
            .unwrap()
            .as_ref()
            .map(|b| b.clone_ref(py).into_bound(py)))
    }

    /// ``senderNonce`` bytes, or ``None`` if not present.
    #[getter]
    fn sender_nonce<'py>(&self, py: Python<'py>) -> PyResult<Option<Bound<'py, PyBytes>>> {
        if let Some(cached) = self.sender_nonce_cache.get() {
            return Ok(cached.as_ref().map(|b| b.clone_ref(py).into_bound(py)));
        }
        let opt = self
            .msg()?
            .header
            .sender_nonce
            .as_ref()
            .map(|o| PyBytes::new(py, o.as_bytes()).as_unbound().clone_ref(py));
        let _ = self.sender_nonce_cache.set(opt);
        Ok(self
            .sender_nonce_cache
            .get()
            .unwrap()
            .as_ref()
            .map(|b| b.clone_ref(py).into_bound(py)))
    }

    /// ``recipNonce`` bytes, or ``None`` if not present.
    #[getter]
    fn recip_nonce<'py>(&self, py: Python<'py>) -> PyResult<Option<Bound<'py, PyBytes>>> {
        if let Some(cached) = self.recip_nonce_cache.get() {
            return Ok(cached.as_ref().map(|b| b.clone_ref(py).into_bound(py)));
        }
        let opt = self
            .msg()?
            .header
            .recip_nonce
            .as_ref()
            .map(|o| PyBytes::new(py, o.as_bytes()).as_unbound().clone_ref(py));
        let _ = self.recip_nonce_cache.set(opt);
        Ok(self
            .recip_nonce_cache
            .get()
            .unwrap()
            .as_ref()
            .map(|b| b.clone_ref(py).into_bound(py)))
    }

    /// OID of the ``protectionAlg`` ``AlgorithmIdentifier``, or ``None``.
    #[getter]
    fn protection_alg_oid(&self, py: Python<'_>) -> PyResult<Option<Py<PyObjectIdentifier>>> {
        if let Some(cached) = self.protection_alg_oid_cache.get() {
            return Ok(cached.as_ref().map(|o| o.clone_ref(py)));
        }
        let opt = self
            .msg()?
            .header
            .protection_alg
            .as_ref()
            .map(|alg| Py::new(py, PyObjectIdentifier::from_oid(alg.algorithm.clone())))
            .transpose()?;
        let _ = self
            .protection_alg_oid_cache
            .set(opt.as_ref().map(|o| o.clone_ref(py)));
        Ok(opt)
    }

    /// ``messageTime`` as a GeneralizedTime string, or ``None`` if not present.
    #[getter]
    fn message_time<'py>(&self, py: Python<'py>) -> PyResult<Option<Bound<'py, PyString>>> {
        if let Some(cached) = self.message_time_cache.get() {
            return Ok(cached.as_ref().map(|s| s.clone_ref(py).into_bound(py)));
        }
        let opt = self
            .msg()?
            .header
            .message_time
            .as_ref()
            .map(|t| PyString::new(py, &t.to_string()).as_unbound().clone_ref(py));
        let _ = self.message_time_cache.set(opt);
        Ok(self
            .message_time_cache
            .get()
            .unwrap()
            .as_ref()
            .map(|s| s.clone_ref(py).into_bound(py)))
    }

    fn __repr__(&self) -> PyResult<String> {
        Ok(format!(
            "CMPMessage(pvno={}, body_type={})",
            self.pvno()?,
            self.body_type()?,
        ))
    }
}

// ── PyCMPMessageBuilder ───────────────────────────────────────────────────────

/// Fluent builder for a CMP ``PKIMessage`` (RFC 9810 / RFC 4210).
///
/// Set sender, recipient, optional nonces, and a body payload, then call
/// :meth:`build` to produce a :class:`CMPMessage`.
///
/// ```python,ignore
/// import synta.cmp as cmp
///
/// msg = (
///     cmp.CMPMessageBuilder()
///     .sender_rfc822("ca@example.com")
///     .recipient_directory_name(subject_der)
///     .transaction_id(b"\x01\x02\x03\x04")
///     .body_pkiconf()
///     .build()
/// )
/// print(msg.pvno, msg.body_type)
/// ```
#[pyclass(name = "CMPMessageBuilder")]
pub struct PyCMPMessageBuilder {
    pvno: i64,
    sender: Option<synta_certificate::GeneralNameSpec>,
    recipient: Option<synta_certificate::GeneralNameSpec>,
    transaction_id: Option<Vec<u8>>,
    sender_nonce: Option<Vec<u8>>,
    recip_nonce: Option<Vec<u8>>,
    /// Body type tag: 0=pkiconf, 1=ir, 2=cr, 3=kur, 4=p10cr, 5=genm
    body_tag: u8,
    body_der: Option<Vec<u8>>,
}

#[pymethods]
impl PyCMPMessageBuilder {
    /// Create a new ``CMPMessageBuilder`` with default ``pvno=2`` (cmp2000) and no body.
    #[new]
    fn new() -> Self {
        Self {
            pvno: 2,
            sender: None,
            recipient: None,
            transaction_id: None,
            sender_nonce: None,
            recip_nonce: None,
            body_tag: 0,
            body_der: None,
        }
    }

    /// Set the ``pvno`` version integer (``2`` = cmp2000, ``3`` = cmp2021).
    fn pvno<'py>(slf: Bound<'py, Self>, pvno: i64) -> Bound<'py, Self> {
        slf.borrow_mut().pvno = pvno;
        slf
    }

    /// Set the sender as an ``rfc822Name`` (e-mail address).
    fn sender_rfc822<'py>(slf: Bound<'py, Self>, email: &str) -> Bound<'py, Self> {
        slf.borrow_mut().sender = Some(synta_certificate::GeneralNameSpec::rfc822(email));
        slf
    }

    /// Set the sender as a ``dNSName`` (DNS host name).
    fn sender_dns<'py>(slf: Bound<'py, Self>, host: &str) -> Bound<'py, Self> {
        slf.borrow_mut().sender = Some(synta_certificate::GeneralNameSpec::dns(host));
        slf
    }

    /// Set the sender as a ``directoryName`` from a DER-encoded ``Name`` SEQUENCE TLV.
    ///
    /// Pass the output of :class:`synta.NameBuilder` or a certificate's
    /// ``subject_raw_der`` bytes.
    fn sender_directory_name<'py>(slf: Bound<'py, Self>, name_der: &[u8]) -> Bound<'py, Self> {
        slf.borrow_mut().sender =
            Some(synta_certificate::GeneralNameSpec::directory_name(name_der));
        slf
    }

    /// Set the sender as a ``uniformResourceIdentifier`` (URI).
    fn sender_uri<'py>(slf: Bound<'py, Self>, uri: &str) -> Bound<'py, Self> {
        slf.borrow_mut().sender = Some(synta_certificate::GeneralNameSpec::uri(uri));
        slf
    }

    /// Set the recipient as an ``rfc822Name`` (e-mail address).
    fn recipient_rfc822<'py>(slf: Bound<'py, Self>, email: &str) -> Bound<'py, Self> {
        slf.borrow_mut().recipient = Some(synta_certificate::GeneralNameSpec::rfc822(email));
        slf
    }

    /// Set the recipient as a ``dNSName`` (DNS host name).
    fn recipient_dns<'py>(slf: Bound<'py, Self>, host: &str) -> Bound<'py, Self> {
        slf.borrow_mut().recipient = Some(synta_certificate::GeneralNameSpec::dns(host));
        slf
    }

    /// Set the recipient as a ``uniformResourceIdentifier`` (URI).
    fn recipient_uri<'py>(slf: Bound<'py, Self>, uri: &str) -> Bound<'py, Self> {
        slf.borrow_mut().recipient = Some(synta_certificate::GeneralNameSpec::uri(uri));
        slf
    }

    /// Set the recipient as a ``directoryName`` from a DER-encoded ``Name`` SEQUENCE TLV.
    fn recipient_directory_name<'py>(slf: Bound<'py, Self>, name_der: &[u8]) -> Bound<'py, Self> {
        slf.borrow_mut().recipient =
            Some(synta_certificate::GeneralNameSpec::directory_name(name_der));
        slf
    }

    /// Set the ``transactionID`` from raw OCTET STRING value bytes.
    fn transaction_id<'py>(slf: Bound<'py, Self>, bytes: &[u8]) -> Bound<'py, Self> {
        slf.borrow_mut().transaction_id = Some(bytes.to_vec());
        slf
    }

    /// Set the ``senderNonce`` from raw OCTET STRING value bytes.
    fn sender_nonce<'py>(slf: Bound<'py, Self>, bytes: &[u8]) -> Bound<'py, Self> {
        slf.borrow_mut().sender_nonce = Some(bytes.to_vec());
        slf
    }

    /// Set the ``recipNonce`` from raw OCTET STRING value bytes.
    fn recip_nonce<'py>(slf: Bound<'py, Self>, bytes: &[u8]) -> Bound<'py, Self> {
        slf.borrow_mut().recip_nonce = Some(bytes.to_vec());
        slf
    }

    /// Set the body to ``pkiConf [19]`` (confirmation, no content).
    fn body_pkiconf<'py>(slf: Bound<'py, Self>) -> Bound<'py, Self> {
        let mut b = slf.borrow_mut();
        b.body_tag = 0;
        b.body_der = None;
        drop(b);
        slf
    }

    /// Set the body to ``ir [0]`` (Initialization Request) from DER-encoded
    /// ``CertReqMessages`` bytes.
    fn body_ir<'py>(slf: Bound<'py, Self>, cert_req_messages_der: &[u8]) -> Bound<'py, Self> {
        let mut b = slf.borrow_mut();
        b.body_tag = 1;
        b.body_der = Some(cert_req_messages_der.to_vec());
        drop(b);
        slf
    }

    /// Set the body to ``cr [2]`` (Certification Request) from DER-encoded
    /// ``CertReqMessages`` bytes.
    fn body_cr<'py>(slf: Bound<'py, Self>, cert_req_messages_der: &[u8]) -> Bound<'py, Self> {
        let mut b = slf.borrow_mut();
        b.body_tag = 2;
        b.body_der = Some(cert_req_messages_der.to_vec());
        drop(b);
        slf
    }

    /// Set the body to ``kur [7]`` (Key Update Request) from DER-encoded
    /// ``CertReqMessages`` bytes.
    fn body_kur<'py>(slf: Bound<'py, Self>, cert_req_messages_der: &[u8]) -> Bound<'py, Self> {
        let mut b = slf.borrow_mut();
        b.body_tag = 3;
        b.body_der = Some(cert_req_messages_der.to_vec());
        drop(b);
        slf
    }

    /// Set the body to ``p10cr [4]`` (PKCS #10 Certification Request) from
    /// DER-encoded CSR bytes.
    fn body_p10cr<'py>(slf: Bound<'py, Self>, csr_der: &[u8]) -> Bound<'py, Self> {
        let mut b = slf.borrow_mut();
        b.body_tag = 4;
        b.body_der = Some(csr_der.to_vec());
        drop(b);
        slf
    }

    /// Set the body to ``genm [21]`` (General Message) from DER-encoded
    /// ``GenMsgContent`` bytes.
    fn body_genm<'py>(slf: Bound<'py, Self>, gen_msg_der: &[u8]) -> Bound<'py, Self> {
        let mut b = slf.borrow_mut();
        b.body_tag = 5;
        b.body_der = Some(gen_msg_der.to_vec());
        drop(b);
        slf
    }

    /// Build the :class:`CMPMessage`.
    ///
    /// :raises ValueError: if sender or recipient are not set, or if any
    ///     ``GeneralName`` data is invalid.
    fn build(&self, py: Python<'_>) -> PyResult<PyCMPMessage> {
        use pyo3::exceptions::PyValueError;
        use synta_certificate::CMPMessageBuilder;

        let sender_spec = self
            .sender
            .clone()
            .ok_or_else(|| PyValueError::new_err("sender is required"))?;
        let recipient_spec = self
            .recipient
            .clone()
            .ok_or_else(|| PyValueError::new_err("recipient is required"))?;

        let mut rust_builder = CMPMessageBuilder::new()
            .pvno(self.pvno)
            .sender(sender_spec)
            .recipient(recipient_spec);

        if let Some(ref b) = self.transaction_id {
            rust_builder = rust_builder.transaction_id(b);
        }
        if let Some(ref b) = self.sender_nonce {
            rust_builder = rust_builder.sender_nonce(b);
        }
        if let Some(ref b) = self.recip_nonce {
            rust_builder = rust_builder.recip_nonce(b);
        }

        match self.body_tag {
            0 => {
                rust_builder = rust_builder.body_pkiconf();
            }
            1 => {
                rust_builder = rust_builder.body_ir(self.body_der.as_deref().unwrap_or(&[]));
            }
            2 => {
                rust_builder = rust_builder.body_cr(self.body_der.as_deref().unwrap_or(&[]));
            }
            3 => {
                rust_builder = rust_builder.body_kur(self.body_der.as_deref().unwrap_or(&[]));
            }
            4 => {
                rust_builder = rust_builder.body_p10cr(self.body_der.as_deref().unwrap_or(&[]));
            }
            5 => {
                rust_builder = rust_builder.body_genm(self.body_der.as_deref().unwrap_or(&[]));
            }
            _ => {}
        }

        let der = rust_builder
            .build()
            .map_err(|e| PyValueError::new_err(e.to_string()))?;

        let py_bytes = PyBytes::new(py, &der).unbind();
        let raw: &'static [u8] = unsafe {
            let s = py_bytes.bind(py).as_bytes();
            std::slice::from_raw_parts(s.as_ptr(), s.len())
        };
        Ok(PyCMPMessage {
            _data: py_bytes,
            raw,
            inner: OnceLock::new(),
            pvno_cache: OnceLock::new(),
            body_type_cache: OnceLock::new(),
            body_der_cache: OnceLock::new(),
            sender_der_cache: OnceLock::new(),
            recipient_der_cache: OnceLock::new(),
            transaction_id_cache: OnceLock::new(),
            sender_nonce_cache: OnceLock::new(),
            recip_nonce_cache: OnceLock::new(),
            protection_alg_oid_cache: OnceLock::new(),
            message_time_cache: OnceLock::new(),
        })
    }

    fn __repr__(&self) -> String {
        use synta_certificate::GeneralNameSpec;
        let sender = match &self.sender {
            None => "None".to_string(),
            Some(GeneralNameSpec::Rfc822(s)) => format!("rfc822:{s}"),
            Some(GeneralNameSpec::Dns(s)) => format!("dns:{s}"),
            Some(GeneralNameSpec::Uri(s)) => format!("uri:{s}"),
            Some(GeneralNameSpec::DirectoryName(_)) => "directoryName".to_string(),
            Some(GeneralNameSpec::IpAddress(_)) => "iPAddress".to_string(),
            Some(GeneralNameSpec::RegisteredId(oid)) => format!("registeredID:{oid}"),
        };
        format!("CMPMessageBuilder(pvno={}, sender={})", self.pvno, sender)
    }
}

// ── register_cmp_submodule ────────────────────────────────────────────────────

/// Build and register the ``synta.cmp`` submodule.
pub(super) fn register_cmp_submodule(parent: &Bound<'_, PyModule>) -> PyResult<()> {
    let py = parent.py();
    let m = PyModule::new(py, "cmp")?;

    m.add_class::<PyCMPMessage>()?;
    m.add_class::<PyCMPMessageBuilder>()?;

    // ── MAC algorithm OIDs (RFC 9810 Appendix D) ─────────────────────────────
    m.add(
        "ID_PASSWORD_BASED_MAC",
        super::oid_const(py, synta_certificate::cmp_types::ID_PASSWORD_BASED_MAC),
    )?;
    m.add(
        "ID_DHBASED_MAC",
        super::oid_const(py, synta_certificate::cmp_types::ID_DHBASED_MAC),
    )?;
    m.add(
        "ID_KEM_BASED_MAC",
        super::oid_const(py, synta_certificate::cmp_types::ID_KEM_BASED_MAC),
    )?;

    // ── CMP key-purpose OID (RFC 9810 §4) ────────────────────────────────────
    m.add(
        "ID_KP_CM_KGA",
        super::oid_const(py, synta_certificate::cmp_types::ID_KP_CM_KGA),
    )?;

    // ── CMP registration-control OIDs shared with CRMF (RFC 9810 Appendix) ──
    m.add(
        "ID_REG_CTRL_ALT_CERT_TEMPLATE",
        super::oid_const(
            py,
            synta_certificate::cmp_types::ID_REG_CTRL_ALT_CERT_TEMPLATE,
        ),
    )?;
    m.add(
        "ID_REG_CTRL_ALG_ID",
        super::oid_const(py, synta_certificate::cmp_types::ID_REG_CTRL_ALG_ID),
    )?;
    m.add(
        "ID_REG_CTRL_RSA_KEY_LEN",
        super::oid_const(py, synta_certificate::cmp_types::ID_REG_CTRL_RSA_KEY_LEN),
    )?;

    crate::install_submodule(
        parent,
        &m,
        "synta.cmp",
        Some(concat!(
            "synta.cmp — RFC 9810 Certificate Management Protocol v3 types.\n\n",
            "Provides CMPMessage (wrapping PKIMessage) for decoding CMP\n",
            "envelopes.  body_type names the active PKIBody arm; body_der\n",
            "returns the raw bytes for further decoding with synta.crmf or\n",
            "a synta.Decoder.  Also exposes MAC algorithm and key-purpose\n",
            "OID constants.",
        )),
    )
}