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

use sequoia_openpgp as openpgp;

use openpgp::Result;
use openpgp::cert::prelude::*;
use openpgp::cert::raw::RawCert;
use openpgp::policy::Policy;

use crate::CertSynopsis;
use crate::Certification;
use crate::store::RawCerts;
use crate::store::CertSlice;
use crate::store::Store;
use crate::store::SynopsisSlice;

pub(crate) mod filter;
mod root;
pub use root::Root;
mod roots;
pub use roots::Roots;
mod query;
pub use query::Query;
pub use query::QueryBuilder;
mod path;
pub use path::PathError;
pub use path::CertLints;
pub use path::CertificationLints;
pub use path::PathLints;
mod gossip;

use super::TRACE;

/// A certification network.
pub struct Network<S>
    where S: Store
{
    store: S,
}

impl<S> fmt::Debug for Network<S>
    where S: Store
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Network {{\n")?;
        write!(f, "  Reference time: {:?}\n", self.reference_time())?;
        write!(f, "  Nodes:\n")?;

        let mut certs: Vec<_> = self.certs().map(|cert| {
            (
                cert.userids()
                    .map(|userid| {
                        String::from_utf8_lossy(userid.value())
                            .into_owned()
                    })
                    .collect::<Vec<String>>()
                    .join(", "),
                cert.fingerprint()
            )
        }).collect();
        certs.sort();

        for (userid, fpr) in certs {
            write!(f, "    {}: {}\n", fpr, userid)?;
        }

        write!(f, "  Edges:\n")?;

        let mut certifications = self.list().filter_map(|fpr| {
            if let Ok(cs) = self.certifications_of(&fpr, 0.into()) {
                if cs.is_empty() {
                    None
                } else {
                    Some(cs)
                }
            } else {
                None
            }
        }).flatten().collect::<Vec<_>>();
        certifications.sort_by_key(|cs| {
            (cs.issuer().primary_userid().map(|u| u.userid().clone()),
             cs.issuer().fingerprint(),
             cs.target().fingerprint())
        });

        let mut last_issuer_fpr = None;
        for cs in certifications.into_iter() {
            let issuer = &cs.issuer();
            let issuer_fpr = issuer.fingerprint();
            if Some(&issuer_fpr) != last_issuer_fpr.as_ref() {
                write!(f, "    {} certifies:\n", issuer)?;
                last_issuer_fpr = Some(issuer_fpr);
            }

            for (userid, c) in cs.certifications() {
                for c in c.iter() {
                    write!(f, "      {}, {}: {}, {}, {}\n",
                           cs.target().fingerprint(),
                           userid.as_ref().map(|userid| {
                               String::from_utf8_lossy(userid.value()).into_owned()
                           }).unwrap_or_else(|| "<No User ID>".into()),
                           c.depth(), c.amount(),
                           if c.regular_expressions().matches_everything() { "*".into() }
                           else { format!("{:?}", c.regular_expressions()) })?;
                }
            }
        }

        write!(f, "}}\n")?;

        Ok(())
    }
}

impl<S> Deref for Network<S>
    where S: Store
{
    type Target = S;

    fn deref(&self) -> &Self::Target {
        &self.store
    }
}

impl<S> Network<S>
    where S: Store
{
    /// Returns a Network.
    pub fn new(store: S)
        -> Result<Self>
    {
        tracer!(TRACE, "Network::new");

        Ok(Network {
            store: store,
        })
    }
}

impl<'a> Network<CertSlice<'a>> {
    /// Builds a web of trust network from a set of certificates.
    ///
    /// If a certificate is invalid according to the policy, the
    /// certificate is silently ignored.
    pub fn from_certs<T, P>(certs: &'a [Cert], policy: &'a P, t: T)
        -> Result<Self>
    where T: Into<Option<SystemTime>>,
          P: Policy,
    {
        tracer!(TRACE, "Network::from_certs");

        let t = t.into().unwrap_or_else(|| SystemTime::now());
        Network::new(CertSlice::new(certs, policy, t)?)
    }
}

impl<'a> Network<SynopsisSlice<'a>> {
    /// Builds a web of trust network from a set of certificates.
    ///
    /// If a certificate is invalid according to the policy, the
    /// certificate is silently ignored.
    pub fn from_synopses(certs: &'a [CertSynopsis],
                         certifications: &'a [Certification],
                         t: SystemTime)
        -> Result<Self>
    {
        Network::new(SynopsisSlice::new(certs, certifications, t)?)
    }
}

impl<'a> Network<RawCerts<'a>>
{
    /// Builds a web of trust network from a keyring.
    ///
    /// If a certificate is invalid according to the policy, the
    /// certificate is silently ignored.
    pub fn from_bytes<T>(certs: &'a [u8], policy: &'a dyn Policy, t: T)
        -> Result<Self>
    where T: Into<Option<SystemTime>>,
    {
        tracer!(TRACE, "Network::from_bytes");

        let t = t.into().unwrap_or_else(|| SystemTime::now());
        Network::new(RawCerts::new(certs, policy, t)?)
    }

    /// Builds a web of trust network from a set of raw certificates.
    ///
    /// If a certificate is invalid according to the policy, the
    /// certificate is silently ignored.
    pub fn from_raw_certs<T>(certs: &'a [RawCert<'a>],
                             policy: &'a dyn Policy, t: T)
        -> Result<Self>
    where T: Into<Option<SystemTime>>,
    {
        tracer!(TRACE, "Network::from_bytes");

        let t = t.into().unwrap_or_else(|| SystemTime::now());
        Network::new(RawCerts::from_raw_certs(certs, policy, t)?)
    }
}

#[cfg(test)]
mod test {
    use super::*;

    use openpgp::Fingerprint;
    use openpgp::packet::UserID;
    use openpgp::parse::Parse;
    use openpgp::policy::StandardPolicy;

    #[allow(unused)]
    #[test]
    fn third_party_certifications_of() -> Result<()> {
        let p = &StandardPolicy::new();

        let alice_fpr: Fingerprint =
            "2A2A4A23A7EEC119BC0B46642B3825DC02A05FEA"
           .parse().expect("valid fingerprint");
        let alice_uid
            = UserID::from("<alice@example.org>");

        let bob_fpr: Fingerprint =
            "03182611B91B1E7E20B848E83DFC151ABFAD85D5"
           .parse().expect("valid fingerprint");
        let bob_uid
            = UserID::from("<bob@other.org>");
        // Certified by: 2A2A4A23A7EEC119BC0B46642B3825DC02A05FEA
        let bob_some_org_uid
            = UserID::from("<bob@some.org>");
        // Certified by: 2A2A4A23A7EEC119BC0B46642B3825DC02A05FEA

        let carol_fpr: Fingerprint =
            "9CA36907B46FE7B6B9EE9601E78064C12B6D7902"
           .parse().expect("valid fingerprint");
        let carol_uid
            = UserID::from("<carol@example.org>");
        // Certified by: 03182611B91B1E7E20B848E83DFC151ABFAD85D5

        let dave_fpr: Fingerprint =
            "C1BC6794A6C6281B968A6A41ACE2055D610CEA03"
           .parse().expect("valid fingerprint");
        let dave_uid
            = UserID::from("<dave@other.org>");
        // Certified by: 9CA36907B46FE7B6B9EE9601E78064C12B6D7902


        let certs: Vec<Cert> = CertParser::from_bytes(
            &crate::testdata::data("multiple-userids-1.pgp"))?
            .map(|c| c.expect("Valid certificate"))
            .collect();
        let n = Network::from_certs(&certs[..], p, None)?;

        eprintln!("{:?}", n);

        // No one certified alice.
        assert!(
            n.third_party_certifications_of(&alice_fpr.clone())
                .is_empty());

        // Alice (and no one else) certified each of Bob's User IDs.
        let mut c = n.third_party_certifications_of(&bob_fpr);
        assert_eq!(c.len(), 2);
        c.sort_by_key(|c| (c.issuer().fingerprint(),
                           c.userid().map(Clone::clone)));
        assert_eq!(&c[0].issuer().fingerprint(), &alice_fpr);
        assert_eq!(c[0].userid(), Some(&bob_uid));
        assert_eq!(&c[1].issuer().fingerprint(), &alice_fpr);
        assert_eq!(c[1].userid(), Some(&bob_some_org_uid));

        Ok(())
    }

    #[allow(unused)]
    #[test]
    fn certified_userids_of() -> Result<()> {
        let p = &StandardPolicy::new();

        let alice_fpr: Fingerprint =
            "2A2A4A23A7EEC119BC0B46642B3825DC02A05FEA"
           .parse().expect("valid fingerprint");
        let alice_uid
            = UserID::from("<alice@example.org>");

        let bob_fpr: Fingerprint =
            "03182611B91B1E7E20B848E83DFC151ABFAD85D5"
           .parse().expect("valid fingerprint");
        let bob_uid
            = UserID::from("<bob@other.org>");
        // Certified by: 2A2A4A23A7EEC119BC0B46642B3825DC02A05FEA
        let bob_some_org_uid
            = UserID::from("<bob@some.org>");
        // Certified by: 2A2A4A23A7EEC119BC0B46642B3825DC02A05FEA

        let carol_fpr: Fingerprint =
            "9CA36907B46FE7B6B9EE9601E78064C12B6D7902"
           .parse().expect("valid fingerprint");
        let carol_uid
            = UserID::from("<carol@example.org>");
        // Certified by: 03182611B91B1E7E20B848E83DFC151ABFAD85D5

        let dave_fpr: Fingerprint =
            "C1BC6794A6C6281B968A6A41ACE2055D610CEA03"
           .parse().expect("valid fingerprint");
        let dave_uid
            = UserID::from("<dave@other.org>");
        // Certified by: 9CA36907B46FE7B6B9EE9601E78064C12B6D7902


        let certs: Vec<Cert> = CertParser::from_bytes(
            &crate::testdata::data("multiple-userids-1.pgp"))?
            .map(|c| c.expect("Valid certificate"))
            .collect();
        let n = Network::from_certs(&certs[..], p, None)?;

        eprintln!("{:?}", n);

        // There is the self signature.
        let mut c = n.certified_userids_of(&alice_fpr);
        assert_eq!(c.len(), 1);

        // Alice (and no one else) certified each of Bob's User IDs
        // for the two self signed User ID.
        let mut c = n.certified_userids_of(&bob_fpr);
        assert_eq!(c.len(), 2);
        c.sort_unstable();
        assert_eq!(&c[0], &bob_uid);
        assert_eq!(&c[1], &bob_some_org_uid);

        Ok(())
    }

    #[allow(unused)]
    #[test]
    fn certified_userids() -> Result<()> {
        let p = &StandardPolicy::new();

        let alice_fpr: Fingerprint =
            "2A2A4A23A7EEC119BC0B46642B3825DC02A05FEA"
           .parse().expect("valid fingerprint");
        let alice_uid
            = UserID::from("<alice@example.org>");

        let bob_fpr: Fingerprint =
            "03182611B91B1E7E20B848E83DFC151ABFAD85D5"
           .parse().expect("valid fingerprint");
        let bob_uid
            = UserID::from("<bob@other.org>");
        // Certified by: 2A2A4A23A7EEC119BC0B46642B3825DC02A05FEA
        let bob_some_org_uid
            = UserID::from("<bob@some.org>");
        // Certified by: 2A2A4A23A7EEC119BC0B46642B3825DC02A05FEA

        let carol_fpr: Fingerprint =
            "9CA36907B46FE7B6B9EE9601E78064C12B6D7902"
           .parse().expect("valid fingerprint");
        let carol_uid
            = UserID::from("<carol@example.org>");
        // Certified by: 03182611B91B1E7E20B848E83DFC151ABFAD85D5

        let dave_fpr: Fingerprint =
            "C1BC6794A6C6281B968A6A41ACE2055D610CEA03"
           .parse().expect("valid fingerprint");
        let dave_uid
            = UserID::from("<dave@other.org>");
        // Certified by: 9CA36907B46FE7B6B9EE9601E78064C12B6D7902


        let certs: Vec<Cert> = CertParser::from_bytes(
            &crate::testdata::data("multiple-userids-1.pgp"))?
            .map(|c| c.expect("Valid certificate"))
            .collect();
        let n = Network::from_certs(&certs[..], p, None)?;

        eprintln!("{:?}", n);

        // Alice is the root, but self signatures count, so there are
        // five certified User IDs in this network.
        let mut got = n.certified_userids();
        assert_eq!(got.len(), 5);

        got.sort_unstable();

        let mut expected = [
            (alice_fpr.clone(), alice_uid.clone()),
            (bob_fpr.clone(), bob_uid.clone()),
            (bob_fpr.clone(), bob_some_org_uid.clone()),
            (carol_fpr.clone(), carol_uid.clone()),
            (dave_fpr.clone(), dave_uid.clone()),
        ];
        expected.sort_unstable();

        assert_eq!(got, expected);

        Ok(())
    }
}