use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::fmt;
use core::time::Duration;
#[cfg(feature = "std")]
use std::time::SystemTime;
pub trait Clock: Send + Sync {
#[must_use]
fn now(&self) -> u64;
}
#[cfg(feature = "std")]
#[derive(Debug, Clone, Copy, Default)]
pub struct SystemClock;
#[cfg(feature = "std")]
impl Clock for SystemClock {
fn now(&self) -> u64 {
SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap_or_default()
.as_secs()
}
}
#[must_use]
#[non_exhaustive]
#[derive(Clone, PartialEq, Eq)]
pub enum VerifyingKeyMaterial {
X509Certificate(Vec<u8>),
EcdsaP256PublicKey(Vec<u8>),
}
impl fmt::Debug for VerifyingKeyMaterial {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
VerifyingKeyMaterial::X509Certificate(bytes) => f
.debug_tuple("X509Certificate")
.field(&format_args!("<{} bytes>", bytes.len()))
.finish(),
VerifyingKeyMaterial::EcdsaP256PublicKey(bytes) => f
.debug_tuple("EcdsaP256PublicKey")
.field(&format_args!("<{} bytes>", bytes.len()))
.finish(),
}
}
}
#[must_use]
#[non_exhaustive]
#[derive(Clone)]
pub struct VerifyOptions {
pub max_age: Option<Duration>,
pub clock: Option<Arc<dyn Clock>>,
pub request_url: Option<String>,
pub form_params: Option<Vec<(String, String)>>,
pub verifying_material: Option<VerifyingKeyMaterial>,
pub webhook_id: Option<String>,
}
impl Default for VerifyOptions {
fn default() -> Self {
Self {
max_age: Some(Duration::from_secs(300)),
clock: None,
request_url: None,
form_params: None,
verifying_material: None,
webhook_id: None,
}
}
}
impl VerifyOptions {
pub fn with_request_url(mut self, url: impl Into<String>) -> Self {
self.request_url = Some(url.into());
self
}
pub fn with_form_params<I, K, V>(mut self, params: I) -> Self
where
I: IntoIterator<Item = (K, V)>,
K: Into<String>,
V: Into<String>,
{
self.form_params = Some(
params
.into_iter()
.map(|(k, v)| (k.into(), v.into()))
.collect(),
);
self
}
pub fn with_max_age(mut self, max_age: Option<Duration>) -> Self {
self.max_age = max_age;
self
}
pub fn with_clock(mut self, clock: Option<Arc<dyn Clock>>) -> Self {
self.clock = clock;
self
}
pub fn with_verifying_material(mut self, material: VerifyingKeyMaterial) -> Self {
self.verifying_material = Some(material);
self
}
pub fn with_webhook_id(mut self, webhook_id: impl Into<String>) -> Self {
self.webhook_id = Some(webhook_id.into());
self
}
#[must_use]
pub fn now(&self) -> u64 {
match &self.clock {
Some(clock) => clock.now(),
#[cfg(feature = "std")]
None => SystemClock.now(),
#[cfg(not(feature = "std"))]
None => 0,
}
}
}
impl fmt::Debug for VerifyOptions {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("VerifyOptions")
.field("max_age", &self.max_age)
.field("clock", &self.clock.as_ref().map(|_| "<injected>"))
.field("request_url_set", &self.request_url.is_some())
.field(
"form_params_count",
&self.form_params.as_ref().map(|p| p.len()),
)
.field("verifying_material", &self.verifying_material)
.field("webhook_id_set", &self.webhook_id.is_some())
.finish()
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use std::time::Duration;
use super::{VerifyOptions, VerifyingKeyMaterial};
use crate::test_helpers::{FixedClock, epoch};
#[test]
fn default_is_five_minutes_without_injected_clock() {
let opts = VerifyOptions::default();
assert_eq!(opts.max_age, Some(Duration::from_secs(300)));
assert!(opts.clock.is_none());
}
#[test]
fn injected_clock_is_used_for_now() {
let fixed = FixedClock(epoch(1_700_000_000));
let opts = VerifyOptions {
max_age: Some(Duration::from_secs(300)),
clock: Some(Arc::new(FixedClock(epoch(1_700_000_000)))),
request_url: None,
form_params: None,
verifying_material: None,
webhook_id: None,
};
assert_eq!(opts.now(), fixed.0);
}
#[test]
fn builder_sets_request_url() {
let opts = VerifyOptions::default().with_request_url("https://example.com/webhook");
assert_eq!(
opts.request_url.as_deref(),
Some("https://example.com/webhook")
);
}
#[test]
fn debug_does_not_print_request_url_value() {
let opts = VerifyOptions::default().with_request_url("https://internal.example/hook");
assert!(!format!("{opts:?}").contains("internal.example"));
}
#[test]
fn builder_sets_verifying_material() {
let key = b"\x30\x59\x13".to_vec();
let opts = VerifyOptions::default()
.with_verifying_material(VerifyingKeyMaterial::EcdsaP256PublicKey(key.clone()));
assert_eq!(
opts.verifying_material,
Some(VerifyingKeyMaterial::EcdsaP256PublicKey(key))
);
assert!(VerifyOptions::default().verifying_material.is_none());
}
#[test]
fn builder_sets_webhook_id() {
let opts = VerifyOptions::default().with_webhook_id("0NH55953DH663215D");
assert_eq!(opts.webhook_id.as_deref(), Some("0NH55953DH663215D"));
assert!(VerifyOptions::default().webhook_id.is_none());
}
#[test]
fn debug_redacts_verifying_material_bytes() {
let opts = VerifyOptions::default()
.with_verifying_material(VerifyingKeyMaterial::EcdsaP256PublicKey(vec![0xde, 0xad]));
let debug = format!("{opts:?}");
assert!(!debug.contains("222")); assert!(debug.contains("<2 bytes>"));
}
#[test]
fn builder_sets_form_params_in_any_order() {
let opts = VerifyOptions::default()
.with_request_url("https://example.com/myapp")
.with_form_params([("Digits", "1234"), ("CallSid", "CA123")]);
assert_eq!(
opts.form_params,
Some(vec![
("Digits".to_string(), "1234".to_string()),
("CallSid".to_string(), "CA123".to_string())
])
);
}
#[test]
fn debug_does_not_print_form_param_values() {
let opts = VerifyOptions::default().with_form_params([("Body", "s3cr3t-message")]);
let debug = format!("{opts:?}");
assert!(!debug.contains("s3cr3t-message"));
assert!(debug.contains("form_params_count: Some(1)"));
}
#[test]
fn builder_sets_max_age() {
let opts = VerifyOptions::default().with_max_age(Some(Duration::from_secs(600)));
assert_eq!(opts.max_age, Some(Duration::from_secs(600)));
}
#[test]
fn builder_disables_max_age() {
let opts = VerifyOptions::default().with_max_age(None);
assert!(opts.max_age.is_none());
}
#[test]
fn builder_sets_clock() {
let fixed = FixedClock(epoch(1_700_000_000));
let opts =
VerifyOptions::default().with_clock(Some(Arc::new(FixedClock(epoch(1_700_000_000)))));
assert_eq!(opts.now(), fixed.0);
}
#[test]
fn builder_disables_clock() {
let fixed = epoch(1_700_000_000);
let opts = VerifyOptions::default()
.with_clock(Some(Arc::new(FixedClock(fixed))))
.with_clock(None);
assert!(opts.clock.is_none());
let _ = opts.now();
}
}