Skip to main content

adk_server/webhooks/
forge.rs

1//! Forge push signatures for the webhook ingress (spec 3.5 §7.8.2 "Files and git").
2//!
3//! A [`WebhookHook`](super::WebhookHook) authenticates its deliveries with Standard Webhooks
4//! by default; [`WebhookHook::forge`](super::WebhookHook::forge) takes a forge's own push
5//! signature instead, so a repository host that cannot sign Standard Webhooks still reaches
6//! the same ingress, idempotency and kill switch. No forge is preferred: each scheme is one
7//! variant of [`ForgeSignature`].
8//!
9//! | Scheme | Authenticity | Delivery id |
10//! |---|---|---|
11//! | [`ForgeSignature::GitHub`] | `X-Hub-Signature-256: sha256=<hex>`, HMAC-SHA256 of the raw body keyed with the secret, compared in constant time | `X-GitHub-Delivery` |
12//! | [`ForgeSignature::GitLab`] | `X-Gitlab-Token` equal to the secret token, compared in constant time | `X-Gitlab-Event-UUID`, else `Idempotency-Key` |
13//!
14//! Neither forge signs a timestamp, so a captured delivery verifies again later: the
15//! ingress keys each run by the delivery id, so a redelivery is taken once, and a consumer
16//! that acts on a delivery's content (such as a commit) deduplicates by that content too.
17
18use std::sync::Arc;
19
20use adk_core::webhook::{VerifiedWebhook, WebhookError};
21use hmac::{Hmac, Mac};
22use sha2::{Digest, Sha256};
23
24/// GitHub's signature header.
25pub const GITHUB_SIGNATURE_HEADER: &str = "x-hub-signature-256";
26/// GitHub's delivery id header.
27pub const GITHUB_DELIVERY_HEADER: &str = "x-github-delivery";
28/// GitLab's secret token header.
29pub const GITLAB_TOKEN_HEADER: &str = "x-gitlab-token";
30/// GitLab's event id header.
31pub const GITLAB_EVENT_HEADER: &str = "x-gitlab-event-uuid";
32/// GitLab's idempotency key header, sent on retries of one event.
33pub const GITLAB_IDEMPOTENCY_HEADER: &str = "idempotency-key";
34
35/// A forge's shared secret: the HMAC key GitHub signs with, or the token GitLab sends.
36///
37/// # Example
38///
39/// ```rust
40/// use adk_server::webhooks::ForgeSecret;
41///
42/// let secret = ForgeSecret::new("a shared secret").unwrap();
43/// assert!(format!("{secret:?}").contains("REDACTED"));
44/// assert!(ForgeSecret::new("  ").is_err());
45/// ```
46#[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    /// The secret as the forge's settings hold it, surrounding whitespace removed.
59    ///
60    /// # Errors
61    ///
62    /// Returns [`WebhookError::InvalidSecret`] when the secret is empty.
63    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/// How a forge signs its push deliveries (spec 3.5 §7.8.2 "Files and git").
73///
74/// # Example
75///
76/// ```rust
77/// use adk_server::webhooks::{ForgeSecret, ForgeSignature};
78///
79/// let github = ForgeSignature::GitHub(ForgeSecret::new("It's a Secret to Everybody").unwrap());
80/// let body = b"Hello, World!";
81/// // GitHub's documented example of `X-Hub-Signature-256`.
82/// let signature = "sha256=757107ea0eb2509fc211221cce984b8a37570b6d7586c22c46f4379c8b043e17";
83/// let headers = [("x-hub-signature-256", signature), ("x-github-delivery", "72d3162e")];
84/// let lookup = |name: &str| headers.iter().find(|(n, _)| *n == name).map(|(_, v)| *v);
85/// assert_eq!(github.verify(lookup, body).unwrap().id, "72d3162e");
86/// assert!(github.verify(lookup, b"Hello, World?").is_err());
87/// ```
88#[derive(Clone, Debug)]
89pub enum ForgeSignature {
90    /// GitHub: `X-Hub-Signature-256`, HMAC-SHA256 of the raw body.
91    GitHub(ForgeSecret),
92    /// GitLab: `X-Gitlab-Token`, the secret token itself.
93    GitLab(ForgeSecret),
94}
95
96impl ForgeSignature {
97    /// The scheme's name: `github` or `gitlab`.
98    pub fn name(&self) -> &'static str {
99        match self {
100            Self::GitHub(_) => "github",
101            Self::GitLab(_) => "gitlab",
102        }
103    }
104
105    /// Checks a delivery's signature and returns its delivery id; the timestamp is the time
106    /// of receipt, since neither forge signs one.
107    ///
108    /// `lookup` returns a header's value by lowercase name; `body` is the raw request body.
109    ///
110    /// # Errors
111    ///
112    /// [`WebhookError::MissingHeader`] without the signature or delivery header,
113    /// [`WebhookError::MalformedHeader`] for a signature that is not `sha256=<hex>` or an
114    /// empty or oversized delivery id, and [`WebhookError::SignatureMismatch`] when the
115    /// signature or token does not match.
116    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                // HMAC accepts keys of any length, and `ForgeSecret::new` refuses an empty one.
134                let mut mac = Hmac::<Sha256>::new_from_slice(&secret.key)
135                    .map_err(|_| WebhookError::SignatureMismatch)?;
136                mac.update(body);
137                // `verify_slice` compares in constant time.
138                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
167/// Compares two secrets in constant time: their SHA-256 digests have one length, whatever
168/// the secrets' lengths, and every byte is compared.
169fn 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}