sequoia-net 0.32.0

Network services for OpenPGP
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
//! OpenPGP Web Key Directory client.
//!
//! A Web Key Directory is a Web service that can be queried with email
//! addresses to obtain the associated OpenPGP keys.
//!
//! It is specified in [draft-koch].
//!
//! See the [get example].
//!
//! [draft-koch]: https://datatracker.ietf.org/doc/html/draft-koch-openpgp-webkey-service
//! [get example]: get#examples
//!


// XXX: We might want to merge the 2 structs in the future and move the
// functions to methods.

use std::collections::HashMap;
use std::fmt;
use std::fs;
use std::path::{Path, PathBuf};
use std::fs::File;
use std::fs::OpenOptions;

use anyhow::Context;

use openpgp::policy::StandardPolicy;
use sequoia_openpgp::{
    self as openpgp,
    Fingerprint,
    Cert,
    parse::Parse,
    serialize::Serialize,
    types::HashAlgorithm,
    cert::prelude::*,
};

use percent_encoding::percent_encode;
use crate::KEYSERVER_GET_ENCODE_SET;

use crate::email::EmailAddress;
use crate::Error;
use crate::HttpClient;
use crate::HttpClientOptions;
use crate::Result;

/// Returns an `OpenOptions` that sets `O_NOFOLLOW` (or the near
/// equivalent on Windows).
fn open_options_nofollow() -> OpenOptions {
    let mut options = std::fs::OpenOptions::new();

    platform! {
        unix => {
            use std::os::unix::fs::OpenOptionsExt;

            options.custom_flags(libc::O_NOFOLLOW);
        },
        windows => {
            use std::os::windows::fs::OpenOptionsExt;
            use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OPEN_REPARSE_POINT;

            options.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT);
        }
    }

    options
}

/// Returns an error if we opened a symbolic link.
///
/// This happens on Window if we open a symbolink link using
/// `FILE_OPEN_REPARSE_POINT`: Windows doesn't follow the link, but
/// returns a file handle to the symbolic link.  We want to reject it,
/// like `O_FOLLOW` does on POSIX systems.
fn reject_symlink(file: File, path: PathBuf) -> Result<File> {
    // On Unix, if the target is a symlink, O_NOFOLLOW fails
    // immediately.  On Windows we still need to check if the
    // opened file is a symlink.
    platform! {
        unix => {
            // Suppress unused variable warning.
            let _ = path;
        },
        windows => {
            // Make sure it is not a symlink.
            if file.metadata()?.is_symlink() {
                return Err(Error::SymbolicLink(path).into());
            }
        }
    }

    Ok(file)
}

fn is_symlink_error(err: &anyhow::Error) -> bool {
    if let Some(Error::SymbolicLink(_path)) = err.downcast_ref() {
        return true;
    }

    platform! {
        unix => {
            if let Some(err) = err.downcast_ref::<std::io::Error>() {
                if err.raw_os_error() == Some(libc::ELOOP) {
                    return true;
                }
            }
        },
        windows => {
        }
    }

    false
}

/// WKD variants.
///
/// There are two variants of the URL scheme.  `Advanced` should be
/// preferred.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Variant {
    /// Advanced variant.
    ///
    /// This method uses a separate subdomain and is more flexible.
    /// This method should be preferred.
    Advanced,
    /// Direct variant.
    ///
    /// This method is deprecated.
    Direct,
}

impl Default for Variant {
    fn default() -> Self {
        Variant::Advanced
    }
}

/// Stores the parts needed to create a Web Key Directory URL.
///
/// NOTE: This is a different `Url` than [`url::Url`] (`url` crate) that is
/// actually returned with the method [to_url](Url::to_url())
#[derive(Debug, Clone)]
pub struct Url {
    domain: String,
    local_encoded: String,
    local_part: String,
}

impl fmt::Display for Url {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.build(None))
    }
}

impl Url {
    /// Returns a [`Url`] from an email address string.
    pub fn from<S: AsRef<str>>(email_address: S) -> Result<Self> {
        let email = EmailAddress::from(email_address)?;
        let local_encoded = encode_local_part(&email.local_part.to_ascii_lowercase());
        let url = Url {
            domain : email.domain,
            local_encoded,
            local_part : email.local_part,
        };
        Ok(url)
    }

    /// Returns an URL string from a [`Url`].
    pub fn build<V>(&self, variant: V) -> String
        where V: Into<Option<Variant>>
    {
        let variant = variant.into().unwrap_or_default();
        if variant == Variant::Direct {
            format!("https://{}/.well-known/openpgpkey/hu/{}?l={}",
                    self.domain, self.local_encoded,
                    percent_encode(self.local_part.as_bytes(),
                                   &KEYSERVER_GET_ENCODE_SET)
            )
        } else {
            format!("https://openpgpkey.{}/.well-known/openpgpkey/{}/hu/{}\
                    ?l={}", self.domain, self.domain, self.local_encoded,
                    percent_encode(self.local_part.as_bytes(),
                                   &KEYSERVER_GET_ENCODE_SET)
            )
        }
    }

    /// Returns an [`url::Url`].
    pub fn to_url<V>(&self, variant: V) -> Result<url::Url>
            where V: Into<Option<Variant>> {
        Ok(url::Url::parse(self.build(variant).as_str())?)
    }

    /// Returns a [`PathBuf`].
    pub fn to_file_path<V>(&self, variant: V) -> Result<PathBuf>
        where V: Into<Option<Variant>>
    {
        // Create the directories string.
        let variant = variant.into().unwrap_or_default();
        let url = self.to_url(variant)?;
        Ok(PathBuf::from(url.path()).strip_prefix("/")?.into())
    }
}


/// Returns a 32 characters string from the local part of an email address
///
/// From [draft-koch]:
///     The so mapped local-part is hashed using the SHA-1 algorithm. The
///     resulting 160 bit digest is encoded using the Z-Base-32 method as
///     described in RFC6189, section 5.1.6. The resulting string has a
///     fixed length of 32 octets.
fn encode_local_part<S: AsRef<str>>(local_part: S) -> String {
    let local_part = local_part.as_ref();

    let mut digest = vec![0; 20];
    let mut ctx = HashAlgorithm::SHA1.context().expect("must be implemented")
        .for_digest();
    ctx.update(local_part.as_bytes());
    let _ = ctx.digest(&mut digest);

    // After z-base-32 encoding 20 bytes, it will be 32 bytes long.
    zbase32::encode(&digest[..])
}


/// Parse an HTTP response body that may contain Certs and filter them based on
/// whether they contain a userid with the given email address.
///
/// From [draft-koch]:
///
/// ```text
/// The key needs to carry a User ID packet ([RFC4880]) with that mail
/// address.
/// ```
fn parse_body<S: AsRef<str>>(body: &[u8], email_address: S)
        -> Result<Vec<Result<Cert>>> {
    let email_address = email_address.as_ref();
    // This will fail on the first packet that can not be parsed.
    let packets = CertParser::from_bytes(&body)?;
    // Collect only the correct packets.
    let certs: Vec<Result<Cert>> = packets.collect();
    if certs.is_empty() {
        return Err(crate::Error::NotFound.into());
    }

    // Collect only the Certs that contain the email in any of their userids
    let valid_certs: Vec<Result<Cert>> = certs.into_iter()
        // XXX: This filter could become a Cert method, but it adds other API
        // method to maintain
        .filter(|cert| match cert {
            Ok(cert) => cert.userids()
                .any(|uidb|
                     if let Ok(Some(a)) = uidb.userid().email() {
                         a == email_address
                     } else { false }),
            Err(_) => true,
        }).collect();
    if valid_certs.is_empty() {
        Err(crate::Error::EmailNotInUserids(email_address.into()).into())
    } else {
        Ok(valid_certs)
    }
}

/// Retrieves the Certs that contain userids with a given email address
/// from a Web Key Directory URL.
///
/// From [draft-koch]:
///
/// ```text
/// There are two variants on how to form the request URI: The advanced
/// and the direct method. Implementations MUST first try the advanced
/// method. Only if the required sub-domain does not exist, they SHOULD
/// fall back to the direct method.
///
/// [...]
///
/// The HTTP GET method MUST return the binary representation of the
/// OpenPGP key for the given mail address.
///
/// [...]
///
/// Note that the key may be revoked or expired - it is up to the
/// client to handle such conditions. To ease distribution of revoked
/// keys, a server may return revoked keys in addition to a new key.
/// The keys are returned by a single request as concatenated key
/// blocks.
/// ```
///
/// [draft-koch]: https://datatracker.ietf.org/doc/html/draft-koch-openpgp-webkey-service/#section-3.1
///
/// # Examples
///
/// ```no_run
/// # use sequoia_net::{Result, wkd};
/// # use sequoia_openpgp::Cert;
/// # #[cfg(any(feature = "reqwest", feature = "isahc"))]
/// # async fn f() -> Result<()> {
/// let email_address = "foo@bar.baz";
/// let certs: Vec<Result<Cert>> = wkd::get(&email_address).await?;
/// # Ok(())
/// # }
/// ```
#[cfg(any(feature = "reqwest", feature = "isahc"))]
pub async fn get<S: AsRef<str>>(email_address: S)
                                -> Result<Vec<Result<Cert>>>
{
    let options = HttpClientOptions::certificate();

    #[cfg(feature = "reqwest")]
    {
        return get_with_client(
            &reqwest::Client::new(), &options, email_address).await;
    }
    #[cfg(feature = "isahc")]
    {
        return get_with_client(
            &isahc::HttpClient::new()?, &options, email_address).await;
    }
}

/// Retrieves the Certs that contain userids with a given email address
/// from a Web Key Directory URL.
///
/// This is like [`get`](crate::wkd::get), but takes an [`HttpClient`].
// XXX: Maybe the direct method should be tried on other errors too.
// https://mailarchive.ietf.org/arch/msg/openpgp/6TxZc2dQFLKXtS0Hzmrk963EteE
pub async fn get_with_client<S: AsRef<str>, Client: HttpClient>(
    c: &Client, options: &HttpClientOptions, email_address: S)
    -> Result<Vec<Result<Cert>>>
{
    let email = email_address.as_ref().to_string();
    // First, prepare URIs and client.
    let wkd_url = Url::from(&email)?;

    let advanced_uri = wkd_url.to_url(Variant::Advanced)?;
    let direct_uri = wkd_url.to_url(Variant::Direct)?;

    // First, try the Advanced Method.
    let body = if let Ok(res) = c.get(options, advanced_uri).await {
        Ok(res)
    } else {
        // Fall back to the Direct Method.
        c.get(&options, direct_uri).await
    }?;

    parse_body(&body, &email)
}

/// Returns all e-mail addresses from certificate's User IDs matching `domain`.
fn get_cert_domains<'a>(domain: &'a str, cert: &ValidCert<'a>) -> impl Iterator<Item = Url> + 'a
{
    cert.userids().filter_map(move |uidb| {
        uidb.userid().email().unwrap_or(None).and_then(|addr| {
            if EmailAddress::from(&addr).ok().map(|e| e.domain == domain)
                .unwrap_or(false)
            {
                Url::from(&addr).ok()
            } else {
                None
            }
        })
    })
}

/// Checks if the certificate contains a User ID for given domain.
///
/// Returns `true` if at least one of `cert`'s UserIDs contains an
/// e-mail address in the domain passed as an argument.
pub fn cert_contains_domain_userid<S>(domain: S, cert: &ValidCert) -> bool
    where S: AsRef<str>
{
    get_cert_domains(domain.as_ref(), cert).next().is_some()
}

/// Inserts a key into a Web Key Directory.
///
/// Creates a WKD hierarchy at `base_path` for `domain`, and inserts
/// the given `cert`.  If `cert` already exists in the WKD, it is
/// updated.  Any existing Certs are left in place.
///
/// # Errors
///
/// If the Cert does not have a well-formed UserID with `domain`,
/// `Error::InvalidArgument` is returned.
pub fn insert<P, S, V>(base_path: P, domain: S, variant: V,
                       cert: &Cert)
                       -> Result<()>
    where P: AsRef<Path>,
          S: AsRef<str>,
          V: Into<Option<Variant>>
{
    let base_path = base_path.as_ref();
    let domain = domain.as_ref();
    let variant = variant.into().unwrap_or_default();
    let policy = &StandardPolicy::new();
    let cert = cert.with_policy(policy, None)?;

    // First, check which UserIDs are in `domain`.
    let addresses = get_cert_domains(domain, &cert).collect::<Vec<_>>();

    // Any?
    if addresses.is_empty() {
        return Err(openpgp::Error::InvalidArgument(
            format!("Key {} does not have a User ID in {}", cert, domain)
        ).into());
    }

    // Finally, create the files.
    let mut well_known = None;
    for address in addresses.into_iter() {
        let path = base_path.join(address.to_file_path(variant)?);
        fs::create_dir_all(path.parent().expect("by construction"))?;
        let mut keyring = KeyRing::default();
        if path.is_file() {
            for t in CertParser::from_file(&path).context(
                format!("Error parsing existing file {:?}", path))?
            {
                keyring.insert(t.context(
                    format!("Malformed Cert in existing {:?}", path))?)?;
            }
        }
        keyring.insert(cert.cert().clone())?;

        // Try a few times to open the file, but don't loop forever.
        let mut retries = 0;
        let result = loop {
            let result = open_options_nofollow()
                .write(true)
                .truncate(true)
                .create(true)
                .open(&path);

            // Replace symlinks.  Propagate other error.
            let result = match result {
                Ok(file) => reject_symlink(file, path.clone()),
                Err(err) => Err(err.into()),
            };

            if let Err(err) = result.as_ref() {
                if is_symlink_error(err) {
                    // It's a symlink.  Remove the symlink and loop.
                    if let Err(err) = std::fs::remove_file(&path) {
                        // On Windows how we remove a symlink depends
                        // on the target!
                        if std::fs::remove_dir(&path).is_err() {
                            // Prefer the error from remove_file.
                            return Err(err.into());
                        }
                    }

                    retries += 1;
                    if retries > 5 {
                        // We retried enough.
                        break result;
                    } else {
                        continue;
                    }
                }
            }

            break result;
        };
        let mut file = result?;
        keyring.export(&mut file)?;

        // Keep track of the WELL_KNOWN base path.
        well_known = Some(path
                          .parent().expect("by construction")
                          .parent().expect("by construction")
                          .to_path_buf());
    }

    // Create policy file if it does not exist.
    let path = well_known.expect("at least one address").join("policy");
    match open_options_nofollow()
        .write(true)
        .create_new(true)
        .open(&path)
    {
        Err(ref e) if e.kind() == std::io::ErrorKind::AlreadyExists => (),
        r => {
            let r = match r {
                Ok(file) => reject_symlink(file, path.clone()),
                Err(err) => Err(err.into()),
            };

            match r {
                Ok(file) => {
                    drop(file);
                }
                Err(err) => {
                    if is_symlink_error(&err) {
                        // Don't overwrite the symlink.
                    } else {
                        return Err(err);
                    }
                }
            }
        },
    }

    Ok(())
}

#[derive(Default)]
struct KeyRing(HashMap<Fingerprint, Cert>);

impl KeyRing {
    fn insert(&mut self, cert: Cert) -> Result<()> {
        let fp = cert.fingerprint();
        if let Some(existing) = self.0.get_mut(&fp) {
            *existing = existing.clone().merge_public(cert)?;
        } else {
            self.0.insert(fp, cert);
        }
        Ok(())
    }

    fn export(&self, o: &mut dyn std::io::Write) -> openpgp::Result<()> {
        for cert in self.0.values() {
            cert.export(o)?;
        }
        Ok(())
    }
}

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

    #[test]
    fn encode_local_part_succed() {
        let encoded_part = encode_local_part("test1");
        assert_eq!("stnkabub89rpcphiz4ppbxixkwyt1pic", encoded_part);
        assert_eq!(32, encoded_part.len());
    }


    #[test]
    fn email_address_from() {
        let email_address = EmailAddress::from("test1@example.com").unwrap();
        assert_eq!(email_address.domain, "example.com");
        assert_eq!(email_address.local_part, "test1");
        assert!(EmailAddress::from("thisisnotanemailaddress").is_err());
    }

    #[test]
    fn url_roundtrip() {
        // Advanced method
        let expected_url =
            "https://openpgpkey.example.com/\
             .well-known/openpgpkey/example.com/hu/\
             stnkabub89rpcphiz4ppbxixkwyt1pic?l=test1";
        let wkd_url = Url::from("test1@example.com").unwrap();
        assert_eq!(expected_url, wkd_url.to_string());
        assert_eq!(url::Url::parse(expected_url).unwrap(),
                   wkd_url.to_url(None).unwrap());
        assert_eq!(expected_url.parse::<url::Url>().unwrap(),
                   wkd_url.to_url(None).unwrap());

        // Direct method
        let expected_url =
            "https://example.com/\
             .well-known/openpgpkey/hu/\
             stnkabub89rpcphiz4ppbxixkwyt1pic?l=test1";
        assert_eq!(expected_url, wkd_url.build(Direct));
        assert_eq!(url::Url::parse(expected_url).unwrap(),
                   wkd_url.to_url(Direct).unwrap());
        assert_eq!(expected_url.parse::<url::Url>().unwrap(),
                   wkd_url.to_url(Direct).unwrap());
    }

    #[test]
    fn url_to_file_path() {
        // Advanced method
        let expected_path =
            ".well-known/openpgpkey/example.com/hu/\
             stnkabub89rpcphiz4ppbxixkwyt1pic";
        let wkd_url = Url::from("test1@example.com").unwrap();
        assert_eq!(expected_path,
            wkd_url.to_file_path(None).unwrap().to_str().unwrap());

        // Direct method
        let expected_path =
            ".well-known/openpgpkey/hu/\
             stnkabub89rpcphiz4ppbxixkwyt1pic";
        assert_eq!(expected_path,
            wkd_url.to_file_path(Direct).unwrap().to_str().unwrap());
    }

    #[test]
    fn test_parse_body() {
        let (cert, _) = CertBuilder::new()
            .add_userid("test@example.example")
            .generate()
            .unwrap();
        let mut buffer: Vec<u8> = Vec::new();
        cert.serialize(&mut buffer).unwrap();
        let valid_certs = parse_body(&buffer, "juga@sequoia-pgp.org");
        // The userid is not in the Cert
        assert!(valid_certs.is_err());
        // XXX: add userid to the cert, instead of creating a new one
        // cert.add_userid("juga@sequoia.org");
        let (cert, _) = CertBuilder::new()
            .add_userid("test@example.example")
            .add_userid("juga@sequoia-pgp.org")
            .generate()
            .unwrap();
        cert.serialize(&mut buffer).unwrap();
        let valid_certs = parse_body(&buffer, "juga@sequoia-pgp.org");
        assert!(valid_certs.is_ok());
        assert!(valid_certs.unwrap().len() == 1);
        // XXX: Test with more Certs
    }

    #[test]
    fn wkd_generate() {
       let (cert, _) = CertBuilder::new()
            .add_userid("test1@example.example")
            .add_userid("juga@sequoia-pgp.org")
            .generate()
            .unwrap();
        let (cert2, _) = CertBuilder::new()
            .add_userid("justus@sequoia-pgp.org")
            .generate()
            .unwrap();

        let dir = tempfile::tempdir().unwrap();
        let dir_path = dir.path();
        insert(&dir_path, "sequoia-pgp.org", None, &cert).unwrap();
        insert(&dir_path, "sequoia-pgp.org", None, &cert2).unwrap();

        // justus and juga files will be generated, but not test one.
        let path = dir_path.join(
            ".well-known/openpgpkey/sequoia-pgp.org/hu\
             /jwp7xjqkdujgz5op6bpsoypg34pnrgmq");
        // Check that justus file was created
        assert!(path.is_file());
        let path = dir_path.join(
            ".well-known/openpgpkey/sequoia-pgp.org/hu\
             /7t1uqk9cwh1955776rc4z1gqf388566j");
        // Check that juga file was created.
        assert!(path.is_file());
        // Check that the file for test uid is not created.
        let path = dir_path.join(
            ".well-known/openpgpkey/example.com/hu/\
             stnkabub89rpcphiz4ppbxixkwyt1pic");
        assert!(!path.is_file());
    }

    #[test]
    fn wkd_generate_check_for_symlinks() {
       let (cert, _) = CertBuilder::new()
            .add_userid("test1@example.example")
            .add_userid("juga@sequoia-pgp.org")
            .generate()
            .unwrap();
        let (cert2, _) = CertBuilder::new()
            .add_userid("justus@sequoia-pgp.org")
            .generate()
            .unwrap();

        let dir = tempfile::tempdir().unwrap();
        let dir_path = dir.path();
        insert(&dir_path, "sequoia-pgp.org", None, &cert).unwrap();

        let juga_path = dir_path.join(
            ".well-known/openpgpkey/sequoia-pgp.org/hu\
             /7t1uqk9cwh1955776rc4z1gqf388566j");
        // Check that the juga file was created
        assert!(juga_path.is_file());

        let justus_path = dir_path.join(
            ".well-known/openpgpkey/sequoia-pgp.org/hu\
             /jwp7xjqkdujgz5op6bpsoypg34pnrgmq");
        // Make sure the justus file was not created.
        assert!(! justus_path.exists());

        // Make justus a symlink to juga.
        platform! {
            unix => {
                use std::os::unix::fs;
                fs::symlink(&juga_path, &justus_path)
                    .expect("can create symbolic link");
            },
            windows => {
                use std::os::windows::fs;
                fs::symlink_file(&juga_path, &justus_path)
                    .expect("can create symbolic link");
            }
        }

        assert!(justus_path.is_symlink());

        // Insert justus's certificate.  This should replace the
        // symbolic link, not follow it.
        insert(&dir_path, "sequoia-pgp.org", None, &cert2).unwrap();

        assert!(! justus_path.is_symlink());
        assert!(! juga_path.is_symlink());

        // Make sure that inserting justus didn't update juga's file.
        let juga = Cert::from_file(&juga_path).expect("can read");
        assert_eq!(juga.fingerprint(), cert.fingerprint());
    }

    #[test]
    fn test_get_cert_domains() -> Result<()> {
        let (cert, _) = CertBuilder::new()
             .add_userid("test1@example.example")
             .add_userid("juga@sequoia-pgp.org")
             .generate()
             .unwrap();
        let policy = &StandardPolicy::new();
        let user_ids: Vec<_> = get_cert_domains("sequoia-pgp.org", &cert.with_policy(policy, None)?)
            .map(|addr| addr.to_string())
            .collect();
        assert_eq!(user_ids, vec!["https://openpgpkey.sequoia-pgp.org/.well-known/openpgpkey/sequoia-pgp.org/hu/7t1uqk9cwh1955776rc4z1gqf388566j?l=juga"]);

        let user_ids: Vec<_> = get_cert_domains("example.example", &cert.with_policy(policy, None)?)
            .map(|addr| addr.to_string())
            .collect();
        assert_eq!(user_ids, vec!["https://openpgpkey.example.example/.well-known/openpgpkey/example.example/hu/stnkabub89rpcphiz4ppbxixkwyt1pic?l=test1"]);
        Ok(())
    }

    #[test]
    fn test_cert_contains_domain_userid() -> Result<()> {
        let (cert, _) = CertBuilder::new()
             .add_userid("test1@example.example")
             .add_userid("juga@sequoia-pgp.org")
             .generate()
             .unwrap();
        let policy = &StandardPolicy::new();
        assert!(cert_contains_domain_userid("sequoia-pgp.org", &cert.with_policy(policy, None)?));
        assert!(cert_contains_domain_userid("example.example", &cert.with_policy(policy, None)?));
        assert!(!cert_contains_domain_userid("example.org", &cert.with_policy(policy, None)?));
        Ok(())
    }

    #[test]
    fn test_protect_localpart_in_get_request() -> Result<()> {
        let wkd_url = Url::from("test1+tag_&admin=root%@example.com").unwrap();
        assert_eq!(
            "https://openpgpkey.example.com/.well-known/openpgpkey/example.com/hu/zpceuwttodc1e13yw1bo5dwot183s6kc?l=test1%2Btag_%26admin%3Droot%25",
            wkd_url.to_string());

        Ok(())
    }

    #[test]
    fn test_case_folding() -> Result<()> {
        // Upper and lower german 'U'-umlaut in unicode.
        let email_upper = "\u{00DC}ser@example.com";
        let email_lower = "\u{00FC}ser@example.com";

        let url_upper = Url::from(email_upper)?.to_string();
        let url_lower = Url::from(email_lower)?.to_string();

        // Cut off the query of the url (everything after '?').
        let url_upper = url_upper.split("?").next().unwrap();
        let url_lower = url_lower.split("?").next().unwrap();

        // The urls should be different.
        assert_ne!(url_upper, url_lower);

        Ok(())
    }
}