bc-envelope 0.43.0

Gordian Envelope for Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
use bc_components::{
    DigestProvider, Signature, Signer, SigningOptions, Verifier,
};
#[cfg(feature = "known_value")]
use known_values;

use super::SignatureMetadata;
use crate::{Envelope, EnvelopeEncodable, Error, Result};

/// Support for signing envelopes and verifying signatures.
///
/// This implementation provides methods for digitally signing envelopes and
/// verifying signatures. It supports both basic signatures and signatures with
/// metadata, as well as multi-signature scenarios.
impl Envelope {
    /// Creates a signature for the envelope's subject and returns a new
    /// envelope with a `'signed': Signature` assertion.
    ///
    /// - Parameters:
    ///   - private_key: The signer's `SigningPrivateKey`
    ///
    /// - Returns: The signed envelope.
    pub fn add_signature(&self, private_key: &dyn Signer) -> Self {
        self.add_signature_opt(private_key, None, None)
    }

    #[doc(hidden)]
    /// Creates a signature for the envelope's subject and returns a new
    /// envelope with a `'signed': Signature` assertion.
    ///
    /// - Parameters:
    ///   - private_key: A signer's `PrivateKeyBase` or `SigningPrivateKey`.
    ///   - options: Optional signing options.
    ///   - metadata: Optional metadata for the signature, which itself will be
    ///     signed.
    ///
    /// - Returns: The signed envelope.
    pub fn add_signature_opt(
        &self,
        private_key: &dyn Signer,
        options: Option<SigningOptions>,
        metadata: Option<SignatureMetadata>,
    ) -> Self {
        let digest = *self.subject().digest().data();
        let mut signature = Envelope::new(
            private_key
                .sign_with_options(&digest as &dyn AsRef<[u8]>, options.clone())
                .unwrap(),
        );

        if let Some(metadata) = metadata
            && metadata.has_assertions()
        {
            let mut signature_with_metadata = signature;

            metadata.assertions().iter().for_each(|assertion| {
                signature_with_metadata = signature_with_metadata
                    .add_assertion_envelope(assertion.to_envelope())
                    .unwrap();
            });

            signature_with_metadata = signature_with_metadata.wrap();

            let outer_signature = Envelope::new(
                private_key
                    .sign_with_options(
                        &signature_with_metadata.digest(),
                        options,
                    )
                    .unwrap(),
            );
            signature = signature_with_metadata
                .add_assertion(known_values::SIGNED, outer_signature);
        }

        self.add_assertion(known_values::SIGNED, signature)
    }

    #[doc(hidden)]
    /// Creates several signatures for the envelope's subject and returns a new
    /// envelope with additional `'signed': Signature` assertions.
    ///
    /// - Parameters:
    ///  - private_keys: An array of signers' `SigningPrivateKey`s.
    ///
    /// - Returns: The signed envelope.
    pub fn add_signatures(&self, private_keys: &[&dyn Signer]) -> Self {
        private_keys
            .iter()
            .fold(self.clone(), |envelope, private_key| {
                envelope.add_signature(*private_key)
            })
    }

    #[doc(hidden)]
    /// Creates several signatures for the envelope's subject and returns a new
    /// envelope with additional `'signed': Signature` assertions.
    ///
    /// - Parameters:
    ///   - private_keys: An array of signers' `SigningPrivateKey`s and optional
    ///     `SigningOptions`.
    ///
    /// - Returns: The signed envelope.
    pub fn add_signatures_opt(
        &self,
        private_keys: &[(
            &dyn Signer,
            Option<SigningOptions>,
            Option<SignatureMetadata>,
        )],
    ) -> Self {
        private_keys.iter().fold(
            self.clone(),
            |envelope, (private_key, options, metadata)| {
                envelope.add_signature_opt(
                    *private_key,
                    options.clone(),
                    metadata.clone(),
                )
            },
        )
    }

    /// Convenience constructor for a `'signed': Signature` assertion envelope.
    ///
    /// - Parameters:
    ///   - signature: The `Signature` for the object.
    ///   - note: An optional note to be added to the `Signature`.
    ///
    /// - Returns: The new assertion envelope.
    pub fn make_signed_assertion(
        &self,
        signature: &Signature,
        note: Option<&str>,
    ) -> Self {
        let mut envelope =
            Envelope::new_assertion(known_values::SIGNED, signature.clone());
        if let Some(note) = note {
            envelope = envelope.add_assertion(known_values::NOTE, note);
        }
        envelope
    }

    /// Returns whether the given signature is valid.
    ///
    /// - Parameters:
    ///   - signature: The `Signature` to be checked.
    ///   - public_key: The potential signer's `Verifier`.
    ///
    /// - Returns: `true` if the signature is valid for this envelope's subject,
    ///   `false` otherwise.
    pub fn is_verified_signature(
        &self,
        signature: &Signature,
        public_key: &dyn Verifier,
    ) -> bool {
        self.is_signature_from_key(signature, public_key)
    }

    /// Checks whether the given signature is valid for the given public key.
    ///
    /// Used for chaining a series of operations that include validating
    /// signatures.
    ///
    /// - Parameters:
    ///   - signature: The `Signature` to be checked.
    ///   - public_key: The potential signer's `Verifier`.
    ///
    /// - Returns: This envelope.
    ///
    /// - Throws: Throws `EnvelopeError.unverifiedSignature` if the signature is
    ///   not valid. valid.
    pub fn verify_signature(
        &self,
        signature: &Signature,
        public_key: &dyn Verifier,
    ) -> Result<Self> {
        if !self.is_signature_from_key(signature, public_key) {
            return Err(Error::UnverifiedSignature);
        }
        Ok(self.clone())
    }

    /// Returns whether the envelope's subject has a valid signature from the
    /// given public key.
    ///
    /// - Parameters:
    ///   - public_key: The potential signer's `Verifier`.
    ///
    /// - Returns: `true` if any signature is valid for this envelope's subject,
    ///   `false` otherwise.
    ///
    /// - Throws: Throws an exception if any `'signed'` assertion doesn't
    ///   contain a valid `Signature` as its object.
    pub fn has_signature_from(
        &self,
        public_key: &dyn Verifier,
    ) -> Result<bool> {
        self.has_some_signature_from_key(public_key)
    }

    /// Returns whether the envelope's subject has a valid signature from the
    /// given public key by returning the signature metadata.
    ///
    /// - Parameters:
    ///  - public_key: The potential signer's `Verifier`.
    ///
    /// - Returns: The metadata envelope if the signature is valid, `None`
    ///   otherwise.
    pub fn has_signature_from_returning_metadata(
        &self,
        public_key: &dyn Verifier,
    ) -> Result<Option<Envelope>> {
        self.has_some_signature_from_key_returning_metadata(public_key)
    }

    /// Returns whether the envelope's subject has a valid signature from the
    /// given public key.
    ///
    /// Used for chaining a series of operations that include validating
    /// signatures.
    ///
    /// - Parameters:
    ///   - public_key: The potential signer's `Verifier`.
    ///
    /// - Returns: This envelope.
    ///
    /// - Throws: Throws `EnvelopeError.unverifiedSignature` if the signature is
    ///   not valid. valid.
    pub fn verify_signature_from(
        &self,
        public_key: &dyn Verifier,
    ) -> Result<Self> {
        if !self.has_some_signature_from_key(public_key)? {
            return Err(Error::UnverifiedSignature);
        }
        Ok(self.clone())
    }

    pub fn verify_signature_from_returning_metadata(
        &self,
        public_key: &dyn Verifier,
    ) -> Result<Envelope> {
        let metadata =
            self.has_some_signature_from_key_returning_metadata(public_key)?;
        if metadata.is_none() {
            return Err(Error::UnverifiedSignature);
        }
        Ok(metadata.unwrap())
    }

    /// Checks whether the envelope's subject has a set of signatures.
    pub fn has_signatures_from(
        &self,
        public_keys: &[&dyn Verifier],
    ) -> Result<bool> {
        self.has_signatures_from_threshold(public_keys, None)
    }

    /// Returns whether the envelope's subject has some threshold of signatures.
    ///
    /// If `threshold` is `nil`, then *all* signers in `public_keys` must have
    /// signed. If `threshold` is `1`, then at least one signer must have
    /// signed.
    ///
    /// - Parameters:
    ///   - public_keys: An array of potential signers' `Verifier`s.
    ///   - threshold: Optional minimum number of signers.
    ///
    /// - Returns: `true` if the threshold of valid signatures is met, `false`
    ///   otherwise.
    ///
    /// - Throws: Throws an exception if any `'signed'` assertion doesn't
    ///   contain a valid `Signature` as its object.
    pub fn has_signatures_from_threshold(
        &self,
        public_keys: &[&dyn Verifier],
        threshold: Option<usize>,
    ) -> Result<bool> {
        let threshold = threshold.unwrap_or(public_keys.len());
        let mut count = 0;
        for key in public_keys {
            if self.clone().has_some_signature_from_key(*key)? {
                count += 1;
                if count >= threshold {
                    return Ok(true);
                }
            }
        }
        Ok(false)
    }

    /// Checks whether the envelope's subject has some threshold of signatures.
    ///
    /// If `threshold` is `nil`, then *all* signers in `public_keys` must have
    /// signed. If `threshold` is `1`, then at least one signer must have
    /// signed.
    ///
    /// Used for chaining a series of operations that include validating
    /// signatures.
    ///
    /// - Parameters:
    ///   - public_keys: An array of potential signers' `Verifier`s.
    ///   - threshold: Optional minimum number of signers.
    ///
    /// - Returns: This envelope.
    ///
    /// - Throws: Throws an exception if the threshold of valid signatures is
    ///   not met.
    pub fn verify_signatures_from_threshold(
        &self,
        public_keys: &[&dyn Verifier],
        threshold: Option<usize>,
    ) -> Result<Self> {
        if !self.has_signatures_from_threshold(public_keys, threshold)? {
            return Err(Error::UnverifiedSignature);
        }
        Ok(self.clone())
    }

    /// Checks whether the envelope's subject has a set of signatures.
    pub fn verify_signatures_from(
        &self,
        public_keys: &[&dyn Verifier],
    ) -> Result<Self> {
        self.verify_signatures_from_threshold(public_keys, None)
    }
}

/// Internal implementation details for signature operations.
#[doc(hidden)]
impl Envelope {
    fn is_signature_from_key(
        &self,
        signature: &Signature,
        key: &dyn Verifier,
    ) -> bool {
        key.verify(signature, &self.subject().digest())
    }

    fn has_some_signature_from_key(&self, key: &dyn Verifier) -> Result<bool> {
        self.has_some_signature_from_key_returning_metadata(key)
            .map(|x| x.is_some())
    }

    fn has_some_signature_from_key_returning_metadata(
        &self,
        key: &dyn Verifier,
    ) -> Result<Option<Envelope>> {
        // Valid signature objects are either:
        //
        // - `Signature` objects, or
        // - `Signature` objects with additional metadata assertions, wrapped
        // and then signed by the same key.
        let signature_objects =
            self.objects_for_predicate(known_values::SIGNED);
        let result: Option<Result<Option<Envelope>>> =
            signature_objects.iter().find_map(|signature_object| {
                let signature_object_subject = signature_object.subject();
                if signature_object_subject.is_wrapped() {
                    if let Ok(outer_signature_object) = signature_object
                        .object_for_predicate(known_values::SIGNED)
                    {
                        if let Ok(outer_signature) = outer_signature_object
                            .extract_subject::<Signature>(
                        ) {
                            if !signature_object_subject
                                .is_signature_from_key(&outer_signature, key)
                            {
                                return None;
                            }
                        } else {
                            return Some(Err(Error::InvalidOuterSignatureType));
                        }
                    }

                    let signature_metadata_envelope =
                        signature_object_subject.try_unwrap().unwrap();
                    if let Ok(signature) = signature_metadata_envelope
                        .extract_subject::<Signature>()
                    {
                        let signing_target = self.subject();
                        if !signing_target
                            .is_signature_from_key(&signature, key)
                        {
                            return Some(Err(Error::UnverifiedInnerSignature));
                        }
                        Some(Ok(Some(signature_metadata_envelope)))
                    } else {
                        Some(Err(Error::InvalidInnerSignatureType))
                    }
                } else if let Ok(signature) =
                    signature_object.extract_subject::<Signature>()
                {
                    if !self.is_signature_from_key(&signature, key) {
                        return None;
                    }
                    Some(Ok(Some(signature_object.clone())))
                } else {
                    Some(Err(Error::InvalidSignatureType))
                }
            });

        match result {
            Some(Ok(Some(envelope))) => Ok(Some(envelope)),
            Some(Err(err)) => Err(err),
            _ => Ok(None),
        }
    }
}

/// Convenience methods for signing and verifying envelopes.
///
/// These methods provide a simpler API for common signature operations,
/// particularly for signing entire envelopes by automatically wrapping them.
impl Envelope {
    /// Signs the entire envelope (subject and assertions) by wrapping it first.
    ///
    /// This is a convenience method that wraps the envelope before signing,
    /// ensuring that all assertions are included in the signature, not just
    /// the subject.
    ///
    /// # Parameters
    ///
    /// * `signer` - The signer that will produce the signature.
    ///
    /// # Returns
    ///
    /// A new envelope with the wrapped envelope as subject and a signature
    /// assertion.
    pub fn sign(&self, signer: &dyn Signer) -> Envelope {
        self.sign_opt(signer, None)
    }

    /// Signs the entire envelope with options but no metadata.
    ///
    /// This is a convenience method that wraps the envelope before signing with
    /// the specified options.
    ///
    /// # Parameters
    ///
    /// * `signer` - The signer that will produce the signature.
    /// * `options` - Optional signing options to customize the signature
    ///   generation.
    ///
    /// # Returns
    ///
    /// A new envelope with the wrapped envelope as subject and a signature
    /// assertion.
    pub fn sign_opt(
        &self,
        signer: &dyn Signer,
        options: Option<SigningOptions>,
    ) -> Envelope {
        self.wrap().add_signature_opt(signer, options, None)
    }

    /// Verifies that the envelope has a valid signature from the specified
    /// verifier.
    ///
    /// This method assumes the envelope is wrapped (i.e., was signed using
    /// `sign()` rather than `add_signature()`), and unwraps it after
    /// verification.
    ///
    /// # Parameters
    ///
    /// * `verifier` - The verifier to check the signature against.
    ///
    /// # Returns
    ///
    /// The unwrapped envelope if verification succeeds, otherwise an error.
    ///
    /// # Errors
    ///
    /// Returns an error if the signature verification fails or if the envelope
    /// cannot be unwrapped.
    pub fn verify(&self, verifier: &dyn Verifier) -> Result<Envelope> {
        self.verify_signature_from(verifier)?.try_unwrap()
    }

    /// Verifies the envelope's signature and returns both the unwrapped
    /// envelope and signature metadata.
    ///
    /// This method verifies that the envelope has a valid signature from the
    /// specified verifier, then unwraps it and returns both the envelope
    /// and any metadata associated with the signature.
    ///
    /// # Parameters
    ///
    /// * `verifier` - The verifier to check the signature against.
    ///
    /// # Returns
    ///
    /// A tuple containing the unwrapped envelope and the signature metadata
    /// envelope if verification succeeds, otherwise an error.
    ///
    /// # Errors
    ///
    /// Returns an error if the signature verification fails or if the envelope
    /// cannot be unwrapped.
    pub fn verify_returning_metadata(
        &self,
        verifier: &dyn Verifier,
    ) -> Result<(Envelope, Envelope)> {
        let metadata =
            self.verify_signature_from_returning_metadata(verifier)?;
        Ok((self.try_unwrap()?, metadata))
    }
}