use crate::signature::{
DEFAULT_TOLERANCE_SECONDS, InvalidSignatureError, VerifyOptions, verify_signature,
};
use crate::webhook::{HookHeaders, MissingHookIdError, parse_headers};
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ReceiveOptions {
pub secrets: Vec<String>,
pub allow_unsigned: bool,
pub tolerance_seconds: Option<u64>,
pub now: Option<u64>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReceivedDelivery<'a> {
pub headers: HookHeaders<'a>,
pub verified: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ReceiveError {
#[error(transparent)]
Signature(#[from] InvalidSignatureError),
#[error(transparent)]
MissingHookId(#[from] MissingHookIdError),
}
pub fn receive_delivery<'a>(
headers: &'a http::HeaderMap,
body: &[u8],
options: &ReceiveOptions,
) -> Result<ReceivedDelivery<'a>, ReceiveError> {
let verified = if options.secrets.is_empty() {
if !options.allow_unsigned {
return Err(InvalidSignatureError::new("invalid_secret", None).into());
}
false
} else {
let verify = VerifyOptions {
tolerance_seconds: options
.tolerance_seconds
.unwrap_or(DEFAULT_TOLERANCE_SECONDS),
now: options.now,
};
verify_signature(headers, body, &options.secrets, verify)?;
true
};
Ok(ReceivedDelivery {
headers: parse_headers(headers)?,
verified,
})
}