structured-cades 0.21.3

Source-bound CAdES baseline composition over CMS and long-term validation facts
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
//! Original optional property values. Open credential/policy semantics stay
//! explicit obligations; reading an ASN.1 envelope never authenticates them.

use crate::{Error, Result};
use structured_asn1::memory::{OwnedVec, Work};
use structured_asn1::{Element, Oid, Reader, Span, Tag, universal};
use structured_cms::{ErrorCode, Octets, attribute::Attribute, oid, signer::SignerInfo};
use structured_pkix::algorithm::{self, AlgorithmIdentifier};

pub(crate) mod legacy;
pub mod values;

/// Complete original value diagnostic. Processing refusals are never retained
/// here as malformed syntax: they terminate before a partial report escapes.
#[derive(Debug)]
pub struct Fault {
    /// Original attribute type whose value failed.
    pub attribute: Oid<'static>,
    /// Field used by the format's single schema reader.
    pub field: &'static str,
    /// Original shared/schema error, including its source coordinates.
    pub cause: Error,
}

/// Open-format original input requiring its actual format owner. This is not
/// an authenticated credential or a caller-writable positive baseline fact.
#[derive(Debug, Clone, Copy)]
pub struct OpenValue<'a> {
    /// Outer format service that owns this value.
    pub role: OpenRole,
    /// Original type, when the open schema carries an identifier.
    pub kind: Option<Oid<'a>>,
    /// Whole original open pair/attribute, including an absent OPTIONAL value.
    pub enclosure: Element<'a>,
    /// Original payload context, or explicit absence. The enclosing pair is
    /// never substituted for a missing open value.
    pub value: Option<crate::source::Value<'a>>,
}

/// Distinct services cannot substitute for each other during composition.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OpenRole {
    /// Claimed (unauthenticated) signer attribute.
    Claimed,
    /// X.509 attribute certificate with its own authority/material requirements.
    AttributeCertificate,
    /// An independently specified non-X.509 attribute certificate.
    OtherAttributeCertificate,
    /// An independently authenticated assertion (including signed SAML).
    SignedAssertion,
    /// A commitment qualifier whose semantics its OID defines.
    CommitmentQualifier,
    /// A signature-policy qualifier whose semantics its OID defines.
    PolicyQualifier,
}

/// Original signature-policy identifier and declared document digest. The
/// signature-policy document's technical specification determines the hashing
/// input; an all-zero digest means UNKNOWN, never the empty document's digest.
pub struct Policy<'a> {
    /// Original signature policy OID.
    pub identifier: Oid<'a>,
    /// Original written digest mechanism and parameter provenance.
    pub algorithm: AlgorithmIdentifier<'a>,
    /// Original declared digest, including constructed BER fragments.
    pub hash: Octets<'a>,
    /// Normative zero-hash marker, independent of output width (§5.2.9.1).
    pub hash_unknown: bool,
}

/// Original policy store, without filesystem/network discovery or acquisition.
pub struct Store<'a> {
    /// Original technical specification choice (OID or `IA5String` URI).
    pub specification: Element<'a>,
    /// Original embedded document or explicit caller-resolved local URI.
    pub document: crate::source::Value<'a>,
}

/// One complete original signer's optional property reading. Unknown open
/// values stay visible, and a failing value does not hide later occurrences.
pub struct Properties<'a> {
    faults: OwnedVec<Fault>,
    open: OwnedVec<OpenValue<'a>>,
    issuer_hints: OwnedVec<Span>,
    policy: Option<Policy<'a>>,
    store: Option<Store<'a>>,
    values: Option<values::Values<'a>>,
}

impl<'a> Properties<'a> {
    /// Read each recognized value under its original attribute reader. Existing
    /// CMS placement/cardinality and signed-DER checks remain the CMS kernel's
    /// responsibility; registered legacy cardinality and value schemas from
    /// EN319122-1 Annex A/D are checked here for every signer, including TSAs.
    /// This also checks baseline attribute encoding. A finding does not forbid
    /// independent CMS decoding or mathematical verification.
    /// Reference timestamp envelopes and carried `TSTInfo` are inspected by
    /// full preparation, retaining mapped diagnostics with the original source.
    pub fn read(signer: &SignerInfo<'a>, parent: &Reader<'a>) -> Result<Self> {
        signer.require_session(parent, "cades.properties")?;
        let work = parent.execution();
        let mut policy = None;
        let mut store = None;
        let mut values = None;
        let mut faults = work.vector();
        let mut open = work.vector();
        let mut issuer_hints = work.vector();
        for set in [signer.signed_attributes(), signer.unsigned_attributes()]
            .into_iter()
            .flatten()
        {
            for attribute in set.items() {
                // Fixed registered identifiers are at most twelve octets; a
                // different width is rejected by OID equality before scanning.
                parent
                    .charge(11 * (1 + attribute.kind().as_bytes().len().min(12) as u64))
                    .map_err(|cause| Error::encoding(cause, "cades.properties"))?;
                let Some((kind, field)) = known(attribute.kind()) else {
                    legacy::inspect(
                        attribute,
                        parent,
                        &mut faults,
                        &mut issuer_hints,
                        &mut values,
                        &work,
                    )?;
                    continue;
                };
                let reading = read_value(
                    attribute,
                    kind,
                    field,
                    parent,
                    &mut open,
                    &mut policy,
                    &mut store,
                );
                if let Err(cause) = reading {
                    if cause.is_terminal() {
                        return Err(cause);
                    }
                    let at = cause.offset();
                    faults
                        .try_push(Fault {
                            attribute: kind,
                            field,
                            cause,
                        })
                        .map_err(|cause| Error::resource(cause, field, at))?;
                }
            }
        }
        Ok(Self {
            faults: faults.into_owned(),
            open: open.into_owned(),
            issuer_hints: issuer_hints.into_owned(),
            policy,
            store,
            values: values.map(values::Values::into_owned),
        })
    }
    /// Every located value-schema failure, retaining its original cause.
    #[must_use]
    pub fn faults(&self) -> &[Fault] {
        &self.faults
    }
    pub(crate) fn issuer_hints(&self) -> &[Span] {
        &self.issuer_hints
    }
    /// All original open semantic inputs, not only successfully bound ones.
    #[must_use]
    pub fn open_values(&self) -> &[OpenValue<'a>] {
        &self.open
    }
    /// Parsed written policy; no hash comparison or policy acceptance implied.
    #[must_use]
    pub fn policy(&self) -> Option<&Policy<'a>> {
        self.policy.as_ref()
    }
    /// Parsed original store; no file or URI is accessed by reading it.
    #[must_use]
    pub fn store(&self) -> Option<&Store<'a>> {
        self.store.as_ref()
    }
    /// Original legacy validation models, retained once without copying their
    /// bytes. An empty written value set remains distinct from absence.
    pub fn legacy_values(&self) -> Option<&values::Values<'a>> {
        self.values.as_ref()
    }

    pub(crate) fn has_legacy_values(signer: &SignerInfo<'_>, parent: &Reader<'_>) -> Result<bool> {
        for set in [signer.signed_attributes(), signer.unsigned_attributes()]
            .into_iter()
            .flatten()
        {
            for attribute in set.items() {
                parent
                    .charge(2 * (1 + attribute.kind().as_bytes().len().min(11) as u64))
                    .map_err(|cause| Error::encoding(cause, "cades.legacy"))?;
                if attribute.kind() == legacy::LEGACY[2] || attribute.kind() == legacy::LEGACY[3] {
                    return Ok(true);
                }
            }
        }
        Ok(false)
    }
}

/// Whether an attribute belongs to the `CAdES` schemas recognized by this core.
/// Profiles which permit only a subset use the same identifier catalogue;
/// this does not validate placement, cardinality or an attribute value.
pub fn defines(
    kind: Oid<'_>,
    work: &impl Work,
) -> core::result::Result<bool, structured_asn1::memory::MemoryError> {
    work.charge_work(11 * (1 + kind.as_bytes().len().min(12) as u64))?;
    if known(kind).is_some() {
        return Ok(true);
    }
    for expected in legacy::LEGACY.into_iter().chain([
        oid::CONTENT_TYPE,
        oid::MESSAGE_DIGEST,
        oid::SIGNING_TIME,
        oid::SIGNING_CERTIFICATE,
        oid::SIGNING_CERTIFICATE_V2,
        oid::CONTENT_TIMESTAMP,
        oid::ARCHIVE_TIMESTAMP_V3,
        oid::ATS_HASH_INDEX_V3,
        oid::CLAIMED_SAML_ASSERTION,
    ]) {
        work.charge_work(1 + kind.as_bytes().len().min(expected.as_bytes().len()) as u64)?;
        if kind == expected {
            return Ok(true);
        }
    }
    work.charge_work(1 + kind.as_bytes().len().min(11) as u64)?;
    Ok(crate::preservation::Kind::from_oid(kind).is_some())
}

fn known(kind: Oid<'_>) -> Option<(Oid<'static>, &'static str)> {
    for (expected, field) in [
        (oid::COMMITMENT_TYPE_INDICATION, "commitmentTypeIndication"),
        (oid::MIME_TYPE, "mimeType"),
        (oid::CONTENT_HINTS, "contentHints"),
        (oid::CONTENT_IDENTIFIER, "contentIdentifier"),
        (oid::CONTENT_REFERENCE, "contentReference"),
        (oid::SIGNER_LOCATION, "signerLocation"),
        (oid::SIGNER_ATTRIBUTES_V2, "signerAttributesV2"),
        (
            oid::SIGNATURE_POLICY_IDENTIFIER,
            "signaturePolicyIdentifier",
        ),
        (oid::SIGNATURE_POLICY_STORE, "signaturePolicyStore"),
        (oid::SIGNATURE_TIMESTAMP, "signatureTimeStamp"),
        (oid::COUNTERSIGNATURE, "countersignature"),
    ] {
        if kind == expected {
            return Some((expected, field));
        }
    }
    None
}

fn read_value<'a, W: Work>(
    attribute: &Attribute<'a>,
    kind: Oid<'static>,
    field: &'static str,
    parent: &Reader<'a>,
    open: &mut OwnedVec<OpenValue<'a>, W>,
    policy: &mut Option<Policy<'a>>,
    store: &mut Option<Store<'a>>,
) -> Result<()> {
    if kind == oid::COUNTERSIGNATURE {
        return if attribute.values().is_empty() {
            Err(syntax(field, attribute.span().start))
        } else {
            Ok(())
        };
    }
    if kind == oid::SIGNATURE_TIMESTAMP {
        // EN319122-1 §6.3 Table1(l), not §5.3, requires DER for the WHOLE
        // signature-time-stamp attribute. §5.3 only specifies its token type.
        // This reports baseline conformance; generic CMS BER decoding and
        // independent root/token signature verification remain available.
        // https://www.etsi.org/deliver/etsi_en/319100_319199/31912201/01.03.01_60/en_31912201v010301p.pdf
        let mut der = parent
            .reread(attribute.element(), structured_asn1::Encoding::Der)
            .map_err(|cause| Error::encoding(cause, field))?;
        let element = der
            .expect(Tag::constructed(universal::SEQUENCE))
            .map_err(|cause| Error::encoding(cause, field))?;
        return structured_pkix::der::conforms(&der, &element, field).map_err(Error::Pkix);
    }
    if attribute.values().len() != 1 {
        return Err(syntax(field, attribute.span().start));
    }
    let mut reader = attribute
        .value_reader_in(0, parent, field)?
        .ok_or_else(|| syntax(field, attribute.span().start))?;
    let value = reader
        .next_element()
        .map_err(|cause| Error::encoding(cause, field))?
        .ok_or_else(|| syntax(field, reader.offset()))?;
    if !reader.is_empty() {
        return Err(syntax(field, reader.offset()));
    }
    if kind == oid::MIME_TYPE {
        require_tag(&value, Tag::primitive(universal::UTF8_STRING), field)?;
        structured_pkix::der::conforms(&reader, &value, field).map_err(Error::Pkix)?;
        let valid =
            structured_cms::mime::media_type_or_headers(value.contents(), &reader.execution())
                .map_err(|cause| Error::resource(cause, field, value.span().start))?;
        return if valid {
            Ok(())
        } else {
            Err(syntax(field, value.span().start))
        };
    }
    if kind == oid::CONTENT_IDENTIFIER {
        Octets::read(&reader, &value, field)?;
        return Ok(());
    }
    let inside = sequence(&reader, &value, field)?;
    read_sequence(inside, kind, field, open, policy, store)
}

fn read_sequence<'a, W: Work>(
    mut inside: Reader<'a>,
    kind: Oid<'static>,
    field: &'static str,
    open: &mut OwnedVec<OpenValue<'a>, W>,
    policy: &mut Option<Policy<'a>>,
    store: &mut Option<Store<'a>>,
) -> Result<()> {
    if kind == oid::CONTENT_HINTS {
        let first = next(&mut inside, field)?;
        if first.tag() == Tag::primitive(universal::UTF8_STRING) {
            string(&inside, &first, field)?;
            inside
                .read_oid()
                .map_err(|cause| Error::encoding(cause, field))?;
        } else {
            inside
                .oid(&first)
                .map_err(|cause| Error::encoding(cause, field))?;
        }
    } else if kind == oid::CONTENT_REFERENCE {
        inside
            .read_oid()
            .map_err(|cause| Error::encoding(cause, field))?;
        for _ in 0..2 {
            let part = next(&mut inside, field)?;
            Octets::read(&inside, &part, field)?;
        }
    } else if kind == oid::COMMITMENT_TYPE_INDICATION {
        inside
            .read_oid()
            .map_err(|cause| Error::encoding(cause, field))?;
        if let Some(qualifiers) = inside
            .next_element()
            .map_err(|cause| Error::encoding(cause, field))?
        {
            let mut values = sequence(&inside, &qualifiers, field)?;
            if values.is_empty() {
                return Err(syntax(field, qualifiers.span().start));
            }
            while let Some(value) = values
                .next_element()
                .map_err(|cause| Error::encoding(cause, field))?
            {
                open_pair(&values, &value, OpenRole::CommitmentQualifier, field, open)?;
            }
        }
    } else if kind == oid::SIGNER_LOCATION {
        location(&mut inside, field)?;
    } else if kind == oid::SIGNER_ATTRIBUTES_V2 {
        attributes(&mut inside, field, open)?;
    } else if kind == oid::SIGNATURE_POLICY_IDENTIFIER {
        let identifier = inside
            .read_oid()
            .map_err(|cause| Error::encoding(cause, field))?;
        let hash_value = next(&mut inside, field)?;
        let mut hash_fields = sequence(&inside, &hash_value, field)?;
        let id = next(&mut hash_fields, field)?;
        let algorithm = algorithm::read(&hash_fields, &id, field).map_err(Error::Pkix)?;
        let hash_value = next(&mut hash_fields, field)?;
        let hash = Octets::read(&hash_fields, &hash_value, field)?;
        end(&hash_fields, field)?;
        let mut hash_unknown = true;
        for piece in hash.pieces() {
            inside
                .charge(1 + piece.as_bytes().len() as u64)
                .map_err(|cause| Error::encoding(cause, field))?;
            if piece.as_bytes().iter().any(|byte| *byte != 0) {
                hash_unknown = false;
            }
        }
        if let Some(qualifiers) = inside
            .next_element()
            .map_err(|cause| Error::encoding(cause, field))?
        {
            let mut values = sequence(&inside, &qualifiers, field)?;
            if values.is_empty() {
                return Err(syntax(field, qualifiers.span().start));
            }
            while let Some(value) = values
                .next_element()
                .map_err(|cause| Error::encoding(cause, field))?
            {
                open_pair(&values, &value, OpenRole::PolicyQualifier, field, open)?;
            }
        }
        *policy = Some(Policy {
            identifier,
            algorithm,
            hash,
            hash_unknown,
        });
    } else if kind == oid::SIGNATURE_POLICY_STORE {
        let specification = next(&mut inside, field)?;
        spec(&inside, &specification, field)?;
        let document = next(&mut inside, field)?;
        if document.tag().number() == Some(universal::OCTET_STRING) {
            Octets::read(&inside, &document, field)?;
        } else {
            // EN319122-1 §5.2.10 selects a local-store URI, not arbitrary
            // IA5 text. Syntax validation never fetches or resolves the URI.
            // https://www.etsi.org/deliver/etsi_en/319100_319199/31912201/01.03.01_60/en_31912201v010301p.pdf
            uri_value(&inside, &document, field)?;
        }
        *store = Some(Store {
            specification,
            document: crate::source::Value::of(&inside, document, field),
        });
    }
    end(&inside, field)
}

fn location(reader: &mut Reader<'_>, field: &'static str) -> Result<()> {
    // Annex D uses EXPLICIT TAGS, even though the containing CMS is BER.
    // At least one field and postalAddress SIZE(1..6) are format constraints.
    let mut previous = None;
    while let Some(value) = reader
        .next_element()
        .map_err(|cause| Error::encoding(cause, field))?
    {
        let Some(number) = value.tag().number() else {
            return Err(syntax(field, value.span().start));
        };
        if number > 2
            || value.tag() != Tag::context(true, number)
            || previous.is_some_and(|p| number <= p)
        {
            return Err(syntax(field, value.span().start));
        }
        previous = Some(number);
        let mut explicit = reader
            .enter(&value)
            .map_err(|cause| Error::encoding(cause, field))?;
        let part = next(&mut explicit, field)?;
        end(&explicit, field)?;
        if number < 2 {
            directory_string(&explicit, &part, field)?;
        } else {
            let mut lines = sequence(&explicit, &part, field)?;
            let mut count = 0;
            while let Some(line) = lines
                .next_element()
                .map_err(|cause| Error::encoding(cause, field))?
            {
                count += 1;
                if count > 6 {
                    return Err(syntax(field, line.span().start));
                }
                directory_string(&lines, &line, field)?;
            }
            if count == 0 {
                return Err(syntax(field, part.span().start));
            }
        }
    }
    if previous.is_none() {
        return Err(syntax(field, reader.offset()));
    }
    Ok(())
}

fn claimed_value(claimed: &Attribute<'_>, parent: &Reader<'_>, field: &'static str) -> Result<()> {
    parent
        .charge(
            1 + claimed
                .kind()
                .as_bytes()
                .len()
                .min(oid::CLAIMED_SAML_ASSERTION.as_bytes().len()) as u64,
        )
        .map_err(|cause| Error::encoding(cause, field))?;
    if claimed.kind() != oid::CLAIMED_SAML_ASSERTION {
        return Ok(());
    }
    // EN319122-1 §5.2.6.2 requires exactly one OCTET STRING. Reading
    // this envelope neither interprets nor authenticates the SAML claim.
    // https://www.etsi.org/deliver/etsi_en/319100_319199/31912201/01.03.01_60/en_31912201v010301p.pdf
    claimed.single(field)?;
    let mut reader = claimed
        .value_reader_in(0, parent, field)?
        .ok_or_else(|| syntax(field, claimed.span().start))?;
    let value = next(&mut reader, field)?;
    Octets::read(&reader, &value, field)?;
    Ok(())
}

fn attributes<'a, W: Work>(
    reader: &mut Reader<'a>,
    field: &'static str,
    open: &mut OwnedVec<OpenValue<'a>, W>,
) -> Result<()> {
    let mut previous = None;
    let mut populated = false;
    while let Some(value) = reader
        .next_element()
        .map_err(|cause| Error::encoding(cause, field))?
    {
        let Some(number) = value.tag().number() else {
            return Err(syntax(field, value.span().start));
        };
        if number > 2
            || value.tag() != Tag::context(true, number)
            || previous.is_some_and(|p| number <= p)
        {
            return Err(syntax(field, value.span().start));
        }
        previous = Some(number);
        let mut explicit = reader
            .enter(&value)
            .map_err(|cause| Error::encoding(cause, field))?;
        let part = next(&mut explicit, field)?;
        end(&explicit, field)?;
        let mut entries = sequence(&explicit, &part, field)?;
        // §5.2.6.1 requires nonempty certified and assertion sequences.
        if number != 0 && entries.is_empty() {
            return Err(syntax(field, part.span().start));
        }
        while let Some(entry) = entries
            .next_element()
            .map_err(|cause| Error::encoding(cause, field))?
        {
            populated = true;
            if number == 0 {
                let claimed = Attribute::read(&entries, &entry, field)?;
                claimed_value(&claimed, &entries, field)?;
                push(
                    open,
                    OpenValue {
                        role: OpenRole::Claimed,
                        kind: Some(claimed.kind()),
                        enclosure: entry,
                        value: Some(crate::source::Value::of(&entries, entry, field)),
                    },
                    field,
                )?;
            } else if number == 1 {
                let choice = entry.tag();
                if choice != Tag::context(true, 0) && choice != Tag::context(true, 1) {
                    return Err(syntax(field, entry.span().start));
                }
                let mut explicit = entries
                    .enter(&entry)
                    .map_err(|cause| Error::encoding(cause, field))?;
                let certificate = next(&mut explicit, field)?;
                end(&explicit, field)?;
                if choice.number() == Some(0) {
                    require_tag(&certificate, Tag::constructed(universal::SEQUENCE), field)?;
                    push(
                        open,
                        OpenValue {
                            role: OpenRole::AttributeCertificate,
                            kind: None,
                            enclosure: certificate,
                            value: Some(crate::source::Value::of(&explicit, certificate, field)),
                        },
                        field,
                    )?;
                } else {
                    open_pair(
                        &explicit,
                        &certificate,
                        OpenRole::OtherAttributeCertificate,
                        field,
                        open,
                    )?;
                }
            } else {
                open_pair(&entries, &entry, OpenRole::SignedAssertion, field, open)?;
            }
        }
    }
    // EN319122-1 §5.2.6.1 forbids an empty signer-attributes-v2, not
    // merely an absent wrapper. An empty claimedAttributes is allowed only
    // when another field actually contributes an entry.
    // https://www.etsi.org/deliver/etsi_en/319100_319199/31912201/01.03.01_60/en_31912201v010301p.pdf
    if !populated {
        return Err(syntax(field, reader.offset()));
    }
    Ok(())
}

fn open_pair<'a, W: Work>(
    parent: &Reader<'a>,
    element: &Element<'a>,
    role: OpenRole,
    field: &'static str,
    open: &mut OwnedVec<OpenValue<'a>, W>,
) -> Result<()> {
    let mut pair = sequence(parent, element, field)?;
    let kind = pair
        .read_oid()
        .map_err(|cause| Error::encoding(cause, field))?;
    let value = pair
        .next_element()
        .map_err(|cause| Error::encoding(cause, field))?;
    end(&pair, field)?;
    if role == OpenRole::SignedAssertion {
        let saml = Oid::from_bytes(&[4, 0, 0x81, 0x95, 0x32, 3, 0]);
        parent
            .charge(1 + kind.as_bytes().len().min(saml.as_bytes().len()) as u64)
            .map_err(|cause| Error::encoding(cause, field))?;
        // EN319122-1 §5.2.6.3 types this registered payload as OCTET STRING;
        // other assertion types stay open. Reading cannot authenticate SAML.
        // https://www.etsi.org/deliver/etsi_en/319100_319199/31912201/01.03.01_60/en_31912201v010301p.pdf
        if kind == saml
            && let Some(part) = value
        {
            Octets::read(&pair, &part, field)?;
        }
    }
    if role == OpenRole::PolicyQualifier
        && let Some(part) = value
    {
        // EN319122-1 §5.2.9.2 and AnnexD declare qualifier OPTIONAL,
        // including for registered OIDs. Only a present value has a type.
        // https://www.etsi.org/deliver/etsi_en/319100_319199/31912201/01.03.01_60/en_31912201v010301p.pdf
        let uri = Oid::from_bytes(&[42, 134, 72, 134, 247, 13, 1, 9, 16, 5, 1]);
        let notice = Oid::from_bytes(&[42, 134, 72, 134, 247, 13, 1, 9, 16, 5, 2]);
        let specification = Oid::from_bytes(&[4, 0, 0x81, 0x95, 0x32, 2, 1]);
        parent
            .charge(3 * (1 + kind.as_bytes().len() as u64))
            .map_err(|cause| Error::encoding(cause, field))?;
        if kind == uri || kind == notice || kind == specification {
            if kind == uri {
                uri_value(&pair, &part, field)?;
            } else if kind == specification {
                spec(&pair, &part, field)?;
            } else if !structured_pkix::policy::signature_notice_understood(&pair, &part)
                .map_err(Error::Pkix)?
            {
                return Err(syntax(field, part.span().start));
            }
        }
    }
    push(
        open,
        OpenValue {
            role,
            kind: Some(kind),
            enclosure: *element,
            value: value.map(|value| crate::source::Value::of(&pair, value, field)),
        },
        field,
    )
}

fn push<'a, W: Work>(
    out: &mut OwnedVec<OpenValue<'a>, W>,
    value: OpenValue<'a>,
    field: &'static str,
) -> Result<()> {
    let at = value.enclosure.span().start;
    out.try_push(value)
        .map_err(|cause| Error::resource(cause, field, at))
}

fn directory_string(parent: &Reader<'_>, value: &Element<'_>, field: &'static str) -> Result<()> {
    if ![12, 19, 20, 28, 30]
        .into_iter()
        .any(|number| value.tag() == Tag::primitive(number))
    {
        return Err(syntax(field, value.span().start));
    }
    string(parent, value, field)
}

fn string<'a>(parent: &Reader<'a>, value: &Element<'a>, field: &'static str) -> Result<()> {
    if value.contents().is_empty() {
        return Err(syntax(field, value.span().start));
    }
    structured_pkix::der::conforms(parent, value, field).map_err(Error::Pkix)
}

fn spec<'a>(parent: &Reader<'a>, value: &Element<'a>, field: &'static str) -> Result<()> {
    if value.tag() == Tag::primitive(universal::OID) {
        parent
            .oid(value)
            .map_err(|cause| Error::encoding(cause, field))?;
    } else {
        uri_value(parent, value, field)?;
    }
    Ok(())
}

fn uri_value<'a>(parent: &Reader<'a>, value: &Element<'a>, field: &'static str) -> Result<()> {
    let octets = Octets::read_ia5(parent, value, field)?;
    let work = parent.execution();
    let joined;
    let bytes = if let Some(one) = octets.as_one() {
        one
    } else {
        joined = octets.copy_in(parent, field, value.span().start)?;
        &joined
    };
    work.charge_work(1 + bytes.len() as u64)
        .map_err(|cause| Error::resource(cause, field, value.span().start))?;
    let text = core::str::from_utf8(bytes).map_err(|_| syntax(field, value.span().start))?;
    if !structured_pkix::general_name::uri_syntax(text, &work)
        .map_err(|cause| Error::resource(cause, field, value.span().start))?
    {
        return Err(syntax(field, value.span().start));
    }
    Ok(())
}

fn sequence<'a>(
    parent: &Reader<'a>,
    value: &Element<'a>,
    field: &'static str,
) -> Result<Reader<'a>> {
    require_tag(value, Tag::constructed(universal::SEQUENCE), field)?;
    parent
        .enter(value)
        .map_err(|cause| Error::encoding(cause, field))
}
fn next<'a>(reader: &mut Reader<'a>, field: &'static str) -> Result<Element<'a>> {
    reader
        .next_element()
        .map_err(|cause| Error::encoding(cause, field))?
        .ok_or_else(|| syntax(field, reader.offset()))
}
fn end(reader: &Reader<'_>, field: &'static str) -> Result<()> {
    if reader.is_empty() {
        Ok(())
    } else {
        Err(syntax(field, reader.offset()))
    }
}
fn require_tag(value: &Element<'_>, tag: Tag, field: &'static str) -> Result<()> {
    if value.tag() == tag {
        Ok(())
    } else {
        Err(syntax(field, value.span().start))
    }
}
fn syntax(field: &'static str, at: u64) -> Error {
    Error::Syntax {
        code: ErrorCode::AttributeSyntax,
        field,
        at,
    }
}