diff --git a/Cargo.toml b/Cargo.toml index 8cb0bbf..1ccd0da 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,3 +14,6 @@ bson = "1.0" serde = { version = "1.0", features = ["derive"]} uuid = { version = "0.8.1", features = ["v4", "serde"] } mongodb = "1.0" +hmac = "0.8.1" +hcor = { git="https://github.com/hackagotchi/hcor" } +sha2 = "0.9.1" diff --git a/src/main.rs b/src/main.rs index 0f75e55..e04d591 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,7 @@ use actix_web::{get, web, App, HttpRequest, HttpResponse, HttpServer}; pub mod data; +pub mod middlewares; pub mod models; pub mod routes; diff --git a/src/middlewares.rs b/src/middlewares.rs new file mode 100644 index 0000000..31d6e9c --- /dev/null +++ b/src/middlewares.rs @@ -0,0 +1,38 @@ +use actix_web::{middleware::{Middleware, Started}, HttpRequest, Result}; +use hcor::errors::ServiceError; +use std::env; + +use hmac::{Hmac, Mac, NewMac}; +use sha2::Sha256; + +pub struct VerifySignature; + +impl Middleware for VerifySignature { + fn start(&self, req: &mut HttpRequest) -> Result { + use std::io::Read; + + let r = req.clone(); + let s = r + .headers() + .get("X-Signature") + .ok_or(ServiceError::Unauthorized)? + .to_str() + .map_err(ServiceError::Unauthorized)?; + + let (_, sig) = s.split_at(5); + + let mut mac = Hmac::::new_varkey( + env::var("SECERT_KEY") + .expect("set SECRET_KEY environment variable") + .as_bytes(), + ); + + let mut body = String::new(); + req.read_to_string(&mut body) + .map_err(ServiceError::InternalServerError)?; + + mac.update(sig.as_bytes()); + + mac.verify(body.as_bytes()); + } +}