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
//! Selected-provider certificate hash and issuer facts, without trust claims.
use super::{CertificateId, IssuerAgreement, SigningAttributes};
use crate::digest::{DigestBatch, DigestError, PassError};
use crate::provider::Finished;
use crate::stream::RangesError;
use crate::{Error, Octets};
use structured_asn1::digest::{Digest, Resolution};
use structured_asn1::memory::{Execution, OwnedVec, Work};
use structured_asn1::{Reader, Span};
use structured_pkix::Certificate;
use structured_pkix::algorithm::digest::AsnDigest;
/// Agreement of one ESS first identifier with a caller-selected certificate.
/// None of these answers independently establishes signature/path trust or
/// erases the parsed attribute's conformance/restriction diagnostics.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Binding {
/// Whole-certificate hash and the optional readable issuer/serial agree.
Matches,
/// Computed whole-certificate hash does not agree.
HashDiffers,
/// Hash agrees but readable issuer/serial identifies something else.
IssuerDiffers,
/// Written issuer/serial is unreadable; hash agreement is insufficient.
IssuerUnreadable,
/// Known digest width cannot produce the declared certificate hash.
MalformedHash,
/// Selected provider rejects the written algorithm's parameter syntax.
MalformedAlgorithm,
/// The selected provider cannot compute this explicit mechanism.
Unsupported,
}
/// Both independent answers; absence does not imply a successful binding.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Bindings {
/// V1 answer when that signed attribute existed.
pub v1: Option<Binding>,
/// V2 answer when that signed attribute existed.
pub v2: Option<Binding>,
}
/// Resource, source-pass and provider failures remain outside semantic answers.
#[derive(Debug)]
pub enum BindingError<E> {
/// Original common processing/resource refusal and its source location.
Processing(Error),
/// Original comparison failure, including backend resources.
Callback {
/// Original enclosing ESS field whose callback refused.
field: &'static str,
/// Real original identifier span; no offset is synthesized.
span: Span,
/// Original selected-provider cause.
source: E,
},
/// Digest preparation/refusal or provider output contract failure.
Digest {
/// Original whole-certificate range being processed.
span: Span,
/// Common digest/provider cause, independently of document conformance.
source: DigestError<E>,
},
/// Incomplete/failed certificate pass; no successful partial output.
Pass {
/// Original whole-certificate range supplied to the failed pass.
span: Span,
/// Original source/common/provider cause.
source: PassError<RangesError, E>,
},
/// An accepted request is absent from a completed common digest memo.
/// This is an internal processing contract failure, not document syntax
/// or a provider's negative cryptographic answer.
LostRequest(usize),
}
enum Expected<'a, W: Work> {
Borrowed(&'a [u8]),
Joined(OwnedVec<u8, W>),
}
impl<W: Work> Expected<'_, W> {
fn as_bytes(&self) -> &[u8] {
match self {
Self::Borrowed(bytes) => bytes,
Self::Joined(bytes) => bytes,
}
}
}
struct Queued<'s, 'a, W: Work> {
identifier: &'s CertificateId<'a>,
expected: Expected<'a, W>,
ordinal: usize,
}
enum Request<I, H> {
Answer(Binding),
Compute { identity: I, expected: H },
}
type PreparedRequest<'a, 'p, P> = Result<
Request<<P as Digest<'a>>::Identity, Expected<'a, Execution<'p>>>,
BindingError<<P as Digest<'a>>::Error>,
>;
impl<'a> SigningAttributes<'a> {
/// Checks both first identifiers over one complete original DER certificate.
///
/// Resolution and known-width checks precede every state/input side effect.
/// Semantic digest identities are deduplicated through the selected provider;
/// neither digest states nor output identities are cloned. Each version keeps
/// its own outcome, while the target issuer is prepared at most once. Later
/// identifiers and policy terms remain signed validation-set restrictions in
/// this object; the caller must enforce them and signature/path/time policy.
pub fn bind_certificate<P: AsnDigest<'a>>(
&self,
provider: &'a P,
certificate: &Certificate<'_>,
parent: &Reader<'a>,
) -> Result<Bindings, BindingError<P::Error>> {
let current = parent.execution();
// Hashing revisits the certificate source, even when ESS omits its
// optional issuerSerial. Keep its producing ceiling and the current
// operation on the entire batch, including provider state/storage.
let execution = certificate.execution_in(¤t);
let identifiers = [
self.v1().map(super::SigningCertificate::signer),
self.v2().map(super::SigningCertificate::signer),
];
let mut answers = [None, None];
let mut queued = [None, None];
let mut identities = None;
for (index, identifier) in identifiers.iter().enumerate() {
let Some(identifier) = identifier else {
continue;
};
let at = identifier.element().span().start;
let field = identifier.field;
match prepare_request(provider, identifier, parent)? {
Request::Answer(answer) => answers[index] = Some(answer),
Request::Compute { identity, expected } => {
let identities = match identities.as_mut() {
Some(identities) => identities,
None => identities.insert(execution.vector()),
};
let ordinal = identities.len();
identities.try_push(identity).map_err(|reason| {
BindingError::Processing(Error::resource(reason, field, at))
})?;
queued[index] = Some(Queued {
identifier,
expected,
ordinal,
});
}
}
}
let Some(identities) = identities else {
return Ok(Bindings {
v1: answers[0],
v2: answers[1],
});
};
let source_at = certificate.span().start;
let batch = DigestBatch::prepare(
provider,
identities.into_owned(),
&execution,
"ess.certificate",
source_at,
)
.map_err(|source| BindingError::Digest {
span: certificate.span(),
source,
})?;
let mut ranges = [certificate.as_bytes()];
let memo = batch
.run(&mut ranges, &execution)
.map_err(|source| BindingError::Pass {
span: certificate.span(),
source,
})?;
let mut issuer = None;
for (index, request) in queued.into_iter().enumerate() {
let Some(request) = request else {
continue;
};
let Some(digest) = memo
.for_request(request.ordinal, &execution)
.map_err(|source| BindingError::Digest {
span: certificate.span(),
source,
})?
else {
return Err(BindingError::LostRequest(request.ordinal));
};
answers[index] = Some(compare_binding(
provider,
request.identifier,
request.expected.as_bytes(),
digest.finished(),
certificate,
parent,
&mut issuer,
)?);
}
Ok(Bindings {
v1: answers[0],
v2: answers[1],
})
}
}
impl<'a> super::SigningCertificate<'a> {
/// Checks every later signed validation-set identifier against one actual
/// certificate. The first signer identifier is deliberately excluded.
///
/// RFC5035 §§3/5 limits certificates used during validation when later
/// identifiers exist. The format layer supplies actual path/credential
/// certificates; this operation neither builds a path nor selects trust.
/// All declarations are admitted before hashing. Resolved digest identities
/// share one complete certificate pass and one finalized output each.
/// <https://www.rfc-editor.org/rfc/rfc5035#section-3>
pub fn bind_validation_certificate<P: AsnDigest<'a>>(
&self,
provider: &'a P,
certificate: &Certificate<'_>,
parent: &Reader<'a>,
) -> Result<OwnedVec<Binding>, BindingError<P::Error>> {
let current = parent.execution();
// Later validation-set identifiers hash the same original source as
// first-signer identifiers and must use the same execution bridge.
let execution = certificate.execution_in(¤t);
let field = self.version.field();
let at = self.element.span().start;
let refusal = |reason| BindingError::Processing(Error::resource(reason, field, at));
let later = &self.identifiers()[1..];
let mut answers = execution.vector();
let mut queued = execution.vector();
let mut identities = execution.vector();
answers.try_reserve_exact(later.len()).map_err(refusal)?;
queued.try_reserve_exact(later.len()).map_err(refusal)?;
for identifier in later {
execution.charge_work(1).map_err(refusal)?;
match prepare_request(provider, identifier, parent)? {
Request::Answer(answer) => answers.try_push(answer).map_err(refusal)?,
Request::Compute { identity, expected } => {
let ordinal = identities.len();
identities.try_push(identity).map_err(refusal)?;
queued
.try_push((
answers.len(),
Queued {
identifier,
expected,
ordinal,
},
))
.map_err(refusal)?;
// Private pending slot: every queued request must finish
// below or return Err. No pending catalogue is exposed.
answers.try_push(Binding::Unsupported).map_err(refusal)?;
}
}
}
if !identities.is_empty() {
let batch =
DigestBatch::prepare(provider, identities.into_owned(), &execution, field, at)
.map_err(|source| BindingError::Digest {
span: certificate.span(),
source,
})?;
let mut ranges = [certificate.as_bytes()];
let memo = batch
.run(&mut ranges, &execution)
.map_err(|source| BindingError::Pass {
span: certificate.span(),
source,
})?;
let mut issuer = None;
for (slot, request) in queued {
execution.charge_work(1).map_err(refusal)?;
let Some(digest) =
memo.for_request(request.ordinal, &execution)
.map_err(|source| BindingError::Digest {
span: certificate.span(),
source,
})?
else {
return Err(BindingError::LostRequest(request.ordinal));
};
answers[slot] = compare_binding(
provider,
request.identifier,
request.expected.as_bytes(),
digest.finished(),
certificate,
parent,
&mut issuer,
)?;
}
}
Ok(answers.into_owned())
}
}
fn prepare_request<'a, 'p, P: AsnDigest<'a>>(
provider: &'a P,
identifier: &CertificateId<'a>,
parent: &'p Reader<'a>,
) -> PreparedRequest<'a, 'p, P> {
crate::provider::require_instance(
provider,
identifier.field,
identifier.element().span().start,
)
.map_err(BindingError::Processing)?;
let execution = parent.execution();
let at = identifier.element().span().start;
let field = identifier.field;
execution
.charge_work(1)
.map_err(|reason| BindingError::Processing(Error::resource(reason, field, at)))?;
let resolved = crate::provider::resolve_digest(provider, identifier.digest_algorithm(), parent)
.map_err(BindingError::Processing)?;
match resolved {
Resolution::Unsupported => Ok(Request::Answer(Binding::Unsupported)),
Resolution::Malformed => Ok(Request::Answer(Binding::MalformedAlgorithm)),
Resolution::Supported(identity) => {
if let Some(width) = provider.width(&identity)
&& width != identifier.hashed().len()
{
return Ok(Request::Answer(Binding::MalformedHash));
}
// Only a constructed logical hash needs a joined buffer. Every
// declaration's admission finishes before any hash state starts.
let expected = prepare_expected(identifier.hashed(), &execution, field, at)?;
Ok(Request::Compute { identity, expected })
}
}
}
fn prepare_expected<'a, W: Work, E>(
octets: &Octets<'a>,
execution: &W,
field: &'static str,
at: u64,
) -> Result<Expected<'a, W>, BindingError<E>> {
if let Some(bytes) = octets.as_one() {
return Ok(Expected::Borrowed(bytes));
}
let mut joined = execution.vector();
joined
.try_reserve_exact(octets.len())
.map_err(|reason| BindingError::Processing(Error::resource(reason, field, at)))?;
for piece in octets.pieces() {
execution.charge_work(1).map_err(|reason| {
BindingError::Processing(Error::resource(reason, field, piece.span().start))
})?;
joined
.try_extend_from_slice(piece.as_bytes())
.map_err(|reason| {
BindingError::Processing(Error::resource(reason, field, piece.span().start))
})?;
}
Ok(Expected::Joined(joined))
}
fn compare_binding<'a, 'c, 'p, P: Digest<'a>>(
provider: &P,
identifier: &CertificateId<'a>,
expected: &[u8],
digest: Finished<'_, P, P::Identity, P::Output>,
certificate: &Certificate<'c>,
parent: &'p Reader<'_>,
issuer: &mut Option<structured_pkix::Ordered<'c, Execution<'p>>>,
) -> Result<Binding, BindingError<P::Error>> {
// Variable-width identities still require complete declared/actual output
// agreement. A width mismatch is malformed, never an ordinary hash mismatch.
if expected.len() != digest.output().as_ref().len() {
return Ok(Binding::MalformedHash);
}
let matches = provider
.matches(
digest.identity(),
digest.output(),
expected,
&parent.execution(),
)
.map_err(|source| BindingError::Callback {
field: identifier.field,
span: identifier.element().span(),
source,
})?;
if !matches {
return Ok(Binding::HashDiffers);
}
match identifier
.matches_issuer_with(certificate, parent, issuer)
.map_err(BindingError::Processing)?
{
IssuerAgreement::Unstated | IssuerAgreement::Matches => Ok(Binding::Matches),
IssuerAgreement::Differs => Ok(Binding::IssuerDiffers),
IssuerAgreement::Unreadable => Ok(Binding::IssuerUnreadable),
}
}