arks-server 1.3.5

Git server: upload-pack / receive-pack + smart/dumb HTTP + daemon (M11/M25)
Documentation
//! Opt-in BYO self-hosted GitHub App webhook module for `arks serve --github-app-config <path>`.
//!
//! Cite: `.spec/sot/github-app-integration.sot.md` ยง4.
//! - Disabled by default; fail-closed if enabled with missing webhook secret or private key.
//! - Constant-time `X-Hub-Signature-256` verification via `ring::hmac` + `subtle`.
//! - `X-GitHub-Delivery` deduplication and immediate `202 Accepted` async dispatch.

use crate::http::HttpResponse;
use ring::hmac;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::{HashSet, VecDeque};
use std::path::Path;
use std::sync::{Arc, Mutex};
use subtle::ConstantTimeEq as _;

pub const DEFAULT_WEBHOOK_PATH: &str = "/github-app/webhook";
const MAX_DELIVERY_CACHE: usize = 10_000;

/// Operator-supplied JSON configuration loaded via `arks serve --github-app-config <path>`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GithubAppWebhookConfig {
    pub app_id: String,
    #[serde(default)]
    pub webhook_secret: Option<String>,
    #[serde(default)]
    pub webhook_secret_env: Option<String>,
    pub private_key_file: String,
    #[serde(default = "default_webhook_path")]
    pub webhook_path: String,
    #[serde(default)]
    pub api_base: Option<String>,
}

fn default_webhook_path() -> String {
    DEFAULT_WEBHOOK_PATH.to_string()
}

/// Validated runtime configuration (fail-closed on missing secret or unreadable key).
#[derive(Clone)]
pub struct ValidatedGithubAppConfig {
    pub app_id: String,
    pub webhook_secret: String,
    pub private_key_file: String,
    pub webhook_path: String,
    pub api_base: Option<String>,
}

impl GithubAppWebhookConfig {
    /// Load and validate a JSON config file. Fails closed on missing secret or key file.
    pub fn load_from_path(path: &Path) -> Result<ValidatedGithubAppConfig, String> {
        let raw = std::fs::read_to_string(path)
            .map_err(|e| format!("read --github-app-config '{}': {e}", path.display()))?;
        let cfg: Self = serde_json::from_str(&raw)
            .map_err(|e| format!("parse --github-app-config '{}': {e}", path.display()))?;
        cfg.validate()
    }

    pub fn validate(self) -> Result<ValidatedGithubAppConfig, String> {
        if self.app_id.trim().is_empty() {
            return Err("github-app config: missing non-empty 'app_id'".into());
        }
        let secret = self
            .webhook_secret
            .filter(|s| !s.trim().is_empty())
            .or_else(|| {
                self.webhook_secret_env
                    .as_deref()
                    .and_then(|env_name| std::env::var(env_name).ok())
                    .filter(|s| !s.trim().is_empty())
            })
            .ok_or_else(|| {
                "github-app config: missing webhook_secret (or non-empty webhook_secret_env)"
                    .to_string()
            })?;
        if self.private_key_file.trim().is_empty() {
            return Err("github-app config: missing 'private_key_file'".into());
        }
        if !Path::new(&self.private_key_file).is_file() {
            return Err(format!(
                "github-app config: private_key_file '{}' does not exist",
                self.private_key_file
            ));
        }
        let webhook_path = if self.webhook_path.starts_with('/') {
            self.webhook_path
        } else {
            format!("/{}", self.webhook_path)
        };
        Ok(ValidatedGithubAppConfig {
            app_id: self.app_id.trim().to_string(),
            webhook_secret: secret,
            private_key_file: self.private_key_file,
            webhook_path,
            api_base: self.api_base,
        })
    }
}

/// Verified webhook event passed to the async background dispatcher.
#[derive(Debug, Clone)]
pub struct VerifiedWebhookEvent {
    pub delivery_id: String,
    pub event_name: String,
    pub payload: Value,
}

pub type AsyncEventHook = Arc<dyn Fn(VerifiedWebhookEvent) + Send + Sync>;

/// Shared runtime state attached to `ServeHttpOptions`.
pub struct GithubAppWebhookState {
    pub config: ValidatedGithubAppConfig,
    seen_order: Mutex<(VecDeque<String>, HashSet<String>)>,
    on_event: Option<AsyncEventHook>,
}

impl GithubAppWebhookState {
    pub fn new(config: ValidatedGithubAppConfig) -> Self {
        Self {
            config,
            seen_order: Mutex::new((VecDeque::new(), HashSet::new())),
            on_event: None,
        }
    }

    pub fn with_hook(config: ValidatedGithubAppConfig, hook: AsyncEventHook) -> Self {
        Self {
            config,
            seen_order: Mutex::new((VecDeque::new(), HashSet::new())),
            on_event: Some(hook),
        }
    }

    /// Returns `true` if `delivery_id` is new, `false` if already seen.
    fn record_delivery(&self, delivery_id: &str) -> bool {
        let Ok(mut guard) = self.seen_order.lock() else {
            return false;
        };
        let (order, set) = &mut *guard;
        if set.contains(delivery_id) {
            return false;
        }
        if order.len() >= MAX_DELIVERY_CACHE {
            if let Some(old) = order.pop_front() {
                set.remove(&old);
            }
        }
        order.push_back(delivery_id.to_string());
        set.insert(delivery_id.to_string());
        true
    }
}

/// Compute `sha256=<hex>` signature for `body` using HMAC-SHA256.
pub fn compute_signature_256(secret: &str, body: &[u8]) -> String {
    let key = hmac::Key::new(hmac::HMAC_SHA256, secret.as_bytes());
    let tag = hmac::sign(&key, body);
    let mut hex = String::with_capacity(7 + 64);
    hex.push_str("sha256=");
    for b in tag.as_ref() {
        hex.push_str(&format!("{b:02x}"));
    }
    hex
}

/// Constant-time verification of `X-Hub-Signature-256` via `ring::hmac` + `subtle`.
pub fn verify_signature_256(secret: &str, header_val: Option<&str>, body: &[u8]) -> bool {
    if secret.is_empty() {
        return false;
    }
    let Some(raw) = header_val else {
        return false;
    };
    let Some(hex_sig) = raw.trim().strip_prefix("sha256=") else {
        return false;
    };
    let Some(provided) = decode_hex_32(hex_sig.trim()) else {
        return false;
    };
    let key = hmac::Key::new(hmac::HMAC_SHA256, secret.as_bytes());
    let expected = hmac::sign(&key, body);
    bool::from(expected.as_ref().ct_eq(&provided))
}

fn decode_hex_32(hex: &str) -> Option<[u8; 32]> {
    if hex.len() != 64 {
        return None;
    }
    let bytes = hex.as_bytes();
    let mut out = [0u8; 32];
    for i in 0..32 {
        let hi = hex_nibble(bytes[2 * i])?;
        let lo = hex_nibble(bytes[2 * i + 1])?;
        out[i] = (hi << 4) | lo;
    }
    Some(out)
}

fn hex_nibble(b: u8) -> Option<u8> {
    match b {
        b'0'..=b'9' => Some(b - b'0'),
        b'a'..=b'f' => Some(b - b'a' + 10),
        b'A'..=b'F' => Some(b - b'A' + 10),
        _ => None,
    }
}

fn header_ci<'a>(headers: &'a [(String, String)], name: &str) -> Option<&'a str> {
    headers
        .iter()
        .find(|(k, _)| k.eq_ignore_ascii_case(name))
        .map(|(_, v)| v.as_str())
}

fn json_resp(status: u16, body: &str) -> HttpResponse {
    HttpResponse {
        status,
        content_type: "application/json; charset=utf-8".into(),
        body: body.as_bytes().to_vec(),
        www_authenticate: None,
        extra_headers: vec![("Cache-Control".into(), "no-store".into())],
    }
}

/// Handle an incoming GitHub App webhook request fail-closed and return `202 Accepted`
/// immediately while dispatching processing asynchronously.
pub fn handle_github_app_webhook(
    state: &Arc<GithubAppWebhookState>,
    method: &str,
    headers: &[(String, String)],
    body: &[u8],
) -> HttpResponse {
    if method != "POST" {
        return json_resp(405, r#"{"error":"method not allowed"}"#);
    }
    let delivery_id = header_ci(headers, "x-github-delivery")
        .map(str::trim)
        .unwrap_or("");
    let event_name = header_ci(headers, "x-github-event")
        .map(str::trim)
        .unwrap_or("");
    if delivery_id.is_empty() || event_name.is_empty() {
        return json_resp(
            400,
            r#"{"error":"missing X-GitHub-Delivery or X-GitHub-Event header"}"#,
        );
    }

    let sig = header_ci(headers, "x-hub-signature-256");
    if !verify_signature_256(&state.config.webhook_secret, sig, body) {
        return json_resp(401, r#"{"error":"invalid webhook signature"}"#);
    }

    let payload: Value = match serde_json::from_slice(body) {
        Ok(v) => v,
        Err(_) => return json_resp(400, r#"{"error":"invalid JSON payload"}"#),
    };

    if !state.record_delivery(delivery_id) {
        return json_resp(
            202,
            &serde_json::json!({"status": "duplicate", "delivery_id": delivery_id}).to_string(),
        );
    }

    if let Some(hook) = state.on_event.clone() {
        let evt = VerifiedWebhookEvent {
            delivery_id: delivery_id.to_string(),
            event_name: event_name.to_string(),
            payload,
        };
        let _ = std::thread::Builder::new()
            .name("arks-gh-webhook".into())
            .spawn(move || hook(evt));
    }

    json_resp(
        202,
        &serde_json::json!({
            "status": "accepted",
            "delivery_id": delivery_id,
            "event": event_name
        })
        .to_string(),
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::mpsc;
    use std::time::Duration;

    fn test_state(hook: Option<AsyncEventHook>) -> Arc<GithubAppWebhookState> {
        let cfg = ValidatedGithubAppConfig {
            app_id: "12345".into(),
            webhook_secret: "whsec_unit_test".into(),
            private_key_file: "/dev/null".into(),
            webhook_path: DEFAULT_WEBHOOK_PATH.into(),
            api_base: None,
        };
        Arc::new(match hook {
            Some(h) => GithubAppWebhookState::with_hook(cfg, h),
            None => GithubAppWebhookState::new(cfg),
        })
    }

    #[test]
    fn config_validation_fails_closed_on_missing_secret_or_key() {
        let bad = GithubAppWebhookConfig {
            app_id: "1".into(),
            webhook_secret: None,
            webhook_secret_env: None,
            private_key_file: "/nonexistent/key.pem".into(),
            webhook_path: DEFAULT_WEBHOOK_PATH.into(),
            api_base: None,
        };
        assert!(bad.validate().is_err());

        let bad_key = GithubAppWebhookConfig {
            app_id: "1".into(),
            webhook_secret: Some("sec".into()),
            webhook_secret_env: None,
            private_key_file: "/nonexistent/key.pem".into(),
            webhook_path: DEFAULT_WEBHOOK_PATH.into(),
            api_base: None,
        };
        assert!(bad_key.validate().is_err());
    }

    #[test]
    fn webhook_verifies_hmac_rejects_tampered_and_deduplicates_async() {
        let (tx, rx) = mpsc::channel();
        let state = test_state(Some(Arc::new(move |evt| {
            let _ = tx.send(evt.delivery_id);
        })));

        let body = br#"{"action":"opened","number":7}"#;
        let good_sig = compute_signature_256("whsec_unit_test", body);
        let headers = vec![
            ("X-GitHub-Delivery".into(), "deliv-42".into()),
            ("X-GitHub-Event".into(), "pull_request".into()),
            ("X-Hub-Signature-256".into(), good_sig.clone()),
        ];

        // 1. Valid request -> 202 Accepted and async hook fires once.
        let r1 = handle_github_app_webhook(&state, "POST", &headers, body);
        assert_eq!(r1.status, 202);
        assert_eq!(rx.recv_timeout(Duration::from_secs(2)).unwrap(), "deliv-42");

        // 2. Duplicate delivery -> 202 Accepted, hook does NOT fire again.
        let r2 = handle_github_app_webhook(&state, "POST", &headers, body);
        assert_eq!(r2.status, 202);
        assert!(String::from_utf8_lossy(&r2.body).contains("duplicate"));
        assert!(rx.recv_timeout(Duration::from_millis(100)).is_err());

        // 3. Tampered signature -> 401 fail-closed.
        let bad_headers = vec![
            ("X-GitHub-Delivery".into(), "deliv-43".into()),
            ("X-GitHub-Event".into(), "pull_request".into()),
            (
                "X-Hub-Signature-256".into(),
                format!("sha256={}", "00".repeat(32)),
            ),
        ];
        let r3 = handle_github_app_webhook(&state, "POST", &bad_headers, body);
        assert_eq!(r3.status, 401);
    }
}