Skip to main content

structured_pkix/
ocsp.rs

1//! OCSP response evidence over original caller-supplied DER ranges.
2//!
3//! Decoding does not authenticate a responder, validate a request binding or
4//! establish certificate status. No transport, clock or trust discovery occurs.
5
6use crate::algorithm::{self, AlgorithmIdentifier};
7use crate::error::{Error, ErrorCode, Located, Result};
8use crate::extension::{self, Extensions};
9use crate::name::{self, Name};
10use crate::{Certificate, Time, oid, time};
11use structured_asn1::memory::{Memory, OwnedVec, Work};
12use structured_asn1::{
13    BitString, Element, Encoding, Integer, Oid, Parser, Reader, Span, Tag, universal,
14};
15
16const FIELD: &str = "ocspResponse";
17const BASIC: &str = "ocspResponse.basic";
18const DATA: &str = "ocspResponse.responseData";
19const SINGLE: &str = "ocspResponse.singleResponse";
20
21mod digest;
22pub use digest::{CertMatch, Digest, DigestAlgorithm, ResolvedDigest};
23
24mod nonce;
25pub use nonce::{NonceBinding, NonceSizeError, RequestNonce};
26
27mod authentication;
28pub use authentication::{
29    SignatureAuthentication, SignatureError, SignatureFailure, SignedResponse,
30};
31
32mod delegation;
33pub(crate) use delegation::read_no_check;
34
35mod lookup;
36pub use delegation::{
37    DelegateFacts, Delegation, DelegationFailure, ResponderRevocation, check_delegate,
38};
39pub use lookup::Lookup;
40
41mod freshness;
42pub use freshness::UpdateWindow;
43
44mod authority;
45pub use authority::{AuthorityBinding, AuthorityFailure, AuthoritySource, ScopedResponse};
46
47mod extensions;
48pub use extensions::ExtensionProcessing;
49
50mod evidence;
51pub use evidence::{Evaluation, Evidence, RecipientBinding, Request, TargetEvidence};
52
53/// Unsigned protocol failure from RFC6960 §4.2.1, never a certificate verdict.
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub enum Failure {
56    /// Request did not conform to the protocol.
57    MalformedRequest,
58    /// Responder reached an inconsistent state.
59    InternalError,
60    /// Responder cannot currently answer.
61    TryLater,
62    /// Responder requires a signed request.
63    SignatureRequired,
64    /// Request unauthorized or responder unable to answer authoritatively.
65    Unauthorized,
66}
67
68/// A decoded envelope preserves unsupported response types and unsigned errors.
69#[derive(Debug)]
70pub enum Response<'a> {
71    /// Successful wire envelope, whose typed body is decoded on demand.
72    Successful(ResponseBytes<'a>),
73    /// Protocol error. No signed status information accompanies it.
74    Failure {
75        /// Error code chosen by the responder.
76        failure: Failure,
77        /// Original envelope location.
78        span: Span,
79    },
80}
81
82/// Original successful response payload and its producing reader. Keeping the
83/// envelope separate avoids allocating a large basic response for protocol
84/// failures or unsupported types; decoding moves the existing reader.
85#[derive(Debug)]
86pub struct ResponseBytes<'a> {
87    kind: Oid<'a>,
88    payload: &'a [u8],
89    span: Span,
90    reader: Reader<'a>,
91}
92
93impl<'a> ResponseBytes<'a> {
94    /// Original response syntax identifier.
95    #[must_use]
96    pub fn kind(&self) -> Oid<'a> {
97        self.kind
98    }
99    /// Original encoded response payload.
100    #[must_use]
101    pub fn payload(&self) -> &'a [u8] {
102        self.payload
103    }
104    /// Original payload content location.
105    #[must_use]
106    pub fn span(&self) -> Span {
107        self.span
108    }
109    /// Decode the mandatory basic response syntax using current execution.
110    /// `None` means unsupported syntax. The producing reader's cumulative
111    /// work/depth limits remain active; no extra parser or reader copy is made.
112    pub fn into_basic(self, execution: &Memory) -> Result<Option<BasicResponse<'a>>> {
113        let reader = self.reader.with_execution(execution);
114        reader.charge(19).field(FIELD)?;
115        if self.kind != oid::OCSP_BASIC {
116            return Ok(None);
117        }
118        let mut nested = reader
119            .parser()
120            .read_nested_query_in(
121                &reader,
122                self.payload,
123                self.span.start,
124                Encoding::Der,
125                reader.depth(),
126            )
127            .field(BASIC)?;
128        let root = required(&mut nested, BASIC)?;
129        let basic = read_basic(&nested, &root)?;
130        end(&nested, BASIC)?;
131        Ok(Some(basic))
132    }
133}
134
135/// Responder identity used to locate the actual signing certificate.
136#[derive(Debug)]
137pub enum ResponderId<'a> {
138    /// Subject distinguished name of the signer.
139    Name(Name<'a>),
140    /// SHA-1 of original subjectPublicKey contents, excluding ASN.1 wrapper
141    /// and the BIT STRING unused-bits count (RFC6960 verified errata6165–6167).
142    KeyHash(&'a [u8]),
143}
144
145/// Certificate identity retains its original encoded hash algorithm and octets.
146#[derive(Debug, Clone, Copy)]
147pub struct CertId<'a> {
148    algorithm: AlgorithmIdentifier<'a>,
149    issuer_name_hash: &'a [u8],
150    issuer_key_hash: &'a [u8],
151    serial: Integer<'a>,
152    span: Span,
153}
154
155impl<'a> CertId<'a> {
156    /// Hash algorithm, including original parameters.
157    #[must_use]
158    pub fn algorithm(self) -> AlgorithmIdentifier<'a> {
159        self.algorithm
160    }
161    /// Hash of the target certificate's original issuer DER name.
162    #[must_use]
163    pub fn issuer_name_hash(self) -> &'a [u8] {
164        self.issuer_name_hash
165    }
166    /// Hash of the issuer's original subjectPublicKey BIT STRING contents.
167    #[must_use]
168    pub fn issuer_key_hash(self) -> &'a [u8] {
169        self.issuer_key_hash
170    }
171    /// Original arbitrary-width serial INTEGER.
172    #[must_use]
173    pub fn serial(self) -> Integer<'a> {
174        self.serial
175    }
176    /// Original `CertID` location.
177    #[must_use]
178    pub fn span(self) -> Span {
179        self.span
180    }
181}
182
183/// A responder's assertion, independently of authentication and applicability.
184#[derive(Debug, Clone, Copy, PartialEq, Eq)]
185pub enum Status {
186    /// Positive revocation inquiry; not proof that a certificate was issued.
187    Good,
188    /// Responder states revocation or hold, retaining its original date/reason.
189    Revoked {
190        /// Recorded revocation or hold time.
191        time: Time,
192        /// Encoded optional reason, without substituting a policy decision.
193        reason: Option<crate::crl::Reason>,
194    },
195    /// This responder does not know the requested certificate's status.
196    Unknown,
197}
198
199#[derive(Debug)]
200enum RecordedStatus {
201    Good,
202    Unknown,
203    Revoked {
204        time: Time,
205        reason: Option<crate::crl::Reason>,
206        offset: u64,
207    },
208}
209
210/// One signed assertion with deferred extension semantics.
211#[derive(Debug)]
212pub struct SingleResponse<'a> {
213    id: CertId<'a>,
214    status: RecordedStatus,
215    this_update: Time,
216    next_update: Option<Time>,
217    extensions: Extensions<'a>,
218    span: Span,
219}
220
221impl<'a> SingleResponse<'a> {
222    /// Original certificate identity.
223    #[must_use]
224    pub fn id(&self) -> CertId<'a> {
225        self.id
226    }
227    /// Unauthenticated status assertion.
228    #[must_use]
229    pub fn status(&self) -> Status {
230        match self.status {
231            RecordedStatus::Good => Status::Good,
232            RecordedStatus::Unknown => Status::Unknown,
233            RecordedStatus::Revoked { time, reason, .. } => Status::Revoked { time, reason },
234        }
235    }
236
237    /// UTC-qualified recorded revocation time, when this assertion is revoked.
238    /// This never decides whether a future date may be ignored by the product.
239    pub fn revocation_relation(
240        &self,
241        now: crate::temporal::Reading,
242        utc: &crate::temporal::LeapTable<'_>,
243        execution: &Memory,
244    ) -> Result<Option<crate::time::Relation>> {
245        match self.status {
246            RecordedStatus::Good | RecordedStatus::Unknown => Ok(None),
247            RecordedStatus::Revoked { time, offset, .. } => crate::time::relation_in(
248                time.instant(),
249                now,
250                utc,
251                execution,
252                ("ocspResponse.singleResponse.revocationTime", offset),
253            )
254            .map(Some),
255        }
256    }
257    /// Most recent time the responder knew this status to be correct.
258    #[must_use]
259    pub fn this_update(&self) -> Time {
260        self.this_update
261    }
262    /// Recommended update boundary, absent when newer information is always
263    /// available. No lifetime is invented for an absent value.
264    #[must_use]
265    pub fn next_update(&self) -> Option<Time> {
266        self.next_update
267    }
268    /// Deferred extensions, still using their source parser and current account.
269    #[must_use]
270    pub fn extensions(&self) -> &Extensions<'a> {
271        &self.extensions
272    }
273    /// Original assertion location.
274    #[must_use]
275    pub fn span(&self) -> Span {
276        self.span
277    }
278}
279
280/// `BasicOCSPResponse` retains the exact signed `ResponseData` encoding.
281#[derive(Debug)]
282pub struct BasicResponse<'a> {
283    responder: ResponderId<'a>,
284    produced_at: Time,
285    responses: OwnedVec<SingleResponse<'a>>,
286    extensions: Extensions<'a>,
287    algorithm: AlgorithmIdentifier<'a>,
288    signature: BitString<'a>,
289    certificates: OwnedVec<Certificate<'a>>,
290    signed: &'a [u8],
291    bytes: &'a [u8],
292    span: Span,
293}
294
295impl<'a> BasicResponse<'a> {
296    /// Original responder identity, not a resolved signing authority.
297    #[must_use]
298    pub fn responder(&self) -> &ResponderId<'a> {
299        &self.responder
300    }
301    /// Time the responder signed this response, not the status update time.
302    #[must_use]
303    pub fn produced_at(&self) -> Time {
304        self.produced_at
305    }
306    /// Signed assertions in original order; duplicates are not collapsed.
307    #[must_use]
308    pub fn responses(&self) -> &[SingleResponse<'a>] {
309        &self.responses
310    }
311    /// Response-wide deferred extensions.
312    #[must_use]
313    pub fn extensions(&self) -> &Extensions<'a> {
314        &self.extensions
315    }
316    /// Signature algorithm selected by the responder.
317    #[must_use]
318    pub fn signature_algorithm(&self) -> AlgorithmIdentifier<'a> {
319        self.algorithm
320    }
321    /// Original signature BIT STRING.
322    #[must_use]
323    pub fn signature(&self) -> BitString<'a> {
324        self.signature
325    }
326    /// Untrusted included certificates, not a discovered trust path.
327    #[must_use]
328    pub fn certificates(&self) -> &[Certificate<'a>] {
329        &self.certificates
330    }
331    /// Exact original DER `ResponseData` bytes supplied to signature verification.
332    #[must_use]
333    pub fn signed_bytes(&self) -> &'a [u8] {
334        self.signed
335    }
336    /// Original DER `BasicOCSPResponse` bytes.
337    #[must_use]
338    pub fn as_bytes(&self) -> &'a [u8] {
339        self.bytes
340    }
341    /// Original basic-response location inside the payload OCTET STRING.
342    #[must_use]
343    pub fn span(&self) -> Span {
344        self.span
345    }
346}
347
348impl<'a> Response<'a> {
349    /// Read exactly one OCSP response using the supplied source parser.
350    /// No new parser, budget reset or serialization bridge is introduced.
351    pub fn read(parser: &'a Parser, bytes: &'a [u8], base: u64) -> Result<Self> {
352        let mut reader = parser.read(bytes, base).field(FIELD)?;
353        let element = required(&mut reader, FIELD)?;
354        let result = Self::read_element(&reader, &element)?;
355        end(&reader, FIELD)?;
356        Ok(result)
357    }
358
359    /// Decode an embedded OCSP response under DER with its producing Reader.
360    /// RFC6960 §4 uses explicit tagging by default; §§4.2.1/4.2.2 require
361    /// original DER `ResponseData` for signatures and strict profile times.
362    /// <https://www.rfc-editor.org/rfc/rfc6960#section-4.2.1>
363    pub fn read_element(parent: &Reader<'a>, element: &Element<'a>) -> Result<Self> {
364        if element.tag() != Tag::constructed(universal::SEQUENCE) {
365            return Err(Error::new(
366                ErrorCode::Encoding(structured_asn1::ErrorCode::UnexpectedTag),
367                FIELD,
368                element.span().start,
369            ));
370        }
371        let mut distinguished = parent.reread(element, Encoding::Der).field(FIELD)?;
372        let root = distinguished
373            .expect(Tag::constructed(universal::SEQUENCE))
374            .field(FIELD)?;
375        let mut reader = distinguished.enter(&root).field(FIELD)?;
376        let code = reader.expect(Tag::primitive(10)).field(FIELD)?;
377        reader.charge(9).field(FIELD)?;
378        let code = reader.integer(&code).field(FIELD)?.as_u64();
379        let failure = match code {
380            Some(0) => None,
381            Some(1) => Some(Failure::MalformedRequest),
382            Some(2) => Some(Failure::InternalError),
383            Some(3) => Some(Failure::TryLater),
384            Some(5) => Some(Failure::SignatureRequired),
385            Some(6) => Some(Failure::Unauthorized),
386            _ => {
387                return Err(Error::new(
388                    ErrorCode::MalformedValue,
389                    FIELD,
390                    root.span().start,
391                ));
392            }
393        };
394        if let Some(failure) = failure {
395            // RFC6960 §4.2.1: error responses do not set responseBytes.
396            end(&reader, FIELD)?;
397            return Ok(Self::Failure {
398                failure,
399                span: root.span(),
400            });
401        }
402        let wrapper = reader.expect(Tag::context(true, 0)).field(FIELD)?;
403        end(&reader, FIELD)?;
404        let mut explicit = reader.enter(&wrapper).field(FIELD)?;
405        let response_bytes = explicit
406            .expect(Tag::constructed(universal::SEQUENCE))
407            .field(FIELD)?;
408        end(&explicit, FIELD)?;
409        let mut bytes_reader = explicit.enter(&response_bytes).field(FIELD)?;
410        let kind = bytes_reader.read_oid().field(FIELD)?;
411        let payload = bytes_reader
412            .expect(Tag::primitive(universal::OCTET_STRING))
413            .field(FIELD)?;
414        end(&bytes_reader, FIELD)?;
415        Ok(Self::Successful(ResponseBytes {
416            kind,
417            payload: payload.contents(),
418            span: payload.contents_span(),
419            reader: bytes_reader,
420        }))
421    }
422}
423
424fn read_basic<'a>(parent: &Reader<'a>, element: &Element<'a>) -> Result<BasicResponse<'a>> {
425    let mut reader = sequence(parent, element, BASIC)?;
426    let signed = required(&mut reader, DATA)?;
427    let mut data = sequence(&reader, &signed, DATA)?;
428    let responder = required(&mut data, DATA)?;
429    if responder.tag() == Tag::context(true, 0) {
430        let mut version = data.enter(&responder).field(DATA)?;
431        let value = version.read_integer().field(DATA)?;
432        version.charge(9).field(DATA)?;
433        end(&version, DATA)?;
434        return Err(Error::new(
435            if value.as_u64() == Some(0) {
436                ErrorCode::MalformedValue
437            } else {
438                ErrorCode::UnsupportedVersion
439            },
440            DATA,
441            responder.span().start,
442        ));
443    }
444    let responder = read_responder(&data, &responder)?;
445    let produced = required(&mut data, DATA)?;
446    let produced_at = generalized(&data, &produced, DATA)?;
447    let assertions = data
448        .expect(Tag::constructed(universal::SEQUENCE))
449        .field(DATA)?;
450    let mut assertions_reader = data.enter(&assertions).field(SINGLE)?;
451    let work = parent.execution();
452    let mut responses = work.vector();
453    while let Some(assertion) = assertions_reader.next_element().field(SINGLE)? {
454        responses
455            .try_push(read_single(&assertions_reader, &assertion)?)
456            .map_err(|reason| Error::resource(reason, SINGLE, assertion.span().start))?;
457    }
458    if responses.is_empty() {
459        return Err(Error::new(
460            ErrorCode::EmptySequence,
461            SINGLE,
462            assertions.span().start,
463        ));
464    }
465    let extensions = optional_extensions(&mut data, 1, DATA)?;
466    end(&data, DATA)?;
467    let algorithm = required(&mut reader, BASIC)?;
468    let algorithm = algorithm::read(&reader, &algorithm, BASIC)?;
469    let signature = reader.read_bit_string().field(BASIC)?;
470    let mut certificates = work.vector();
471    if let Some(wrapper) = reader.next_element().field(BASIC)? {
472        if wrapper.tag() != Tag::context(true, 0) {
473            return Err(Error::new(
474                ErrorCode::UnexpectedField,
475                BASIC,
476                wrapper.span().start,
477            ));
478        }
479        let mut explicit = reader.enter(&wrapper).field(BASIC)?;
480        let sequence = explicit
481            .expect(Tag::constructed(universal::SEQUENCE))
482            .field(BASIC)?;
483        end(&explicit, BASIC)?;
484        let mut inside = explicit.enter(&sequence).field(BASIC)?;
485        while let Some(certificate) = inside.next_element().field(BASIC)? {
486            certificates
487                .try_push(Certificate::read_element(&inside, &certificate)?)
488                .map_err(|reason| Error::resource(reason, BASIC, certificate.span().start))?;
489        }
490    }
491    end(&reader, BASIC)?;
492    Ok(BasicResponse {
493        responder,
494        produced_at,
495        responses: responses.into_owned(),
496        extensions,
497        algorithm,
498        signature,
499        certificates: certificates.into_owned(),
500        signed: signed.as_bytes(),
501        bytes: element.as_bytes(),
502        span: element.span(),
503    })
504}
505
506fn read_responder<'a>(parent: &Reader<'a>, element: &Element<'a>) -> Result<ResponderId<'a>> {
507    if element.tag() != Tag::context(true, 1) && element.tag() != Tag::context(true, 2) {
508        return Err(Error::new(
509            ErrorCode::UnexpectedField,
510            DATA,
511            element.span().start,
512        ));
513    }
514    let mut wrapper = parent.enter(element).field(DATA)?;
515    let value = required(&mut wrapper, DATA)?;
516    end(&wrapper, DATA)?;
517    match element.tag() {
518        tag if tag == Tag::context(true, 1) => {
519            Ok(ResponderId::Name(name::read(&wrapper, &value, DATA)?))
520        }
521        tag if tag == Tag::context(true, 2) => {
522            if value.tag() != Tag::primitive(universal::OCTET_STRING)
523                || value.contents().len() != 20
524            {
525                return Err(Error::new(
526                    ErrorCode::MalformedValue,
527                    DATA,
528                    value.span().start,
529                ));
530            }
531            Ok(ResponderId::KeyHash(value.contents()))
532        }
533        _ => Err(Error::new(
534            ErrorCode::UnexpectedField,
535            DATA,
536            element.span().start,
537        )),
538    }
539}
540
541fn read_single<'a>(parent: &Reader<'a>, element: &Element<'a>) -> Result<SingleResponse<'a>> {
542    let mut reader = sequence(parent, element, SINGLE)?;
543    let id = required(&mut reader, SINGLE)?;
544    let id = read_id(&reader, &id)?;
545    let status = required(&mut reader, SINGLE)?;
546    let status = match status.tag() {
547        tag if tag == Tag::context(false, 0) => {
548            reader.null(&status).field(SINGLE)?;
549            RecordedStatus::Good
550        }
551        tag if tag == Tag::context(false, 2) => {
552            reader.null(&status).field(SINGLE)?;
553            RecordedStatus::Unknown
554        }
555        tag if tag == Tag::context(true, 1) => {
556            let mut revoked = reader.enter(&status).field(SINGLE)?;
557            let date = required(&mut revoked, SINGLE)?;
558            let time = generalized(&revoked, &date, SINGLE)?;
559            let reason = if let Some(wrapper) = revoked.next_element().field(SINGLE)? {
560                if wrapper.tag() != Tag::context(true, 0) {
561                    return Err(Error::new(
562                        ErrorCode::UnexpectedField,
563                        SINGLE,
564                        wrapper.span().start,
565                    ));
566                }
567                let mut explicit = revoked.enter(&wrapper).field(SINGLE)?;
568                let reason = explicit.expect(Tag::primitive(10)).field(SINGLE)?;
569                end(&explicit, SINGLE)?;
570                Some(crate::crl::reason_element(&explicit, &reason, SINGLE)?)
571            } else {
572                None
573            };
574            end(&revoked, SINGLE)?;
575            RecordedStatus::Revoked {
576                time,
577                reason,
578                offset: date.span().start,
579            }
580        }
581        _ => {
582            return Err(Error::new(
583                ErrorCode::UnexpectedField,
584                SINGLE,
585                status.span().start,
586            ));
587        }
588    };
589    let this = required(&mut reader, SINGLE)?;
590    let this_update = generalized(&reader, &this, SINGLE)?;
591    let mut next = reader.next_element().field(SINGLE)?;
592    let next_update =
593        if let Some(wrapper) = next.filter(|element| element.tag() == Tag::context(true, 0)) {
594            let mut explicit = reader.enter(&wrapper).field(SINGLE)?;
595            let value = required(&mut explicit, SINGLE)?;
596            end(&explicit, SINGLE)?;
597            let value = generalized(&explicit, &value, SINGLE)?;
598            next = reader.next_element().field(SINGLE)?;
599            Some(value)
600        } else {
601            None
602        };
603    let extensions = extensions_element(&reader, next.as_ref(), 1, SINGLE)?;
604    end(&reader, SINGLE)?;
605    Ok(SingleResponse {
606        id,
607        status,
608        this_update,
609        next_update,
610        extensions,
611        span: element.span(),
612    })
613}
614
615fn read_id<'a>(parent: &Reader<'a>, element: &Element<'a>) -> Result<CertId<'a>> {
616    let mut reader = sequence(parent, element, SINGLE)?;
617    let algorithm = required(&mut reader, SINGLE)?;
618    let algorithm = algorithm::read(&reader, &algorithm, SINGLE)?;
619    let name = reader
620        .expect(Tag::primitive(universal::OCTET_STRING))
621        .field(SINGLE)?;
622    let key = reader
623        .expect(Tag::primitive(universal::OCTET_STRING))
624        .field(SINGLE)?;
625    let serial = reader.read_integer().field(SINGLE)?;
626    end(&reader, SINGLE)?;
627    Ok(CertId {
628        algorithm,
629        issuer_name_hash: name.contents(),
630        issuer_key_hash: key.contents(),
631        serial,
632        span: element.span(),
633    })
634}
635
636fn generalized(parent: &Reader<'_>, element: &Element<'_>, field: &'static str) -> Result<Time> {
637    if element.tag() != Tag::primitive(universal::GENERALIZED_TIME) {
638        return Err(Error::new(
639            ErrorCode::Encoding(structured_asn1::ErrorCode::UnexpectedTag),
640            field,
641            element.span().start,
642        ));
643    }
644    time::read_in(parent, element, field)
645}
646fn sequence<'a>(
647    parent: &Reader<'a>,
648    element: &Element<'a>,
649    field: &'static str,
650) -> Result<Reader<'a>> {
651    if element.tag() != Tag::constructed(universal::SEQUENCE) {
652        return Err(Error::new(
653            ErrorCode::Encoding(structured_asn1::ErrorCode::UnexpectedTag),
654            field,
655            element.span().start,
656        ));
657    }
658    parent.enter(element).field(field)
659}
660fn optional_extensions<'a>(
661    reader: &mut Reader<'a>,
662    tag: u32,
663    field: &'static str,
664) -> Result<Extensions<'a>> {
665    let element = reader.next_element().field(field)?;
666    extensions_element(reader, element.as_ref(), tag, field)
667}
668fn extensions_element<'a>(
669    parent: &Reader<'a>,
670    element: Option<&Element<'a>>,
671    tag: u32,
672    field: &'static str,
673) -> Result<Extensions<'a>> {
674    let Some(element) = element else {
675        return Ok(Extensions::empty(parent.memory()));
676    };
677    if element.tag() != Tag::context(true, tag) {
678        return Err(Error::new(
679            ErrorCode::UnexpectedField,
680            field,
681            element.span().start,
682        ));
683    }
684    let mut explicit = parent.enter(element).field(field)?;
685    let value = required(&mut explicit, field)?;
686    end(&explicit, field)?;
687    extension::read(&explicit, &value, field)
688}
689fn required<'a>(reader: &mut Reader<'a>, field: &'static str) -> Result<Element<'a>> {
690    let at = reader.offset();
691    reader
692        .next_element()
693        .field(field)?
694        .ok_or_else(|| Error::new(ErrorCode::MissingField, field, at))
695}
696fn end(reader: &Reader<'_>, field: &'static str) -> Result<()> {
697    if reader.is_empty() {
698        Ok(())
699    } else {
700        Err(Error::new(ErrorCode::TrailingData, field, reader.offset()))
701    }
702}