libp2p_webrtc/tokio/
certificate.rs

1// Copyright 2022 Parity Technologies (UK) Ltd.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the "Software"),
5// to deal in the Software without restriction, including without limitation
6// the rights to use, copy, modify, merge, publish, distribute, sublicense,
7// and/or sell copies of the Software, and to permit persons to whom the
8// Software is furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19// DEALINGS IN THE SOFTWARE.
20
21use rand::{CryptoRng, Rng};
22use webrtc::peer_connection::certificate::RTCCertificate;
23
24use crate::tokio::fingerprint::Fingerprint;
25
26#[derive(Debug, Clone, PartialEq)]
27pub struct Certificate {
28    inner: RTCCertificate,
29}
30
31impl Certificate {
32    /// Generate new certificate.
33    ///
34    /// `_rng` argument is ignored for now. See <https://github.com/melekes/rust-libp2p/pull/12>.
35    #[allow(clippy::unnecessary_wraps)]
36    pub fn generate<R>(_rng: &mut R) -> Result<Self, Error>
37    where
38        R: CryptoRng + Rng,
39    {
40        let keypair = rcgen::KeyPair::generate().expect("keypair to be able to be generated");
41        Ok(Self {
42            inner: RTCCertificate::from_key_pair(keypair).expect("default params to work"),
43        })
44    }
45
46    /// Returns SHA-256 fingerprint of this certificate.
47    ///
48    /// # Panics
49    ///
50    /// This function will panic if there's no fingerprint with the SHA-256 algorithm (see
51    /// [`RTCCertificate::get_fingerprints`]).
52    pub fn fingerprint(&self) -> Fingerprint {
53        let fingerprints = self.inner.get_fingerprints();
54        let sha256_fingerprint = fingerprints
55            .iter()
56            .find(|f| f.algorithm == "sha-256")
57            .expect("a SHA-256 fingerprint");
58
59        Fingerprint::try_from_rtc_dtls(sha256_fingerprint).expect("we filtered by sha-256")
60    }
61
62    /// Parses a certificate from the ASCII PEM format.
63    ///
64    /// See [`RTCCertificate::from_pem`]
65    #[cfg(feature = "pem")]
66    pub fn from_pem(pem_str: &str) -> Result<Self, Error> {
67        Ok(Self {
68            inner: RTCCertificate::from_pem(pem_str).map_err(Kind::InvalidPEM)?,
69        })
70    }
71
72    /// Serializes the certificate (including the private key) in PKCS#8 format in PEM.
73    ///
74    /// See [`RTCCertificate::serialize_pem`]
75    #[cfg(feature = "pem")]
76    pub fn serialize_pem(&self) -> String {
77        self.inner.serialize_pem()
78    }
79
80    /// Extract the [`RTCCertificate`] from this wrapper.
81    ///
82    /// This function is `pub(crate)` to avoid leaking the `webrtc` dependency to our users.
83    pub(crate) fn to_rtc_certificate(&self) -> RTCCertificate {
84        self.inner.clone()
85    }
86}
87
88#[derive(thiserror::Error, Debug)]
89#[error("Failed to generate certificate")]
90pub struct Error(#[from] Kind);
91
92#[derive(thiserror::Error, Debug)]
93enum Kind {
94    #[error(transparent)]
95    InvalidPEM(#[from] webrtc::Error),
96}
97
98#[cfg(all(test, feature = "pem"))]
99mod test {
100    use rand::thread_rng;
101
102    use super::*;
103
104    #[test]
105    fn test_certificate_serialize_pem_and_from_pem() {
106        let cert = Certificate::generate(&mut thread_rng()).unwrap();
107
108        let pem = cert.serialize_pem();
109        let loaded_cert = Certificate::from_pem(&pem).unwrap();
110
111        assert_eq!(loaded_cert, cert)
112    }
113}