synta-python 0.1.4

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
//! Python bindings for PKINIT types (RFC 4556 + RFC 6112 + RFC 8636).
//!
//! Exposes the ASN.1 structures used in PKINIT AS exchanges as frozen
//! Python classes under the ``synta.krb5`` namespace.
//!
//! # Classes
//!
//! | Rust type                       | Python name                   | RFC / section   |
//! |---------------------------------|-------------------------------|-----------------|
//! | [`PyEncryptionKey`]             | `EncryptionKey`               | RFC 3961 §2     |
//! | [`PyChecksum`]                  | `Checksum`                    | RFC 3961 §4     |
//! | [`PyKDFAlgorithmId`]            | `KDFAlgorithmId`              | RFC 8636 §3.1   |
//! | [`PyIssuerAndSerialNumber`]     | `IssuerAndSerialNumber`       | RFC 4556 §3.2.2 |
//! | [`PyExternalPrincipalIdentifier`]| `ExternalPrincipalIdentifier`| RFC 4556 §3.2.2 |
//! | [`PyPKAuthenticator`]           | `PKAuthenticator`             | RFC 4556 §3.2.1 |
//! | [`PyAuthPack`]                  | `AuthPack`                    | RFC 4556 §3.2.1 |
//! | [`PyPaPkAsReq`]                 | `PaPkAsReq`                   | RFC 4556 §3.2.2 |
//! | [`PyDHRepInfo`]                 | `DHRepInfo`                   | RFC 4556 §3.2.4 |
//! | [`PyKDCDHKeyInfo`]              | `KDCDHKeyInfo`                | RFC 4556 §3.2.4 |
//! | [`PyReplyKeyPack`]              | `ReplyKeyPack`                | RFC 4556 §3.2.3 |
//! | [`PyPaPkAsRep`]                 | `PaPkAsRep`                   | RFC 4556 §3.2.4 |
//!
//! Call [`register_pkinit_classes`] from
//! ``synta_python::krb5::register_krb5_module`` to install the classes.

use pyo3::exceptions::PyOverflowError;
use pyo3::prelude::*;
use pyo3::types::{PyBytes, PyList};

use crate::error::SyntaErr;
use crate::types::PyObjectIdentifier;
use synta::traits::Encode;
use synta::{Decoder, Encoding, ObjectIdentifier};

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

/// Re-encode a synta `Element<'_>` to owned DER bytes.
fn encode_element_to_vec(elem: &synta::Element<'_>) -> PyResult<Vec<u8>> {
    let mut encoder = synta::Encoder::new(Encoding::Der);
    elem.encode(&mut encoder).map_err(SyntaErr)?;
    Ok(encoder.finish().map_err(SyntaErr)?)
}

// ── Leaf classes (no nested pyclass fields) ───────────────────────────────────

/// Kerberos EncryptionKey — RFC 3961 §2 / RFC 4556
///
/// Contains the encryption algorithm type identifier and the raw key material.
///
/// ```python
/// key = synta.krb5.EncryptionKey.from_der(der_bytes)
/// print(key.keytype, key.keyvalue.hex())
/// ```
#[pyclass(frozen, name = "EncryptionKey")]
pub struct PyEncryptionKey {
    keytype: i64,
    keyvalue: Vec<u8>,
}

#[pymethods]
impl PyEncryptionKey {
    /// Parse a DER-encoded EncryptionKey SEQUENCE.
    #[staticmethod]
    fn from_der(data: &[u8]) -> PyResult<Self> {
        let mut dec = Decoder::new(data, Encoding::Der);
        let parsed: synta_krb5::pkinit::EncryptionKey<'_> = dec.decode().map_err(SyntaErr)?;
        Ok(Self {
            keytype: parsed
                .keytype
                .as_i64()
                .map_err(|_| PyOverflowError::new_err("keytype out of i64 range"))?,
            keyvalue: parsed.keyvalue.as_bytes().to_vec(),
        })
    }

    /// Kerberos encryption type number (RFC 3961 Table 1).
    #[getter]
    fn keytype(&self) -> i64 {
        self.keytype
    }

    /// Raw key material bytes.
    #[getter]
    fn keyvalue<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        PyBytes::new(py, &self.keyvalue)
    }

    fn __repr__(&self) -> String {
        format!(
            "EncryptionKey(keytype={}, keyvalue=<{} bytes>)",
            self.keytype,
            self.keyvalue.len()
        )
    }
}

/// Kerberos Checksum — RFC 3961 §4 / RFC 4556
///
/// Contains the checksum algorithm type identifier and the raw checksum value.
///
/// ```python
/// ck = synta.krb5.Checksum.from_der(der_bytes)
/// print(ck.cksumtype, ck.checksum.hex())
/// ```
#[pyclass(frozen, name = "Checksum")]
pub struct PyChecksum {
    cksumtype: i64,
    checksum: Vec<u8>,
}

#[pymethods]
impl PyChecksum {
    /// Parse a DER-encoded Checksum SEQUENCE.
    #[staticmethod]
    fn from_der(data: &[u8]) -> PyResult<Self> {
        let mut dec = Decoder::new(data, Encoding::Der);
        let parsed: synta_krb5::pkinit::Checksum<'_> = dec.decode().map_err(SyntaErr)?;
        Ok(Self {
            cksumtype: parsed
                .cksumtype
                .as_i64()
                .map_err(|_| PyOverflowError::new_err("cksumtype out of i64 range"))?,
            checksum: parsed.checksum.as_bytes().to_vec(),
        })
    }

    /// Kerberos checksum type number.
    #[getter]
    fn cksumtype(&self) -> i64 {
        self.cksumtype
    }

    /// Raw checksum bytes.
    #[getter]
    fn checksum<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        PyBytes::new(py, &self.checksum)
    }

    fn __repr__(&self) -> String {
        format!(
            "Checksum(cksumtype={}, checksum=<{} bytes>)",
            self.cksumtype,
            self.checksum.len()
        )
    }
}

/// PKINIT KDF algorithm identifier — RFC 8636 §3.1
///
/// Identifies the key-derivation function used in a PKINIT exchange.
///
/// ```python
/// kdf = synta.krb5.KDFAlgorithmId.from_der(der_bytes)
/// print(kdf.kdf_id)   # ObjectIdentifier("1.3.6.1.5.2.3.6.2")
/// ```
#[pyclass(frozen, name = "KDFAlgorithmId")]
pub struct PyKDFAlgorithmId {
    kdf_id: ObjectIdentifier,
}

#[pymethods]
impl PyKDFAlgorithmId {
    /// Parse a DER-encoded KDFAlgorithmId SEQUENCE.
    #[staticmethod]
    fn from_der(data: &[u8]) -> PyResult<Self> {
        let mut dec = Decoder::new(data, Encoding::Der);
        let parsed: synta_krb5::pkinit::KDFAlgorithmId = dec.decode().map_err(SyntaErr)?;
        Ok(Self {
            kdf_id: parsed.kdf_id,
        })
    }

    /// Key-derivation function OID.
    #[getter]
    fn kdf_id(&self, py: Python<'_>) -> PyResult<Py<PyObjectIdentifier>> {
        Py::new(py, PyObjectIdentifier::from_oid(self.kdf_id.clone()))
    }

    fn __repr__(&self) -> String {
        format!("KDFAlgorithmId(kdf_id='{}')", self.kdf_id)
    }
}

/// PKINIT IssuerAndSerialNumber — RFC 4556 §3.2.2
///
/// Identifies a certificate by its issuer Name and serial number.
///
/// ```python
/// isn = synta.krb5.IssuerAndSerialNumber.from_der(der_bytes)
/// print(isn.serial_number)
/// ```
#[pyclass(frozen, name = "IssuerAndSerialNumber")]
pub struct PyIssuerAndSerialNumber {
    issuer: Vec<u8>,
    serial_number_bytes: Vec<u8>,
}

#[pymethods]
impl PyIssuerAndSerialNumber {
    /// Parse a DER-encoded IssuerAndSerialNumber SEQUENCE.
    #[staticmethod]
    fn from_der(data: &[u8]) -> PyResult<Self> {
        let mut dec = Decoder::new(data, Encoding::Der);
        let parsed: synta_krb5::pkinit::IssuerAndSerialNumber<'_> =
            dec.decode().map_err(SyntaErr)?;
        Ok(Self {
            issuer: parsed.issuer.as_bytes().to_vec(),
            serial_number_bytes: parsed.serial_number.as_bytes().to_vec(),
        })
    }

    /// DER-encoded issuer Name bytes (raw Name SEQUENCE).
    #[getter]
    fn issuer<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        PyBytes::new(py, &self.issuer)
    }

    /// Certificate serial number as a Python :class:`int`.
    #[getter]
    fn serial_number<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
        let bytes_obj = PyBytes::new(py, &self.serial_number_bytes);
        let kwargs = pyo3::types::PyDict::new(py);
        kwargs.set_item(pyo3::intern!(py, "signed"), true)?;
        py.get_type::<pyo3::types::PyInt>().call_method(
            "from_bytes",
            (bytes_obj, "big"),
            Some(&kwargs),
        )
    }

    fn __repr__(&self) -> String {
        format!(
            "IssuerAndSerialNumber(issuer=<{} bytes>, serial=<{} bytes>)",
            self.issuer.len(),
            self.serial_number_bytes.len(),
        )
    }
}

/// PKINIT PKAuthenticator — RFC 4556 §3.2.1
///
/// The client's proof of liveness in a PKINIT AS-REQ.
///
/// ```python
/// auth = synta.krb5.PKAuthenticator.from_der(der_bytes)
/// print(auth.ctime, auth.nonce)
/// ```
#[pyclass(frozen, name = "PKAuthenticator")]
pub struct PyPKAuthenticator {
    cusec: i64,
    ctime: String,
    nonce: i64,
    pa_checksum: Option<Vec<u8>>,
    freshness_token: Option<Vec<u8>>,
}

#[pymethods]
impl PyPKAuthenticator {
    /// Parse a DER-encoded PKAuthenticator SEQUENCE.
    #[staticmethod]
    fn from_der(data: &[u8]) -> PyResult<Self> {
        let mut dec = Decoder::new(data, Encoding::Der);
        let parsed: synta_krb5::pkinit::PKAuthenticator<'_> = dec.decode().map_err(SyntaErr)?;
        Ok(Self {
            cusec: parsed
                .cusec
                .as_i64()
                .map_err(|_| PyOverflowError::new_err("cusec out of i64 range"))?,
            ctime: parsed.ctime.to_string(),
            nonce: parsed
                .nonce
                .as_i64()
                .map_err(|_| PyOverflowError::new_err("nonce out of i64 range"))?,
            pa_checksum: parsed.pa_checksum.map(|s| s.as_bytes().to_vec()),
            freshness_token: parsed.freshness_token.map(|s| s.as_bytes().to_vec()),
        })
    }

    /// Microsecond component of the client's current time (0–999 999).
    #[getter]
    fn cusec(&self) -> i64 {
        self.cusec
    }

    /// Client's current time as a string (``YYYYMMDDHHMMSSz``).
    #[getter]
    fn ctime(&self) -> &str {
        &self.ctime
    }

    /// Nonce preventing replay attacks.
    #[getter]
    fn nonce(&self) -> i64 {
        self.nonce
    }

    /// Optional SHA-1 checksum of the DER-encoded AS-REQ body, or ``None``.
    #[getter]
    fn pa_checksum<'py>(&self, py: Python<'py>) -> Option<Bound<'py, PyBytes>> {
        self.pa_checksum.as_deref().map(|b| PyBytes::new(py, b))
    }

    /// Optional freshness token from the KDC (RFC 8070), or ``None``.
    #[getter]
    fn freshness_token<'py>(&self, py: Python<'py>) -> Option<Bound<'py, PyBytes>> {
        self.freshness_token.as_deref().map(|b| PyBytes::new(py, b))
    }

    fn __repr__(&self) -> String {
        format!(
            "PKAuthenticator(ctime='{}', nonce={})",
            self.ctime, self.nonce
        )
    }
}

/// PKINIT DHRepInfo — RFC 4556 §3.2.4
///
/// Carries the KDC's Diffie-Hellman reply inside a PA-PK-AS-REP.
///
/// ```python
/// rep = synta.krb5.DHRepInfo.from_der(der_bytes)
/// print(len(rep.dh_signed_data))
/// ```
#[pyclass(frozen, name = "DHRepInfo")]
pub struct PyDHRepInfo {
    dh_signed_data: Vec<u8>,
    server_dhnonce: Option<Vec<u8>>,
}

#[pymethods]
impl PyDHRepInfo {
    /// Parse a DER-encoded DHRepInfo SEQUENCE.
    #[staticmethod]
    fn from_der(data: &[u8]) -> PyResult<Self> {
        let mut dec = Decoder::new(data, Encoding::Der);
        let parsed: synta_krb5::pkinit::DHRepInfo<'_> = dec.decode().map_err(SyntaErr)?;
        Ok(Self {
            dh_signed_data: parsed.dh_signed_data.as_bytes().to_vec(),
            server_dhnonce: parsed.server_dhnonce.map(|s| s.as_bytes().to_vec()),
        })
    }

    /// CMS SignedData containing the KDC's DH public key.
    #[getter]
    fn dh_signed_data<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        PyBytes::new(py, &self.dh_signed_data)
    }

    /// Optional server DH nonce, or ``None``.
    #[getter]
    fn server_dhnonce<'py>(&self, py: Python<'py>) -> Option<Bound<'py, PyBytes>> {
        self.server_dhnonce.as_deref().map(|b| PyBytes::new(py, b))
    }

    fn __repr__(&self) -> String {
        format!(
            "DHRepInfo(dh_signed_data=<{} bytes>)",
            self.dh_signed_data.len()
        )
    }
}

/// PKINIT KDCDHKeyInfo — RFC 4556 §3.2.4
///
/// The KDC's DH public key and associated PKINIT parameters.
///
/// ```python
/// info = synta.krb5.KDCDHKeyInfo.from_der(der_bytes)
/// print(info.nonce, info.subject_public_key.hex())
/// ```
#[pyclass(frozen, name = "KDCDHKeyInfo")]
pub struct PyKDCDHKeyInfo {
    subject_public_key: Vec<u8>,
    nonce: i64,
    dh_key_expiration: Option<String>,
}

#[pymethods]
impl PyKDCDHKeyInfo {
    /// Parse a DER-encoded KDCDHKeyInfo SEQUENCE.
    #[staticmethod]
    fn from_der(data: &[u8]) -> PyResult<Self> {
        let mut dec = Decoder::new(data, Encoding::Der);
        let parsed: synta_krb5::pkinit::KDCDHKeyInfo<'_> = dec.decode().map_err(SyntaErr)?;
        Ok(Self {
            subject_public_key: parsed.subject_public_key.as_bytes().to_vec(),
            nonce: parsed
                .nonce
                .as_i64()
                .map_err(|_| PyOverflowError::new_err("nonce out of i64 range"))?,
            dh_key_expiration: parsed.dh_key_expiration.map(|t| t.to_string()),
        })
    }

    /// KDC's DH public key as raw BIT STRING payload bytes.
    #[getter]
    fn subject_public_key<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        PyBytes::new(py, &self.subject_public_key)
    }

    /// Nonce echoed from the client's PA-PK-AS-REQ.
    #[getter]
    fn nonce(&self) -> i64 {
        self.nonce
    }

    /// Optional DH key expiration time as a string (``YYYYMMDDHHMMSSz``), or ``None``.
    #[getter]
    fn dh_key_expiration(&self) -> Option<&str> {
        self.dh_key_expiration.as_deref()
    }

    fn __repr__(&self) -> String {
        format!(
            "KDCDHKeyInfo(nonce={}, subject_public_key=<{} bytes>)",
            self.nonce,
            self.subject_public_key.len()
        )
    }
}

// ── Composite classes (contain nested pyclass fields) ─────────────────────────

/// PKINIT ExternalPrincipalIdentifier — RFC 4556 §3.2.2
///
/// Identifies a certificate by subject name, issuer/serial pair, or SKI.
/// All three fields are OPTIONAL; at least one SHOULD be present.
///
/// ```python
/// epi = synta.krb5.ExternalPrincipalIdentifier.from_der(der_bytes)
/// if epi.subject_key_identifier:
///     print(epi.subject_key_identifier.hex())
/// ```
#[pyclass(frozen, name = "ExternalPrincipalIdentifier")]
pub struct PyExternalPrincipalIdentifier {
    subject_name: Option<Vec<u8>>,
    issuer_and_serial_number: Option<Py<PyIssuerAndSerialNumber>>,
    subject_key_identifier: Option<Vec<u8>>,
}

#[pymethods]
impl PyExternalPrincipalIdentifier {
    /// Parse a DER-encoded ExternalPrincipalIdentifier SEQUENCE.
    #[staticmethod]
    fn from_der(py: Python<'_>, data: &[u8]) -> PyResult<Self> {
        let mut dec = Decoder::new(data, Encoding::Der);
        let parsed: synta_krb5::pkinit::ExternalPrincipalIdentifier<'_> =
            dec.decode().map_err(SyntaErr)?;
        let issuer_and_serial_number = parsed
            .issuer_and_serial_number
            .map(|isn| {
                Py::new(
                    py,
                    PyIssuerAndSerialNumber {
                        issuer: isn.issuer.as_bytes().to_vec(),
                        serial_number_bytes: isn.serial_number.as_bytes().to_vec(),
                    },
                )
            })
            .transpose()?;
        Ok(Self {
            subject_name: parsed.subject_name.map(|s| s.as_bytes().to_vec()),
            issuer_and_serial_number,
            subject_key_identifier: parsed.subject_key_identifier.map(|s| s.as_bytes().to_vec()),
        })
    }

    /// DER-encoded subject Name, or ``None``.
    #[getter]
    fn subject_name<'py>(&self, py: Python<'py>) -> Option<Bound<'py, PyBytes>> {
        self.subject_name.as_deref().map(|b| PyBytes::new(py, b))
    }

    /// :class:`IssuerAndSerialNumber` identifying the certificate, or ``None``.
    #[getter]
    fn issuer_and_serial_number<'py>(
        &self,
        py: Python<'py>,
    ) -> Option<Bound<'py, PyIssuerAndSerialNumber>> {
        self.issuer_and_serial_number
            .as_ref()
            .map(|x| x.clone_ref(py).into_bound(py))
    }

    /// Subject key identifier bytes, or ``None``.
    #[getter]
    fn subject_key_identifier<'py>(&self, py: Python<'py>) -> Option<Bound<'py, PyBytes>> {
        self.subject_key_identifier
            .as_deref()
            .map(|b| PyBytes::new(py, b))
    }
}

/// PKINIT ReplyKeyPack — RFC 4556 §3.2.3
///
/// The session key and checksum sent by the KDC to an authenticated client.
///
/// ```python
/// pack = synta.krb5.ReplyKeyPack.from_der(der_bytes)
/// print(pack.reply_key.keytype)
/// ```
#[pyclass(frozen, name = "ReplyKeyPack")]
pub struct PyReplyKeyPack {
    reply_key: Py<PyEncryptionKey>,
    as_checksum: Py<PyChecksum>,
}

#[pymethods]
impl PyReplyKeyPack {
    /// Parse a DER-encoded ReplyKeyPack SEQUENCE.
    #[staticmethod]
    fn from_der(py: Python<'_>, data: &[u8]) -> PyResult<Self> {
        let mut dec = Decoder::new(data, Encoding::Der);
        let parsed: synta_krb5::pkinit::ReplyKeyPack<'_> = dec.decode().map_err(SyntaErr)?;
        let reply_key = Py::new(
            py,
            PyEncryptionKey {
                keytype: parsed
                    .reply_key
                    .keytype
                    .as_i64()
                    .map_err(|_| PyOverflowError::new_err("keytype out of i64 range"))?,
                keyvalue: parsed.reply_key.keyvalue.as_bytes().to_vec(),
            },
        )?;
        let as_checksum = Py::new(
            py,
            PyChecksum {
                cksumtype: parsed
                    .as_checksum
                    .cksumtype
                    .as_i64()
                    .map_err(|_| PyOverflowError::new_err("cksumtype out of i64 range"))?,
                checksum: parsed.as_checksum.checksum.as_bytes().to_vec(),
            },
        )?;
        Ok(Self {
            reply_key,
            as_checksum,
        })
    }

    /// The session key returned by the KDC.
    #[getter]
    fn reply_key<'py>(&self, py: Python<'py>) -> Bound<'py, PyEncryptionKey> {
        self.reply_key.clone_ref(py).into_bound(py)
    }

    /// The AS-REQ checksum authenticating the exchange.
    #[getter]
    fn as_checksum<'py>(&self, py: Python<'py>) -> Bound<'py, PyChecksum> {
        self.as_checksum.clone_ref(py).into_bound(py)
    }

    fn __repr__(&self) -> String {
        String::from("ReplyKeyPack(...)")
    }
}

/// PKINIT PA-PK-AS-REP — RFC 4556 §3.2.4
///
/// CHOICE: DH-based reply (``DhInfo``) or RSA-encrypted reply (``EncKeyPack``).
///
/// ```python
/// rep = synta.krb5.PaPkAsRep.from_der(der_bytes)
/// if rep.variant == "DhInfo":
///     print(len(rep.dh_info.dh_signed_data))
/// else:
///     print(rep.enc_key_pack.hex())
/// ```
#[pyclass(frozen, name = "PaPkAsRep")]
pub struct PyPaPkAsRep {
    variant: &'static str,
    dh_info: Option<Py<PyDHRepInfo>>,
    enc_key_pack: Option<Vec<u8>>,
}

#[pymethods]
impl PyPaPkAsRep {
    /// Parse a DER-encoded PA-PK-AS-REP CHOICE.
    #[staticmethod]
    fn from_der(py: Python<'_>, data: &[u8]) -> PyResult<Self> {
        let mut dec = Decoder::new(data, Encoding::Der);
        let parsed: synta_krb5::pkinit::PaPkAsRep<'_> = dec.decode().map_err(SyntaErr)?;
        match parsed {
            synta_krb5::pkinit::PaPkAsRep::DhInfo(dh) => {
                let dh_info = Py::new(
                    py,
                    PyDHRepInfo {
                        dh_signed_data: dh.dh_signed_data.as_bytes().to_vec(),
                        server_dhnonce: dh.server_dhnonce.map(|s| s.as_bytes().to_vec()),
                    },
                )?;
                Ok(Self {
                    variant: "DhInfo",
                    dh_info: Some(dh_info),
                    enc_key_pack: None,
                })
            }
            synta_krb5::pkinit::PaPkAsRep::EncKeyPack(pack) => Ok(Self {
                variant: "EncKeyPack",
                dh_info: None,
                enc_key_pack: Some(pack.as_bytes().to_vec()),
            }),
        }
    }

    /// Active CHOICE variant: ``"DhInfo"`` or ``"EncKeyPack"``.
    #[getter]
    fn variant(&self) -> &'static str {
        self.variant
    }

    /// :class:`DHRepInfo` when the variant is ``"DhInfo"``, else ``None``.
    #[getter]
    fn dh_info<'py>(&self, py: Python<'py>) -> Option<Bound<'py, PyDHRepInfo>> {
        self.dh_info
            .as_ref()
            .map(|x| x.clone_ref(py).into_bound(py))
    }

    /// CMS EnvelopedData bytes when the variant is ``"EncKeyPack"``, else ``None``.
    #[getter]
    fn enc_key_pack<'py>(&self, py: Python<'py>) -> Option<Bound<'py, PyBytes>> {
        self.enc_key_pack.as_deref().map(|b| PyBytes::new(py, b))
    }

    fn __repr__(&self) -> String {
        format!("PaPkAsRep(variant='{}')", self.variant)
    }
}

/// PKINIT AuthPack — RFC 4556 §3.2.1
///
/// The client's signed authentication package, embedded in a PA-PK-AS-REQ.
///
/// ```python
/// pack = synta.krb5.AuthPack.from_der(der_bytes)
/// print(pack.pk_authenticator.nonce)
/// ```
#[pyclass(frozen, name = "AuthPack")]
pub struct PyAuthPack {
    pk_authenticator: Py<PyPKAuthenticator>,
    client_public_value: Option<Vec<u8>>,
    supported_cmstypes: Option<Vec<u8>>,
    client_dhnonce: Option<Vec<u8>>,
    supported_kdfs: Option<Vec<Py<PyKDFAlgorithmId>>>,
}

#[pymethods]
impl PyAuthPack {
    /// Parse a DER-encoded AuthPack SEQUENCE.
    #[staticmethod]
    fn from_der(py: Python<'_>, data: &[u8]) -> PyResult<Self> {
        let mut dec = Decoder::new(data, Encoding::Der);
        let parsed: synta_krb5::pkinit::AuthPack<'_> = dec.decode().map_err(SyntaErr)?;
        let pka = parsed.pk_authenticator;
        let pk_authenticator = Py::new(
            py,
            PyPKAuthenticator {
                cusec: pka
                    .cusec
                    .as_i64()
                    .map_err(|_| PyOverflowError::new_err("cusec out of i64 range"))?,
                ctime: pka.ctime.to_string(),
                nonce: pka
                    .nonce
                    .as_i64()
                    .map_err(|_| PyOverflowError::new_err("nonce out of i64 range"))?,
                pa_checksum: pka.pa_checksum.map(|s| s.as_bytes().to_vec()),
                freshness_token: pka.freshness_token.map(|s| s.as_bytes().to_vec()),
            },
        )?;
        let client_public_value = parsed
            .client_public_value
            .as_ref()
            .map(encode_element_to_vec)
            .transpose()?;
        let supported_cmstypes = parsed
            .supported_cmstypes
            .as_ref()
            .map(encode_element_to_vec)
            .transpose()?;
        let client_dhnonce = parsed.client_dhnonce.map(|s| s.as_bytes().to_vec());
        let supported_kdfs = parsed
            .supported_kdfs
            .map(|kdfs| {
                kdfs.into_iter()
                    .map(|kdf| Py::new(py, PyKDFAlgorithmId { kdf_id: kdf.kdf_id }))
                    .collect::<PyResult<Vec<_>>>()
            })
            .transpose()?;
        Ok(Self {
            pk_authenticator,
            client_public_value,
            supported_cmstypes,
            client_dhnonce,
            supported_kdfs,
        })
    }

    /// :class:`PKAuthenticator` proving client liveness.
    #[getter]
    fn pk_authenticator<'py>(&self, py: Python<'py>) -> Bound<'py, PyPKAuthenticator> {
        self.pk_authenticator.clone_ref(py).into_bound(py)
    }

    /// DER-encoded client DH SubjectPublicKeyInfo, or ``None``.
    #[getter]
    fn client_public_value<'py>(&self, py: Python<'py>) -> Option<Bound<'py, PyBytes>> {
        self.client_public_value
            .as_deref()
            .map(|b| PyBytes::new(py, b))
    }

    /// DER-encoded supported CMS algorithm list, or ``None``.
    #[getter]
    fn supported_cmstypes<'py>(&self, py: Python<'py>) -> Option<Bound<'py, PyBytes>> {
        self.supported_cmstypes
            .as_deref()
            .map(|b| PyBytes::new(py, b))
    }

    /// Client DH nonce bytes, or ``None``.
    #[getter]
    fn client_dhnonce<'py>(&self, py: Python<'py>) -> Option<Bound<'py, PyBytes>> {
        self.client_dhnonce.as_deref().map(|b| PyBytes::new(py, b))
    }

    /// List of supported :class:`KDFAlgorithmId` entries, or ``None``.
    #[getter]
    fn supported_kdfs<'py>(&self, py: Python<'py>) -> PyResult<Option<Bound<'py, PyList>>> {
        self.supported_kdfs
            .as_ref()
            .map(|kdfs| {
                let list = PyList::empty(py);
                for kdf in kdfs {
                    list.append(kdf.clone_ref(py).into_bound(py))?;
                }
                Ok(list)
            })
            .transpose()
    }

    fn __repr__(&self) -> String {
        String::from("AuthPack(...)")
    }
}

/// PKINIT PA-PK-AS-REQ — RFC 4556 §3.2.2
///
/// Pre-authentication data sent by the client in the initial AS-REQ.
///
/// ```python
/// req = synta.krb5.PaPkAsReq.from_der(der_bytes)
/// print(len(req.signed_auth_pack))
/// ```
#[pyclass(frozen, name = "PaPkAsReq")]
pub struct PyPaPkAsReq {
    signed_auth_pack: Vec<u8>,
    trusted_certifiers: Option<Vec<Py<PyExternalPrincipalIdentifier>>>,
    kdc_pk_id: Option<Vec<u8>>,
}

#[pymethods]
impl PyPaPkAsReq {
    /// Parse a DER-encoded PA-PK-AS-REQ SEQUENCE.
    #[staticmethod]
    fn from_der(py: Python<'_>, data: &[u8]) -> PyResult<Self> {
        let mut dec = Decoder::new(data, Encoding::Der);
        let parsed: synta_krb5::pkinit::PaPkAsReq<'_> = dec.decode().map_err(SyntaErr)?;
        let signed_auth_pack = parsed.signed_auth_pack.as_bytes().to_vec();
        let trusted_certifiers = parsed
            .trusted_certifiers
            .map(|certs| {
                certs
                    .into_iter()
                    .map(|epi| {
                        let isn = epi
                            .issuer_and_serial_number
                            .map(|isn| {
                                Py::new(
                                    py,
                                    PyIssuerAndSerialNumber {
                                        issuer: isn.issuer.as_bytes().to_vec(),
                                        serial_number_bytes: isn.serial_number.as_bytes().to_vec(),
                                    },
                                )
                            })
                            .transpose()?;
                        Py::new(
                            py,
                            PyExternalPrincipalIdentifier {
                                subject_name: epi.subject_name.map(|s| s.as_bytes().to_vec()),
                                issuer_and_serial_number: isn,
                                subject_key_identifier: epi
                                    .subject_key_identifier
                                    .map(|s| s.as_bytes().to_vec()),
                            },
                        )
                    })
                    .collect::<PyResult<Vec<_>>>()
            })
            .transpose()?;
        let kdc_pk_id = parsed.kdc_pk_id.map(|s| s.as_bytes().to_vec());
        Ok(Self {
            signed_auth_pack,
            trusted_certifiers,
            kdc_pk_id,
        })
    }

    /// CMS SignedData wrapping the client's AuthPack.
    #[getter]
    fn signed_auth_pack<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        PyBytes::new(py, &self.signed_auth_pack)
    }

    /// List of :class:`ExternalPrincipalIdentifier` for acceptable KDC certs, or ``None``.
    #[getter]
    fn trusted_certifiers<'py>(&self, py: Python<'py>) -> PyResult<Option<Bound<'py, PyList>>> {
        self.trusted_certifiers
            .as_ref()
            .map(|certs| {
                let list = PyList::empty(py);
                for cert in certs {
                    list.append(cert.clone_ref(py).into_bound(py))?;
                }
                Ok(list)
            })
            .transpose()
    }

    /// Subject key identifier of the preferred KDC certificate, or ``None``.
    #[getter]
    fn kdc_pk_id<'py>(&self, py: Python<'py>) -> Option<Bound<'py, PyBytes>> {
        self.kdc_pk_id.as_deref().map(|b| PyBytes::new(py, b))
    }

    fn __repr__(&self) -> String {
        format!(
            "PaPkAsReq(signed_auth_pack=<{} bytes>)",
            self.signed_auth_pack.len()
        )
    }
}

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

/// Register all PKINIT Python classes into `m` (the ``synta.krb5`` submodule).
///
/// Called from ``synta_python::krb5::register_krb5_module``.
pub fn register_pkinit_classes(m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add_class::<PyEncryptionKey>()?;
    m.add_class::<PyChecksum>()?;
    m.add_class::<PyKDFAlgorithmId>()?;
    m.add_class::<PyIssuerAndSerialNumber>()?;
    m.add_class::<PyPKAuthenticator>()?;
    m.add_class::<PyDHRepInfo>()?;
    m.add_class::<PyKDCDHKeyInfo>()?;
    m.add_class::<PyExternalPrincipalIdentifier>()?;
    m.add_class::<PyReplyKeyPack>()?;
    m.add_class::<PyPaPkAsRep>()?;
    m.add_class::<PyAuthPack>()?;
    m.add_class::<PyPaPkAsReq>()?;
    Ok(())
}