summaryrefslogtreecommitdiffstats
path: root/openpgp/src/cert/lazysigs.rs
blob: 95ae30b0a28764c615666f63ed409078420f822e (plain)
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
//! Lazily verified signatures.
//!
//! In the original implementation of `Cert::canonicalize`, all
//! self-signatures were verified.  This has turned out to be very
//! expensive.  Instead, we should only verify the signatures we are
//! actually interested in.
//!
//! To preserve the semantics, every self signature we hand out from
//! the `Cert` API must have been verified first.  However, we can do
//! that lazily.  And, when we reason over the cert (i.e. we are
//! looking for the right self-signature), we can search the
//! signatures without triggering the verification, and only verify
//! the one we are really interested in.

use std::{
    cmp::Ordering,
    mem,
    sync::{Arc, Mutex, OnceLock},
};

use crate::{
    Error,
    Result,
    packet::{
        Key,
        Signature,
        key,
        signature::subpacket::{SubpacketTag, SubpacketValue},
    },
};

/// Lazily verified signatures, similar to a `Vec<Signature>`.
///
/// We use two distinct vectors to store the signatures and their
/// state.  The reason for that is that we need to modify the
/// signature states while the signatures are borrowed.
///
/// We provide a subset of `Vec<Signature>`'s interface to make it
/// (mostly) a drop-in replacement.
///
/// # Invariant
///
/// - There are as many signatures as signature states.
///
/// - If the field `verified_sigs` is used, then there must have been
///   a bad signature (i.e. len(verified_sigs) < len(sigs)).
#[derive(Debug)]
pub struct LazySignatures {
    /// The primary key to verify the signatures with.
    primary_key: Arc<Key<key::PublicParts, key::PrimaryRole>>,

    /// The signatures.
    sigs: Vec<Signature>,

    /// The signature states.
    states: Mutex<Vec<SigState>>,

    /// Verified signatures.
    ///
    /// Because of https://gitlab.com/sequoia-pgp/sequoia/-/issues/638
    /// we have to hand out contiguous slices of verified signatures.
    /// If all signatures are good, we can serve that request from
    /// `sigs`.  Otherwise, we have to clone the verified signatures.
    ///
    /// XXXv2: Remove this field.
    verified_sigs: OnceLock<Vec<Signature>>,
}

impl PartialEq for LazySignatures {
    fn eq(&self, other: &Self) -> bool {
        self.assert_invariant();
        other.assert_invariant();
        self.primary_key == other.primary_key
            && self.sigs == other.sigs
    }
}

impl Clone for LazySignatures {
    fn clone(&self) -> Self {
        self.assert_invariant();
        LazySignatures {
            primary_key: self.primary_key.clone(),
            sigs: self.sigs.clone(),
            // Avoid blocking.  If we fail to get the lock, reset the
            // signature states to unverified in the clone.
            states: if let Ok(states) = self.states.try_lock() {
                states.clone()
            } else {
                vec![SigState::Unverified; self.sigs.len()]
            }.into(),
            verified_sigs: Default::default(),
        }
    }
}

/// Verification state of a signature.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SigState {
    /// Not yet verified.
    Unverified,

    /// Verification was successful.
    Good,

    /// Verification failed.
    Bad,
}

impl LazySignatures {
    /// Asserts the invariant.
    fn assert_invariant(&self) {
        debug_assert_eq!(self.sigs.len(), self.states.lock().unwrap().len());
        debug_assert!(
            self.verified_sigs.get().map(|v| v.len() < self.sigs.len())
                .unwrap_or(true));
    }

    /// Creates a vector of lazily verified signatures.
    ///
    /// The provided `primary_key` is used to verify the signatures.
    /// It should be shared across the certificate.
    pub fn new(primary_key: Arc<Key<key::PublicParts, key::PrimaryRole>>)
               -> Self
    {
        LazySignatures {
            primary_key,
            sigs: Default::default(),
            states: Default::default(),
            verified_sigs: Default::default(),
        }
    }

    /// Like [`Vec::is_empty`].
    pub fn is_empty(&self) -> bool {
        self.assert_invariant();
        self.sigs.is_empty()
    }

    /// Like [`std::mem::take`].
    pub fn take(&mut self) -> Vec<Signature> {
        self.assert_invariant();
        self.states.lock().unwrap().clear();
        let r = mem::replace(&mut self.sigs, Vec::new());
        self.verified_sigs.take();
        self.assert_invariant();
        r
    }

    /// Like [`Vec::push`].
    pub fn push(&mut self, s: Signature) {
        self.assert_invariant();
        self.sigs.push(s);
        self.states.lock().unwrap().push(SigState::Unverified);
        self.verified_sigs.take();
        self.assert_invariant();
    }

    /// Like [`Vec::append`].
    pub fn append(&mut self, other: &mut LazySignatures) {
        // XXX check context
        self.assert_invariant();
        other.assert_invariant();
        self.sigs.append(&mut other.sigs);
        self.states.lock().unwrap().append(&mut other.states.lock().unwrap());
        self.verified_sigs.take();
        self.assert_invariant();
    }

    /// Like [`Vec::sort_by`].
    pub fn sort_by<F>(&mut self, compare: F)
    where
        F: FnMut(&Signature, &Signature) -> Ordering,
    {
        self.assert_invariant();
        self.sigs.sort_by(compare);
        self.states.lock().unwrap().iter_mut().for_each(|p| *p = SigState::Unverified);
        self.verified_sigs.take();
        self.assert_invariant();
    }

    /// Like [`Vec::dedup_by`].
    pub fn dedup_by<F>(&mut self, same_bucket: F)
    where
        F: FnMut(&mut Signature, &mut Signature) -> bool,
    {
        self.assert_invariant();
        self.sigs.dedup_by(same_bucket);
        {
            let mut states = self.states.lock().unwrap();
            states.truncate(self.sigs.len());
            states.iter_mut().for_each(|p| *p = SigState::Unverified);
        }
        self.verified_sigs.take();
        self.assert_invariant();
    }

    /// Like [`Vec::iter_mut`], but gives out **potentially
    /// unverified** signatures.
    pub fn iter_mut_unverified(&mut self) -> impl Iterator<Item = &mut Signature> {
        self.assert_invariant();
        self.sigs.iter_mut()
    }

    /// Like [`Vec::into_iter`], but gives out **potentially
    /// unverified** signatures.
    pub fn into_unverified(self) -> impl Iterator<Item = Signature> {
        self.assert_invariant();
        self.sigs.into_iter()
    }

    /// Like [`Vec::iter`], but only gives out verified signatures.
    ///
    /// If this is a subkey binding, `subkey` must be the bundle's
    /// subkey.
    pub fn iter_verified<'a>(&'a self,
                             subkey: Option<&'a Key<key::PublicParts, key::SubordinateRole>>)
                             -> impl Iterator<Item = &'a Signature> + 'a
    {
        self.iter_intern(subkey)
            .filter_map(|(state, s)| match state {
                SigState::Good => Some(s),