Skip to main content

rtci_host/
certificate.rs

1// Copyright 2026 Brainwires. MIT OR Apache-2.0.
2
3//! `RTCCertificate`: DTLS key generation, fingerprints, PEM export and
4//! import, and a per-realm store of certificates by id.
5
6use std::collections::HashMap;
7use std::time::Duration;
8use std::time::SystemTime;
9use std::time::UNIX_EPOCH;
10
11use rtci::peer_connection::certificate::CertificateParams;
12use rtci::peer_connection::certificate::RTCCertificate;
13
14use crate::args::CertificateInfo;
15use crate::args::FingerprintInfo;
16use crate::args::KeygenArg;
17use crate::error::Error;
18use crate::error::ErrorKind;
19
20fn op_err(e: impl std::fmt::Display) -> Error {
21  Error::new(ErrorKind::Operation, e.to_string())
22}
23
24/// The `RTCCertificate`s of a realm, by id: each holds a key and an X.509
25/// certificate for the DTLS handshakes of the connections given it. The
26/// front end removes an entry when its `RTCCertificate` is garbage
27/// collected; a connection keeps its own copy.
28#[derive(Default)]
29pub struct CertificateStore {
30  next: u32,
31  certs: HashMap<u32, RTCCertificate>,
32}
33
34impl CertificateStore {
35  /// A copy of certificate `id`; an unknown id is an `InvalidAccessError`.
36  pub fn get(&self, id: u32) -> Result<RTCCertificate, Error> {
37    self.certs.get(&id).cloned().ok_or_else(|| {
38      Error::new(ErrorKind::InvalidAccess, "Unknown RTCCertificate")
39    })
40  }
41
42  pub fn remove(&mut self, id: u32) {
43    self.certs.remove(&id);
44  }
45
46  /// Keeps `cert` under a new id and describes it for JavaScript.
47  pub fn insert(
48    &mut self,
49    cert: RTCCertificate,
50  ) -> Result<CertificateInfo, Error> {
51    let fingerprints = certificate_fingerprints(&cert)?;
52    let expires = expires_ms(&cert);
53    self.next += 1;
54    let id = self.next;
55    self.certs.insert(id, cert);
56    Ok(CertificateInfo {
57      id,
58      expires,
59      fingerprints,
60    })
61  }
62}
63
64/// The certificate's fingerprints, in each algorithm the engine computes.
65pub fn certificate_fingerprints(
66  cert: &RTCCertificate,
67) -> Result<Vec<FingerprintInfo>, Error> {
68  let provider = rtci::crypto::default_provider().map_err(op_err)?;
69  Ok(
70    cert
71      .get_fingerprints(provider.crypto())
72      .map_err(op_err)?
73      .into_iter()
74      .map(|f| FingerprintInfo {
75        algorithm: f.algorithm,
76        value: f.value,
77      })
78      .collect(),
79  )
80}
81
82/// The W3C `expires`, a DOMTimeStamp: whole milliseconds since the epoch.
83pub fn expires_ms(cert: &RTCCertificate) -> f64 {
84  cert
85    .expires
86    .duration_since(UNIX_EPOCH)
87    .map(|d| d.as_millis() as f64)
88    .unwrap_or(0.0)
89}
90
91/// The DTLS key: ECDSA P-256 (what browsers default to), or RSASSA-PKCS1-v1_5
92/// with SHA-256 and the public exponent 65537 (WebCrypto's algorithm
93/// dictionaries, as `generateCertificate` takes them). CPU-heavy for RSA:
94/// call it off the engine's thread.
95pub fn generate_certificate(
96  alg: &KeygenArg,
97  expires_at_ms: f64,
98) -> Result<RTCCertificate, Error> {
99  use rtci::crypto::SignatureScheme;
100  let provider = rtci::crypto::default_provider().map_err(op_err)?;
101  let not_supported = |m: String| Error::new(ErrorKind::NotSupported, m);
102  let name = alg.name.to_ascii_uppercase();
103  let (scheme, signing_key) = match name.as_str() {
104    "ECDSA" => {
105      if alg.named_curve.as_deref() != Some("P-256") {
106        return Err(not_supported(format!(
107          "ECDSA curve {:?} is not supported (P-256 is)",
108          alg.named_curve.as_deref().unwrap_or("")
109        )));
110      }
111      let key = provider
112        .crypto()
113        .generate_signing_key(SignatureScheme::EcdsaP256Sha256)
114        .map_err(op_err)?;
115      (SignatureScheme::EcdsaP256Sha256, key)
116    }
117    "RSASSA-PKCS1-V1_5" => {
118      let hash = alg
119        .hash
120        .as_deref()
121        .unwrap_or("SHA-256")
122        .to_ascii_uppercase();
123      if hash != "SHA-256" {
124        return Err(not_supported(format!(
125          "RSASSA-PKCS1-v1_5 with {hash} is not supported (SHA-256 is)"
126        )));
127      }
128      let exponent = alg.public_exponent.as_deref().unwrap_or(&[1, 0, 1]);
129      let trimmed: Vec<u8> =
130        exponent.iter().copied().skip_while(|b| *b == 0).collect();
131      if trimmed != [1, 0, 1] {
132        return Err(not_supported(
133          "Only the RSA public exponent 65537 is supported".to_string(),
134        ));
135      }
136      let size = match alg.modulus_length.unwrap_or(2048) {
137        2048 => aws_lc_rs::rsa::KeySize::Rsa2048,
138        3072 => aws_lc_rs::rsa::KeySize::Rsa3072,
139        4096 => aws_lc_rs::rsa::KeySize::Rsa4096,
140        other => {
141          return Err(not_supported(format!(
142            "An RSA modulus of {other} bits is not supported (2048, 3072 or 4096 are)"
143          )));
144        }
145      };
146      let pair = aws_lc_rs::rsa::KeyPair::generate(size).map_err(op_err)?;
147      let der = aws_lc_rs::encoding::AsDer::<
148        aws_lc_rs::encoding::Pkcs8V1Der<'static>,
149      >::as_der(&pair)
150      .map_err(op_err)?;
151      let key = provider
152        .crypto()
153        .import_signing_key(SignatureScheme::RsaPkcs1Sha256, der.as_ref())
154        .map_err(op_err)?;
155      (SignatureScheme::RsaPkcs1Sha256, key)
156    }
157    _ => {
158      return Err(not_supported(format!(
159        "'{}' is not a supported certificate algorithm",
160        alg.name
161      )));
162    }
163  };
164  let params =
165    CertificateParams::new(vec!["WebRTC".to_owned()]).map_err(op_err)?;
166  let mut cert =
167    RTCCertificate::generate_from_signing_key(params, scheme, signing_key)
168      .map_err(op_err)?;
169  // W3C `expires`: the certificate stops being usable for new connections
170  // then (the X.509 validity is the engine's; DTLS peers check fingerprints,
171  // not validity). `expires_at_ms` is a time on the JS clock (`Date.now()`
172  // plus the `expires` the page asked for): the attribute, the constructor's
173  // expiry check and the page all read that clock, which on Windows can lag
174  // the system clock by a few milliseconds, so the instant is kept as given
175  // (at most a year ahead) instead of being re-based on `SystemTime::now()`.
176  let max_ms = SystemTime::now()
177    .duration_since(UNIX_EPOCH)
178    .map(|d| d.as_millis() as f64)
179    .unwrap_or(0.0)
180    + 365.0 * 24.0 * 3600.0 * 1000.0;
181  let expires_at_ms = expires_at_ms.clamp(0.0, max_ms);
182  cert.expires = UNIX_EPOCH + Duration::from_millis(expires_at_ms as u64);
183  Ok(cert)
184}
185
186/// `Deno.webrtc.exportCertificate`: the key and certificate as PEM, with
187/// the `expires` time, to keep a server's DTLS fingerprint across restarts.
188pub fn certificate_to_pem(cert: &RTCCertificate) -> Result<String, Error> {
189  cert.serialize_pem().map_err(op_err)
190}
191
192/// The inverse of [`certificate_to_pem`]; anything else is a `SyntaxError`.
193pub fn certificate_from_pem(pem: &str) -> Result<RTCCertificate, Error> {
194  let provider = rtci::crypto::default_provider().map_err(op_err)?;
195  RTCCertificate::from_pem(pem, provider.crypto()).map_err(|e| {
196    Error::new(
197      ErrorKind::Syntax,
198      format!("Not an exported RTCCertificate: {e}"),
199    )
200  })
201}