Skip to main content

arks_server/
github_app_webhook.rs

1//! Opt-in BYO self-hosted GitHub App webhook module for `arks serve --github-app-config <path>`.
2//!
3//! Cite: `.spec/sot/github-app-integration.sot.md` ยง4.
4//! - Disabled by default; fail-closed if enabled with missing webhook secret or private key.
5//! - Constant-time `X-Hub-Signature-256` verification via `ring::hmac` + `subtle`.
6//! - `X-GitHub-Delivery` deduplication and immediate `202 Accepted` async dispatch.
7
8use crate::http::HttpResponse;
9use ring::hmac;
10use serde::{Deserialize, Serialize};
11use serde_json::Value;
12use std::collections::{HashSet, VecDeque};
13use std::path::Path;
14use std::sync::{Arc, Mutex};
15use subtle::ConstantTimeEq as _;
16
17pub const DEFAULT_WEBHOOK_PATH: &str = "/github-app/webhook";
18const MAX_DELIVERY_CACHE: usize = 10_000;
19
20/// Operator-supplied JSON configuration loaded via `arks serve --github-app-config <path>`.
21#[derive(Debug, Clone, Serialize, Deserialize)]
22pub struct GithubAppWebhookConfig {
23    pub app_id: String,
24    #[serde(default)]
25    pub webhook_secret: Option<String>,
26    #[serde(default)]
27    pub webhook_secret_env: Option<String>,
28    pub private_key_file: String,
29    #[serde(default = "default_webhook_path")]
30    pub webhook_path: String,
31    #[serde(default)]
32    pub api_base: Option<String>,
33}
34
35fn default_webhook_path() -> String {
36    DEFAULT_WEBHOOK_PATH.to_string()
37}
38
39/// Validated runtime configuration (fail-closed on missing secret or unreadable key).
40#[derive(Clone)]
41pub struct ValidatedGithubAppConfig {
42    pub app_id: String,
43    pub webhook_secret: String,
44    pub private_key_file: String,
45    pub webhook_path: String,
46    pub api_base: Option<String>,
47}
48
49impl GithubAppWebhookConfig {
50    /// Load and validate a JSON config file. Fails closed on missing secret or key file.
51    pub fn load_from_path(path: &Path) -> Result<ValidatedGithubAppConfig, String> {
52        let raw = std::fs::read_to_string(path)
53            .map_err(|e| format!("read --github-app-config '{}': {e}", path.display()))?;
54        let cfg: Self = serde_json::from_str(&raw)
55            .map_err(|e| format!("parse --github-app-config '{}': {e}", path.display()))?;
56        cfg.validate()
57    }
58
59    pub fn validate(self) -> Result<ValidatedGithubAppConfig, String> {
60        if self.app_id.trim().is_empty() {
61            return Err("github-app config: missing non-empty 'app_id'".into());
62        }
63        let secret = self
64            .webhook_secret
65            .filter(|s| !s.trim().is_empty())
66            .or_else(|| {
67                self.webhook_secret_env
68                    .as_deref()
69                    .and_then(|env_name| std::env::var(env_name).ok())
70                    .filter(|s| !s.trim().is_empty())
71            })
72            .ok_or_else(|| {
73                "github-app config: missing webhook_secret (or non-empty webhook_secret_env)"
74                    .to_string()
75            })?;
76        if self.private_key_file.trim().is_empty() {
77            return Err("github-app config: missing 'private_key_file'".into());
78        }
79        if !Path::new(&self.private_key_file).is_file() {
80            return Err(format!(
81                "github-app config: private_key_file '{}' does not exist",
82                self.private_key_file
83            ));
84        }
85        let webhook_path = if self.webhook_path.starts_with('/') {
86            self.webhook_path
87        } else {
88            format!("/{}", self.webhook_path)
89        };
90        Ok(ValidatedGithubAppConfig {
91            app_id: self.app_id.trim().to_string(),
92            webhook_secret: secret,
93            private_key_file: self.private_key_file,
94            webhook_path,
95            api_base: self.api_base,
96        })
97    }
98}
99
100/// Verified webhook event passed to the async background dispatcher.
101#[derive(Debug, Clone)]
102pub struct VerifiedWebhookEvent {
103    pub delivery_id: String,
104    pub event_name: String,
105    pub payload: Value,
106}
107
108pub type AsyncEventHook = Arc<dyn Fn(VerifiedWebhookEvent) + Send + Sync>;
109
110/// Shared runtime state attached to `ServeHttpOptions`.
111pub struct GithubAppWebhookState {
112    pub config: ValidatedGithubAppConfig,
113    seen_order: Mutex<(VecDeque<String>, HashSet<String>)>,
114    on_event: Option<AsyncEventHook>,
115}
116
117impl GithubAppWebhookState {
118    pub fn new(config: ValidatedGithubAppConfig) -> Self {
119        Self {
120            config,
121            seen_order: Mutex::new((VecDeque::new(), HashSet::new())),
122            on_event: None,
123        }
124    }
125
126    pub fn with_hook(config: ValidatedGithubAppConfig, hook: AsyncEventHook) -> Self {
127        Self {
128            config,
129            seen_order: Mutex::new((VecDeque::new(), HashSet::new())),
130            on_event: Some(hook),
131        }
132    }
133
134    /// Returns `true` if `delivery_id` is new, `false` if already seen.
135    fn record_delivery(&self, delivery_id: &str) -> bool {
136        let Ok(mut guard) = self.seen_order.lock() else {
137            return false;
138        };
139        let (order, set) = &mut *guard;
140        if set.contains(delivery_id) {
141            return false;
142        }
143        if order.len() >= MAX_DELIVERY_CACHE {
144            if let Some(old) = order.pop_front() {
145                set.remove(&old);
146            }
147        }
148        order.push_back(delivery_id.to_string());
149        set.insert(delivery_id.to_string());
150        true
151    }
152}
153
154/// Compute `sha256=<hex>` signature for `body` using HMAC-SHA256.
155pub fn compute_signature_256(secret: &str, body: &[u8]) -> String {
156    let key = hmac::Key::new(hmac::HMAC_SHA256, secret.as_bytes());
157    let tag = hmac::sign(&key, body);
158    let mut hex = String::with_capacity(7 + 64);
159    hex.push_str("sha256=");
160    for b in tag.as_ref() {
161        hex.push_str(&format!("{b:02x}"));
162    }
163    hex
164}
165
166/// Constant-time verification of `X-Hub-Signature-256` via `ring::hmac` + `subtle`.
167pub fn verify_signature_256(secret: &str, header_val: Option<&str>, body: &[u8]) -> bool {
168    if secret.is_empty() {
169        return false;
170    }
171    let Some(raw) = header_val else {
172        return false;
173    };
174    let Some(hex_sig) = raw.trim().strip_prefix("sha256=") else {
175        return false;
176    };
177    let Some(provided) = decode_hex_32(hex_sig.trim()) else {
178        return false;
179    };
180    let key = hmac::Key::new(hmac::HMAC_SHA256, secret.as_bytes());
181    let expected = hmac::sign(&key, body);
182    bool::from(expected.as_ref().ct_eq(&provided))
183}
184
185fn decode_hex_32(hex: &str) -> Option<[u8; 32]> {
186    if hex.len() != 64 {
187        return None;
188    }
189    let bytes = hex.as_bytes();
190    let mut out = [0u8; 32];
191    for i in 0..32 {
192        let hi = hex_nibble(bytes[2 * i])?;
193        let lo = hex_nibble(bytes[2 * i + 1])?;
194        out[i] = (hi << 4) | lo;
195    }
196    Some(out)
197}
198
199fn hex_nibble(b: u8) -> Option<u8> {
200    match b {
201        b'0'..=b'9' => Some(b - b'0'),
202        b'a'..=b'f' => Some(b - b'a' + 10),
203        b'A'..=b'F' => Some(b - b'A' + 10),
204        _ => None,
205    }
206}
207
208fn header_ci<'a>(headers: &'a [(String, String)], name: &str) -> Option<&'a str> {
209    headers
210        .iter()
211        .find(|(k, _)| k.eq_ignore_ascii_case(name))
212        .map(|(_, v)| v.as_str())
213}
214
215fn json_resp(status: u16, body: &str) -> HttpResponse {
216    HttpResponse {
217        status,
218        content_type: "application/json; charset=utf-8".into(),
219        body: body.as_bytes().to_vec(),
220        www_authenticate: None,
221        extra_headers: vec![("Cache-Control".into(), "no-store".into())],
222    }
223}
224
225/// Handle an incoming GitHub App webhook request fail-closed and return `202 Accepted`
226/// immediately while dispatching processing asynchronously.
227pub fn handle_github_app_webhook(
228    state: &Arc<GithubAppWebhookState>,
229    method: &str,
230    headers: &[(String, String)],
231    body: &[u8],
232) -> HttpResponse {
233    if method != "POST" {
234        return json_resp(405, r#"{"error":"method not allowed"}"#);
235    }
236    let delivery_id = header_ci(headers, "x-github-delivery")
237        .map(str::trim)
238        .unwrap_or("");
239    let event_name = header_ci(headers, "x-github-event")
240        .map(str::trim)
241        .unwrap_or("");
242    if delivery_id.is_empty() || event_name.is_empty() {
243        return json_resp(
244            400,
245            r#"{"error":"missing X-GitHub-Delivery or X-GitHub-Event header"}"#,
246        );
247    }
248
249    let sig = header_ci(headers, "x-hub-signature-256");
250    if !verify_signature_256(&state.config.webhook_secret, sig, body) {
251        return json_resp(401, r#"{"error":"invalid webhook signature"}"#);
252    }
253
254    let payload: Value = match serde_json::from_slice(body) {
255        Ok(v) => v,
256        Err(_) => return json_resp(400, r#"{"error":"invalid JSON payload"}"#),
257    };
258
259    if !state.record_delivery(delivery_id) {
260        return json_resp(
261            202,
262            &serde_json::json!({"status": "duplicate", "delivery_id": delivery_id}).to_string(),
263        );
264    }
265
266    if let Some(hook) = state.on_event.clone() {
267        let evt = VerifiedWebhookEvent {
268            delivery_id: delivery_id.to_string(),
269            event_name: event_name.to_string(),
270            payload,
271        };
272        let _ = std::thread::Builder::new()
273            .name("arks-gh-webhook".into())
274            .spawn(move || hook(evt));
275    }
276
277    json_resp(
278        202,
279        &serde_json::json!({
280            "status": "accepted",
281            "delivery_id": delivery_id,
282            "event": event_name
283        })
284        .to_string(),
285    )
286}
287
288#[cfg(test)]
289mod tests {
290    use super::*;
291    use std::sync::mpsc;
292    use std::time::Duration;
293
294    fn test_state(hook: Option<AsyncEventHook>) -> Arc<GithubAppWebhookState> {
295        let cfg = ValidatedGithubAppConfig {
296            app_id: "12345".into(),
297            webhook_secret: "whsec_unit_test".into(),
298            private_key_file: "/dev/null".into(),
299            webhook_path: DEFAULT_WEBHOOK_PATH.into(),
300            api_base: None,
301        };
302        Arc::new(match hook {
303            Some(h) => GithubAppWebhookState::with_hook(cfg, h),
304            None => GithubAppWebhookState::new(cfg),
305        })
306    }
307
308    #[test]
309    fn config_validation_fails_closed_on_missing_secret_or_key() {
310        let bad = GithubAppWebhookConfig {
311            app_id: "1".into(),
312            webhook_secret: None,
313            webhook_secret_env: None,
314            private_key_file: "/nonexistent/key.pem".into(),
315            webhook_path: DEFAULT_WEBHOOK_PATH.into(),
316            api_base: None,
317        };
318        assert!(bad.validate().is_err());
319
320        let bad_key = GithubAppWebhookConfig {
321            app_id: "1".into(),
322            webhook_secret: Some("sec".into()),
323            webhook_secret_env: None,
324            private_key_file: "/nonexistent/key.pem".into(),
325            webhook_path: DEFAULT_WEBHOOK_PATH.into(),
326            api_base: None,
327        };
328        assert!(bad_key.validate().is_err());
329    }
330
331    #[test]
332    fn webhook_verifies_hmac_rejects_tampered_and_deduplicates_async() {
333        let (tx, rx) = mpsc::channel();
334        let state = test_state(Some(Arc::new(move |evt| {
335            let _ = tx.send(evt.delivery_id);
336        })));
337
338        let body = br#"{"action":"opened","number":7}"#;
339        let good_sig = compute_signature_256("whsec_unit_test", body);
340        let headers = vec![
341            ("X-GitHub-Delivery".into(), "deliv-42".into()),
342            ("X-GitHub-Event".into(), "pull_request".into()),
343            ("X-Hub-Signature-256".into(), good_sig.clone()),
344        ];
345
346        // 1. Valid request -> 202 Accepted and async hook fires once.
347        let r1 = handle_github_app_webhook(&state, "POST", &headers, body);
348        assert_eq!(r1.status, 202);
349        assert_eq!(rx.recv_timeout(Duration::from_secs(2)).unwrap(), "deliv-42");
350
351        // 2. Duplicate delivery -> 202 Accepted, hook does NOT fire again.
352        let r2 = handle_github_app_webhook(&state, "POST", &headers, body);
353        assert_eq!(r2.status, 202);
354        assert!(String::from_utf8_lossy(&r2.body).contains("duplicate"));
355        assert!(rx.recv_timeout(Duration::from_millis(100)).is_err());
356
357        // 3. Tampered signature -> 401 fail-closed.
358        let bad_headers = vec![
359            ("X-GitHub-Delivery".into(), "deliv-43".into()),
360            ("X-GitHub-Event".into(), "pull_request".into()),
361            (
362                "X-Hub-Signature-256".into(),
363                format!("sha256={}", "00".repeat(32)),
364            ),
365        ];
366        let r3 = handle_github_app_webhook(&state, "POST", &bad_headers, body);
367        assert_eq!(r3.status, 401);
368    }
369}