1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
//! A library to secure [GitHub Webhooks][github-webhooks] and extract JSON
//! event payloads in [Axum][axum].
//!
//! The library is an [Extractor][axum-extractor] paired with
//! [State][axum-state] to provide the required [Secret
//! Token][github-secret-token].
//!
//! Usage looks like:
//! ```
//! # use axum::response::IntoResponse;
//! # use axum::routing::post;
//! # use axum::Router;
//! # use serde::Deserialize;
//! # use std::sync::Arc;
//! use axum_github_webhook_extract::{GithubToken, GithubEvent};
//!
//! #[derive(Debug, Deserialize)]
//! struct Event {
//!     action: String,
//! }
//!
//! async fn echo(GithubEvent(e): GithubEvent<Event>) -> impl IntoResponse {
//!     e.action
//! }
//!
//! fn app() -> Router {
//!     let token = String::from("d4705034dd0777ee9e1e3078a12a06985151b76f");
//!     Router::new()
//!         .route("/", post(echo))
//!         .with_state(GithubToken(Arc::new(token)))
//! }
//! ```
//!
//! You will usually get the token from your environment or configuration.
//! The event payload is under your control, just make sure to configure it to
//! use [JSON][github-json].
//!
//! [github-webhooks]: https://docs.github.com/en/webhooks-and-events/webhooks/securing-your-webhooks
//! [axum]: https://docs.rs/axum/latest/axum/
//! [axum-extractor]: https://docs.rs/axum/latest/axum/#extractors
//! [axum-state]: https://docs.rs/axum/latest/axum/#sharing-state-with-handlers
//! [github-secret-token]: https://docs.github.com/en/webhooks-and-events/webhooks/securing-your-webhooks#setting-your-secret-token
//! [github-json]: https://docs.github.com/en/webhooks-and-events/webhooks/creating-webhooks#content-type

use axum::body::{Bytes, HttpBody};
use axum::extract::{FromRef, FromRequest};
use axum::http::{Request, StatusCode};
use axum::{async_trait, BoxError};
use hmac_sha256::HMAC;
use serde::de::DeserializeOwned;
use std::fmt::Display;
use std::sync::Arc;
use subtle::ConstantTimeEq;

/// State to provide the Github Token to verify Event signature.
#[derive(Debug, Clone)]
pub struct GithubToken(pub Arc<String>);

/// Verify and extract Github Event Payload.
#[derive(Debug, Clone, Copy, Default)]
#[must_use]
pub struct GithubEvent<T>(pub T);

fn err(m: impl Display) -> (StatusCode, String) {
    (StatusCode::BAD_REQUEST, m.to_string())
}

#[async_trait]
impl<T, S, B> FromRequest<S, B> for GithubEvent<T>
where
    GithubToken: FromRef<S>,
    T: DeserializeOwned,
    B: HttpBody + Send + 'static,
    B::Data: Send,
    B::Error: Into<BoxError>,
    S: Send + Sync,
{
    type Rejection = (StatusCode, String);

    async fn from_request(req: Request<B>, state: &S) -> Result<Self, Self::Rejection> {
        let token = GithubToken::from_ref(state);
        let signature_sha256 = req
            .headers()
            .get("X-Hub-Signature-256")
            .and_then(|v| v.to_str().ok())
            .ok_or(err("signature missing"))?
            .strip_prefix("sha256=")
            .ok_or(err("signature prefix missing"))?;
        let signature = hex::decode(signature_sha256).map_err(|_| err("signature malformed"))?;
        let body = Bytes::from_request(req, state)
            .await
            .map_err(|_| err("error reading body"))?;
        let mac = HMAC::mac(&body, token.0.as_bytes());
        if mac.ct_ne(&signature).into() {
            return Err(err("signature mismatch"));
        }

        let deserializer = &mut serde_json::Deserializer::from_slice(&body);
        let value = serde_path_to_error::deserialize(deserializer).map_err(err)?;
        Ok(GithubEvent(value))
    }
}

#[cfg(test)]
mod tests {
    use axum::body::{Body, BoxBody};
    use axum::http::{Request, StatusCode};
    use axum::response::IntoResponse;
    use axum::routing::post;
    use axum::Router;
    use serde::Deserialize;
    use std::sync::Arc;
    use tower::ServiceExt;

    use super::{GithubEvent, GithubToken};

    #[derive(Debug, Deserialize)]
    struct Event {
        action: String,
    }

    async fn echo(GithubEvent(e): GithubEvent<Event>) -> impl IntoResponse {
        e.action
    }

    fn app() -> Router {
        Router::new()
            .route("/", post(echo))
            .with_state(GithubToken(Arc::new(String::from("42"))))
    }

    async fn body_string(body: BoxBody) -> String {
        let bytes = hyper::body::to_bytes(body).await.unwrap();
        String::from_utf8_lossy(&bytes).into()
    }

    fn with_header(v: &'static str) -> Request<Body> {
        Request::builder()
            .method("POST")
            .header("X-Hub-Signature-256", v)
            .body(Body::empty())
            .unwrap()
    }

    #[tokio::test]
    async fn signature_missing() {
        let req = Request::builder()
            .method("POST")
            .body(Body::empty())
            .unwrap();
        let res = app().oneshot(req).await.unwrap();
        assert_eq!(res.status(), StatusCode::BAD_REQUEST);
        assert_eq!(body_string(res.into_body()).await, "signature missing");
    }

    #[tokio::test]
    async fn signature_prefix_missing() {
        let res = app().oneshot(with_header("x")).await.unwrap();
        assert_eq!(res.status(), StatusCode::BAD_REQUEST);
        assert_eq!(
            body_string(res.into_body()).await,
            "signature prefix missing"
        );
    }

    #[tokio::test]
    async fn signature_malformed() {
        let res = app().oneshot(with_header("sha256=x")).await.unwrap();
        assert_eq!(res.status(), StatusCode::BAD_REQUEST);
        assert_eq!(body_string(res.into_body()).await, "signature malformed");
    }

    #[tokio::test]
    async fn signature_mismatch() {
        let res = app().oneshot(with_header("sha256=01")).await.unwrap();
        assert_eq!(res.status(), StatusCode::BAD_REQUEST);
        assert_eq!(body_string(res.into_body()).await, "signature mismatch");
    }

    #[tokio::test]
    async fn signature_valid() {
        let req = Request::builder()
            .method("POST")
            .header(
                "X-Hub-Signature-256",
                "sha256=8b99afd7996c3e3c291a0b54399bacb72016bdb088071de42d1d7156a6a4273d",
            )
            .body(r#"{"action":"hello world"}"#.into())
            .unwrap();
        let res = app().oneshot(req).await.unwrap();
        assert_eq!(res.status(), StatusCode::OK);
        assert_eq!(body_string(res.into_body()).await, "hello world");
    }
}