+ Computing encoding key once in a lazy_static

+ unit test verifying is extremely sus.jpg but it looks like it passes
! bs detectors on max rn so i'll keep this under close watch for now
This commit is contained in:
shockrah 2020-12-29 23:57:11 -08:00
parent 477be1fd3f
commit ab12283507

View File

@ -8,9 +8,14 @@ use crate::routes;
use db::{member::Member, common::FromDB}; use db::{member::Member, common::FromDB};
use db::Response; use db::Response;
use jsonwebtoken::EncodingKey;
lazy_static! { lazy_static! {
static ref HMAC_SECRET: String = { static ref HMAC_SECRET: Vec<u8> = {
std::fs::read_to_string("hmac.secret").expect("Couldn't get HMAC secret") std::fs::read("hmac.secret").expect("Couldn't get HMAC secret")
};
static ref ENCODING_KEY: EncodingKey = {
EncodingKey::from_secret(&HMAC_SECRET)
}; };
} }
@ -88,7 +93,7 @@ pub fn generate_secret() -> String {
} }
pub fn generate_cookie() -> String { pub fn generate_cookie() -> String {
return rng_secret(32) return rng_secret(32)
} }
pub fn encrypt_secret(raw: &str) -> BcryptResult<String> { pub fn encrypt_secret(raw: &str) -> BcryptResult<String> {
@ -109,7 +114,7 @@ async fn valid_jwt(p: &Pool, token: &str) -> AuthReason {
}; };
// crypto things that should prolly not fail assuming we're configured correctly // crypto things that should prolly not fail assuming we're configured correctly
let algo = Algorithm::HS512; let algo = Algorithm::HS512;
let dk = DecodingKey::from_base64_secret(&HMAC_SECRET).unwrap(); let dk = DecodingKey::from_secret(&HMAC_SECRET);
if let Ok(decoded) = decode::<Claim>(token, &dk, &Validation::new(algo)) { if let Ok(decoded) = decode::<Claim>(token, &dk, &Validation::new(algo)) {
// subject used for querying speed NOT security // subject used for querying speed NOT security
@ -189,7 +194,7 @@ pub async fn login_get_jwt(p: &Pool, response: &mut hyper::Response<hyper::Body>
// in the json response // in the json response
use jsonwebtoken::{ use jsonwebtoken::{
Header, Algorithm, Header, Algorithm,
encode, EncodingKey encode
}; };
use hyper::header::HeaderValue; use hyper::header::HeaderValue;
let id = params.get("id").unwrap().as_u64().unwrap(); // only route where we have the "id is there guarantee" let id = params.get("id").unwrap().as_u64().unwrap(); // only route where we have the "id is there guarantee"
@ -198,10 +203,9 @@ pub async fn login_get_jwt(p: &Pool, response: &mut hyper::Response<hyper::Body>
let encoded = encode( let encoded = encode(
&header, &header,
&claim, &claim,
&EncodingKey::from_base64_secret(HMAC_SECRET.as_ref()).expect("Couldn't encode from secret")) &ENCODING_KEY).unwrap();
.expect("Could not encode JWT");
match db::auth::add_jwt(p, id, encoded.as_ref()).await { match db::auth::add_jwt(p, id, &encoded).await {
Ok(_) => { Ok(_) => {
response.headers_mut().insert("Content-Type", response.headers_mut().insert("Content-Type",
HeaderValue::from_static("application/json")); HeaderValue::from_static("application/json"));
@ -221,6 +225,9 @@ pub async fn login_get_jwt(p: &Pool, response: &mut hyper::Response<hyper::Body>
#[cfg(test)] #[cfg(test)]
mod auth_tests { mod auth_tests {
use jsonwebtoken::{
Header, encode, Algorithm
};
#[test] #[test]
fn validity_check() { fn validity_check() {
use bcrypt::{hash, DEFAULT_COST}; use bcrypt::{hash, DEFAULT_COST};
@ -230,4 +237,39 @@ mod auth_tests {
Err(err) => panic!("{}", err) Err(err) => panic!("{}", err)
} }
} }
#[test]
fn verify_jwt() {
let claim = super::Claim::new(123); // example claim that we send out
let header = Header::new(Algorithm::HS512); // header that basically all clients get
let encoded = encode(
&header,
&claim,
&super::ENCODING_KEY).unwrap();
use jsonwebtoken::{decode, DecodingKey, Validation};
let dc = decode::<super::Claim>(
&encoded,
&DecodingKey::from_secret(&super::HMAC_SECRET),
&Validation::new(Algorithm::HS512)
); // decoding works yet fails on the debugger
assert_eq!(dc.is_ok(), true);
println!("{:?}", dc);
println!("{}", encoded);
let mut parts:Vec<String> = Vec::new();
for i in encoded.split('.') {
parts.push(i.to_string());
}
let head = &parts[0];
let claim = &parts[1];
let sig = &parts[2];
let res = jsonwebtoken::crypto::verify(
sig,
&format!("{}.{}", head, claim),
&DecodingKey::from_secret(&super::HMAC_SECRET),
Algorithm::HS512);
println!("{:?}", res);
}
} }