adk_server/webhooks/
forge.rs1use std::sync::Arc;
19
20use adk_core::webhook::{VerifiedWebhook, WebhookError};
21use hmac::{Hmac, Mac};
22use sha2::{Digest, Sha256};
23
24pub const GITHUB_SIGNATURE_HEADER: &str = "x-hub-signature-256";
26pub const GITHUB_DELIVERY_HEADER: &str = "x-github-delivery";
28pub const GITLAB_TOKEN_HEADER: &str = "x-gitlab-token";
30pub const GITLAB_EVENT_HEADER: &str = "x-gitlab-event-uuid";
32pub const GITLAB_IDEMPOTENCY_HEADER: &str = "idempotency-key";
34
35#[derive(Clone, PartialEq, Eq)]
47pub struct ForgeSecret {
48 key: Arc<[u8]>,
49}
50
51impl std::fmt::Debug for ForgeSecret {
52 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53 f.debug_struct("ForgeSecret").field("key", &"[REDACTED]").finish()
54 }
55}
56
57impl ForgeSecret {
58 pub fn new(secret: impl AsRef<str>) -> Result<Self, WebhookError> {
64 let secret = secret.as_ref().trim();
65 if secret.is_empty() {
66 return Err(WebhookError::InvalidSecret("the forge secret is empty".to_string()));
67 }
68 Ok(Self { key: secret.as_bytes().into() })
69 }
70}
71
72#[derive(Clone, Debug)]
89pub enum ForgeSignature {
90 GitHub(ForgeSecret),
92 GitLab(ForgeSecret),
94}
95
96impl ForgeSignature {
97 pub fn name(&self) -> &'static str {
99 match self {
100 Self::GitHub(_) => "github",
101 Self::GitLab(_) => "gitlab",
102 }
103 }
104
105 pub fn verify<'a>(
117 &self,
118 lookup: impl Fn(&'static str) -> Option<&'a str>,
119 body: &[u8],
120 ) -> Result<VerifiedWebhook, WebhookError> {
121 let id = match self {
122 Self::GitHub(secret) => {
123 let header = lookup(GITHUB_SIGNATURE_HEADER)
124 .ok_or(WebhookError::MissingHeader(GITHUB_SIGNATURE_HEADER))?;
125 let signature = header
126 .trim()
127 .strip_prefix("sha256=")
128 .and_then(|hex| hex::decode(hex).ok())
129 .ok_or_else(|| WebhookError::MalformedHeader {
130 header: GITHUB_SIGNATURE_HEADER,
131 reason: "not `sha256=<hex>`".to_string(),
132 })?;
133 let mut mac = Hmac::<Sha256>::new_from_slice(&secret.key)
135 .map_err(|_| WebhookError::SignatureMismatch)?;
136 mac.update(body);
137 mac.verify_slice(&signature).map_err(|_| WebhookError::SignatureMismatch)?;
139 lookup(GITHUB_DELIVERY_HEADER)
140 .ok_or(WebhookError::MissingHeader(GITHUB_DELIVERY_HEADER))?
141 }
142 Self::GitLab(secret) => {
143 let token = lookup(GITLAB_TOKEN_HEADER)
144 .ok_or(WebhookError::MissingHeader(GITLAB_TOKEN_HEADER))?;
145 if !same_secret(token.trim().as_bytes(), &secret.key) {
146 return Err(WebhookError::SignatureMismatch);
147 }
148 lookup(GITLAB_EVENT_HEADER)
149 .or_else(|| lookup(GITLAB_IDEMPOTENCY_HEADER))
150 .ok_or(WebhookError::MissingHeader(GITLAB_EVENT_HEADER))?
151 }
152 };
153 let id = id.trim();
154 if id.is_empty() || id.len() > 256 {
155 return Err(WebhookError::MalformedHeader {
156 header: match self {
157 Self::GitHub(_) => GITHUB_DELIVERY_HEADER,
158 Self::GitLab(_) => GITLAB_EVENT_HEADER,
159 },
160 reason: "must contain 1 to 256 bytes".to_string(),
161 });
162 }
163 Ok(VerifiedWebhook { id: id.to_string(), timestamp: chrono::Utc::now() })
164 }
165}
166
167fn same_secret(given: &[u8], expected: &[u8]) -> bool {
170 let (given, expected) = (Sha256::digest(given), Sha256::digest(expected));
171 given.iter().zip(expected.iter()).fold(0u8, |diff, (a, b)| diff | (a ^ b)) == 0
172}
173
174#[cfg(test)]
175mod tests {
176 use super::*;
177
178 fn lookup<'a>(headers: &'a [(&'static str, &'a str)]) -> impl Fn(&str) -> Option<&'a str> {
179 move |name| headers.iter().find(|(n, _)| *n == name).map(|(_, v)| *v)
180 }
181
182 #[test]
183 fn github_signatures_verify_over_the_raw_body() {
184 let forge = ForgeSignature::GitHub(ForgeSecret::new("It's a Secret to Everybody").unwrap());
185 let good = "sha256=757107ea0eb2509fc211221cce984b8a37570b6d7586c22c46f4379c8b043e17";
186 let headers = [(GITHUB_SIGNATURE_HEADER, good), (GITHUB_DELIVERY_HEADER, "d-1")];
187 assert_eq!(forge.verify(lookup(&headers), b"Hello, World!").unwrap().id, "d-1");
188 assert_eq!(
189 forge.verify(lookup(&headers), b"Hello, World?"),
190 Err(WebhookError::SignatureMismatch)
191 );
192 let malformed = [(GITHUB_SIGNATURE_HEADER, "sha1=abc"), (GITHUB_DELIVERY_HEADER, "d-1")];
193 assert!(matches!(
194 forge.verify(lookup(&malformed), b"Hello, World!"),
195 Err(WebhookError::MalformedHeader { .. })
196 ));
197 let unsigned = [(GITHUB_DELIVERY_HEADER, "d-1")];
198 assert_eq!(
199 forge.verify(lookup(&unsigned), b"Hello, World!"),
200 Err(WebhookError::MissingHeader(GITHUB_SIGNATURE_HEADER))
201 );
202 let anonymous = [(GITHUB_SIGNATURE_HEADER, good)];
203 assert_eq!(
204 forge.verify(lookup(&anonymous), b"Hello, World!"),
205 Err(WebhookError::MissingHeader(GITHUB_DELIVERY_HEADER))
206 );
207 }
208
209 #[test]
210 fn gitlab_tokens_match_exactly() {
211 let forge = ForgeSignature::GitLab(ForgeSecret::new("token-1").unwrap());
212 let headers = [(GITLAB_TOKEN_HEADER, "token-1"), (GITLAB_EVENT_HEADER, "e-1")];
213 assert_eq!(forge.verify(lookup(&headers), b"{}").unwrap().id, "e-1");
214 let retried = [(GITLAB_TOKEN_HEADER, "token-1"), (GITLAB_IDEMPOTENCY_HEADER, "k-1")];
215 assert_eq!(forge.verify(lookup(&retried), b"{}").unwrap().id, "k-1");
216 for wrong in ["token-2", "token-", "token-11", ""] {
217 let headers = [(GITLAB_TOKEN_HEADER, wrong), (GITLAB_EVENT_HEADER, "e-1")];
218 assert_eq!(
219 forge.verify(lookup(&headers), b"{}"),
220 Err(WebhookError::SignatureMismatch),
221 "{wrong}"
222 );
223 }
224 }
225}