Skip to content
This repository has been archived by the owner on Sep 20, 2023. It is now read-only.

Add HMAC middleware #8

Draft
wants to merge 8 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
1 change: 1 addition & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -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;

Expand Down
38 changes: 38 additions & 0 deletions src/middlewares.rs
Original file line number Diff line number Diff line change
@@ -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<S> Middleware<S> for VerifySignature {
fn start(&self, req: &mut HttpRequest<S>) -> Result<Started> {
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::<Sha256>::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());

cedric-h marked this conversation as resolved.
Show resolved Hide resolved
mac.verify(body.as_bytes());
}
}