Skip to main content

structured_pkix/
name.rs

1//! Distinguished names, kept as they were encoded.
2//!
3//! A name has two jobs here and they pull in opposite directions. One is
4//! identity: an issuer name in one certificate has to be recognized as the
5//! subject name of another, or no path is ever built. The other is
6//! explanation: somebody has to read who this is.
7//!
8//! They are kept apart. Identity is the bytes, and the comparison below is the
9//! profile's rule over the encoded values. Explanation is [`Attribute::text`],
10//! which decodes for a person to read and is never what two names are compared
11//! on. A parser that folded the two would let a name that renders identically
12//! stand in for the one it imitates.
13
14use crate::error::{Error, ErrorCode, Located, Result};
15use crate::oid;
16#[cfg(test)]
17use alloc::vec::Vec;
18use structured_asn1::memory::{Memory, OwnedString, OwnedVec, Work};
19use structured_asn1::{Class, Element, Oid, Reader, Tag, universal};
20use unicode_bidi::BidiClass;
21
22mod fold;
23mod normalize;
24mod prepared;
25mod render;
26pub(crate) mod segments;
27mod selector;
28pub use selector::Selector;
29pub(crate) use selector::attribute_type_syntax_fits;
30pub(crate) use selector::syntax_fits as dn_syntax_fits;
31mod unassigned;
32
33/// A distinguished name, as the sequence of parts the certificate holds.
34#[derive(Debug)]
35pub struct Name<'a> {
36    der: &'a [u8],
37    parts: OwnedVec<RelativeName<'a>>,
38    offset: u64,
39    field: &'static str,
40}
41
42/// One part of a name: usually one attribute, occasionally several that are
43/// unordered among themselves.
44#[derive(Debug)]
45pub struct RelativeName<'a> {
46    attributes: OwnedVec<Attribute<'a>>,
47}
48
49/// One attribute of a name: what kind of thing it is, and the value.
50#[derive(Debug, Clone, Copy)]
51pub struct Attribute<'a> {
52    kind: Oid<'a>,
53    value: AttributeValue<'a>,
54}
55
56/// The value of an attribute, as it was encoded.
57#[derive(Debug, Clone, Copy)]
58pub struct AttributeValue<'a> {
59    tag: Tag,
60    contents: &'a [u8],
61    der: &'a [u8],
62    offset: u64,
63    // Original container depth for deferred constructed-string preparation.
64    depth: u32,
65}
66
67/// Which string encoding a value was written in, where it is a string at all.
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69#[non_exhaustive]
70pub enum Encoding {
71    /// `UTF8String`.
72    Utf8,
73    /// `PrintableString`, a restricted set of ASCII.
74    Printable,
75    /// `IA5String`, ASCII.
76    Ia5,
77    /// `VisibleString`, printable ASCII.
78    Visible,
79    /// `NumericString`, digits and spaces.
80    Numeric,
81    /// `TeletexString`, from before the others, and read here as an
82    /// approximation.
83    Teletex,
84    /// `BMPString`, sixteen bits a character.
85    Bmp,
86    /// `UniversalString`, thirty-two bits a character.
87    Universal,
88    /// Not a string type this crate reads as text.
89    Other,
90}
91
92impl<'a> Name<'a> {
93    /// The name exactly as it was encoded, which is what identity is.
94    #[must_use]
95    pub fn as_bytes(&self) -> &'a [u8] {
96        self.der
97    }
98
99    /// The parts, outermost first, as the certificate wrote them.
100    #[must_use]
101    pub fn parts(&self) -> &[RelativeName<'a>] {
102        &self.parts
103    }
104
105    /// Whether the name has no parts at all, which a certificate is allowed to
106    /// do when the subject is named somewhere else instead.
107    #[must_use]
108    pub fn is_empty(&self) -> bool {
109        self.parts.is_empty()
110    }
111
112    /// Copies descriptors into the current domain; document bytes remain borrowed.
113    ///
114    /// # Errors
115    /// Returns a located resource error before unfunded copying or allocation.
116    pub fn try_copy(&self, execution: &Memory) -> Result<Self> {
117        let mut parts = execution.vector();
118        for part in &self.parts {
119            execution
120                .charge_work(1)
121                .map_err(|reason| Error::resource(reason, self.field, self.offset))?;
122            parts
123                .try_push(part.try_copy(execution)?)
124                .map_err(|reason| Error::resource(reason, self.field, self.offset))?;
125        }
126        Ok(Self {
127            der: self.der,
128            parts,
129            offset: self.offset,
130            field: self.field,
131        })
132    }
133
134    /// Every attribute, in the order the name holds them.
135    /// The caller admits its own traversal of this borrowed view.
136    pub fn attributes(&self) -> impl Iterator<Item = &Attribute<'a>> {
137        self.parts.iter().flat_map(RelativeName::attributes)
138    }
139
140    /// The attributes of one kind, in order. Several is not an error: a name
141    /// can carry more than one organizational unit, and which one matters is
142    /// not this layer's decision.
143    /// Each search step is admitted in the current execution domain. A refusal
144    /// is yielded once, after which repeated `next()` calls do no further work.
145    /// Returned references borrow the name, independently of the budget borrow.
146    pub fn attributes_of<'n, 'q>(
147        &'n self,
148        kind: Oid<'q>,
149        execution: &'q Memory,
150    ) -> impl Iterator<Item = Result<&'n Attribute<'a>>> + 'q
151    where
152        'n: 'q,
153    {
154        let mut attributes = self.attributes();
155        let mut failed = false;
156        core::iter::from_fn(move || {
157            if failed {
158                return None;
159            }
160            for attribute in attributes.by_ref() {
161                let work = 1 + attribute.kind.as_bytes().len().max(kind.as_bytes().len()) as u64;
162                if let Err(reason) = execution.charge_work(work) {
163                    failed = true;
164                    return Some(Err(self.resource(reason)));
165                }
166                if attribute.kind == kind {
167                    return Some(Ok(attribute));
168                }
169            }
170            None
171        })
172    }
173
174    /// The first attribute of one kind.
175    pub fn attribute(&self, kind: Oid<'_>, execution: &Memory) -> Result<Option<&Attribute<'a>>> {
176        self.attributes_of(kind, execution).next().transpose()
177    }
178
179    /// The common name, which describes the subject and does not identify it.
180    pub fn common_name(&self, execution: &Memory) -> Result<Option<&Attribute<'a>>> {
181        self.attribute(oid::COMMON_NAME, execution)
182    }
183
184    /// The organization identifier, which is how a legal entity is identified
185    /// rather than described, and is the attribute an attribution decision may
186    /// rest on where the common name is not.
187    pub fn organization_identifier(&self, execution: &Memory) -> Result<Option<&Attribute<'a>>> {
188        self.attribute(oid::ORGANIZATION_IDENTIFIER, execution)
189    }
190
191    /// Whether two names are the same name, by the profile's rule: the same
192    /// parts in the same order, each holding the same attributes, with strings
193    /// compared under their declared equality rule.
194    ///
195    /// Directory strings are compared after the preparation the profile requires
196    /// (RFC 5280 7.1, over RFC 4518): the characters that carry no meaning
197    /// are dropped, case is folded in full, the value is normalized to form
198    /// KC, and runs of space count as one between words and none at the
199    /// edges. Unsupported types and nonconforming stored values retain their
200    /// encoded identity; that preservation does not validate an LDAP assertion.
201    /// Valid supported values use the schema's size bounds and the current
202    /// work/storage budget, independently of display truncation.
203    /// IA5 emailAddress and domainComponent values instead use their exact
204    /// ASCII case-insensitive rules without whitespace compression; the DN
205    /// emailAddress rule covers the whole value, unlike rfc822Name mailboxes.
206    /// Pseudonym uses caseExactMatch (RFC2985 §5.2.9): the same preparation
207    /// and insignificant-space handling, with case preserved.
208    ///
209    /// # Errors
210    /// Returns a located resource error before unfunded comparison work.
211    pub fn matches(&self, other: &Name<'_>, execution: &Memory) -> Result<bool> {
212        self.matches_with(other, execution, None)
213    }
214
215    /// Compares retained names under the current query reader's execution.
216    ///
217    /// Names may come from independently parsed certificates. Their storage
218    /// stays on its original account; normalization/comparison scratch and
219    /// deferred string decoding use the query's local and aggregate ceilings.
220    /// This is a comparison, not permission to reparse a foreign certificate.
221    pub fn matches_in(&self, other: &Name<'_>, parent: &Reader<'_>) -> Result<bool> {
222        self.matches_with(other, &parent.execution(), Some(parent))
223    }
224
225    pub(crate) fn matches_with<W: structured_asn1::memory::Work>(
226        &self,
227        other: &Name<'_>,
228        execution: &W,
229        parent: Option<&Reader<'_>>,
230    ) -> Result<bool> {
231        if self.parts.len() != other.parts.len() {
232            return Ok(false);
233        }
234        // Identical original encodings have the same retained wire identity.
235        // This fast path does not validate a nonconforming stored value.
236        if self.der.len() == other.der.len() {
237            execution
238                .charge_work(self.der.len() as u64)
239                .map_err(|reason| self.resource(reason))?;
240            if self.der == other.der {
241                return Ok(true);
242            }
243        }
244        Ok(self.order_with(other, execution, parent)? == core::cmp::Ordering::Equal)
245    }
246
247    pub(crate) fn offset(&self) -> u64 {
248        self.offset
249    }
250
251    pub(crate) fn field(&self) -> &'static str {
252        self.field
253    }
254
255    pub(crate) fn resource(&self, reason: structured_asn1::memory::MemoryError) -> Error {
256        Error::resource(reason, self.field, self.offset)
257    }
258
259    /// A total order over names that calls two of them equal exactly when
260    /// [`Name::matches`] does.
261    ///
262    /// It exists so that a set of names can be searched rather than walked. A
263    /// caller holding many certificates and asking which one a name belongs to
264    /// otherwise compares against every one of them, and comparing names is
265    /// where the profile's folding lives; ordering them once turns that into a
266    /// search. Answering the same question two ways is only safe because this
267    /// is the same comparison: it is built from the ordering the multiset
268    /// matching already uses, not from a second reading of what identity is.
269    ///
270    /// Preparation and comparison use the current execution domain. Unicode
271    /// scratch storage is released when this comparison returns.
272    ///
273    /// # Errors
274    /// Returns a located resource error before unfunded preparation or comparison.
275    pub fn order(&self, other: &Name<'_>, execution: &Memory) -> Result<core::cmp::Ordering> {
276        self.order_with(other, execution, None)
277    }
278
279    fn order_with<W: structured_asn1::memory::Work>(
280        &self,
281        other: &Name<'_>,
282        execution: &W,
283        parent: Option<&Reader<'_>>,
284    ) -> Result<core::cmp::Ordering> {
285        let order = self.parts.len().cmp(&other.parts.len());
286        if order != core::cmp::Ordering::Equal {
287            return Ok(order);
288        }
289        // Stop at the first distinguishing RDN: unrelated tail values must
290        // not pay for normalization or scratch storage that cannot affect order.
291        for (left, right) in self.parts.iter().zip(&other.parts) {
292            execution
293                .charge_work(1)
294                .map_err(|reason| Error::resource(reason, self.field, self.offset))?;
295            let order = prepared::compare_parts_in(left, right, execution, parent)?;
296            if order != core::cmp::Ordering::Equal {
297                return Ok(order);
298            }
299        }
300        Ok(core::cmp::Ordering::Equal)
301    }
302
303    /// Prepares this name once for repeated comparisons.
304    ///
305    /// Encoded values remain borrowed. Sorted descriptors and any Unicode
306    /// canonical text retain their storage charge until this result is dropped.
307    /// Comparisons subsequently use the execution domain passed to them.
308    ///
309    /// # Errors
310    /// Returns a located resource error if preparation cannot be financed.
311    pub fn ordered(&self, execution: &Memory) -> Result<Ordered<'a>> {
312        Ok(Ordered {
313            prepared: prepared::PreparedName::of(&self.parts, execution)?,
314            offset: self.offset,
315        })
316    }
317
318    /// Prepares a cache inside the current producing operation's work ceilings.
319    ///
320    /// Original document values and their retained nesting depths remain intact.
321    /// Deferred BER strings use the supplied reader's session/account instead
322    /// of a new Parser. Cache storage retains its current account; its work
323    /// owner borrows the operation independently of the document's lifetime.
324    /// This is the same semantic order as [`Name::ordered`], with scoped funding.
325    pub fn ordered_in<'p>(
326        &self,
327        parent: &'p Reader<'_>,
328    ) -> Result<Ordered<'a, structured_asn1::memory::Execution<'p>>> {
329        Ok(Ordered {
330            prepared: prepared::PreparedName::of_in(
331                &self.parts,
332                &parent.execution(),
333                Some(parent),
334            )?,
335            offset: self.offset,
336        })
337    }
338
339    /// Whether this name sits below another one: the parts of the other, in
340    /// order, from the top down, and anything at all after them.
341    ///
342    /// This is the containment a name-constraint subtree asks about, where
343    /// the base "specifies a subtree of the X.500 directory tree" and a name
344    /// is within it when it begins with the base (RFC 5280 4.2.1.10). A base
345    /// of no parts is the root of the tree and holds every name. Parts are
346    /// compared by the rule identity uses, so a name sits below itself.
347    ///
348    /// # Errors
349    /// Returns a located resource error before unfunded prefix preparation.
350    pub fn starts_with(&self, base: &Name<'_>, execution: &Memory) -> Result<bool> {
351        if base.parts.len() > self.parts.len() {
352            return Ok(false);
353        }
354        for (left, right) in self.parts.iter().zip(&base.parts) {
355            execution
356                .charge_work(1)
357                .map_err(|reason| self.resource(reason))?;
358            let order = prepared::compare_parts(left, right, execution)?;
359            if order != core::cmp::Ordering::Equal {
360                return Ok(false);
361            }
362        }
363        Ok(true)
364    }
365}
366
367/// A prepared name with independently accounted descriptors and canonical text.
368///
369/// Encoded values borrow the source document. Storage charges survive the
370/// parser; every comparison is paid by its explicit current execution domain.
371#[derive(Debug)]
372pub struct Ordered<'a, W: structured_asn1::memory::Work = Memory> {
373    prepared: prepared::PreparedName<'a, W>,
374    offset: u64,
375}
376
377impl<W: structured_asn1::memory::Work> Ordered<'_, W> {
378    /// The same order [`Name::order`] gives, using already prepared values.
379    ///
380    /// # Errors
381    /// Returns a located resource error before unfunded comparison work.
382    pub fn order<V: structured_asn1::memory::Work, E: structured_asn1::memory::Work>(
383        &self,
384        other: &Ordered<'_, V>,
385        execution: &E,
386    ) -> Result<core::cmp::Ordering> {
387        self.prepared
388            .order(&other.prepared, execution)
389            .map_err(|reason| Error::resource(reason, "name", self.offset))
390    }
391}
392
393/// Match virtual names without inventing an encoding for the appended RDN.
394/// CRL distribution names append relative fragments to their own issuer bases.
395/// The existing prepared-part core owns all attribute and SET semantics.
396pub(crate) fn matches_composed<const ENCODED: bool>(
397    left: &Name<'_>,
398    left_suffix: Option<&RelativeName<'_>>,
399    right: &Name<'_>,
400    right_suffix: Option<&RelativeName<'_>>,
401    execution: &Memory,
402) -> Result<bool> {
403    if left_suffix.is_none() && right_suffix.is_none() {
404        if ENCODED {
405            return encoded_bytes_match(left.der, right.der, left, execution);
406        }
407        return left.matches(right, execution);
408    }
409    if ENCODED && let (Some(left_part), Some(right_part)) = (left_suffix, right_suffix) {
410        // The original DP fields encode the relative RDN, not their issuer
411        // bases. RFC5280 §5.2.5 fixes that RDN encoding; §6.3.3(b)(1) retains
412        // ordinary issuer-name equality for the separately encoded bases.
413        if !left.matches(right, execution)? {
414            return Ok(false);
415        }
416        return encoded_parts_match(left_part, right_part, left, execution);
417    }
418    let left_len = left
419        .parts
420        .len()
421        .checked_add(usize::from(left_suffix.is_some()))
422        .ok_or_else(|| left.resource(structured_asn1::memory::MemoryError::WorkExceeded))?;
423    let right_len = right
424        .parts
425        .len()
426        .checked_add(usize::from(right_suffix.is_some()))
427        .ok_or_else(|| right.resource(structured_asn1::memory::MemoryError::WorkExceeded))?;
428    if left_len != right_len {
429        return Ok(false);
430    }
431    for index in 0..left_len {
432        execution
433            .charge_work(1)
434            .map_err(|reason| left.resource(reason))?;
435        let left_part = if index < left.parts.len() {
436            &left.parts[index]
437        } else {
438            left_suffix.expect("suffix was counted")
439        };
440        let right_part = if index < right.parts.len() {
441            &right.parts[index]
442        } else {
443            right_suffix.expect("suffix was counted")
444        };
445        let matches = if ENCODED {
446            encoded_parts_match(left_part, right_part, left, execution)?
447        } else {
448            prepared::compare_parts(left_part, right_part, execution)? == core::cmp::Ordering::Equal
449        };
450        if !matches {
451            return Ok(false);
452        }
453    }
454    Ok(true)
455}
456
457fn encoded_bytes_match(
458    left: &[u8],
459    right: &[u8],
460    source: &Name<'_>,
461    execution: &Memory,
462) -> Result<bool> {
463    let work = u64::try_from(left.len().max(right.len()))
464        .ok()
465        .and_then(|n| n.checked_mul(2))
466        .and_then(|n| n.checked_add(1))
467        .ok_or_else(|| source.resource(structured_asn1::memory::MemoryError::WorkExceeded))?;
468    execution
469        .charge_work(work)
470        .map_err(|reason| source.resource(reason))?;
471    Ok(left == right)
472}
473
474fn encoded_parts_match(
475    left: &RelativeName<'_>,
476    right: &RelativeName<'_>,
477    source: &Name<'_>,
478    execution: &Memory,
479) -> Result<bool> {
480    if left.attributes.len() != right.attributes.len() {
481        return Ok(false);
482    }
483    // Original DER SET order and canonical tag/length encoding make exact OID
484    // plus complete value TLVs sufficient for exact RDN encoding, without an
485    // encode/reparse bridge. No attribute preparation or reordering occurs.
486    for (left, right) in left.attributes.iter().zip(right.attributes.iter()) {
487        execution
488            .charge_work(1)
489            .map_err(|reason| source.resource(reason))?;
490        if !encoded_bytes_match(
491            left.kind.as_bytes(),
492            right.kind.as_bytes(),
493            source,
494            execution,
495        )? || !encoded_bytes_match(left.value.der, right.value.der, source, execution)?
496        {
497            return Ok(false);
498        }
499    }
500    Ok(true)
501}
502
503impl<'a> RelativeName<'a> {
504    /// The attributes of this part.
505    #[must_use]
506    pub fn attributes(&self) -> &[Attribute<'a>] {
507        &self.attributes
508    }
509
510    /// Copies borrowed descriptors into independently accounted storage.
511    ///
512    /// # Errors
513    /// Returns a located resource error before unfunded copying or allocation.
514    pub fn try_copy(&self, execution: &Memory) -> Result<Self> {
515        let mut attributes = execution.vector();
516        attributes
517            .try_extend_from_slice(&self.attributes)
518            .map_err(|reason| {
519                Error::resource(reason, "name.relative", self.attributes[0].value.offset)
520            })?;
521        Ok(Self { attributes })
522    }
523
524    /// Whether two parts hold the same attributes. They are a set, so order
525    /// within a part is not part of what they say, and the correspondence is
526    /// one to one: a part written with a duplicate does not match a part
527    /// without one.
528    ///
529    /// Both sides are ordered by a total order that agrees with attribute
530    /// equality, then compared in step. Ordering is streamed: nothing is
531    /// materialized, so a part holding a value the element limit permits, up
532    /// to four gibibytes, costs a list of references and not a copy of the
533    /// value. The alternative, one canonical key per attribute, is a copy the
534    /// size of the name; scanning one list per attribute of the other is work
535    /// proportional to the square of a count the parse budget never sees.
536    #[must_use]
537    #[cfg(test)]
538    fn matches(&self, other: &RelativeName<'_>) -> bool {
539        if self.attributes.len() != other.attributes.len() {
540            return false;
541        }
542        // One attribute is the common case, and it needs no ordering at all.
543        if let ([left], [right]) = (&self.attributes[..], &other.attributes[..]) {
544            return left.matches(right);
545        }
546        let mut ours: Vec<&Attribute<'a>> = self.attributes.iter().collect();
547        let mut theirs: Vec<&Attribute<'_>> = other.attributes.iter().collect();
548        ours.sort_unstable_by(|left, right| left.order(right));
549        theirs.sort_unstable_by(|left, right| left.order(right));
550        ours.iter()
551            .zip(&theirs)
552            .all(|(left, right)| left.matches(right))
553    }
554
555    /// A total order over parts that calls two of them equal exactly when
556    /// [`RelativeName::matches`] does, built the same way: both sides ordered
557    /// by the attribute order, then compared in step.
558    #[cfg(test)]
559    fn order(&self, other: &RelativeName<'_>) -> core::cmp::Ordering {
560        self.attributes
561            .len()
562            .cmp(&other.attributes.len())
563            .then_with(|| {
564                if let ([left], [right]) = (&self.attributes[..], &other.attributes[..]) {
565                    return left.order(right);
566                }
567                let mut ours: Vec<&Attribute<'a>> = self.attributes.iter().collect();
568                let mut theirs: Vec<&Attribute<'_>> = other.attributes.iter().collect();
569                ours.sort_unstable_by(|left, right| left.order(right));
570                theirs.sort_unstable_by(|left, right| left.order(right));
571                ours.iter()
572                    .zip(&theirs)
573                    .map(|(left, right)| left.order(right))
574                    .find(|ordering| ordering.is_ne())
575                    .unwrap_or(core::cmp::Ordering::Equal)
576            })
577    }
578}
579
580/// The value syntax of an attribute type this crate names, or `None` for a
581/// kind it does not.
582fn syntax_of(kind: Oid<'_>) -> Option<Syntax> {
583    // The X.520 attributes whose value is a DirectoryString.
584    const DIRECTORY: &[Oid<'static>] = &[
585        oid::COMMON_NAME,
586        oid::SURNAME,
587        oid::LOCALITY,
588        oid::STATE_OR_PROVINCE,
589        oid::STREET_ADDRESS,
590        oid::ORGANIZATION,
591        oid::ORGANIZATIONAL_UNIT,
592        oid::TITLE,
593        oid::GIVEN_NAME,
594        oid::INITIALS,
595        oid::GENERATION_QUALIFIER,
596        oid::PSEUDONYM,
597        oid::ORGANIZATION_IDENTIFIER,
598        oid::USER_ID,
599    ];
600    if DIRECTORY.contains(&kind) {
601        Some(Syntax::Directory)
602    } else if kind == oid::COUNTRY || kind == oid::SERIAL_NUMBER || kind == oid::DN_QUALIFIER {
603        // X.520 gives these a PrintableString.
604        Some(Syntax::Printable)
605    } else if kind == oid::EMAIL_ADDRESS || kind == oid::DOMAIN_COMPONENT {
606        // And these an IA5String.
607        Some(Syntax::Ia5)
608    } else {
609        None
610    }
611}
612
613/// The value syntaxes the named attribute types take.
614#[derive(Clone, Copy)]
615enum Syntax {
616    /// The `DirectoryString` choice of X.520.
617    Directory,
618    /// A `PrintableString`.
619    Printable,
620    /// An `IA5String`.
621    Ia5,
622}
623
624impl Syntax {
625    fn permits(self, encoding: Encoding) -> bool {
626        match self {
627            Self::Directory => matches!(
628                encoding,
629                Encoding::Utf8
630                    | Encoding::Printable
631                    | Encoding::Teletex
632                    | Encoding::Bmp
633                    | Encoding::Universal
634            ),
635            Self::Printable => encoding == Encoding::Printable,
636            Self::Ia5 => encoding == Encoding::Ia5,
637        }
638    }
639}
640
641/// Whether an attribute type's schema permits folding a value in one string
642/// encoding. A value outside its type's choices takes part in identity as
643/// bytes only: text folded out of an encoding the type does not have would
644/// let a malformed value match a genuine one it never equals. And a kind
645/// this crate does not name may define case-sensitive equality, so folding
646/// under a rule the type may not have would match names that differ: its
647/// values too equal themselves and nothing else.
648fn permits(kind: Oid<'_>, encoding: Encoding) -> bool {
649    syntax_of(kind).is_some_and(|syntax| syntax.permits(encoding))
650}
651
652/// The size an attribute kind's schema puts on its value, in characters:
653/// the country is exactly two, and the rest follow the upper bounds of
654/// RFC 5280 appendix A. A kind the appendix does not bound stays unbounded.
655fn size_bounds(kind: Oid<'_>) -> (usize, usize) {
656    if kind == oid::COUNTRY {
657        (2, 2)
658    } else if kind == oid::COMMON_NAME
659        || kind == oid::ORGANIZATION
660        || kind == oid::ORGANIZATIONAL_UNIT
661        || kind == oid::TITLE
662        || kind == oid::SERIAL_NUMBER
663    {
664        (1, 64)
665    } else if kind == oid::LOCALITY || kind == oid::STATE_OR_PROVINCE {
666        (1, 128)
667    } else if kind == oid::EMAIL_ADDRESS {
668        (1, 255)
669    } else if kind == oid::PSEUDONYM {
670        (1, 128)
671    } else if kind == oid::STREET_ADDRESS {
672        // ub-street-address (X.520).
673        (1, 128)
674    } else if kind == oid::SURNAME
675        || kind == oid::GIVEN_NAME
676        || kind == oid::INITIALS
677        || kind == oid::GENERATION_QUALIFIER
678    {
679        // The name components share ub-name, 32768.
680        (1, 32768)
681    } else {
682        (1, usize::MAX)
683    }
684}
685
686/// Whether an attribute of a kind this crate names is written inside that
687/// kind's syntax: the encoding is one its type permits, the value decodes
688/// under it, and the decoded text fits the size the schema gives the kind.
689/// An unknown kind answers yes, having no schema here to hold it to; where
690/// an identity must have been read entirely, this is the question each
691/// attribute is asked.
692pub(crate) fn well_formed(attribute: &Attribute<'_>) -> bool {
693    inside_syntax(attribute, Asking::Shape, |_| true)
694}
695
696/// Schema validation of retained string bytes, admitted before scanning.
697pub(crate) fn well_formed_in(
698    attribute: &Attribute<'_>,
699    parent: &Reader<'_>,
700    field: &'static str,
701) -> Result<bool> {
702    let work = (attribute.kind.as_bytes().len() as u64)
703        .checked_mul(64)
704        .and_then(|kinds| {
705            (attribute.value.contents.len() as u64)
706                .checked_mul(2)
707                .and_then(|contents| kinds.checked_add(contents))
708        })
709        .and_then(|work| work.checked_add(1))
710        .ok_or_else(|| {
711            Error::resource(
712                structured_asn1::memory::MemoryError::WorkExceeded,
713                field,
714                attribute.value.offset,
715            )
716        })?;
717    parent.charge(work).field(field)?;
718    let value = attribute.value;
719    if value.tag.is_constructed()
720        && value.tag.class() == Class::Universal
721        && value.tag.number().is_some_and(segmented_universal_type)
722        && value.tag.number() != Some(universal::BIT_STRING)
723        && syntax_of(attribute.kind).is_some()
724    {
725        // X.690 §8.23: the BER restricted-string spelling has OCTET STRING
726        // fragments. Validate the joined logical value under the same schema
727        // rather than treating its constructed tag as unsupported text.
728        // https://www.itu.int/rec/T-REC-X.690-202102-I/en
729        debug_assert!(value.depth > 0);
730        let mut reader = parent
731            .parser()
732            .read_nested_query_in(
733                parent,
734                value.der,
735                value.offset,
736                structured_asn1::Encoding::Ber,
737                value.depth - 1,
738            )
739            .field(field)?;
740        let element = reader
741            .next_element()
742            .field(field)?
743            .expect("retained complete attribute value");
744        let execution = parent.execution();
745        let mut contents = execution.vector();
746        segments::walk_in(
747            &reader,
748            &element,
749            field,
750            false,
751            Some(&mut contents),
752            &execution,
753        )?;
754        parent
755            .charge((contents.len() as u64).checked_mul(2).ok_or_else(|| {
756                Error::resource(
757                    structured_asn1::memory::MemoryError::WorkExceeded,
758                    field,
759                    value.offset,
760                )
761            })?)
762            .field(field)?;
763        return Ok(well_formed(&Attribute {
764            kind: attribute.kind,
765            value: AttributeValue {
766                tag: Tag::primitive(value.tag.number().expect("universal string")),
767                contents: &contents,
768                ..value
769            },
770        }));
771    }
772    Ok(well_formed(attribute))
773}
774
775/// Display text may truncate at this bound. Identity preparation instead uses
776/// the schema bound and the operation's admitted work/storage: RFC5280 §7.1
777/// requires `StringPrep` for valid `UTF8String`/`PrintableString` values.
778/// A display limit must never silently substitute binary equality.
779/// <https://www.rfc-editor.org/rfc/rfc5280.html#section-7.1>
780const DISPLAY_CEILING: usize = 32_768;
781
782/// Whether the preparation can run on a value at all.
783///
784/// Unsupported encodings, malformed stored values and prohibited code points
785/// retain only their encoded identity. That preservation does not validate
786/// an LDAP assertion. Valid values have no display-derived preparation limit.
787#[cfg(test)]
788fn preparable(attribute: &Attribute<'_>) -> bool {
789    if !inside_syntax(attribute, Asking::Folding, |c| !prohibited(c)) {
790        return false;
791    }
792    // The direction step reads the value the normalizing step leaves, which
793    // is the order the profile puts them in (RFC 4518 2, steps 3 then 5).
794    // The order decides the answer: a compatibility form can expand into
795    // letters of a direction the character it replaces did not have, U+2121
796    // into TEL, so a value read before normalizing can look right-to-left
797    // and be mixed once prepared. The walk is bounded by the step above,
798    // which already held the value to the size its schema gives it.
799    let mut direction = Direction::default();
800    for c in normalized(attribute.value.decoded_chars()) {
801        direction.see(c);
802    }
803    direction.settled()
804}
805
806/// The direction step of the preparation (RFC 4518 2.5, over RFC 3454 6),
807/// read as the value is scanned.
808///
809/// A value holding a right-to-left letter may hold no left-to-right one, and
810/// must begin and end with a right-to-left one. Failing either leaves the
811/// value unprepared, which here means compared as bytes.
812///
813/// The edges are decided on the characters that are still there when the
814/// preparation ends. The step that drops the spaces at the edges is part of
815/// the same preparation and comes after this one, so holding a value to an
816/// edge its own preparation deletes would refuse it over its spacing rather
817/// than over its direction.
818///
819/// The steps before this one decide what it sees, so it reads the value as
820/// they leave it: mapped and normalized. The mapping sends a set of
821/// characters to nothing, and the direction marks are among them: a value is
822/// written right to left because of its letters, not because it carries a
823/// mark saying so, and counting a mark the preparation deletes would refuse
824/// a name over a character that is not there by the time anything compares
825/// it. Normalizing matters here too, and in the other direction: a
826/// compatibility form can expand into letters that carry a direction the
827/// character it replaces did not have, U+2121 into TEL, so a value read
828/// before that step can look settled and be mixed after it.
829#[derive(Default)]
830struct Direction {
831    /// The first character that is not a space, and whether it is
832    /// right-to-left.
833    first: Option<bool>,
834    /// The same for the last one seen so far.
835    last: bool,
836    any_right: bool,
837    any_left: bool,
838}
839
840impl Direction {
841    fn see(&mut self, c: char) {
842        if mapped_to_nothing(c) || c.is_whitespace() {
843            return;
844        }
845        let class = unicode_bidi::bidi_class(c);
846        let right = matches!(class, BidiClass::R | BidiClass::AL);
847        if self.first.is_none() {
848            self.first = Some(right);
849        }
850        self.last = right;
851        self.any_right |= right;
852        self.any_left |= class == BidiClass::L;
853    }
854
855    fn settled(&self) -> bool {
856        !self.any_right || (!self.any_left && self.first == Some(true) && self.last)
857    }
858}
859
860/// Whether the profile prohibits a code point (RFC 4518 2.4).
861///
862/// Private use, the non-characters, and the replacement character a decoder
863/// writes when it could not read something: nobody agrees what any of them
864/// says, so nothing downstream can be defined over them. None of the three
865/// is touched by the mapping or the normalization, so asking about them
866/// before those steps is asking about the same characters they ask about.
867/// Surrogates are prohibited too and cannot arrive: nothing here produces
868/// one, because a character is a scalar value.
869///
870/// The step also prohibits the deprecated code points and the ones that
871/// change display properties, and none of those can reach it. The mapping
872/// sends the display controls to nothing two steps earlier, and the
873/// normalization takes the two deprecated tone marks to the ordinary marks
874/// they are equivalent to. Testing for them here would refuse a value the
875/// profile prepares, which is a name that stops matching itself.
876///
877/// The step's table of code points unassigned in Unicode 3.2 is applied,
878/// which costs the folded comparison for a character assigned since. That is
879/// the direction to lose in. The preparation is defined over one repertoire,
880/// and every step after this one is a table this crate reaches at its
881/// current version: a character the profile never saw carries a case folding
882/// and a compatibility decomposition today, so folding one makes two names
883/// equal by a rule the profile does not contain. Refusing it leaves the two
884/// compared as bytes, which reports a path as unproven; folding it can
885/// report an issuer as a subject it is not.
886fn prohibited(c: char) -> bool {
887    let point = u32::from(c);
888    unassigned::in_unicode_3_2(c)
889        || matches!(c,
890        // Private use (RFC 3454 C.3).
891        '\u{e000}'..='\u{f8ff}' | '\u{f0000}'..='\u{ffffd}' | '\u{100000}'..='\u{10fffd}'
892        // The non-characters of the arabic presentation forms (C.4).
893        | '\u{fdd0}'..='\u{fdef}'
894        // The replacement character.
895        | '\u{fffd}')
896        // The last two code points of every plane, which are the rest of C.4.
897        || point & 0xfffe == 0xfffe
898}
899
900/// Which of the two questions about a value is being asked.
901///
902/// They differ where a value can be kept without being read. A value whose
903/// shape its schema names is not refused, and it is what the two callers of
904/// this share; whether the preparation can then run on it is a narrower
905/// question, and answering no to it costs a folded comparison rather than a
906/// certificate.
907#[derive(Clone, Copy, PartialEq, Eq)]
908enum Asking {
909    /// Whether the value is written inside its kind's syntax at all. A no
910    /// here refuses the value where an identity must have been read whole.
911    Shape,
912    /// Whether the preparation the comparison runs can run on this value.
913    /// A no here leaves it compared as bytes.
914    Folding,
915}
916
917/// The shared reading of an attribute against its kind's schema, with a
918/// further test on each character the caller supplies.
919fn inside_syntax(
920    attribute: &Attribute<'_>,
921    asking: Asking,
922    mut keep: impl FnMut(char) -> bool,
923) -> bool {
924    match syntax_of(attribute.kind) {
925        Some(syntax) => {
926            let (least, schema) = size_bounds(attribute.kind);
927            let most = schema;
928            // The ceiling is checked on the encoded bytes first: no encoding
929            // here spends fewer than one byte per character or more than
930            // four, so a value whose bytes exceed four times the character
931            // bound can never fit it. The saturation is deliberate: an
932            // unbounded kind saturates the ceiling to the type's maximum,
933            // and the streaming scan below still touches it one character
934            // at a time without materializing a copy the size of the value.
935            if attribute.value.contents().len() > most.saturating_mul(4) {
936                return false;
937            }
938            if !syntax.permits(attribute.value.encoding()) {
939                return false;
940            }
941            // TeletexString is T.61, and its repertoire is a negotiation this
942            // crate does not implement: the bytes being there and inside the
943            // size the schema gives the kind is what is checkable. Asking it
944            // to decode as anything would call a legacy value malformed, and
945            // where a name must be written inside its syntax that refuses a
946            // certificate over an encoding the schema names. It is counted
947            // in bytes here and not folded at all, which is the other half
948            // of the same answer: a value nobody has agreed how to read
949            // takes part in identity as its bytes.
950            if attribute.value.encoding() == Encoding::Teletex && asking == Asking::Shape {
951                return (least..=most).contains(&attribute.value.contents().len());
952            }
953            let country = attribute.kind == oid::COUNTRY;
954            attribute
955                .value
956                // The country is a two-letter ISO 3166 code: digits and
957                // punctuation fit the printable repertoire and the size
958                // without naming any country. Case is left to folding.
959                .validated_count(|c| (!country || c.is_ascii_alphabetic()) && keep(c))
960                .is_some_and(|count| (least..=most).contains(&count))
961        }
962        None => true,
963    }
964}
965
966/// Whether the preparation this comparison runs sends a character to nothing.
967///
968/// The Map step of the string preparation the profile requires (RFC 5280 7.1,
969/// which requires RFC 4518) sends soft hyphen, the grapheme joiner, the
970/// variation selectors, the object replacement character, the zero width
971/// space and "all other control code (e.g., Cc) points or code points with a
972/// control function (e.g., Cf)" to nothing. The list below is the one that
973/// section writes out. What it does NOT contain is tab, line feed, vertical
974/// tab, form feed, carriage return and next line: those are mapped to SPACE,
975/// which is why the whitespace fold beside this covers them.
976fn mapped_to_nothing(c: char) -> bool {
977    matches!(
978        c,
979        '\u{00ad}'
980            | '\u{1806}'
981            | '\u{034f}'
982            | '\u{180b}'..='\u{180d}'
983            | '\u{fe00}'..='\u{fe0f}'
984            | '\u{fffc}'
985            | '\u{0000}'..='\u{0008}'
986            | '\u{000e}'..='\u{001f}'
987            | '\u{007f}'..='\u{0084}'
988            | '\u{0086}'..='\u{009f}'
989            | '\u{06dd}'
990            | '\u{070f}'
991            | '\u{180e}'
992            | '\u{200b}'..='\u{200f}'
993            | '\u{202a}'..='\u{202e}'
994            | '\u{2060}'..='\u{2063}'
995            | '\u{206a}'..='\u{206f}'
996            | '\u{feff}'
997            | '\u{fff9}'..='\u{fffb}'
998            | '\u{1d173}'..='\u{1d17a}'
999            | '\u{e0001}'
1000            | '\u{e0020}'..='\u{e007f}'
1001    )
1002}
1003
1004/// Streams the canonical form of a character stream: the preparation's steps
1005/// in the order it gives them, each one an adapter over the one before, so
1006/// that no step ever holds the value.
1007///
1008/// Map (RFC 4518 2.2), then Normalize (2.3), then the insignificant space
1009/// handling (2.6.1). The order is the profile's and it is not free to
1010/// change: normalization can produce a space of its own, out of a character
1011/// whose compatibility form begins with one, and a space it produces has to
1012/// reach the step that decides which spaces count.
1013///
1014/// The mapping runs on both sides of the normalization, which is what makes
1015/// it the profile's mapping rather than a case fold. The table the profile
1016/// names is B.2 of RFC 3454, a fold that carries the compatibility mappings
1017/// with it: `2102; 0063; Additional folding` takes the double-struck
1018/// capital C straight to a lowercase c. This crate's fold is the published
1019/// case folding, which leaves that character alone, and the normalization
1020/// after it produces a capital. Folding what the normalization produces
1021/// arrives where the profile's table does, and costs a second walk of a
1022/// stream already bounded.
1023///
1024/// What bounds the work is upstream of here: only an attribute type this
1025/// crate names is folded at all, and only inside the size its schema gives
1026/// it, so the longest stream this sees is a few tens of thousands of
1027/// characters rather than a document's worth.
1028#[cfg(test)]
1029type Canonical<I> = Spaced<Mapped<Recomposed<Mapped<I>>>>;
1030
1031/// What the normalization step hands on, named so the pipeline above reads
1032/// as the steps it is.
1033#[cfg(test)]
1034type Recomposed<I> = unicode_normalization::Recompositions<I>;
1035
1036/// Assembles the pipeline over one decoded value.
1037#[cfg(test)]
1038fn canonical<I: Iterator<Item = char>>(inner: I) -> Canonical<I> {
1039    Spaced::over(Mapped::over(normalized(inner)))
1040}
1041
1042/// The value as the two steps before the direction one leave it: mapped
1043/// (RFC 4518 2.2), then normalized to form KC (2.3).
1044///
1045/// The steps that read a value rather than produce one, Prohibit and the
1046/// direction check, come after these two (2.4 and 2.5), so this is the
1047/// stream they are defined over.
1048#[cfg(test)]
1049fn normalized<I: Iterator<Item = char>>(inner: I) -> Recomposed<Mapped<I>> {
1050    use unicode_normalization::UnicodeNormalization;
1051    Mapped::over(inner).nfkc()
1052}
1053
1054/// The Map step: what the preparation sends to nothing is dropped, what it
1055/// sends to SPACE becomes one, and case is folded. One held expansion is the
1056/// whole state.
1057///
1058/// The characters mapped to a space are exactly the ones RFC 4518 names: tab,
1059/// line feed, vertical tab, form feed, carriage return and next line, plus
1060/// the separator code points, which is what `is_whitespace` names.
1061struct Mapped<I, const FOLD_CASE: bool = true> {
1062    inner: I,
1063    /// What one folded character expands to, which is at most a few.
1064    folded: Option<Folded>,
1065}
1066
1067/// The tail of one character's fold, after its first character has been
1068/// handed out.
1069enum Folded {
1070    Mapped(core::str::Chars<'static>),
1071    Lowered(core::char::ToLowercase),
1072}
1073
1074impl Iterator for Folded {
1075    type Item = char;
1076
1077    fn next(&mut self) -> Option<char> {
1078        match self {
1079            Self::Mapped(rest) => rest.next(),
1080            Self::Lowered(rest) => rest.next(),
1081        }
1082    }
1083}
1084
1085impl<I: Iterator<Item = char>, const FOLD_CASE: bool> Mapped<I, FOLD_CASE> {
1086    fn over(inner: I) -> Self {
1087        Self {
1088            inner,
1089            folded: None,
1090        }
1091    }
1092
1093    /// Folds one character's case and hands back its first output, keeping
1094    /// the rest for the next call.
1095    ///
1096    /// The fold is the one the preparation names (RFC 4518 2.2 folds case by
1097    /// the table of RFC 3454 B.2): a letter may fold to a different letter
1098    /// or to more than one, and an issuer written in one case is the same
1099    /// name as the subject written in another. See [`fold`] for what the map
1100    /// is and what it still leaves out.
1101    fn fold(&mut self, c: char) -> Option<char> {
1102        match fold::of(c) {
1103            fold::Fold::Mapped(mapped) => {
1104                let mut rest = mapped.chars();
1105                let first = rest.next();
1106                self.folded = Some(Folded::Mapped(rest));
1107                first
1108            }
1109            fold::Fold::One(one) => {
1110                self.folded = None;
1111                Some(one)
1112            }
1113            fold::Fold::Lowercase => {
1114                let mut lowered = c.to_lowercase();
1115                let first = lowered.next();
1116                self.folded = Some(Folded::Lowered(lowered));
1117                first
1118            }
1119        }
1120    }
1121}
1122
1123impl<I: Iterator<Item = char>, const FOLD_CASE: bool> Iterator for Mapped<I, FOLD_CASE> {
1124    type Item = char;
1125
1126    fn next(&mut self) -> Option<char> {
1127        if let Some(rest) = self.folded.as_mut()
1128            && let Some(c) = rest.next()
1129        {
1130            return Some(c);
1131        }
1132        self.folded = None;
1133        for c in self.inner.by_ref() {
1134            // Mapped to nothing, so it takes no part in what the value says
1135            // and does not separate words either.
1136            if mapped_to_nothing(c) {
1137                continue;
1138            }
1139            if c.is_whitespace() {
1140                return Some(' ');
1141            }
1142            return if FOLD_CASE { self.fold(c) } else { Some(c) };
1143        }
1144        None
1145    }
1146}
1147
1148/// The insignificant space handling: a run of spaces between words counts as
1149/// one and the runs at either end count as none.
1150///
1151/// The profile writes the same rule as padding rather than trimming, one
1152/// space at each end and two between words (RFC 4518 2.6.1), which is what
1153/// makes a substring assertion's edges line up. For deciding whether two
1154/// whole values are equal the two forms put exactly the same values
1155/// together, and this one holds one character of state instead of emitting
1156/// an edge the value does not have.
1157struct Spaced<I> {
1158    inner: I,
1159    held: Option<char>,
1160    gap: bool,
1161    started: bool,
1162}
1163
1164impl<I: Iterator<Item = char>> Spaced<I> {
1165    fn over(inner: I) -> Self {
1166        Self {
1167            inner,
1168            held: None,
1169            gap: false,
1170            started: false,
1171        }
1172    }
1173}
1174
1175impl<I: Iterator<Item = char>> Iterator for Spaced<I> {
1176    type Item = char;
1177
1178    fn next(&mut self) -> Option<char> {
1179        if let Some(c) = self.held.take() {
1180            return Some(c);
1181        }
1182        for c in self.inner.by_ref() {
1183            if c == ' ' {
1184                // A gap counts only between words: a leading run has no word
1185                // before it, and a trailing run meets the end instead.
1186                self.gap = self.started;
1187                continue;
1188            }
1189            self.started = true;
1190            if self.gap {
1191                self.gap = false;
1192                self.held = Some(c);
1193                return Some(' ');
1194            }
1195            return Some(c);
1196        }
1197        None
1198    }
1199}
1200
1201impl<'a> Attribute<'a> {
1202    /// What kind of attribute this is.
1203    #[must_use]
1204    pub fn kind(self) -> Oid<'a> {
1205        self.kind
1206    }
1207
1208    /// The value, as encoded.
1209    #[must_use]
1210    pub fn value(self) -> AttributeValue<'a> {
1211        self.value
1212    }
1213
1214    /// The value as text for a person to read, where it is text at all.
1215    ///
1216    /// For display. Never for deciding that two names are the same one: see
1217    /// [`Name::matches`].
1218    ///
1219    /// # Errors
1220    /// Returns a located resource error if the execution or storage budget is spent.
1221    pub fn text(self, execution: &Memory) -> Result<Option<OwnedString>> {
1222        self.value.text(execution)
1223    }
1224
1225    #[cfg(test)]
1226    fn matches(self, other: &Attribute<'_>) -> bool {
1227        if self.kind != other.kind {
1228            return false;
1229        }
1230        if self.value.der == other.value.der {
1231            return true;
1232        }
1233        // Both are strings the type permits and that decode: the profile
1234        // compares what they say, ignoring case and the width of the gaps.
1235        // Streamed, so two long differently encoded values cost no copy.
1236        // Anything else is compared as it was encoded, because this layer has
1237        // no rule for what it means, and such bytes only ever equal
1238        // themselves.
1239        match (self.folding_chars(), other.folding_chars()) {
1240            (Some(left), Some(right)) => canonical(left).eq(canonical(right)),
1241            _ => false,
1242        }
1243    }
1244
1245    /// A total order over attributes that calls two of them equal exactly
1246    /// when [`Attribute::matches`] does, so ordering both sides of a part and
1247    /// walking them in step answers the multiset question.
1248    ///
1249    /// Kind first, then whether the value folds, then the values themselves:
1250    /// folded ones by their canonical characters, the rest by their bytes. A
1251    /// value that folds can never share its encoding with one that does not,
1252    /// the two questions being asked of the same kind and bytes, so no pair
1253    /// this separates is a pair `matches` would join.
1254    #[cfg(test)]
1255    fn order(&self, other: &Attribute<'_>) -> core::cmp::Ordering {
1256        self.kind
1257            .as_bytes()
1258            .cmp(other.kind.as_bytes())
1259            .then_with(|| match (self.folding_chars(), other.folding_chars()) {
1260                (Some(left), Some(right)) => canonical(left).cmp(canonical(right)),
1261                (None, None) => self.value.der.cmp(other.value.der),
1262                (Some(_), None) => core::cmp::Ordering::Less,
1263                (None, Some(_)) => core::cmp::Ordering::Greater,
1264            })
1265    }
1266
1267    /// Whether this value takes part in the preparation the profile describes,
1268    /// or is compared only as the bytes it was written in.
1269    ///
1270    /// A caller explaining why a name did not match needs the same answer this
1271    /// comparison uses, not a guess at it: a value can be excluded for its
1272    /// encoding, for a code point the type prohibits, or for failing the
1273    /// direction step, and only one of those is visible from the outside.
1274    ///
1275    /// # Errors
1276    /// Returns a located resource error if preparation cannot be financed.
1277    pub fn folds(self, execution: &Memory) -> Result<bool> {
1278        prepared::folds(self, execution)
1279    }
1280
1281    /// The decoded characters of a value that takes part in folding: the
1282    /// type's schema permits the encoding it was written in, and it sits
1283    /// inside the schema's size bounds. A known attribute outside them is not
1284    /// a value the schema names, and folding one would let a malformed issuer
1285    /// match a genuine subject; it stays byte-only equality.
1286    #[cfg(test)]
1287    fn folding_chars(self) -> Option<DecodedChars<'a>> {
1288        (permits(self.kind, self.value.encoding()) && preparable(&self))
1289            .then(|| self.value.decoded_chars())
1290    }
1291}
1292
1293impl<'a> AttributeValue<'a> {
1294    /// The value exactly as it was encoded, tag included.
1295    #[must_use]
1296    pub fn as_bytes(self) -> &'a [u8] {
1297        self.der
1298    }
1299
1300    /// The contents, without the tag and length.
1301    #[must_use]
1302    pub fn contents(self) -> &'a [u8] {
1303        self.contents
1304    }
1305
1306    /// Which string encoding this was written in.
1307    #[must_use]
1308    pub fn encoding(self) -> Encoding {
1309        if self.tag.class() != Class::Universal || self.tag.is_constructed() {
1310            return Encoding::Other;
1311        }
1312        match self.tag.number() {
1313            Some(universal::UTF8_STRING) => Encoding::Utf8,
1314            Some(universal::PRINTABLE_STRING) => Encoding::Printable,
1315            Some(universal::IA5_STRING) => Encoding::Ia5,
1316            Some(NUMERIC_STRING) => Encoding::Numeric,
1317            Some(TELETEX_STRING) => Encoding::Teletex,
1318            Some(VISIBLE_STRING) => Encoding::Visible,
1319            Some(BMP_STRING) => Encoding::Bmp,
1320            Some(UNIVERSAL_STRING) => Encoding::Universal,
1321            _ => Encoding::Other,
1322        }
1323    }
1324
1325    /// The value as text for a person to read, where it is text at all.
1326    ///
1327    /// Bounded, because this is the public reading path and a value may be
1328    /// as wide as the element limit permits while several attribute types
1329    /// have no ceiling in the schema. What is shown is as much of the value
1330    /// as the widest name component the profile names, and a mark saying the
1331    /// rest is there. Identity is the bytes and is never this.
1332    ///
1333    /// The returned string retains its storage charge independently of the parser.
1334    /// # Errors
1335    /// Returns a located resource error before unfunded decoding or allocation.
1336    pub fn text(self, execution: &Memory) -> Result<Option<OwnedString>> {
1337        let fail = |reason| Error::resource(reason, "name.attribute", self.offset);
1338        let width = match self.encoding() {
1339            Encoding::Other => return Ok(None),
1340            Encoding::Bmp => Some(2),
1341            Encoding::Universal => Some(4),
1342            _ => None,
1343        };
1344        // UTF-8 validation and subsequent decoding each visit the input at most
1345        // once. Admit both before entering either scan.
1346        execution
1347            .charge_work((self.contents.len() as u64) * 2)
1348            .map_err(fail)?;
1349        match width {
1350            Some(width) => {
1351                if !self.contents.len().is_multiple_of(width) {
1352                    return Ok(None);
1353                }
1354                let bound = ((DISPLAY_CEILING + 1) * width).min(self.contents.len());
1355                display_text(wide_chars(&self.contents[..bound], width), execution).map_err(fail)
1356            }
1357            // Every remaining type is a subset of ASCII by its definition, and
1358            // an issuer writing outside it has written something. Where those
1359            // bytes are UTF-8 they are read as UTF-8, which is what the issuer
1360            // meant; where they are not, they are read as one byte a
1361            // character. Both are approximations for a person to read, and
1362            // neither is what two names are compared on.
1363            None => match core::str::from_utf8(self.contents) {
1364                Ok(text) => display_text(text.chars().map(Some), execution).map_err(fail),
1365                Err(_) => display_text(
1366                    self.contents.iter().map(|byte| Some(char::from(*byte))),
1367                    execution,
1368                )
1369                .map_err(fail),
1370            },
1371        }
1372    }
1373
1374    /// Streams the value's characters through its declared alphabet and
1375    /// `keep`, counting them, without materializing the text: a value can be
1376    /// as long as the element limit permits, and validating one must not
1377    /// allocate a copy its size. `None` is a value that does not decode or a
1378    /// character either test refuses.
1379    fn validated_count(self, mut keep: impl FnMut(char) -> bool) -> Option<usize> {
1380        let encoding = self.encoding();
1381        let mut count = 0usize;
1382        match encoding {
1383            Encoding::Other => return None,
1384            Encoding::Bmp | Encoding::Universal => {
1385                let width = if encoding == Encoding::Bmp { 2 } else { 4 };
1386                if !self.contents.len().is_multiple_of(width) {
1387                    return None;
1388                }
1389                for c in wide_chars(self.contents, width) {
1390                    if !keep(c?) {
1391                        return None;
1392                    }
1393                    count += 1;
1394                }
1395            }
1396            _ => {
1397                let text = core::str::from_utf8(self.contents).ok()?;
1398                for c in text.chars() {
1399                    if !in_alphabet(encoding, c) || !keep(c) {
1400                        return None;
1401                    }
1402                    count += 1;
1403                }
1404            }
1405        }
1406        Some(count)
1407    }
1408
1409    /// The decoded characters of a value [`preparable`] has already
1410    /// validated: total and allocation free, for folding without a copy.
1411    fn decoded_chars(self) -> DecodedChars<'a> {
1412        match self.encoding() {
1413            Encoding::Bmp => DecodedChars::Wide {
1414                contents: self.contents,
1415                width: 2,
1416            },
1417            Encoding::Universal => DecodedChars::Wide {
1418                contents: self.contents,
1419                width: 4,
1420            },
1421            _ => DecodedChars::Narrow(
1422                core::str::from_utf8(self.contents)
1423                    .expect("the value was decoded before this iterator was built")
1424                    .chars(),
1425            ),
1426        }
1427    }
1428}
1429
1430/// Whether a character sits inside the alphabet a narrow string type
1431/// declares. IA5 is ASCII by definition. The teletex repertoire is a
1432/// negotiation this crate does not implement; its invariant subset is ASCII,
1433/// and only that subset takes part in matching.
1434fn in_alphabet(encoding: Encoding, c: char) -> bool {
1435    match encoding {
1436        Encoding::Printable => is_printable_string(c),
1437        Encoding::Numeric => c.is_ascii_digit() || c == ' ',
1438        Encoding::Visible => matches!(c, '\x20'..='\x7e'),
1439        Encoding::Ia5 | Encoding::Teletex => c.is_ascii(),
1440        _ => true,
1441    }
1442}
1443
1444/// The decoded characters of a wide string, one unit at a time: a unit that
1445/// is not a character, a surrogate included, is `None` (X.680, 41.16 puts
1446/// `BMPString` in the basic plane, and `char::from_u32` refuses surrogates).
1447fn wide_chars(contents: &[u8], width: usize) -> impl Iterator<Item = Option<char>> + '_ {
1448    contents.chunks_exact(width).map(|chunk| {
1449        char::from_u32(
1450            chunk
1451                .iter()
1452                .fold(0u32, |value, byte| (value << 8) | u32::from(*byte)),
1453        )
1454    })
1455}
1456
1457/// The characters of an already validated value, streamed without an
1458/// allocation.
1459enum DecodedChars<'a> {
1460    Narrow(core::str::Chars<'a>),
1461    Wide { contents: &'a [u8], width: usize },
1462}
1463
1464impl Iterator for DecodedChars<'_> {
1465    type Item = char;
1466
1467    fn next(&mut self) -> Option<char> {
1468        match self {
1469            Self::Narrow(chars) => chars.next(),
1470            Self::Wide { contents, width } => {
1471                if contents.len() < *width {
1472                    return None;
1473                }
1474                let (unit, rest) = contents.split_at(*width);
1475                *contents = rest;
1476                // A substitute character here would make two values that do
1477                // not decode compare equal, which is the forged match this
1478                // module exists to prevent.
1479                Some(
1480                    char::from_u32(
1481                        unit.iter()
1482                            .fold(0u32, |value, byte| (value << 8) | u32::from(*byte)),
1483                    )
1484                    .expect("the value was decoded before this iterator was built"),
1485                )
1486            }
1487        }
1488    }
1489}
1490
1491/// Tag numbers X.680 gives the types this crate reads past the ones
1492/// `sig-asn1` names, which are the ones nothing below the schema needs.
1493const REAL: u32 = 9;
1494const ENUMERATED: u32 = 10;
1495const RELATIVE_OID: u32 = 13;
1496const NUMERIC_STRING: u32 = 18;
1497const TELETEX_STRING: u32 = 20;
1498const VISIBLE_STRING: u32 = 26;
1499const UNIVERSAL_STRING: u32 = 28;
1500const BMP_STRING: u32 = 30;
1501const EXTERNAL: u32 = 8;
1502const EMBEDDED_PDV: u32 = 11;
1503const OBJECT_DESCRIPTOR: u32 = 7;
1504const TIME: u32 = 14;
1505const DATE: u32 = 31;
1506const TIME_OF_DAY: u32 = 32;
1507const DATE_TIME: u32 = 33;
1508const DURATION: u32 = 34;
1509const OID_IRI: u32 = 35;
1510const RELATIVE_OID_IRI: u32 = 36;
1511
1512/// Whether contents are the value notation of an identifier written as a
1513/// resource name: the arcs in UTF-8, no arc empty and none carrying white
1514/// space, the object form opening with the separator and the relative one
1515/// not (X.680 34.3 and 35.3, X.690 8.21.2 and 8.22.2).
1516///
1517/// What an arc may say beyond that is a registry's business, so nothing here
1518/// reads one: this is the shape of the value, which is what deciding it is a
1519/// value of the type asks for.
1520fn iri_fits(contents: &[u8], rooted: bool) -> bool {
1521    let Ok(text) = core::str::from_utf8(contents) else {
1522        return false;
1523    };
1524    let arcs = match text.strip_prefix('/') {
1525        Some(rest) if rooted => rest,
1526        None if !rooted => text,
1527        _ => return false,
1528    };
1529    !arcs.is_empty() && arcs.split('/').all(arc_fits)
1530}
1531
1532/// Whether one arc is a Unicode label: either the digits of an arc's own
1533/// number, or a name written from the characters X.660 7.5.2 lists.
1534///
1535/// The number opens with a zero only where it is that one digit (7.3). The
1536/// name holds at least one character that is not a digit, which is what
1537/// tells the two apart (7.5.1), carries no hyphen at either end and no pair
1538/// of them in the third and fourth places, where a normalized form would
1539/// read them as a prefix (7.5.4).
1540///
1541/// What is not applied is 7.5.3, which excludes the positions ISO/IEC 10646
1542/// marks as not to be used: that marking is not stable across editions, and
1543/// the clause's own note tells a reader to be tolerant of it. Everything
1544/// else here is the label as the standard writes it.
1545fn arc_fits(arc: &str) -> bool {
1546    if arc.is_empty() {
1547        return false;
1548    }
1549    if arc.bytes().all(|byte| byte.is_ascii_digit()) {
1550        return arc == "0" || !arc.starts_with('0');
1551    }
1552    if arc.starts_with('-') || arc.ends_with('-') {
1553        return false;
1554    }
1555    let hyphenated = arc
1556        .chars()
1557        .nth(2)
1558        .zip(arc.chars().nth(3))
1559        .is_some_and(|(third, fourth)| third == '-' && fourth == '-');
1560    !hyphenated && arc.chars().all(label_character)
1561}
1562
1563/// Whether a character is one a Unicode label is written from (X.660 7.5.2).
1564fn label_character(c: char) -> bool {
1565    matches!(c, '-' | '.' | '_' | '~' | '0'..='9' | 'A'..='Z' | 'a'..='z')
1566        || matches!(u32::from(c),
1567            0xa0..=0xdffe
1568            | 0xf900..=0xfdcf
1569            | 0xfdf0..=0xffef
1570            | 0x1_0000..=0x1_fffd
1571            | 0x2_0000..=0x2_fffd
1572            | 0x3_0000..=0x3_fffd
1573            | 0x4_0000..=0x4_fffd
1574            | 0x5_0000..=0x5_fffd
1575            | 0x6_0000..=0x6_fffd
1576            | 0x7_0000..=0x7_fffd
1577            | 0x8_0000..=0x8_fffd
1578            | 0x9_0000..=0x9_fffd
1579            | 0xa_0000..=0xa_fffd
1580            | 0xb_0000..=0xb_fffd
1581            | 0xc_0000..=0xc_fffd
1582            | 0xd_0000..=0xd_fffd
1583            | 0xe_1000..=0xe_fffd)
1584}
1585
1586/// Whether a universal type is one DER writes constructed, so finding it that
1587/// way is the type rather than a second spelling of a primitive one.
1588///
1589/// The containers, and the three types whose definition is an associated
1590/// sequence: external and instance-of under tag 8 (X.690 8.16.1, 8.18.1),
1591/// embedded-pdv under 11 (8.17.1), and the unrestricted character string
1592/// under 29 (8.24.1). Everything else universal is primitive here (10.2).
1593pub(crate) fn constructed_universal_type(number: u32) -> bool {
1594    matches!(
1595        number,
1596        universal::SEQUENCE | universal::SET | 8 | 11 | CHARACTER_STRING
1597    )
1598}
1599
1600/// `CHARACTER STRING`, the unrestricted one, which this crate names itself
1601/// because nothing below the schema needs it.
1602const CHARACTER_STRING: u32 = 29;
1603
1604/// Whether the members of one of the three types whose encoding is a
1605/// sequence defined for it are the components that definition names.
1606///
1607/// The external type is a sequence of three optional members, an identifier,
1608/// a reference and a descriptor, and then the encoding it carries, which is
1609/// one of three choices and is not optional (X.690 8.18.1). The embedded-pdv
1610/// type and the unrestricted character string are the same shape as each
1611/// other: how the value is identified, then the value, both required and
1612/// tagged in order, with the descriptor between them absent by the
1613/// definition's own constraint (X.680 36.5 and 44.5).
1614///
1615/// What each member says is somebody else's business, and nothing here reads
1616/// one. This is the shape, which is what deciding it is a value of the type
1617/// asks for. The walk that follows holds each member to its own rules.
1618fn associated_sequence_fits<'a>(
1619    parent: &Reader<'a>,
1620    element: &Element<'a>,
1621    field: &'static str,
1622    number: u32,
1623) -> Result<bool> {
1624    let mut inside = parent.enter(element).field(field)?;
1625    if number == EXTERNAL {
1626        // The optional members come in this order and each appears once.
1627        let mut left: &[u32] = &[universal::OID, universal::INTEGER, OBJECT_DESCRIPTOR];
1628        while let Some(member) = inside.next_element().field(field)? {
1629            let tag = member.tag();
1630            if tag.class() == Class::ContextSpecific {
1631                // The encoding closes the sequence, and each of its three
1632                // ways says what its contents are: one whole value carried
1633                // inside the tag, a value in octets, which any bytes are, or
1634                // a value in bits, which opens with the count of the unused
1635                // ones.
1636                let carried = match tag.number() {
1637                    Some(0) => {
1638                        let mut held = inside.enter(&member).field(field)?;
1639                        held.next_element().field(field)?.is_some() && held.is_empty()
1640                    }
1641                    Some(1) => segments::implicit(&inside, &member, field, false)?,
1642                    Some(2) => segments::implicit(&inside, &member, field, true)?,
1643                    _ => false,
1644                };
1645                return Ok(carried && inside.is_empty());
1646            }
1647            let Some(at) = tag
1648                .number()
1649                .filter(|_| tag.class() == Class::Universal)
1650                .and_then(|number| left.iter().position(|kind| *kind == number))
1651            else {
1652                return Ok(false);
1653            };
1654            left = &left[at + 1..];
1655        }
1656        // Nothing carried, which is the one member the definition requires.
1657        return Ok(false);
1658    }
1659
1660    // How the value is identified: a choice, so its member wears an explicit
1661    // tag over whichever of the six alternatives was written.
1662    let Some(identification) = inside.next_element().field(field)? else {
1663        return Ok(false);
1664    };
1665    if identification.tag() != Tag::context(true, 0) {
1666        return Ok(false);
1667    }
1668    let mut chosen = inside.enter(&identification).field(field)?;
1669    let Some(alternative) = chosen.next_element().field(field)? else {
1670        return Ok(false);
1671    };
1672    if alternative.tag().class() != Class::ContextSpecific
1673        || !chosen.is_empty()
1674        || !identification_fits(&chosen, &alternative, field)?
1675    {
1676        return Ok(false);
1677    }
1678    // Then the value itself, which is the third component of the definition
1679    // and keeps that number whether or not the second one is written. It is
1680    // an octet string under its tag, and the distinguished rules write a
1681    // string in one piece (X.690 10.2), so the segmented form is a second
1682    // spelling of it there. The basic rules have both, and a document read
1683    // under them keeps what it was written with.
1684    let Some(value) = inside.next_element().field(field)? else {
1685        return Ok(false);
1686    };
1687    Ok(value.tag().class() == Class::ContextSpecific
1688        && value.tag().number() == Some(2)
1689        && segments::implicit(&inside, &value, field, false)?
1690        && inside.is_empty())
1691}
1692
1693/// Whether a member read as the type it is, with a spent budget kept as
1694/// what it is.
1695///
1696/// A value that is not the type is an answer about the document, and this
1697/// says no. A budget that ran out is this run giving up, and it says
1698/// nothing about the document, so it travels on rather than being folded
1699/// into the no beside it: a report must not blame a certificate for a
1700/// device that stopped.
1701fn reads<T>(outcome: structured_asn1::Result<T>, field: &'static str) -> Result<bool> {
1702    match outcome.field(field) {
1703        Ok(_) => Ok(true),
1704        Err(error) if error.is_resource() => Err(error),
1705        Err(_) => Ok(false),
1706    }
1707}
1708
1709/// Whether one alternative of the identification choice is the type that
1710/// alternative is (X.680 36.5, and 44.5 for the same choice again).
1711///
1712/// The alternatives are tagged over their types rather than beside them, so
1713/// what arrives is the type's contents under a context tag, and the contents
1714/// are the type's: the pair of identifiers, one identifier, a context named
1715/// by a number, that number with an identifier beside it, the transfer
1716/// syntax as an identifier, and the fixed alternative, which is nothing at
1717/// all. A tag with the wrong contents under it is the same defect as a
1718/// container with the wrong members, one level down.
1719fn identification_fits<'a>(
1720    parent: &Reader<'a>,
1721    alternative: &Element<'a>,
1722    field: &'static str,
1723) -> Result<bool> {
1724    /// The two members of the alternatives that hold a pair, as the types
1725    /// they are: the syntaxes are two identifiers, the negotiation is a
1726    /// context and the syntax to encode it in.
1727    fn pair<'a>(
1728        parent: &Reader<'a>,
1729        alternative: &Element<'a>,
1730        field: &'static str,
1731        numbered: bool,
1732    ) -> Result<bool> {
1733        let mut inside = parent.enter(alternative).field(field)?;
1734        let (Some(first), Some(second)) = (
1735            inside.next_element().field(field)?,
1736            inside.next_element().field(field)?,
1737        ) else {
1738            return Ok(false);
1739        };
1740        let opens = if numbered {
1741            reads(inside.integer(&first), field)?
1742        } else {
1743            reads(inside.oid(&first), field)?
1744        };
1745        Ok(opens
1746            && first.tag() == Tag::context(false, 0)
1747            && second.tag() == Tag::context(false, 1)
1748            && reads(inside.oid(&second), field)?
1749            && inside.is_empty())
1750    }
1751
1752    let constructed = alternative.tag().is_constructed();
1753    Ok(match alternative.tag().number() {
1754        Some(0) => constructed && pair(parent, alternative, field, false)?,
1755        Some(1 | 4) => reads(parent.oid(alternative), field)?,
1756        Some(2) => reads(parent.integer(alternative), field)?,
1757        Some(3) => constructed && pair(parent, alternative, field, true)?,
1758        // The fixed alternative is a null, which says what it says by being
1759        // there and carries nothing.
1760        Some(5) => !constructed && alternative.contents().is_empty(),
1761        _ => false,
1762    })
1763}
1764
1765/// Whether a universal number belongs to a type at all.
1766///
1767/// Table 1 of X.680 assigns them. Zero is kept by the encoding rules,
1768/// fifteen is reserved for future editions, and thirty-seven and up are
1769/// reserved for addenda: nothing between the standard's covers gives any of
1770/// them a meaning, so bytes wearing one are a value of no type.
1771fn assigned_universal_type(number: u32) -> bool {
1772    !matches!(number, 0 | 15) && number <= RELATIVE_OID_IRI
1773}
1774
1775/// Whether a restricted string's contents are held to the alphabet its type
1776/// names.
1777///
1778/// The two answers are the two things a preserved value goes on to do. A
1779/// value handed to a scheme that clears a critical extension has to be a
1780/// value of the type it claims, or the extension is cleared on something
1781/// that is not one. A value that takes part in a name is kept as written:
1782/// refusing it would block a certificate over a spelling, and the profile
1783/// names binary comparison as a sufficient matching rule (RFC 5280 7.1), so
1784/// a malformed value still has an identity and is still shown to a person.
1785/// It is only withheld from folding, which is defined over values the schema
1786/// names.
1787#[derive(Clone, Copy, PartialEq, Eq)]
1788pub(crate) enum Strings {
1789    Checked,
1790    AsWritten,
1791}
1792
1793/// Reads every element under one, holding each to the rules the encoding
1794/// names even where nothing here interprets the value.
1795///
1796/// The places that preserve an opaque value share this: an attribute of a
1797/// name, the value of an other-name, the information of a qualified
1798/// statement, an algorithm's parameter and the value of a policy qualifier.
1799/// Each is handed to somebody who decides an identity, names the service that
1800/// issued the certificate, or clears a critical extension on the strength of
1801/// it, so what is preserved has to be the encoding the document claims, all
1802/// the way down. Checking the outer tag
1803/// alone leaves the same second spelling of a value one level lower, where it
1804/// arrives at the same reader by the same route.
1805pub(crate) fn walk_der<'a>(
1806    parent: &Reader<'a>,
1807    element: &Element<'a>,
1808    field: &'static str,
1809    strings: Strings,
1810) -> Result<()> {
1811    if !check_der(parent, element, field, strings)? {
1812        return Ok(());
1813    }
1814    // The descent keeps its own stack rather than the machine's. Depth is
1815    // the reader's to bound and a caller may raise that bound, so spending a
1816    // machine stack frame per element would turn a limit into a crash for
1817    // whoever raised it. On this stack the same input is the refusal the
1818    // limit describes.
1819    let mut open = parent.execution().vector::<Open<'a>>();
1820    open.try_push(Open::of(parent.enter(element).field(field)?, element.tag()))
1821        .map_err(|reason| Error::resource(reason, field, element.span().start))?;
1822    while let Some(level) = open.last_mut() {
1823        let Some(child) = level.reader.next_element().field(field)? else {
1824            open.pop();
1825            continue;
1826        };
1827        // The members of a set appear in ascending order of their encodings
1828        // (X.690 11.6), and a set's components in the tag order 10.3 names,
1829        // which the same comparison decides because a tag leads its own
1830        // encoding. Deciding it walks up to the longer member, so that
1831        // length is charged before the walk: a caller bounding work sees
1832        // this on the same meter the reads use.
1833        if level.ordered
1834            && let Some(previous) = level.previous
1835        {
1836            level
1837                .reader
1838                .charge(previous.len().max(child.as_bytes().len()) as u64)
1839                .field(field)?;
1840            if !der_set_ordered(previous, child.as_bytes()) {
1841                return Err(Error::new(
1842                    ErrorCode::MalformedValue,
1843                    field,
1844                    child.span().start,
1845                ));
1846            }
1847        }
1848        level.previous = Some(child.as_bytes());
1849
1850        let inside = &open
1851            .last()
1852            .expect("the reader the child was read from")
1853            .reader;
1854        if check_der(inside, &child, field, strings)? {
1855            let entered = inside.enter(&child).field(field)?;
1856            let tag = child.tag();
1857            open.try_push(Open::of(entered, tag))
1858                .map_err(|reason| Error::resource(reason, field, child.span().start))?;
1859        }
1860    }
1861    Ok(())
1862}
1863
1864/// One container the walk is inside, and what deciding its members needs.
1865struct Open<'a> {
1866    reader: Reader<'a>,
1867    /// Whether this container's members are ordered by their encodings,
1868    /// which is the case for a set and for nothing else.
1869    ordered: bool,
1870    /// The member read before this one, for that comparison.
1871    previous: Option<&'a [u8]>,
1872}
1873
1874impl<'a> Open<'a> {
1875    fn of(reader: Reader<'a>, tag: Tag) -> Self {
1876        let ordered = reader.encoding().is_der()
1877            && tag.class() == Class::Universal
1878            && tag.number() == Some(universal::SET);
1879        Self {
1880            reader,
1881            ordered,
1882            previous: None,
1883        }
1884    }
1885}
1886
1887/// Holds one element to the rules its tag names, and says whether it has
1888/// children the caller still has to walk.
1889fn check_der<'a>(
1890    parent: &Reader<'a>,
1891    element: &Element<'a>,
1892    field: &'static str,
1893    strings: Strings,
1894) -> Result<bool> {
1895    let fail = |code| Error::new(code, field, element.span().start);
1896    let tag = element.tag();
1897    // The construction rule runs both ways, and only one of the two is
1898    // about DER. A string written constructed is a second spelling of one
1899    // value, which the distinguished rules forbid (X.690 10.2). A container
1900    // written primitive is not the type at all: a sequence and a set are
1901    // constructed by definition (8.9.1, 8.11.1), as are the three types
1902    // whose definition is an associated sequence (8.17.1, 8.18.1, 8.24.1),
1903    // and that holds in either encoding.
1904    if tag.class() == Class::Universal {
1905        // Before the form, the number itself. Table 1 of X.680 assigns the
1906        // universal numbers, and three ranges belong to no type: zero, which
1907        // the encoding rules keep for themselves, fifteen, and everything
1908        // from thirty-seven up. Bytes wearing one of those claim a type the
1909        // standard has not defined, in either encoding, so preserving them
1910        // would hand a scheme a value of nothing.
1911        if !tag.number().is_some_and(assigned_universal_type) {
1912            return Err(fail(ErrorCode::Encoding(
1913                structured_asn1::ErrorCode::UnexpectedTag,
1914            )));
1915        }
1916        // A number this reader does not name is not one of the containers,
1917        // and universal numbers that wide are not assigned at all.
1918        let container = tag.number().is_some_and(constructed_universal_type);
1919        let wrong = if tag.is_constructed() {
1920            !container
1921                && (parent.encoding().is_der()
1922                    || !tag.number().is_some_and(segmented_universal_type))
1923        } else {
1924            container
1925        };
1926        if wrong {
1927            return Err(fail(ErrorCode::Encoding(
1928                structured_asn1::ErrorCode::UnexpectedTag,
1929            )));
1930        }
1931        if tag.is_constructed() && tag.number().is_some_and(segmented_universal_type) {
1932            segments::validate(parent, element, field, strings)?;
1933            return Ok(false);
1934        }
1935        // Three of the containers are not containers of anything: their
1936        // encoding is the encoding of a sequence defined for them, whose
1937        // components are the type. A tag with the wrong members under it
1938        // wears the type without being a value of it.
1939        if let Some(number @ (EXTERNAL | EMBEDDED_PDV | CHARACTER_STRING)) = tag.number()
1940            && !associated_sequence_fits(parent, element, field, number)?
1941        {
1942            return Err(fail(ErrorCode::MalformedValue));
1943        }
1944    }
1945    if !tag.is_constructed() {
1946        // The types whose contents the encoding settles: an integer written
1947        // a byte longer than it needs, a boolean spelled with a byte other
1948        // than the two DER allows, a bit string whose padding carries data.
1949        // Nothing here means anything by the value; what is checked is that
1950        // it is written the one way DER writes it.
1951        if tag.class() == Class::Universal {
1952            match tag.number() {
1953                Some(universal::INTEGER) => parent.integer(element).field(field).map(|_| ())?,
1954                Some(universal::BIT_STRING) => {
1955                    parent.bit_string(element).field(field).map(|_| ())?;
1956                }
1957                Some(universal::BOOLEAN) => parent.boolean(element).field(field).map(|_| ())?,
1958                Some(universal::NULL) => parent.null(element).field(field)?,
1959                Some(universal::OID) => parent.oid(element).field(field).map(|_| ())?,
1960                // An enumerated value is encoded as the integer it is
1961                // associated with (X.690 8.4), so the integer's rules are
1962                // its rules.
1963                Some(ENUMERATED) => parent.integer(element).field(field).map(|_| ())?,
1964                // A real's octets are settled to the last one (8.5), and the
1965                // distinguished rules settle them further (11.3). Nothing
1966                // here reads the number.
1967                Some(REAL) => parent.real(element).field(field)?,
1968                // A relative identifier's sub-identifiers are written the
1969                // way an identifier's are: in the fewest octets, so none
1970                // begins with 0x80, and the last of each series closes it
1971                // (X.690 8.20.2). That is what the identifier reader checks,
1972                // the joint first arc aside, which a relative one does not
1973                // have.
1974                Some(RELATIVE_OID) => parent.oid(element).field(field).map(|_| ())?,
1975                // Under the encoding's rule and not the profile's: a
1976                // certificate's validity dates are written without a
1977                // fraction because the profile says so (RFC 5280 4.1.2.5.2),
1978                // and a value preserved inside somebody else's payload is
1979                // not a validity date.
1980                Some(universal::UTC_TIME | universal::GENERALIZED_TIME) => {
1981                    // A fraction is held to digits by walking it, and it is
1982                    // as long as the element permits: the length goes on the
1983                    // shared meter first, as it does for the identifier and
1984                    // the strings below.
1985                    useful_time_fits(parent, element, field)?;
1986                }
1987                // The newer time types, whose contents are the value notation
1988                // with the characters X.690 8.26 names taken out. What each
1989                // one writes is settled by its property settings (X.680
1990                // 38.4), so a value that is not that notation is not a value
1991                // of the type, whatever the tag says.
1992                Some(kind @ (TIME | DATE | TIME_OF_DAY | DATE_TIME | DURATION)) => {
1993                    parent
1994                        .charge(element.contents().len() as u64)
1995                        .field(field)?;
1996                    let defined = match kind {
1997                        DATE => crate::time::Defined::Date,
1998                        TIME_OF_DAY => crate::time::Defined::TimeOfDay,
1999                        DATE_TIME => crate::time::Defined::DateTime,
2000                        DURATION => crate::time::Defined::Duration,
2001                        _ => crate::time::Defined::Any,
2002                    };
2003                    if !crate::time::defined_fits(defined, element.contents()) {
2004                        return Err(fail(ErrorCode::MalformedValue));
2005                    }
2006                }
2007                // The two identifiers written as resource names: their
2008                // contents are the arcs in UTF-8 with no white space between
2009                // the lexical items (X.690 8.21.2, 8.22.2), the object form
2010                // beginning at the root and the relative one not (X.680 34.3
2011                // and 35.3).
2012                Some(kind @ (OID_IRI | RELATIVE_OID_IRI)) => {
2013                    parent
2014                        .charge(element.contents().len() as u64)
2015                        .field(field)?;
2016                    if !iri_fits(element.contents(), kind == OID_IRI) {
2017                        return Err(fail(ErrorCode::MalformedValue));
2018                    }
2019                }
2020                // A restricted string's contents are settled by its type as
2021                // much as an integer's are by DER: bytes outside the type's
2022                // alphabet, a width that is not whole, or a unit that is not
2023                // a character wear the tag without being a value of it
2024                // (X.680 41). The scan streams and counts rather than
2025                // decoding into a copy, so a value the element limit permits
2026                // costs its length and not its size in memory.
2027                _ if strings == Strings::Checked => {
2028                    // The scan walks every character, and a preserved value
2029                    // has no ceiling of its own: the length is charged to
2030                    // the shared work budget first, so a caller who bounded
2031                    // the work gets the bound here as everywhere else.
2032                    parent
2033                        .charge(element.contents().len() as u64)
2034                        .field(field)?;
2035                    let value = AttributeValue {
2036                        tag,
2037                        contents: element.contents(),
2038                        der: element.as_bytes(),
2039                        offset: element.span().start,
2040                        depth: parent.depth(),
2041                    };
2042                    // TeletexString is left out of this, as it is left out
2043                    // of the shape question a name asks: its repertoire is
2044                    // T.61, a negotiation this crate does not implement, so
2045                    // the bytes being there is what is checkable. What the
2046                    // alphabet below says about it is the approximation
2047                    // this crate reads it as for display, and holding a
2048                    // preserved value to that would refuse a legacy value
2049                    // the schema names.
2050                    let settled = !matches!(value.encoding(), Encoding::Other | Encoding::Teletex);
2051                    if settled && value.validated_count(|_| true).is_none() {
2052                        return Err(fail(ErrorCode::MalformedValue));
2053                    }
2054                }
2055                // What is left is what the encoding does not settle, and it
2056                // is left on purpose. The graphic and general strings and
2057                // the object descriptor carry a repertoire that is
2058                // negotiated rather than fixed (X.680 41, and the same
2059                // reasoning as the teletex string a name may hold). The
2060                // types that write a time as characters, and the two that
2061                // write an identifier as an internationalized resource
2062                // name, are settled by a syntax rather than by the octets,
2063                // and none of them has a reader here because no schema this
2064                // product parses names one; checking them would mean
2065                // writing a parser whose only caller is this check.
2066                _ => (),
2067            }
2068        }
2069        return Ok(false);
2070    }
2071    Ok(true)
2072}
2073
2074fn useful_time_fits(parent: &Reader<'_>, element: &Element<'_>, field: &'static str) -> Result<()> {
2075    let generalized = element.tag().number() == Some(universal::GENERALIZED_TIME);
2076    let bytes = element.contents();
2077    if parent.encoding().is_der() {
2078        parent.charge(bytes.len() as u64).field(field)?;
2079        if generalized {
2080            crate::temporal::admit_generalized(parent, element, field)?;
2081        }
2082        crate::time::read_as(element, field, crate::time::Fraction::Written)?;
2083    } else {
2084        let work = (bytes.len() as u64).checked_mul(3).ok_or_else(|| {
2085            Error::resource(
2086                structured_asn1::memory::MemoryError::WorkExceeded,
2087                field,
2088                element.span().start,
2089            )
2090        })?;
2091        parent.charge(work).field(field)?;
2092        if !crate::time::ber_fits(bytes, generalized) {
2093            return Err(Error::new(
2094                ErrorCode::MalformedTime,
2095                field,
2096                element.span().start,
2097            ));
2098        }
2099    }
2100    Ok(())
2101}
2102
2103/// BER permits segmentation only for bit/octet strings and the restricted
2104/// character strings, including the useful time types implicitly based on
2105/// `VisibleString`. It does not change primitive-only scalar encodings.
2106/// X.690 §§8.6, 8.7, 8.23; X.680 §§46.3, 47.3, 48.3.
2107/// <https://www.itu.int/rec/T-REC-X.690-202102-I/en>
2108fn segmented_universal_type(number: u32) -> bool {
2109    matches!(number, 3 | 4 | 7 | 12 | 18..=28 | 30)
2110}
2111
2112/// Whether the bytes stay inside the `IA5String` alphabet, the 128-character
2113/// IRV (X.680, 41.4): a byte above 0x7f wears the tag but is not the type.
2114pub(crate) fn is_ia5(bytes: &[u8]) -> bool {
2115    bytes.iter().all(u8::is_ascii)
2116}
2117
2118/// Whether the bytes stay inside the `NumericString` alphabet, digits and
2119/// space (X.680, 41.2).
2120pub(crate) fn is_numeric(bytes: &[u8]) -> bool {
2121    bytes
2122        .iter()
2123        .all(|&byte| byte.is_ascii_digit() || byte == b' ')
2124}
2125
2126/// Whether the bytes stay inside the closed `PrintableString` alphabet of
2127/// X.680, 41.4.
2128pub(crate) fn is_printable(bytes: &[u8]) -> bool {
2129    bytes
2130        .iter()
2131        .all(|&byte| byte.is_ascii() && is_printable_string(char::from(byte)))
2132}
2133
2134/// Whether a character belongs to the `PrintableString` alphabet, which X.680
2135/// closes over letters, digits, space and a short list of punctuation.
2136pub(crate) fn is_printable_string(c: char) -> bool {
2137    c.is_ascii_alphanumeric()
2138        || matches!(
2139            c,
2140            ' ' | '\'' | '(' | ')' | '+' | ',' | '-' | '.' | '/' | ':' | '=' | '?'
2141        )
2142}
2143
2144/// Whether two adjacent members of a set are in the order DER requires:
2145/// ascending as octet strings, the shorter compared as if padded at its end
2146/// with zeroes. Equal members are permitted, which is how a genuine duplicate
2147/// is encoded.
2148pub(crate) fn der_set_ordered(previous: &[u8], next: &[u8]) -> bool {
2149    let length = previous.len().max(next.len());
2150    for position in 0..length {
2151        let left = previous.get(position).copied().unwrap_or(0);
2152        let right = next.get(position).copied().unwrap_or(0);
2153        if left != right {
2154            return left < right;
2155        }
2156    }
2157    true
2158}
2159
2160/// Decodes a string of characters `width` bytes each.
2161/// Counts the characters of a wide string without building one: the size
2162/// constraint on such a value is in characters, and answering it is all a
2163/// gate needs. `None` is a value that does not decode.
2164pub(crate) fn wide_char_count(contents: &[u8], width: usize) -> Option<usize> {
2165    if !contents.len().is_multiple_of(width) {
2166        return None;
2167    }
2168    let mut count = 0usize;
2169    for character in wide_chars(contents, width) {
2170        character?;
2171        count += 1;
2172    }
2173    Some(count)
2174}
2175
2176/// The same reading, stopped one character past the bound a report shows.
2177///
2178/// A unit that is not a character still refuses the whole value, as it does
2179/// when the value is read entire; the difference is only that the units past
2180/// the bound are not looked at, because they are not going to be shown.
2181fn display_text(
2182    mut characters: impl Iterator<Item = Option<char>>,
2183    execution: &Memory,
2184) -> core::result::Result<Option<OwnedString>, structured_asn1::memory::MemoryError> {
2185    let mut text = execution.string();
2186    for index in 0..=DISPLAY_CEILING {
2187        execution.charge_work(1)?;
2188        let Some(character) = characters.next() else {
2189            break;
2190        };
2191        let Some(character) = character else {
2192            return Ok(None);
2193        };
2194        if index == DISPLAY_CEILING {
2195            text.try_push('…')?;
2196            break;
2197        }
2198        text.try_push(character)?;
2199    }
2200    Ok(Some(text))
2201}
2202
2203/// Reads a name from an element a schema said is one.
2204///
2205/// It is public for the same reason as [`crate::algorithm::read`]: a signed
2206/// message names a signer by the issuer name of its certificate, and comparing
2207/// that against a certificate requires both to have been read by the same
2208/// rules. A second reader would be a second answer to which encodings of a
2209/// name are the same name.
2210/// Catalogue allocation and copying use the producing reader's local work
2211/// ceiling and current aggregate account. A successful result retains its
2212/// capacity charge until it is dropped; the borrowed input lifetime is unchanged.
2213///
2214/// # Errors
2215///
2216/// Reports encoding faults or resource refusals with the original field and
2217/// source position.
2218pub fn read<'a>(
2219    parent: &Reader<'a>,
2220    element: &Element<'a>,
2221    field: &'static str,
2222) -> Result<Name<'a>> {
2223    let fail = |code| Error::new(code, field, element.span().start);
2224
2225    if element.tag() != Tag::constructed(universal::SEQUENCE) {
2226        return Err(fail(ErrorCode::Encoding(
2227            structured_asn1::ErrorCode::UnexpectedTag,
2228        )));
2229    }
2230
2231    let mut sequence = parent.enter(element).field(field)?;
2232    let mut parts = parent.execution().vector();
2233
2234    while let Some(part) = sequence.next_element().field(field)? {
2235        if part.tag() != Tag::constructed(universal::SET) {
2236            return Err(Error::new(
2237                ErrorCode::Encoding(structured_asn1::ErrorCode::UnexpectedTag),
2238                field,
2239                part.span().start,
2240            ));
2241        }
2242        parts
2243            .try_push(read_relative(&sequence, &part, field)?)
2244            .map_err(|reason| Error::resource(reason, field, part.span().start))?;
2245    }
2246
2247    Ok(Name {
2248        der: element.as_bytes(),
2249        parts: parts.into_owned(),
2250        offset: element.span().start,
2251        field,
2252    })
2253}
2254
2255/// Reads one part of a name, which a distribution point carries on its own.
2256///
2257/// The tag belongs to the caller: here it is the set the schema names, and in
2258/// a distribution point it is the number that position gives it.
2259pub(crate) fn read_relative<'a>(
2260    parent: &Reader<'a>,
2261    element: &Element<'a>,
2262    field: &'static str,
2263) -> Result<RelativeName<'a>> {
2264    let fail = |code| Error::new(code, field, element.span().start);
2265
2266    let mut inside = parent.enter(element).field(field)?;
2267    let mut attributes = parent.execution().vector();
2268    let mut previous: Option<&[u8]> = None;
2269    while let Some(pair) = inside.next_element().field(field)? {
2270        // DER orders the members of a set by their encodings, ascending, and
2271        // the comparison of names deliberately ignores order. Without this
2272        // check an unsorted part would match a correctly sorted one, and a
2273        // malformed issuer could take part in a path. The comparison walks
2274        // up to the longer encoding, so that length is charged to the
2275        // shared work budget before the walk: a caller bounding work sees
2276        // two huge common-prefix members on the same meter the reads use.
2277        if inside.encoding().is_der()
2278            && let Some(previous) = previous
2279            && {
2280                inside
2281                    .charge(previous.len().max(pair.as_bytes().len()) as u64)
2282                    .field(field)?;
2283                !der_set_ordered(previous, pair.as_bytes())
2284            }
2285        {
2286            return Err(Error::new(
2287                ErrorCode::MalformedValue,
2288                field,
2289                pair.span().start,
2290            ));
2291        }
2292        previous = Some(pair.as_bytes());
2293        attributes
2294            .try_push(read_attribute(&inside, &pair, field)?)
2295            .map_err(|reason| Error::resource(reason, field, pair.span().start))?;
2296    }
2297
2298    // A part with nothing in it names nothing, and two names that differ only
2299    // by one of these would compare as different names.
2300    if attributes.is_empty() {
2301        return Err(fail(ErrorCode::EmptySequence));
2302    }
2303
2304    Ok(RelativeName {
2305        attributes: attributes.into_owned(),
2306    })
2307}
2308
2309fn read_attribute<'a>(
2310    parent: &Reader<'a>,
2311    element: &Element<'a>,
2312    field: &'static str,
2313) -> Result<Attribute<'a>> {
2314    let fail = |code| Error::new(code, field, element.span().start);
2315
2316    if element.tag() != Tag::constructed(universal::SEQUENCE) {
2317        return Err(fail(ErrorCode::Encoding(
2318            structured_asn1::ErrorCode::UnexpectedTag,
2319        )));
2320    }
2321
2322    let mut pair = parent.enter(element).field(field)?;
2323    let kind = pair.read_oid().field(field)?;
2324    let value = pair
2325        .next_element()
2326        .field(field)?
2327        .ok_or_else(|| fail(ErrorCode::MissingField))?;
2328
2329    // Even an unknown kind's opaque value must be DER before it is
2330    // preserved: what is kept here is compared against the same attribute in
2331    // another certificate, and a second spelling of one value would be a
2332    // different name for the same holder.
2333    walk_der(&pair, &value, field, Strings::AsWritten)?;
2334
2335    if !pair.is_empty() {
2336        return Err(fail(ErrorCode::TrailingData));
2337    }
2338
2339    Ok(Attribute {
2340        kind,
2341        value: AttributeValue {
2342            tag: value.tag(),
2343            contents: value.contents(),
2344            der: value.as_bytes(),
2345            offset: value.span().start,
2346            depth: pair.depth(),
2347        },
2348    })
2349}
2350
2351#[cfg(test)]
2352mod tests;