synta-python-mtc 0.2.6

Python extension module for synta Merkle Tree Certificates types
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
use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
use pyo3::types::PyBytes;
use synta::traits::{Decode, Encode};

use super::proof::PyHashAlgorithm;
use synta_python_common::SyntaErr;

// ── ValidationPolicy ─────────────────────────────────────────────────────────

/// Validation policy for Merkle Tree Certificates.
///
/// Controls which hash algorithms are allowed, cosignature quorum requirements,
/// and other validation constraints.  Use :class:`CertificateValidator` to apply
/// a policy during certificate validation.
///
/// The default policy allows only SHA-256 and requires at least one cosignature.
/// Use :meth:`permissive` for testing (all hash algorithms, no cosignature
/// requirement).
///
/// ```python,ignore
/// import synta.mtc as mtc
///
/// policy = mtc.ValidationPolicy()
/// policy.allow_hash_algorithm(mtc.HashAlgorithm.Sha384)
/// policy.set_min_cosignatures(2)
/// ```
#[pyclass(name = "ValidationPolicy")]
pub struct PyValidationPolicy {
    /// Allowed hash algorithm OID strings (dotted-decimal).
    allowed_hash_algorithm_oids: Vec<String>,
    /// Minimum number of valid cosignatures required.
    min_cosignatures: usize,
    /// Maximum number of cosignatures allowed (DoS protection).
    max_cosignatures: usize,
    /// Whether duplicate cosigners are allowed.
    allow_duplicate_cosigners: bool,
    /// Whether to require valid timestamps.
    require_valid_timestamps: bool,
    /// Whether to check certificate expiration.
    check_expiration: bool,
    /// Maximum certificate age in seconds, or ``None``.
    max_certificate_age: Option<u64>,
}

impl PyValidationPolicy {
    /// Build a ``synta_mtc::config::ValidationPolicy`` from this Python wrapper.
    fn to_rust(&self) -> synta_mtc::config::ValidationPolicy {
        use std::str::FromStr;
        use synta_mtc::config::ValidationPolicy;

        let mut policy = ValidationPolicy::new();
        policy.allowed_hash_algorithms.clear();
        for oid_str in &self.allowed_hash_algorithm_oids {
            if let Ok(oid) = synta::ObjectIdentifier::from_str(oid_str) {
                policy.allowed_hash_algorithms.push(oid);
            }
        }
        policy.cosignature_policy.min_cosignatures = self.min_cosignatures;
        policy.cosignature_policy.max_cosignatures = self.max_cosignatures;
        policy.cosignature_policy.allow_duplicate_cosigners = self.allow_duplicate_cosigners;
        policy.require_valid_timestamps = self.require_valid_timestamps;
        policy.check_expiration = self.check_expiration;
        policy.max_certificate_age = self.max_certificate_age;
        policy
    }
}

#[pymethods]
impl PyValidationPolicy {
    /// Create a new ``ValidationPolicy`` with default settings.
    ///
    /// Default: SHA-256 allowed, at least 1 cosignature required, timestamps
    /// and expiration checked.
    #[new]
    fn new() -> Self {
        use synta_mtc::config::ValidationPolicy;
        let default = ValidationPolicy::default();
        PyValidationPolicy {
            allowed_hash_algorithm_oids: default
                .allowed_hash_algorithms
                .iter()
                .map(|o| o.to_string())
                .collect(),
            min_cosignatures: default.cosignature_policy.min_cosignatures,
            max_cosignatures: default.cosignature_policy.max_cosignatures,
            allow_duplicate_cosigners: default.cosignature_policy.allow_duplicate_cosigners,
            require_valid_timestamps: default.require_valid_timestamps,
            check_expiration: default.check_expiration,
            max_certificate_age: default.max_certificate_age,
        }
    }

    /// Create a permissive ``ValidationPolicy`` for testing.
    ///
    /// Allows all supported hash algorithms, requires zero cosignatures, and
    /// disables timestamp and expiration checks.
    #[staticmethod]
    fn permissive() -> Self {
        use synta_mtc::config::ValidationPolicy;
        let p = ValidationPolicy::permissive();
        PyValidationPolicy {
            allowed_hash_algorithm_oids: p
                .allowed_hash_algorithms
                .iter()
                .map(|o| o.to_string())
                .collect(),
            min_cosignatures: p.cosignature_policy.min_cosignatures,
            max_cosignatures: p.cosignature_policy.max_cosignatures,
            allow_duplicate_cosigners: p.cosignature_policy.allow_duplicate_cosigners,
            require_valid_timestamps: p.require_valid_timestamps,
            check_expiration: p.check_expiration,
            max_certificate_age: p.max_certificate_age,
        }
    }

    /// Allow an additional hash algorithm.
    ///
    /// :param algo: A :class:`HashAlgorithm` instance (e.g. ``HashAlgorithm.Sha384``).
    fn allow_hash_algorithm(&mut self, algo: &PyHashAlgorithm) {
        let oid_str = algo.inner.to_oid().to_string();
        if !self.allowed_hash_algorithm_oids.contains(&oid_str) {
            self.allowed_hash_algorithm_oids.push(oid_str);
        }
    }

    /// Set the minimum number of cosignatures required for validation.
    ///
    /// :param n: Minimum count (0 = no cosignatures required).
    fn set_min_cosignatures(&mut self, n: usize) {
        self.min_cosignatures = n;
    }

    /// Set the maximum number of cosignatures accepted (DoS protection).
    ///
    /// :param n: Maximum count.
    fn set_max_cosignatures(&mut self, n: usize) {
        self.max_cosignatures = n;
    }

    /// Allow or forbid duplicate cosigner IDs in the same certificate.
    ///
    /// :param allow: When ``True``, a single cosigner may contribute multiple
    ///     entries toward the quorum (insecure — leave ``False`` in production).
    fn set_allow_duplicate_cosigners(&mut self, allow: bool) {
        self.allow_duplicate_cosigners = allow;
    }

    /// Enable or disable timestamp validity checking.
    ///
    /// :param require: When ``True``, certificates with invalid timestamps are rejected.
    fn set_require_valid_timestamps(&mut self, require: bool) {
        self.require_valid_timestamps = require;
    }

    /// Enable or disable certificate expiration checking.
    ///
    /// :param check: When ``True``, expired certificates are rejected.
    fn set_check_expiration(&mut self, check: bool) {
        self.check_expiration = check;
    }

    /// Allowed hash algorithm OID strings (dotted-decimal).
    #[getter]
    fn allowed_hash_algorithm_oids(&self) -> Vec<String> {
        self.allowed_hash_algorithm_oids.clone()
    }

    /// Minimum number of valid cosignatures required.
    #[getter]
    fn min_cosignatures(&self) -> usize {
        self.min_cosignatures
    }

    /// Maximum number of cosignatures accepted (DoS protection).
    #[getter]
    fn max_cosignatures(&self) -> usize {
        self.max_cosignatures
    }

    /// Whether duplicate cosigners are allowed.
    #[getter]
    fn allow_duplicate_cosigners(&self) -> bool {
        self.allow_duplicate_cosigners
    }

    /// Whether timestamp validity is checked.
    #[getter]
    fn require_valid_timestamps(&self) -> bool {
        self.require_valid_timestamps
    }

    /// Whether certificate expiration is checked.
    #[getter]
    fn check_expiration(&self) -> bool {
        self.check_expiration
    }

    fn __repr__(&self) -> String {
        format!(
            "ValidationPolicy(min_cosignatures={}, algorithms={})",
            self.min_cosignatures,
            self.allowed_hash_algorithm_oids.len()
        )
    }
}

// ── TrustAnchor ───────────────────────────────────────────────────────────────

/// A trust anchor for a Merkle Tree Certificate log.
///
/// Identifies a log operator by their ``LogID`` (hash algorithm + public key),
/// provides a human-readable name for diagnostics, tracks whether the anchor is
/// active, and carries an optional revocation list (spec §7.5).
///
/// Construct with :meth:`from_log_id_der` and add to a
/// :class:`CertificateValidator` via :meth:`CertificateValidator.add_trust_anchor`.
///
/// ```python,ignore
/// import synta.mtc as mtc
///
/// anchor = mtc.TrustAnchor.from_log_id_der(log_id_der, "My Log")
/// anchor.revoke_range(1, 100)
///
/// validator = mtc.CertificateValidator()
/// validator.add_trust_anchor(anchor)
/// ```
#[pyclass(name = "TrustAnchor")]
pub struct PyTrustAnchor {
    /// Owned DER bytes for the LogID (keeps the decoded LogID alive).
    pub(super) log_id_der: Box<[u8]>,
    /// Human-readable name for diagnostics.
    pub(super) name: String,
    /// Whether this anchor is currently active.
    pub(super) active: bool,
    /// Revocation ranges for this anchor.
    pub(super) revoked_ranges: synta_mtc::revocation::RevokedRanges,
}

#[pymethods]
impl PyTrustAnchor {
    /// Construct a ``TrustAnchor`` from a DER-encoded ``LogID`` and a display name.
    ///
    /// :param log_id_der: DER-encoded ``LogID`` SEQUENCE bytes.
    /// :param name: Human-readable name for diagnostics.
    /// :raises ValueError: if *log_id_der* cannot be decoded as a ``LogID``.
    #[staticmethod]
    fn from_log_id_der(log_id_der: &[u8], name: String) -> PyResult<Self> {
        // Validate by decoding.
        let validated = {
            let mut dec = synta::Decoder::new(log_id_der, synta::Encoding::Der);
            synta_mtc::types::LogID::decode(&mut dec).map_err(SyntaErr)?
        };
        // Re-encode to get a fully owned, canonical copy.
        let mut enc = synta::Encoder::new(synta::Encoding::Der);
        validated.encode(&mut enc).map_err(SyntaErr)?;
        let owned: Box<[u8]> = enc.finish().map_err(SyntaErr)?.into_boxed_slice();
        Ok(PyTrustAnchor {
            log_id_der: owned,
            name,
            active: true,
            revoked_ranges: synta_mtc::revocation::RevokedRanges::new(),
        })
    }

    /// Return the DER-encoded ``LogID`` for this trust anchor.
    #[getter]
    fn log_id_der<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        PyBytes::new(py, &self.log_id_der)
    }

    /// Human-readable name for this trust anchor (for diagnostics).
    #[getter]
    fn name(&self) -> &str {
        &self.name
    }

    /// Whether this trust anchor is currently active.
    ///
    /// Inactive anchors are ignored during validation.
    #[getter]
    fn active(&self) -> bool {
        self.active
    }

    /// Activate this trust anchor.
    fn activate(&mut self) {
        self.active = true;
    }

    /// Deactivate this trust anchor.
    ///
    /// Deactivated anchors are skipped by the validator.
    fn deactivate(&mut self) {
        self.active = false;
    }

    /// Return ``True`` if *entry_index* falls within a revoked range (spec §7.5).
    ///
    /// :param entry_index: Leaf index to check.
    fn is_revoked(&self, entry_index: u64) -> bool {
        self.revoked_ranges.is_revoked(entry_index)
    }

    /// Add an inclusive range ``[start, end]`` of revoked entry indices (spec §7.5).
    ///
    /// Overlapping and adjacent ranges are automatically merged.
    ///
    /// :param start: Start of the revoked range (inclusive).
    /// :param end: End of the revoked range (inclusive).
    /// :raises ValueError: if *start* > *end*.
    fn revoke_range(&mut self, start: u64, end: u64) -> PyResult<()> {
        self.revoked_ranges
            .add(start, end)
            .map_err(|e| PyValueError::new_err(e.to_string()))
    }

    fn __repr__(&self) -> String {
        format!("TrustAnchor(name='{}', active={})", self.name, self.active)
    }
}

// ── CertificateValidator ──────────────────────────────────────────────────────

/// Validates Merkle Tree Certificates against trusted checkpoints.
///
/// Combines trust anchor lookup, inclusion proof verification, subtree
/// consistency checking, and policy enforcement.
///
/// Construction: create a validator, add trust anchors, then call
/// :meth:`validate_standalone` or :meth:`validate_landmark`.
///
/// ```python,ignore
/// import synta.mtc as mtc
///
/// anchor = mtc.TrustAnchor.from_log_id_der(log_id_der, "My Log")
///
/// policy = mtc.ValidationPolicy()
/// policy.allow_hash_algorithm(mtc.HashAlgorithm.Sha256)
///
/// validator = mtc.CertificateValidator(policy)
/// validator.add_trust_anchor(anchor)
///
/// try:
///     validator.validate_standalone(standalone_cert_der)
///     print("certificate is valid")
/// except ValueError as e:
///     print("invalid:", e)
/// ```
#[pyclass(name = "CertificateValidator")]
pub struct PyCertificateValidator {
    /// Owned DER bytes for each trust anchor's LogID.
    /// Each `Box<[u8]>` has a stable heap address that the decoded
    /// `LogID<'static>` borrows from.
    anchor_log_id_bytes: Vec<Box<[u8]>>,
    /// Trust anchor metadata (name, active flag, revoked ranges), parallel to
    /// `anchor_log_id_bytes`.
    anchor_meta: Vec<(String, bool, synta_mtc::revocation::RevokedRanges)>,
    /// Validation policy stored as a Python wrapper (cheap to clone).
    policy: PyValidationPolicy,
}

impl PyCertificateValidator {
    /// Build a ``CertificateValidator<'static>`` whose trust anchors borrow from
    /// the stable ``Box<[u8]>`` heap addresses in ``self.anchor_log_id_bytes``.
    ///
    /// SAFETY: the returned validator must not outlive `self` because the
    /// `LogID<'static>` values borrow from boxes owned by `self`.
    fn build_rust_validator(
        &self,
    ) -> PyResult<synta_mtc::validator::CertificateValidator<'static>> {
        use synta_mtc::config::{TrustAnchor, ValidatorConfig};
        use synta_mtc::types::LogID;

        let policy = self.policy.to_rust();
        let mut config = ValidatorConfig::with_policy(policy);

        for (der_box, (name, active, revoked)) in
            self.anchor_log_id_bytes.iter().zip(self.anchor_meta.iter())
        {
            // SAFETY: the Box heap address is stable for the life of `self`.
            let static_bytes: &'static [u8] = unsafe { &*(der_box.as_ref() as *const [u8]) };
            let mut dec = synta::Decoder::new(static_bytes, synta::Encoding::Der);
            let log_id_decoded = LogID::decode(&mut dec).map_err(SyntaErr)?;
            // SAFETY: `log_id_decoded` borrows `static_bytes`, which is backed by
            // the Box heap address that outlives the validator we build here
            // (the validator is used synchronously and dropped before any Box moves).
            let log_id: LogID<'static> = unsafe { std::mem::transmute(log_id_decoded) };
            let mut anchor = TrustAnchor::new(log_id, name.clone());
            anchor.active = *active;
            anchor.revoked_ranges = revoked.clone();
            config.add_trust_anchor(anchor);
        }

        Ok(synta_mtc::validator::CertificateValidator::new(config))
    }
}

#[pymethods]
impl PyCertificateValidator {
    /// Create a new ``CertificateValidator`` with an optional policy.
    ///
    /// If *policy* is omitted the default policy is used (SHA-256 only,
    /// at least one cosignature required).
    ///
    /// :param policy: A :class:`ValidationPolicy` instance, or ``None`` for defaults.
    #[new]
    #[pyo3(signature = (policy=None))]
    fn new(policy: Option<&PyValidationPolicy>) -> Self {
        let policy = match policy {
            Some(p) => PyValidationPolicy {
                allowed_hash_algorithm_oids: p.allowed_hash_algorithm_oids.clone(),
                min_cosignatures: p.min_cosignatures,
                max_cosignatures: p.max_cosignatures,
                allow_duplicate_cosigners: p.allow_duplicate_cosigners,
                require_valid_timestamps: p.require_valid_timestamps,
                check_expiration: p.check_expiration,
                max_certificate_age: p.max_certificate_age,
            },
            None => PyValidationPolicy::new(),
        };
        PyCertificateValidator {
            anchor_log_id_bytes: Vec::new(),
            anchor_meta: Vec::new(),
            policy,
        }
    }

    /// Add a trust anchor to the validator.
    ///
    /// The anchor's ``LogID`` DER bytes are copied into stable owned storage
    /// so that the anchor can be used across calls without holding a reference
    /// to the original :class:`TrustAnchor` object.
    ///
    /// :param anchor: A :class:`TrustAnchor` instance.
    fn add_trust_anchor(&mut self, anchor: &PyTrustAnchor) {
        self.anchor_log_id_bytes.push(anchor.log_id_der.clone());
        self.anchor_meta.push((
            anchor.name.clone(),
            anchor.active,
            anchor.revoked_ranges.clone(),
        ));
    }

    /// Return the number of trust anchors currently registered.
    fn trust_anchor_count(&self) -> usize {
        self.anchor_log_id_bytes.len()
    }

    /// Validate a DER-encoded ``StandaloneCertificate``.
    ///
    /// Runs the full validation pipeline (spec §4.3.3):
    ///
    /// 1. Cosignature quorum check.
    /// 2. Find a trusted cosignature.
    /// 3. Resolve and policy-check the hash algorithm.
    /// 4. Verify the leaf index falls within the cosigner's subtree.
    /// 5. Check the leaf index against the trust anchor's revocation list (§7.5).
    /// 6. Compute the leaf hash from the embedded TBS certificate.
    /// 7. Verify the embedded inclusion proof against the trusted checkpoint root.
    ///
    /// :param cert_der: DER-encoded ``StandaloneCertificate`` bytes.
    /// :raises ValueError: if validation fails for any reason.
    fn validate_standalone(&self, cert_der: &[u8]) -> PyResult<()> {
        use synta_mtc::types::StandaloneCertificate;

        let mut dec = synta::Decoder::new(cert_der, synta::Encoding::Der);
        let cert = StandaloneCertificate::decode(&mut dec).map_err(SyntaErr)?;
        let validator = self.build_rust_validator()?;
        validator
            .validate_standalone(&cert)
            .map_err(|e| PyValueError::new_err(e.to_string()))
    }

    /// Validate a DER-encoded ``LandmarkCertificate`` against a trusted checkpoint.
    ///
    /// Landmark certificates carry no embedded cosignatures. You must supply
    /// the trusted :class:`Checkpoint` DER bytes (obtained from a separately
    /// validated subtree proof for the log referenced by the certificate's
    /// ``landmark_id``).
    ///
    /// Validation pipeline (spec §4.3.3):
    ///
    /// 1. Verify that ``landmark_id.log_id`` matches an active trust anchor.
    /// 2. Resolve and policy-check the hash algorithm.
    /// 3. Extract the leaf index from the serial number (§6.1).
    /// 4. Check the leaf index against the trust anchor's revocation list (§7.5).
    /// 5. Compute the leaf hash from the embedded TBS certificate.
    /// 6. Verify the inclusion proof against the supplied checkpoint's root.
    ///
    /// :param cert_der: DER-encoded ``LandmarkCertificate`` bytes.
    /// :param checkpoint_der: DER-encoded ``Checkpoint`` bytes (must be trusted).
    /// :raises ValueError: if validation fails for any reason.
    fn validate_landmark(&self, cert_der: &[u8], checkpoint_der: &[u8]) -> PyResult<()> {
        use synta_mtc::types::{Checkpoint, LandmarkCertificate};

        let cert = {
            let mut dec = synta::Decoder::new(cert_der, synta::Encoding::Der);
            LandmarkCertificate::decode(&mut dec).map_err(SyntaErr)?
        };
        let checkpoint = {
            let mut dec = synta::Decoder::new(checkpoint_der, synta::Encoding::Der);
            Checkpoint::decode(&mut dec).map_err(SyntaErr)?
        };
        let validator = self.build_rust_validator()?;
        validator
            .validate_landmark(&cert, &checkpoint)
            .map_err(|e| PyValueError::new_err(e.to_string()))
    }

    fn __repr__(&self) -> String {
        format!(
            "CertificateValidator(trust_anchors={}, min_cosignatures={})",
            self.anchor_log_id_bytes.len(),
            self.policy.min_cosignatures
        )
    }
}