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::{distributions::DistString, 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 mut params = rcgen::CertificateParams::new(vec![
41            rand::distributions::Alphanumeric.sample_string(&mut rand::thread_rng(), 16)
42        ]);
43        params.alg = &rcgen::PKCS_ECDSA_P256_SHA256;
44        Ok(Self {
45            inner: RTCCertificate::from_params(params).expect("default params to work"),
46        })
47    }
48
49    /// Returns SHA-256 fingerprint of this certificate.
50    ///
51    /// # Panics
52    ///
53    /// This function will panic if there's no fingerprint with the SHA-256 algorithm (see
54    /// [`RTCCertificate::get_fingerprints`]).
55    pub fn fingerprint(&self) -> Fingerprint {
56        let fingerprints = self.inner.get_fingerprints();
57        let sha256_fingerprint = fingerprints
58            .iter()
59            .find(|f| f.algorithm == "sha-256")
60            .expect("a SHA-256 fingerprint");
61
62        Fingerprint::try_from_rtc_dtls(sha256_fingerprint).expect("we filtered by sha-256")
63    }
64
65    /// Parses a certificate from the ASCII PEM format.
66    ///
67    /// See [`RTCCertificate::from_pem`]
68    #[cfg(feature = "pem")]
69    pub fn from_pem(pem_str: &str) -> Result<Self, Error> {
70        Ok(Self {
71            inner: RTCCertificate::from_pem(pem_str).map_err(Kind::InvalidPEM)?,
72        })
73    }
74
75    /// Serializes the certificate (including the private key) in PKCS#8 format in PEM.
76    ///
77    /// See [`RTCCertificate::serialize_pem`]
78    #[cfg(feature = "pem")]
79    pub fn serialize_pem(&self) -> String {
80        self.inner.serialize_pem()
81    }
82
83    /// Extract the [`RTCCertificate`] from this wrapper.
84    ///
85    /// This function is `pub(crate)` to avoid leaking the `webrtc` dependency to our users.
86    pub(crate) fn to_rtc_certificate(&self) -> RTCCertificate {
87        self.inner.clone()
88    }
89}
90
91#[derive(thiserror::Error, Debug)]
92#[error("Failed to generate certificate")]
93pub struct Error(#[from] Kind);
94
95#[derive(thiserror::Error, Debug)]
96enum Kind {
97    #[error(transparent)]
98    InvalidPEM(#[from] webrtc::Error),
99}
100
101#[cfg(all(test, feature = "pem"))]
102mod test {
103    use rand::thread_rng;
104
105    use super::*;
106
107    #[test]
108    fn test_certificate_serialize_pem_and_from_pem() {
109        let cert = Certificate::generate(&mut thread_rng()).unwrap();
110
111        let pem = cert.serialize_pem();
112        let loaded_cert = Certificate::from_pem(&pem).unwrap();
113
114        assert_eq!(loaded_cert, cert)
115    }
116}