structured-cms 0.6.1

Borrowed CMS SignedData processing with explicit providers and resource accounting
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
//! Accounted certificate hint indexes, without signer identity or trust verdicts.

use crate::Error as ProcessingError;
use crate::signer::SignerIdentifier;
use core::cmp::Ordering;
use core::fmt;
use structured_asn1::Reader;
use structured_asn1::memory::{Execution, Memory, MemoryError, OwnedVec, SortError, Work};
use structured_pkix::{Certificate, Name, Ordered};

/// A directory operation has either an original document cause or a storage/
/// metadata admission failure that has no document position of its own.
#[derive(Debug)]
pub enum Error {
    /// Original certificate, name or signer-hint processing failure.
    Processing(ProcessingError),
    /// Source-free retained catalogue work or storage refusal.
    Resource(MemoryError),
}

impl Error {
    fn pkix(source: structured_pkix::Error) -> Self {
        Self::Processing(ProcessingError::pkix(source))
    }
    fn resource(reason: MemoryError, field: &'static str, at: u64) -> Self {
        Self::Processing(ProcessingError::resource(reason, field, at))
    }
    fn admission(reason: MemoryError, origin: Option<u64>) -> Self {
        match origin {
            Some(at) => Self::resource(reason, "signedData.certificates", at),
            None => Self::Resource(reason),
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Processing(source) => source.fmt(formatter),
            Self::Resource(source) => source.fmt(formatter),
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Processing(source) => Some(source),
            Self::Resource(source) => Some(source),
        }
    }
}

/// A complete catalogue operation; refusal never becomes a match answer.
pub type Result<T> = core::result::Result<T, Error>;

/// What the complete catalogue can establish about one certificate hint.
/// Matching a hint never authenticates that certificate or its path.
#[derive(Debug)]
pub enum Match<'c, 'a> {
    /// No certificate answers the complete hint, with no unreadable SKI gap.
    None,
    /// Exactly one certificate answers the complete hint.
    One(&'c Certificate<'a>),
    /// More than one certificate answers the complete hint; no candidate chosen.
    Ambiguous,
    /// An SKI value could not be read, so uniqueness/absence is unestablished.
    /// Original diagnostics are retained by [`Directory::unreadable_identifiers`].
    Unreadable,
}

/// One caller-selected certificate's hint agreement, without uniqueness/trust.
#[derive(Debug)]
pub enum CertificateAgreement {
    /// The original issuer/serial or SKI hint agrees.
    Matches,
    /// The complete readable hint names something else.
    Differs,
    /// Original certificate SKI syntax prevents a comparison.
    Unreadable(structured_pkix::Error),
}

/// Compares a selected certificate without constructing an issuer directory.
///
/// This uses the same paid byte/segmented and shared Name kernels as directory
/// search. Original certificate parsing may be a different session; lazy SKI
/// keeps that origin and also obeys the current query operation. This establishes
/// neither uniqueness in a pool nor signature/path trust for the selected key.
pub fn matches_certificate_in(
    named: &SignerIdentifier<'_>,
    certificate: &Certificate<'_>,
    parent: &Reader<'_>,
) -> Result<CertificateAgreement> {
    let execution = parent.execution();
    let at = certificate.span().start;
    match named {
        SignerIdentifier::IssuerAndSerial { issuer, serial } => {
            if bytes_order(
                serial.as_bytes(),
                certificate.tbs().serial().as_bytes(),
                &execution,
                at,
            )? != Ordering::Equal
            {
                return Ok(CertificateAgreement::Differs);
            }
            if issuer
                .matches_in(certificate.tbs().issuer(), parent)
                .map_err(Error::pkix)?
            {
                Ok(CertificateAgreement::Matches)
            } else {
                Ok(CertificateAgreement::Differs)
            }
        }
        SignerIdentifier::SubjectKeyIdentifier(wanted) => {
            let Some(extension) = certificate
                .tbs()
                .extensions()
                .get(structured_pkix::oid::SUBJECT_KEY_IDENTIFIER, &execution)
                .map_err(Error::pkix)?
            else {
                return Ok(CertificateAgreement::Differs);
            };
            let identifier =
                match structured_pkix::identifier::SubjectKeyIdentifier::read_in(extension, parent)
                {
                    Ok(identifier) => identifier,
                    Err(error)
                        if error.is_resource()
                            || error.code() == structured_pkix::ErrorCode::ForeignReader =>
                    {
                        return Err(Error::pkix(error));
                    }
                    Err(error) => return Ok(CertificateAgreement::Unreadable(error)),
                };
            if segmented_matches(wanted, identifier.as_bytes(), &execution, at)? {
                Ok(CertificateAgreement::Matches)
            } else {
                Ok(CertificateAgreement::Differs)
            }
        }
    }
}

/// Original malformed identifier diagnostic, independently of resource failures.
#[derive(Debug)]
pub struct Unreadable<'c, 'a> {
    certificate: &'c Certificate<'a>,
    reason: structured_pkix::Error,
}
impl<'c, 'a> Unreadable<'c, 'a> {
    /// Certificate whose actual extension was unreadable.
    #[must_use]
    pub fn certificate(&self) -> &'c Certificate<'a> {
        self.certificate
    }
    /// Original located encoding/schema cause, without conversion to absence.
    #[must_use]
    pub fn reason(&self) -> &structured_pkix::Error {
        &self.reason
    }
}

struct Identifier<'a> {
    bytes: &'a [u8],
    index: usize,
}

/// Prepared issuer/serial and SKI indexes retaining their own capacity charges.
///
/// Names are prepared once per certificate, not inside sorting comparators.
/// Owner type determines storage/execution lifetime, never semantic ordering.
/// Every new lookup explicitly funds its current domain. Unknown/malformed SKI
/// gaps cannot become a completed None/One result; resource refusal aborts.
pub struct Directory<'c, 'a, W: Work = Memory> {
    certificates: OwnedVec<&'c Certificate<'a>, W>,
    issuers: OwnedVec<Ordered<'a, W>, W>,
    serials: OwnedVec<usize, W>,
    identifiers: OwnedVec<Identifier<'a>, W>,
    unreadable: OwnedVec<Unreadable<'c, 'a>, W>,
}

impl<'c, 'a> Directory<'c, 'a> {
    /// Independently retained directory over certificates from any source session.
    /// Current Memory funds all construction; deferred SKI parsing preserves
    /// each original certificate's reader/depth and its cumulative parse ceiling.
    pub fn of(certificates: &[&'c Certificate<'a>], execution: &Memory) -> Result<Self> {
        let mut kept = execution.vector();
        kept.try_extend_from_slice(certificates)
            .map_err(Error::Resource)?;
        build(
            kept,
            execution,
            None,
            |name| name.ordered(execution),
            |extension| {
                structured_pkix::identifier::SubjectKeyIdentifier::read(extension, execution)
            },
        )
    }
}

impl<'c, 'a, 'p> Directory<'c, 'a, Execution<'p>> {
    /// Scoped directory over carried certificates from this one parser session.
    ///
    /// The source identity of every certificate is checked before allocation,
    /// normalization or lazy SKI parsing. A foreign pool belongs in [`Directory::of`];
    /// account equality cannot make it part of the producing document session.
    pub fn of_in(certificates: &[&'c Certificate<'a>], parent: &'p Reader<'_>) -> Result<Self>
    where
        'a: 'p,
    {
        let execution = parent.execution();
        // Preflight the borrowed catalogue before any retained storage or
        // deferred processing. One handle copy then feeds the shared builder.
        for certificate in certificates {
            execution.charge_work(1).map_err(|reason| {
                Error::resource(reason, "signedData.certificates", parent.offset())
            })?;
            if !certificate
                .tbs()
                .public_key()
                .algorithm()
                .same_session(parent)
            {
                return Err(Error::pkix(structured_pkix::Error::new(
                    structured_pkix::ErrorCode::ForeignReader,
                    "signedData.certificates",
                    certificate.span().start,
                )));
            }
        }
        let mut gathered = execution.vector();
        gathered
            .try_extend_from_slice(certificates)
            .map_err(|reason| Error::admission(reason, Some(parent.offset())))?;
        build(
            gathered,
            &execution,
            Some(parent.offset()),
            |name| name.ordered_in(parent),
            |extension| {
                structured_pkix::identifier::SubjectKeyIdentifier::read_in(extension, parent)
            },
        )
    }
}

impl<'c, 'a, W: Work> Directory<'c, 'a, W> {
    /// Indexed certificate count, without rescanning.
    #[must_use]
    pub fn len(&self) -> usize {
        self.certificates.len()
    }
    /// Whether this directory carries no certificate hints.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.certificates.is_empty()
    }
    /// Original malformed SKI diagnostics, with their actual certificates.
    #[must_use]
    pub fn unreadable_identifiers(&self) -> &[Unreadable<'c, 'a>] {
        &self.unreadable
    }

    /// Retained query using current aggregate funding, independent of storage owner.
    pub fn find(&self, named: &SignerIdentifier<'_>, execution: &Memory) -> Result<Match<'c, 'a>> {
        self.find_with(named, execution, None, |name| name.ordered(execution))
    }
    /// Producing query using both current local and aggregate ceilings.
    /// A retained pool and scoped pool use the same index/search kernel.
    pub fn find_in(
        &self,
        named: &SignerIdentifier<'_>,
        parent: &Reader<'_>,
    ) -> Result<Match<'c, 'a>> {
        self.find_with(named, &parent.execution(), Some(parent.offset()), |name| {
            name.ordered_in(parent)
        })
    }

    fn find_with<'n, V: Work, E: Work>(
        &self,
        named: &SignerIdentifier<'n>,
        execution: &E,
        origin: Option<u64>,
        prepare: impl FnOnce(&Name<'n>) -> structured_pkix::Result<Ordered<'n, V>>,
    ) -> Result<Match<'c, 'a>> {
        match named {
            SignerIdentifier::IssuerAndSerial { issuer, serial } => {
                let asked = prepare(issuer).map_err(Error::pkix)?;
                let against = |index: usize| -> Result<Ordering> {
                    let held = self.certificates[index].tbs().serial().as_bytes();
                    let order = bytes_order(
                        held,
                        serial.as_bytes(),
                        execution,
                        self.certificates[index].span().start,
                    )?;
                    if order != Ordering::Equal {
                        return Ok(order);
                    }
                    self.issuers[index]
                        .order(&asked, execution)
                        .map_err(Error::pkix)
                };
                let from = lower_bound(self.serials.len(), execution, origin, |at| {
                    against(self.serials[at])
                })?;
                let mut first = None;
                for &index in &self.serials[from..] {
                    if against(index)? != Ordering::Equal {
                        break;
                    }
                    if first.is_some() {
                        return Ok(Match::Ambiguous);
                    }
                    first = Some(self.certificates[index]);
                }
                Ok(match first {
                    Some(certificate) => Match::One(certificate),
                    None => Match::None,
                })
            }
            SignerIdentifier::SubjectKeyIdentifier(wanted) => {
                let mut first = None;
                if let Some(bytes) = wanted.as_one() {
                    let from = lower_bound(self.identifiers.len(), execution, origin, |at| {
                        bytes_order(
                            self.identifiers[at].bytes,
                            bytes,
                            execution,
                            self.certificates[self.identifiers[at].index].span().start,
                        )
                    })?;
                    for held in &self.identifiers[from..] {
                        if bytes_order(
                            held.bytes,
                            bytes,
                            execution,
                            self.certificates[held.index].span().start,
                        )? != Ordering::Equal
                        {
                            break;
                        }
                        if first.is_some() {
                            return Ok(Match::Ambiguous);
                        }
                        first = Some(self.certificates[held.index]);
                    }
                } else {
                    // Compare the original segmented identifier without joining.
                    for held in &self.identifiers {
                        let at = self.certificates[held.index].span().start;
                        execution
                            .charge_work(1)
                            .map_err(|reason| Error::resource(reason, "signerInfo.sid", at))?;
                        if segmented_matches(wanted, held.bytes, execution, at)? {
                            if first.is_some() {
                                return Ok(Match::Ambiguous);
                            }
                            first = Some(self.certificates[held.index]);
                        }
                    }
                }
                if !self.unreadable.is_empty() {
                    return Ok(Match::Unreadable);
                }
                Ok(match first {
                    Some(certificate) => Match::One(certificate),
                    None => Match::None,
                })
            }
        }
    }
}

fn build<'c, 'a, W: Work>(
    kept: OwnedVec<&'c Certificate<'a>, W>,
    execution: &W,
    origin: Option<u64>,
    mut prepare: impl FnMut(&Name<'a>) -> structured_pkix::Result<Ordered<'a, W>>,
    mut read_identifier: impl FnMut(
        &structured_pkix::Extension<'a>,
    ) -> structured_pkix::Result<
        structured_pkix::identifier::SubjectKeyIdentifier<'a>,
    >,
) -> Result<Directory<'c, 'a, W>> {
    let mut issuers = execution.vector();
    let mut serials = execution.vector();
    let mut identifiers = execution.vector();
    let mut unreadable = execution.vector();
    for (index, certificate) in kept.iter().enumerate() {
        let at = certificate.span().start;
        execution
            .charge_work(1)
            .map_err(|reason| Error::resource(reason, "signedData.certificates", at))?;
        issuers
            .try_push(prepare(certificate.tbs().issuer()).map_err(Error::pkix)?)
            .map_err(|reason| Error::resource(reason, "signedData.certificates", at))?;
        serials
            .try_push(index)
            .map_err(|reason| Error::resource(reason, "signedData.certificates", at))?;
        let extension = certificate
            .tbs()
            .extensions()
            .get(structured_pkix::oid::SUBJECT_KEY_IDENTIFIER, execution)
            .map_err(Error::pkix)?;
        if let Some(extension) = extension {
            match read_identifier(extension) {
                Ok(identifier) => identifiers
                    .try_push(Identifier {
                        bytes: identifier.as_bytes(),
                        index,
                    })
                    .map_err(|reason| {
                        Error::resource(
                            reason,
                            "extensions.subjectKeyIdentifier",
                            extension.span().start,
                        )
                    })?,
                Err(reason) if reason.is_resource() => return Err(Error::pkix(reason)),
                Err(reason) => unreadable
                    .try_push(Unreadable {
                        certificate,
                        reason,
                    })
                    .map_err(|reason| {
                        Error::resource(
                            reason,
                            "extensions.subjectKeyIdentifier",
                            extension.span().start,
                        )
                    })?,
            }
        }
    }
    serials
        .try_sort_unstable_by(|left, right| {
            let order = bytes_order(
                kept[*left].tbs().serial().as_bytes(),
                kept[*right].tbs().serial().as_bytes(),
                execution,
                kept[*left].span().start,
            )?;
            if order != Ordering::Equal {
                return Ok(order);
            }
            issuers[*left]
                .order(&issuers[*right], execution)
                .map_err(Error::pkix)
        })
        .map_err(|error| sort_error(error, origin))?;
    identifiers
        .try_sort_unstable_by(|left, right| {
            bytes_order(
                left.bytes,
                right.bytes,
                execution,
                kept[left.index].span().start,
            )
        })
        .map_err(|error| sort_error(error, origin))?;
    Ok(Directory {
        certificates: kept,
        issuers,
        serials,
        identifiers,
        unreadable,
    })
}

fn sort_error(error: SortError<Error>, origin: Option<u64>) -> Error {
    match error {
        SortError::Resource(reason) => Error::admission(reason, origin),
        SortError::Comparison(error) => error,
    }
}
fn bytes_order<W: Work>(left: &[u8], right: &[u8], execution: &W, at: u64) -> Result<Ordering> {
    execution
        .charge_work(1 + left.len().max(right.len()) as u64)
        .map_err(|reason| Error::resource(reason, "signerInfo.sid", at))?;
    Ok(left.cmp(right))
}
fn lower_bound<W: Work>(
    length: usize,
    execution: &W,
    origin: Option<u64>,
    mut compare: impl FnMut(usize) -> Result<Ordering>,
) -> Result<usize> {
    let mut from = 0;
    let mut to = length;
    while from < to {
        execution
            .charge_work(1)
            .map_err(|reason| Error::admission(reason, origin))?;
        let middle = from + (to - from) / 2;
        if compare(middle)? == Ordering::Less {
            from = middle + 1;
        } else {
            to = middle;
        }
    }
    Ok(from)
}
fn segmented_matches<W: Work>(
    wanted: &crate::Octets<'_>,
    held: &[u8],
    execution: &W,
    at: u64,
) -> Result<bool> {
    execution
        .charge_work(1)
        .map_err(|reason| Error::resource(reason, "signerInfo.sid", at))?;
    if wanted.len() != held.len() {
        return Ok(false);
    }
    let mut offset = 0;
    for piece in wanted.pieces() {
        let bytes = piece.as_bytes();
        execution
            .charge_work(1 + bytes.len() as u64)
            .map_err(|reason| Error::resource(reason, "signerInfo.sid", at))?;
        if bytes != &held[offset..offset + bytes.len()] {
            return Ok(false);
        }
        offset += bytes.len();
    }
    debug_assert_eq!(offset, held.len());
    Ok(true)
}