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
use std::slice;
use std::fmt;
use std::time::SystemTime;

use crate::{
    types::RevocationStatus,
    cert::prelude::*,
    packet::{
        Unknown,
        UserAttribute,
        UserID,
    },
    policy::Policy,
};

/// An iterator over components.
///
/// Using the [`ComponentAmalgamationIter::with_policy`], it is
/// possible to change the iterator to only return
/// [`ComponentAmalgamation`]s for valid components.  In this case,
/// `ComponentAmalgamationIter::with_policy` transforms the
/// `ComponentAmalgamationIter` into a
/// [`ValidComponentAmalgamationIter`], which returns
/// [`ValidComponentAmalgamation`]s.  `ValidComponentAmalgamation`
/// offers additional filters.
///
/// `ComponentAmalgamationIter` follows the builder pattern.  There is
/// no need to explicitly finalize it: it already implements the
/// `Iterator` trait.
///
/// A `ComponentAmalgamationIter` is returned by [`Cert::userids`],
/// [`Cert::user_attributes`], and [`Cert::unknowns`].
/// ([`Cert::keys`] returns a [`KeyAmalgamationIter`].)
///
/// # Examples
///
/// Iterate over the User IDs in a certificate:
///
/// ```
/// # use sequoia_openpgp as openpgp;
/// use openpgp::cert::prelude::*;
///
/// #
/// # fn main() -> openpgp::Result<()> {
/// #     let (cert, _) =
/// #         CertBuilder::general_purpose(None, Some("alice@example.org"))
/// #         .generate()?;
/// #     let fpr = cert.fingerprint();
/// // Iterate over all User IDs.
/// for ua in cert.userids() {
///     // ua is a `ComponentAmalgamation`, specifically, a `UserIDAmalgamation`.
/// }
/// #     Ok(())
/// # }
/// ```
///
/// Only return valid User IDs.
///
/// ```
/// # use sequoia_openpgp as openpgp;
/// use openpgp::cert::prelude::*;
/// use openpgp::policy::StandardPolicy;
/// #
/// # fn main() -> openpgp::Result<()> {
/// let p = &StandardPolicy::new();
///
/// #     let (cert, _) =
/// #         CertBuilder::general_purpose(None, Some("alice@example.org"))
/// #         .generate()?;
/// #     let fpr = cert.fingerprint();
/// // Iterate over all valid User IDs.
/// for ua in cert.userids().with_policy(p, None) {
///     // ua is a `ValidComponentAmalgamation`, specifically, a
///     // `ValidUserIDAmalgamation`.
/// }
/// #     Ok(())
/// # }
/// ```
///
/// [`ComponentAmalgamationIter::with_policy`]: #method.with_policy
/// [`ComponentAmalgamation`]: struct.ComponentAmalgamation.html
/// [`ValidComponentAmalgamationIter`]: struct.ValidComponentAmalgamationIter.html
/// [`ValidComponentAmalgamation`]: struct.ValidComponentAmalgamation.html
/// [`Cert::userids`]: ../struct.Cert.html#method.userids
/// [`Cert::user_attributes`]: ../struct.Cert.html#method.user_attributes
/// [`Cert::unknowns`]: ../struct.Cert.html#method.unknown
/// [`Cert::keys`]: ../struct.Cert.html#method.keys
/// [`KeyAmalgamationIter`]: struct.KeyAmalgamationIter.html
pub struct ComponentAmalgamationIter<'a, C> {
    cert: &'a Cert,
    iter: slice::Iter<'a, ComponentBundle<C>>,
}
assert_send_and_sync!(ComponentAmalgamationIter<'_, C> where C);

/// An iterator over `UserIDAmalgamtion`s.
///
/// A specialized version of [`ComponentAmalgamationIter`].
///
/// [`ComponentAmalgamationIter`]: struct.ComponentAmalgamationIter.html
pub type UserIDAmalgamationIter<'a>
    = ComponentAmalgamationIter<'a, UserID>;

/// An iterator over `UserAttributeAmalgamtion`s.
///
/// A specialized version of [`ComponentAmalgamationIter`].
///
/// [`ComponentAmalgamationIter`]: struct.ComponentAmalgamationIter.html
pub type UserAttributeAmalgamationIter<'a>
    = ComponentAmalgamationIter<'a, UserAttribute>;

/// An iterator over `UnknownComponentAmalgamtion`s.
///
/// A specialized version of [`ComponentAmalgamationIter`].
///
/// [`ComponentAmalgamationIter`]: struct.ComponentAmalgamationIter.html
pub type UnknownComponentAmalgamationIter<'a>
    = ComponentAmalgamationIter<'a, Unknown>;


impl<'a, C> fmt::Debug for ComponentAmalgamationIter<'a, C> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("ComponentAmalgamationIter")
            .finish()
    }
}

impl<'a, C> Iterator for ComponentAmalgamationIter<'a, C>
{
    type Item = ComponentAmalgamation<'a, C>;

    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next().map(|c| ComponentAmalgamation::new(self.cert, c))
    }
}

impl<'a, C> ComponentAmalgamationIter<'a, C> {
    /// Returns a new `ComponentAmalgamationIter` instance.
    pub(crate) fn new(cert: &'a Cert,
                      iter: std::slice::Iter<'a, ComponentBundle<C>>) -> Self
        where Self: 'a
    {
        ComponentAmalgamationIter {
            cert, iter,
        }
    }

    /// Changes the iterator to only return components that are valid
    /// according to the policy at the specified time.
    ///
    /// If `time` is None, then the current time is used.
    ///
    /// Refer to the [`ValidateAmalgamation`] trait for a definition
    /// of a valid component.
    ///
    /// # Examples
    ///
    /// ```
    /// # use sequoia_openpgp as openpgp;
    /// use openpgp::cert::prelude::*;
    /// use openpgp::policy::StandardPolicy;
    /// #
    /// # fn main() -> openpgp::Result<()> {
    /// let p = &StandardPolicy::new();
    ///
    /// #     let (cert, _) =
    /// #         CertBuilder::general_purpose(None, Some("alice@example.org"))
    /// #         .generate()?;
    /// #     let fpr = cert.fingerprint();
    /// // Iterate over all valid User Attributes.
    /// for ua in cert.user_attributes().with_policy(p, None) {
    ///     // ua is a `ValidComponentAmalgamation`, specifically, a
    ///     // `ValidUserAttributeAmalgamation`.
    /// }
    /// #     Ok(())
    /// # }
    /// ```
    ///
    /// [`ValidateAmalgamation`]: trait.ValidateAmalgamation.html
    pub fn with_policy<T>(self, policy: &'a dyn Policy, time: T)
        -> ValidComponentAmalgamationIter<'a, C>
        where T: Into<Option<SystemTime>>
    {
        ValidComponentAmalgamationIter {
            cert: self.cert,
            iter: self.iter,
            time: time.into().unwrap_or_else(SystemTime::now),
            policy,
            revoked: None,
        }
    }
}

/// An iterator over valid components.
///
/// A `ValidComponentAmalgamationIter` is a
/// [`ComponentAmalgamationIter`] with a policy and a reference time.
///
/// This allows it to filter the returned components based on
/// information available in the components' binding signatures.  For
/// instance, [`ValidComponentAmalgamationIter::revoked`] filters the
/// returned components by whether or not they are revoked.
///
/// `ValidComponentAmalgamationIter` follows the builder pattern.
/// There is no need to explicitly finalize it: it already implements
/// the `Iterator` trait.
///
/// A `ValidComponentAmalgamationIter` is returned by
/// [`ComponentAmalgamationIter::with_policy`].
///
/// # Examples
///
/// ```
/// # use sequoia_openpgp as openpgp;
/// use openpgp::cert::prelude::*;
/// use openpgp::policy::StandardPolicy;
/// #
/// # fn main() -> openpgp::Result<()> {
/// let p = &StandardPolicy::new();
///
/// #     let (cert, _) =
/// #         CertBuilder::general_purpose(None, Some("alice@example.org"))
/// #         .generate()?;
/// #     let fpr = cert.fingerprint();
/// // Iterate over all valid User Attributes.
/// for ua in cert.userids().with_policy(p, None) {
///     // ua is a `ValidComponentAmalgamation`, specifically, a
///     // `ValidUserIDAmalgamation`.
/// }
/// #     Ok(())
/// # }
/// ```
///
/// [`ComponentAmalgamationIter`]: struct.ComponentAmalgamationIter.html
/// [`ValidComponentAmalgamationIter::revoked`]: #method.revoked
/// [`ComponentAmalgamationIter::with_policy`]: struct.ComponentAmalgamationIter.html#method.with_policy
pub struct ValidComponentAmalgamationIter<'a, C> {
    // This is an option to make it easier to create an empty ValidComponentAmalgamationIter.
    cert: &'a Cert,
    iter: slice::Iter<'a, ComponentBundle<C>>,

    policy: &'a dyn Policy,
    // The time.
    time: SystemTime,

    // If not None, filters by whether the component is revoked or not
    // at time `t`.
    revoked: Option<bool>,
}
assert_send_and_sync!(ValidComponentAmalgamationIter<'_, C> where C);

/// An iterator over `ValidUserIDAmalgamtion`s.
///
/// This is just a specialized version of `ValidComponentAmalgamationIter`.
pub type ValidUserIDAmalgamationIter<'a>
    = ValidComponentAmalgamationIter<'a, UserID>;

/// An iterator over `ValidUserAttributeAmalgamtion`s.
///
/// This is just a specialized version of `ValidComponentAmalgamationIter`.
pub type ValidUserAttributeAmalgamationIter<'a>
    = ValidComponentAmalgamationIter<'a, UserAttribute>;


impl<'a, C> fmt::Debug for ValidComponentAmalgamationIter<'a, C> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("ValidComponentAmalgamationIter")
            .field("time", &self.time)
            .field("revoked", &self.revoked)
            .finish()
    }
}

impl<'a, C> Iterator for ValidComponentAmalgamationIter<'a, C>
    where C: std::fmt::Debug
{
    type Item = ValidComponentAmalgamation<'a, C>;

    fn next(&mut self) -> Option<Self::Item> {
        tracer!(false, "ValidComponentAmalgamationIter::next", 0);
        t!("ValidComponentAmalgamationIter: {:?}", self);

        loop {
            let ca = ComponentAmalgamation::new(self.cert, self.iter.next()?);
            t!("Considering component: {:?}", ca.component());

            let vca = match ca.with_policy(self.policy, self.time) {
                Ok(vca) => vca,
                Err(e) => {
                    t!("Rejected: {}", e);
                    continue;
                },
            };

            if let Some(want_revoked) = self.revoked {
                if let RevocationStatus::Revoked(_) = vca.revocation_status() {
                    // The component is definitely revoked.
                    if ! want_revoked {
                        t!("Component revoked... skipping.");
                        continue;
                    }
                } else {
                    // The component is probably not revoked.
                    if want_revoked {
                        t!("Component not revoked... skipping.");
                        continue;
                    }
                }
            }

            return Some(vca);
        }
    }
}

impl<'a, C> ExactSizeIterator for ComponentAmalgamationIter<'a, C>
{
    fn len(&self) -> usize {
        self.iter.len()
    }
}

impl<'a, C> ValidComponentAmalgamationIter<'a, C> {
    /// Filters by whether a component is definitely revoked.
    ///
    /// A value of None disables this filter.
    ///
    /// If you call this function multiple times on the same iterator,
    /// only the last value is used.
    ///
    /// This filter only checks if the component is not revoked; it
    /// does not check whether the certificate not revoked.
    ///
    /// This filter checks whether a component's revocation status is
    /// [`RevocationStatus::Revoked`] or not.  The latter (i.e.,
    /// `revoked(false)`) is equivalent to:
    ///
    /// ```rust
    /// use sequoia_openpgp as openpgp;
    /// # use openpgp::Result;
    /// use openpgp::cert::prelude::*;
    /// use openpgp::types::RevocationStatus;
    /// use sequoia_openpgp::policy::StandardPolicy;
    ///
    /// # fn main() -> Result<()> {
    /// let p = &StandardPolicy::new();
    ///
    /// # let (cert, _) =
    /// #     CertBuilder::general_purpose(None, Some("alice@example.org"))
    /// #     .generate()?;
    /// # let timestamp = None;
    /// let non_revoked_uas = cert
    ///     .user_attributes()
    ///     .with_policy(p, timestamp)
    ///     .filter(|ca| {
    ///         match ca.revocation_status() {
    ///             RevocationStatus::Revoked(_) =>
    ///                 // It's definitely revoked, skip it.
    ///                 false,
    ///             RevocationStatus::CouldBe(_) =>
    ///                 // There is a designated revoker that we
    ///                 // should check, but don't (or can't).  To
    ///                 // avoid a denial of service arising from fake
    ///                 // revocations, we assume that the component has not
    ///                 // been revoked and return it.
    ///                 true,
    ///             RevocationStatus::NotAsFarAsWeKnow =>
    ///                 // We have no evidence to suggest that the component
    ///                 // is revoked.
    ///                 true,
    ///         }
    ///     })
    ///     .collect::<Vec<_>>();
    /// #     Ok(())
    /// # }
    /// ```
    ///
    /// As the example shows, this filter is significantly less
    /// flexible than using `ValidComponentAmalgamation::revocation_status`.
    /// However, this filter implements a typical policy, and does not
    /// preclude using `filter` to realize alternative policies.
    ///
    /// [`RevocationStatus::Revoked`]: ../../types/enum.RevocationStatus.html#variant.Revoked
    pub fn revoked<T>(mut self, revoked: T) -> Self
        where T: Into<Option<bool>>
    {
        self.revoked = revoked.into();
        self
    }
}