structured-cms 0.12.0

Borrowed CMS signatures, digital envelopes and timestamps with explicit providers and resource accounting
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
//! Attribute-certificate recipient targeting (RFC5755 §4.3.2 / Appendix B).
//!
//! This predicate is separate from holder authentication, AA trust, revocation
//! and application authorization. A positive answer only establishes targeting
//! for the caller's already-known recipient names or group-membership facts.
//! <https://www.rfc-editor.org/rfc/rfc5755#section-4.3.2>

use super::{IssuerSerial, ObjectDigestInfo, end, issuer_serial, object_digest, sequence, tag};
use crate::signer::required;
use crate::{Error, ErrorCode, Result};
use core::ops::Range;
use structured_asn1::memory::{Execution, OwnedVec, Work};
use structured_asn1::{Class, Element, Oid, Parser, ScopedReader, Span, Tag};
use structured_pkix::Extension;
use structured_pkix::general_name::{self, GeneralName};

pub(super) const FIELD: &str = "attributeCertificate.targetInformation";

/// `id-ce-targetInformation`, RFC5755 Appendix B.
pub const IDENTIFIER: Oid<'static> = Oid::from_bytes(&[0x55, 0x1d, 55]);

/// One original `Targets` group. Consumers treat all groups as one union.
#[derive(Debug)]
pub struct Group<'a> {
    /// Original SEQUENCE, including an empty group.
    pub element: Element<'a>,
    /// Range in [`TargetInformation::targets`], in original source order.
    pub targets: Range<usize>,
}

/// One original recipient or group assertion.
#[derive(Debug)]
pub struct Target<'a> {
    /// Original context-tagged CHOICE, without retagging.
    pub element: Element<'a>,
    /// Ordinal of its original `Targets` group.
    pub group: usize,
    /// Decoded alternative. It is not an authenticated identity.
    pub value: Value<'a>,
}

/// All ASN.1 alternatives remain inspectable, including the forbidden one.
#[derive(Debug)]
pub enum Value<'a> {
    /// `[0] EXPLICIT GeneralName` (a tagged CHOICE is explicitly wrapped).
    Name(GeneralName<'a>),
    /// `[1] EXPLICIT GeneralName`; membership is supplied by the caller.
    Group(GeneralName<'a>),
    /// Index in [`TargetInformation::certificates`]. RFC5755 forbids its use.
    Certificate(usize),
}

/// Original `TargetCert`, inspectable but never sufficient for a targeting match.
#[derive(Debug)]
pub struct TargetCertificate<'a> {
    /// Ordinal in [`TargetInformation::targets`].
    pub target: usize,
    /// Original `[2] IMPLICIT TargetCert`.
    pub element: Element<'a>,
    /// Certificate assertion, without looking up a certificate.
    pub certificate: IssuerSerial<'a>,
    /// Optional original name.
    pub name: Option<GeneralName<'a>>,
    /// Optional original digest assertion, without hashing an object.
    pub digest: Option<ObjectDigestInfo<'a>>,
}

/// Fully decoded extension, retaining original ranges and independently owned
/// catalogues. The short operation used to read it need not remain alive.
#[derive(Debug)]
pub struct TargetInformation<'a> {
    parser: &'a Parser,
    element: Element<'a>,
    critical: bool,
    groups: OwnedVec<Group<'a>>,
    targets: OwnedVec<Target<'a>>,
    certificates: OwnedVec<TargetCertificate<'a>>,
}

impl<'a> TargetInformation<'a> {
    /// Reads the complete original extension using the shared Extension reader.
    /// All alternatives are decoded before any membership callback can run.
    /// Catalogues and nested Name storage obey source and current work/capacity
    /// admission; no bytes are joined, retagged or re-encoded.
    pub fn read<W: Work>(extension: &Extension<'a>, work: &W) -> Result<Self> {
        Self::read_as(extension, work, IDENTIFIER, FIELD)
    }

    pub(super) fn read_as<W: Work>(
        extension: &Extension<'a>,
        work: &W,
        identifier: Oid<'_>,
        field: &'static str,
    ) -> Result<Self> {
        let execution = work.execution_for(extension.parser());
        execution
            .charge_work(identifier.as_bytes().len() as u64 + 1)
            .map_err(|e| Error::resource(e, field, extension.span().start))?;
        if extension.kind() != identifier {
            return Err(Error::schema(
                ErrorCode::UnexpectedContentType,
                field,
                extension.span().start,
            ));
        }
        let mut reader = extension
            .reader_scoped(&execution)
            .map_err(|e| Error::encoding(e, field))?;
        let element = required(&mut reader, field)?;
        tag(&element, sequence(), field)?;
        end(&reader, field)?;
        let mut inside = reader
            .enter(&element)
            .map_err(|e| Error::encoding(e, field))?;
        let mut groups = execution.vector();
        let mut targets = execution.vector();
        let mut certificates = execution.vector();
        while let Some(group) = inside
            .next_element()
            .map_err(|e| Error::encoding(e, field))?
        {
            tag(&group, sequence(), field)?;
            groups
                .try_reserve(1)
                .map_err(|e| Error::resource(e, field, group.span().start))?;
            let start = targets.len();
            let mut entries = inside
                .enter(&group)
                .map_err(|e| Error::encoding(e, field))?;
            while let Some(entry) = entries
                .next_element()
                .map_err(|e| Error::encoding(e, field))?
            {
                let at = entry.span().start;
                targets
                    .try_reserve(1)
                    .map_err(|e| Error::resource(e, field, at))?;
                let value = if entry.tag() == Tag::context(true, 0)
                    || entry.tag() == Tag::context(true, 1)
                {
                    // RFC5755 Appendix B tags GeneralName, an untagged CHOICE:
                    // its selected name tag remains inside an explicit wrapper.
                    let mut name = entries
                        .enter(&entry)
                        .map_err(|e| Error::encoding(e, field))?;
                    let encoded = required(&mut name, field)?;
                    let decoded =
                        general_name::read(&name, &encoded, field).map_err(Error::pkix)?;
                    end(&name, field)?;
                    if entry.tag() == Tag::context(true, 0) {
                        Value::Name(decoded)
                    } else {
                        Value::Group(decoded)
                    }
                } else if entry.tag() == Tag::context(true, 2) {
                    certificates
                        .try_reserve(1)
                        .map_err(|e| Error::resource(e, field, at))?;
                    let decoded = certificate(&entries, &entry, targets.len(), field)?;
                    let index = certificates.len();
                    certificates
                        .try_push(decoded)
                        .map_err(|e| Error::resource(e, field, at))?;
                    Value::Certificate(index)
                } else {
                    return Err(Error::schema(ErrorCode::UnexpectedTag, field, at));
                };
                targets
                    .try_push(Target {
                        element: entry,
                        group: groups.len(),
                        value,
                    })
                    .map_err(|e| Error::resource(e, field, at))?;
            }
            groups
                .try_push(Group {
                    element: group,
                    targets: start..targets.len(),
                })
                .map_err(|e| Error::resource(e, field, group.span().start))?;
        }
        Ok(Self {
            parser: extension.parser(),
            element,
            critical: extension.is_critical(),
            groups: groups.into_owned(),
            targets: targets.into_owned(),
            certificates: certificates.into_owned(),
        })
    }

    /// Original whole extension value SEQUENCE.
    #[must_use]
    pub fn element(&self) -> Element<'a> {
        self.element
    }
    /// Original extension criticality, not inferred from its identifier.
    #[must_use]
    pub fn is_critical(&self) -> bool {
        self.critical
    }
    /// Original groups and their flat target ranges. Traversal by callers must
    /// be admitted by their own current Work; [`Self::check`] does this itself.
    #[must_use]
    pub fn groups(&self) -> &[Group<'a>] {
        &self.groups
    }
    /// Original target order, with no implicit sorting or deduplication.
    #[must_use]
    pub fn targets(&self) -> &[Target<'a>] {
        &self.targets
    }
    /// Typed forbidden alternatives, without treating them as accepted targets.
    #[must_use]
    pub fn certificates(&self) -> &[TargetCertificate<'a>] {
        &self.certificates
    }

    /// Tests recipient targeting only. Names must be already-known identities;
    /// successfully decode untrusted names before supplying them here.
    ///
    /// RFC5755 §4.3.2 requires criticality, prohibits targetCert and treats all
    /// Targets groups as one union. These profile gates run before comparison
    /// or callback effects. A recipient-name match OR confirmed group membership
    /// suffices. Present empty groups match nothing. Other/X.400/EDI recipient
    /// names remain unproven because the shared name core only knows their
    /// encoded identity; their type-specific semantic identity is not inferred.
    /// This is not a complete AC profile check (including `GeneralName` profile
    /// restrictions), holder authentication or an authorization decision.
    ///
    /// `membership` owns group discovery and must admit its own data-dependent
    /// work through the supplied execution. Unknown membership differs from a
    /// completed negative answer. Errors preserve their cause and original
    /// target span; external callback side effects cannot be rolled back.
    pub fn check<W: Work, E>(
        &self,
        recipients: &[GeneralName<'_>],
        work: &W,
        mut membership: impl FnMut(
            &GeneralName<'a>,
            &Execution<'_>,
        ) -> core::result::Result<Membership, E>,
    ) -> core::result::Result<Decision, CheckError<E>> {
        let execution = work.execution_for(self.parser);
        let pay = |at| {
            execution
                .charge_work(1)
                .map_err(|e| CheckError::Processing(Error::resource(e, FIELD, at)))
        };
        pay(self.element.span().start)?;
        if !self.critical {
            return Ok(Decision::NonCritical);
        }
        if let Some(certificate) = self.certificates.first() {
            return Ok(Decision::ProhibitedTargetCertificate {
                target: certificate.target,
            });
        }
        let mut unknown = false;
        for (index, target) in self.targets.iter().enumerate() {
            match matches_target(target, recipients, &execution, FIELD, &mut membership)? {
                Membership::Member => return Ok(Decision::Matches { target: index }),
                Membership::NotMember => {}
                Membership::Unknown => unknown = true,
            }
        }
        Ok(if unknown {
            Decision::Unproven
        } else {
            Decision::Differs
        })
    }
}

pub(super) fn opaque(name: &GeneralName<'_>) -> bool {
    matches!(
        name,
        GeneralName::Other { .. } | GeneralName::X400(_) | GeneralName::EdiParty(_)
    )
}

// Recipient targeting and proxy-set matching differ in their quantifiers,
// not the meaning or funding of one target. Keep that identity kernel shared.
pub(super) fn matches_target<'a, E>(
    target: &Target<'a>,
    recipients: &[GeneralName<'_>],
    execution: &Execution<'_>,
    field: &'static str,
    membership: &mut impl FnMut(&GeneralName<'a>, &Execution<'_>) -> core::result::Result<Membership, E>,
) -> core::result::Result<Membership, CheckError<E>> {
    let at = target.element.span().start;
    let pay = || {
        execution
            .charge_work(1)
            .map_err(|e| CheckError::Processing(Error::resource(e, field, at)))
    };
    pay()?;
    match &target.value {
        Value::Name(name) => {
            if opaque(name) {
                return Ok(Membership::Unknown);
            }
            for recipient in recipients {
                pay()?;
                if general_name::matches_at(name, recipient, execution, at, field)
                    .map_err(|e| CheckError::Processing(Error::pkix(e)))?
                {
                    return Ok(Membership::Member);
                }
            }
            Ok(Membership::NotMember)
        }
        Value::Group(name) => membership(name, execution).map_err(|source| CheckError::Callback {
            target: target.element.span(),
            source,
        }),
        Value::Certificate(_) => unreachable!("complete certificate preflight"),
    }
}

fn certificate<'a>(
    parent: &ScopedReader<'a, '_>,
    element: &Element<'a>,
    target: usize,
    field: &'static str,
) -> Result<TargetCertificate<'a>> {
    let mut inside = parent
        .enter(element)
        .map_err(|e| Error::encoding(e, field))?;
    let issuer = required(&mut inside, field)?;
    tag(&issuer, sequence(), field)?;
    let certificate = issuer_serial(&inside, &issuer, field)?;
    let mut next = inside
        .next_element()
        .map_err(|e| Error::encoding(e, field))?;
    let name = if next
        .as_ref()
        .is_some_and(|e| e.tag().class() == Class::ContextSpecific)
    {
        let decoded = general_name::read(&inside, next.as_ref().expect("present name"), field)
            .map_err(Error::pkix)?;
        next = inside
            .next_element()
            .map_err(|e| Error::encoding(e, field))?;
        Some(decoded)
    } else {
        None
    };
    let digest = if let Some(value) = next {
        tag(&value, sequence(), field)?;
        Some(object_digest(&inside, &value, field)?)
    } else {
        None
    };
    end(&inside, field)?;
    Ok(TargetCertificate {
        target,
        element: *element,
        certificate,
        name,
        digest,
    })
}

/// Caller-known group membership. No group is discovered by the format reader.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Membership {
    /// The recipient belongs to the named group.
    Member,
    /// Membership was checked and the recipient is not a member.
    NotMember,
    /// The caller cannot establish whether the recipient belongs to this group.
    Unknown,
}

/// Completed targeting facts, not AA trust or application permission.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Decision {
    /// The indicated original target names the recipient or one of its groups.
    Matches {
        /// Original flat target ordinal.
        target: usize,
    },
    /// All target alternatives were checked and none matched.
    Differs,
    /// No match was established, with at least one undecidable name/membership.
    Unproven,
    /// RFC5755 §4.3.2 requires this extension to be critical.
    NonCritical,
    /// RFC5755 §4.3.2 prohibits targetCert, even if another target would match.
    ProhibitedTargetCertificate {
        /// Original flat target ordinal.
        target: usize,
    },
}

/// Terminal processing/callback refusal, never represented as a mismatch.
#[derive(Debug)]
pub enum CheckError<E> {
    /// A source/current-operation resource or shared name processing failure.
    Processing(Error),
    /// The caller's original cause and the original group-target range.
    Callback {
        /// Original group target CHOICE range.
        target: Span,
        /// Original callback error, without conversion.
        source: E,
    },
}