use std::sync::Arc;
use adk_core::webhook::{VerifiedWebhook, WebhookError};
use hmac::{Hmac, Mac};
use sha2::{Digest, Sha256};
pub const GITHUB_SIGNATURE_HEADER: &str = "x-hub-signature-256";
pub const GITHUB_DELIVERY_HEADER: &str = "x-github-delivery";
pub const GITLAB_TOKEN_HEADER: &str = "x-gitlab-token";
pub const GITLAB_EVENT_HEADER: &str = "x-gitlab-event-uuid";
pub const GITLAB_IDEMPOTENCY_HEADER: &str = "idempotency-key";
#[derive(Clone, PartialEq, Eq)]
pub struct ForgeSecret {
key: Arc<[u8]>,
}
impl std::fmt::Debug for ForgeSecret {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ForgeSecret").field("key", &"[REDACTED]").finish()
}
}
impl ForgeSecret {
pub fn new(secret: impl AsRef<str>) -> Result<Self, WebhookError> {
let secret = secret.as_ref().trim();
if secret.is_empty() {
return Err(WebhookError::InvalidSecret("the forge secret is empty".to_string()));
}
Ok(Self { key: secret.as_bytes().into() })
}
}
#[derive(Clone, Debug)]
pub enum ForgeSignature {
GitHub(ForgeSecret),
GitLab(ForgeSecret),
}
impl ForgeSignature {
pub fn name(&self) -> &'static str {
match self {
Self::GitHub(_) => "github",
Self::GitLab(_) => "gitlab",
}
}
pub fn verify<'a>(
&self,
lookup: impl Fn(&'static str) -> Option<&'a str>,
body: &[u8],
) -> Result<VerifiedWebhook, WebhookError> {
let id = match self {
Self::GitHub(secret) => {
let header = lookup(GITHUB_SIGNATURE_HEADER)
.ok_or(WebhookError::MissingHeader(GITHUB_SIGNATURE_HEADER))?;
let signature = header
.trim()
.strip_prefix("sha256=")
.and_then(|hex| hex::decode(hex).ok())
.ok_or_else(|| WebhookError::MalformedHeader {
header: GITHUB_SIGNATURE_HEADER,
reason: "not `sha256=<hex>`".to_string(),
})?;
let mut mac = Hmac::<Sha256>::new_from_slice(&secret.key)
.map_err(|_| WebhookError::SignatureMismatch)?;
mac.update(body);
mac.verify_slice(&signature).map_err(|_| WebhookError::SignatureMismatch)?;
lookup(GITHUB_DELIVERY_HEADER)
.ok_or(WebhookError::MissingHeader(GITHUB_DELIVERY_HEADER))?
}
Self::GitLab(secret) => {
let token = lookup(GITLAB_TOKEN_HEADER)
.ok_or(WebhookError::MissingHeader(GITLAB_TOKEN_HEADER))?;
if !same_secret(token.trim().as_bytes(), &secret.key) {
return Err(WebhookError::SignatureMismatch);
}
lookup(GITLAB_EVENT_HEADER)
.or_else(|| lookup(GITLAB_IDEMPOTENCY_HEADER))
.ok_or(WebhookError::MissingHeader(GITLAB_EVENT_HEADER))?
}
};
let id = id.trim();
if id.is_empty() || id.len() > 256 {
return Err(WebhookError::MalformedHeader {
header: match self {
Self::GitHub(_) => GITHUB_DELIVERY_HEADER,
Self::GitLab(_) => GITLAB_EVENT_HEADER,
},
reason: "must contain 1 to 256 bytes".to_string(),
});
}
Ok(VerifiedWebhook { id: id.to_string(), timestamp: chrono::Utc::now() })
}
}
fn same_secret(given: &[u8], expected: &[u8]) -> bool {
let (given, expected) = (Sha256::digest(given), Sha256::digest(expected));
given.iter().zip(expected.iter()).fold(0u8, |diff, (a, b)| diff | (a ^ b)) == 0
}
#[cfg(test)]
mod tests {
use super::*;
fn lookup<'a>(headers: &'a [(&'static str, &'a str)]) -> impl Fn(&str) -> Option<&'a str> {
move |name| headers.iter().find(|(n, _)| *n == name).map(|(_, v)| *v)
}
#[test]
fn github_signatures_verify_over_the_raw_body() {
let forge = ForgeSignature::GitHub(ForgeSecret::new("It's a Secret to Everybody").unwrap());
let good = "sha256=757107ea0eb2509fc211221cce984b8a37570b6d7586c22c46f4379c8b043e17";
let headers = [(GITHUB_SIGNATURE_HEADER, good), (GITHUB_DELIVERY_HEADER, "d-1")];
assert_eq!(forge.verify(lookup(&headers), b"Hello, World!").unwrap().id, "d-1");
assert_eq!(
forge.verify(lookup(&headers), b"Hello, World?"),
Err(WebhookError::SignatureMismatch)
);
let malformed = [(GITHUB_SIGNATURE_HEADER, "sha1=abc"), (GITHUB_DELIVERY_HEADER, "d-1")];
assert!(matches!(
forge.verify(lookup(&malformed), b"Hello, World!"),
Err(WebhookError::MalformedHeader { .. })
));
let unsigned = [(GITHUB_DELIVERY_HEADER, "d-1")];
assert_eq!(
forge.verify(lookup(&unsigned), b"Hello, World!"),
Err(WebhookError::MissingHeader(GITHUB_SIGNATURE_HEADER))
);
let anonymous = [(GITHUB_SIGNATURE_HEADER, good)];
assert_eq!(
forge.verify(lookup(&anonymous), b"Hello, World!"),
Err(WebhookError::MissingHeader(GITHUB_DELIVERY_HEADER))
);
}
#[test]
fn gitlab_tokens_match_exactly() {
let forge = ForgeSignature::GitLab(ForgeSecret::new("token-1").unwrap());
let headers = [(GITLAB_TOKEN_HEADER, "token-1"), (GITLAB_EVENT_HEADER, "e-1")];
assert_eq!(forge.verify(lookup(&headers), b"{}").unwrap().id, "e-1");
let retried = [(GITLAB_TOKEN_HEADER, "token-1"), (GITLAB_IDEMPOTENCY_HEADER, "k-1")];
assert_eq!(forge.verify(lookup(&retried), b"{}").unwrap().id, "k-1");
for wrong in ["token-2", "token-", "token-11", ""] {
let headers = [(GITLAB_TOKEN_HEADER, wrong), (GITLAB_EVENT_HEADER, "e-1")];
assert_eq!(
forge.verify(lookup(&headers), b"{}"),
Err(WebhookError::SignatureMismatch),
"{wrong}"
);
}
}
}