feat: #11 impl config (#9) + set JWT with asymmetric signatures

This commit is contained in:
2022-10-12 14:51:24 +00:00
parent 72d1fba8f4
commit 55d524ea1b
7 changed files with 404 additions and 67 deletions
+1 -1
View File
@@ -6,4 +6,4 @@ pub mod router;
pub use request::HTTPRequest;
pub use response::{HTTPResponse, HTTPStatusCode};
pub use router::ROUTER;
pub use router::{Config, ROUTER};
+1
View File
@@ -206,6 +206,7 @@ impl HTTPRequest {
}
}
#[allow(dead_code)]
pub fn is_valid(&self) -> bool {
return self.start_line.is_valid();
}
+1
View File
@@ -53,6 +53,7 @@ impl HTTPStatusLine {
self.status_code = code;
}
#[allow(dead_code)]
pub fn get_status_code(&self) -> HTTPStatusCode {
self.status_code.clone()
}
+169 -18
View File
@@ -1,25 +1,109 @@
//! router aims to handle correctly the request corresponding to the target
//! it implements all the logic to build an `HTTPResponse`
use super::{HTTPRequest, HTTPResponse, HTTPStatusCode};
use super::{HTTPRequest, HTTPResponse};
use crate::stores::FileStore;
use crate::stores::Store;
use configparser::ini::Ini;
use jwt_simple::prelude::*;
use lazy_static::lazy_static;
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
const JWT_EXPIRATION_TIME: u64 = 2;
const ISSUER: &'static str = "thegux.fr";
use std::str::FromStr;
type FuturePinned<HTTPResponse> = Pin<Box<dyn Future<Output = HTTPResponse>>>;
type Handler = fn(HTTPRequest) -> FuturePinned<HTTPResponse>;
type Handler = fn(HTTPRequest, Config) -> FuturePinned<HTTPResponse>;
fn handle_get(request: HTTPRequest) -> FuturePinned<HTTPResponse> {
#[derive(Clone)]
pub struct Config {
jwt_exp_time: u64,
jwt_issuer: String,
jwt_priv_key: String,
jwt_pub_key: String,
filestore_path: String,
}
impl Default for Config {
fn default() -> Self {
Config {
jwt_exp_time: 0,
jwt_issuer: "".to_string(),
jwt_priv_key: "".to_string(),
jwt_pub_key: "".to_string(),
filestore_path: "".to_string(),
}
}
}
impl TryFrom<Ini> for Config {
type Error = String;
fn try_from(config: Ini) -> Result<Self, Self::Error> {
let exp_time = config
.get("jwt", "expiration_time")
.unwrap_or("".to_string());
let jwt_exp_time = {
match u64::from_str(&exp_time) {
Ok(v) => v,
Err(e) => {
eprintln!("unable to convert JWT expiration time into u64 err={}", e);
0
}
}
};
let config = Config {
jwt_exp_time,
jwt_issuer: config.get("jwt", "issuer").unwrap_or("".to_string()),
jwt_pub_key: config.get("jwt", "public_key").unwrap_or("".to_string()),
jwt_priv_key: config.get("jwt", "private_key").unwrap_or("".to_string()),
filestore_path: config.get("store", "path").unwrap_or("".to_string()),
};
if !config.validate() {
return Err("ini file configuration validation failed".to_string());
}
Ok(config)
}
}
impl Config {
/// validates config ini file
fn validate(&self) -> bool {
if self.jwt_exp_time <= 0 {
eprintln!("invalid config parameter: JWT expiration time is negative or equals to 0");
return false;
}
if self.jwt_issuer == "" {
eprintln!("invalid config parameter: JWT issuer is empty");
return false;
}
// TODO: check if the file exists and rights are ok
if self.jwt_pub_key == "" {
eprintln!("invalid config parameter: JWT public key file path is empty");
return false;
}
// TODO: check if the file exists and rights are ok
if self.jwt_priv_key == "" {
eprintln!("invalid config parameter: JWT private key file path is empty");
return false;
}
if self.filestore_path == "" {
eprintln!("invalid config parameter: filestore path is empty");
return false;
}
true
}
}
fn handle_get(request: HTTPRequest, config: Config) -> FuturePinned<HTTPResponse> {
Box::pin(async move {
// TODO: path to `store.txt` must not be hardcoded, should be in a config file and load at runtime
let mut store = FileStore::new("tests/data/store.txt".to_string());
let mut store = FileStore::new(config.filestore_path);
match &request.body {
Some(ref b) => {
let is_auth = store.is_auth(&b.get_data()).await;
@@ -27,13 +111,35 @@ fn handle_get(request: HTTPRequest) -> FuturePinned<HTTPResponse> {
return HTTPResponse::as_403();
}
let mut claims = Claims::create(Duration::from_hours(JWT_EXPIRATION_TIME));
claims.issuer = Some(ISSUER.to_string());
let priv_key_content = {
match std::fs::read_to_string(config.jwt_priv_key) {
Ok(c) => c,
Err(e) => {
eprintln!("error while reading JWT priv key content err={}", e);
"".to_string()
}
}
};
let jwt_key = {
match RS384KeyPair::from_pem(priv_key_content.as_str()) {
Ok(k) => k,
// TODO: set error in the message body
Err(e) => {
eprintln!("error occurred while getting private key err={}", e);
return HTTPResponse::as_500();
}
}
};
let mut claims = Claims::create(Duration::from_hours(config.jwt_exp_time));
claims.issuer = Some(config.jwt_issuer);
match JWT_KEY.authenticate(claims) {
match jwt_key.sign(claims) {
Ok(token) => HTTPResponse::as_200(token),
// TODO: set the error in the message body
Err(_e) => HTTPResponse::as_500(),
Err(e) => {
eprintln!("error occurred while signing the token err={}", e);
return HTTPResponse::as_500();
}
}
}
None => HTTPResponse::as_400(),
@@ -43,7 +149,7 @@ fn handle_get(request: HTTPRequest) -> FuturePinned<HTTPResponse> {
/// validates the token by checking:
/// * expiration time
fn handle_validate(request: HTTPRequest) -> FuturePinned<HTTPResponse> {
fn handle_validate(request: HTTPRequest, _config: Config) -> FuturePinned<HTTPResponse> {
Box::pin(async move {
match &request.body {
Some(ref _b) => {
@@ -66,19 +172,17 @@ lazy_static! {
("/validate/", handle_validate as Handler)
]
);
static ref JWT_KEY: jwt_simple::algorithms::HS256Key = HS256Key::generate();
}
pub struct Router;
impl Router {
pub async fn route(&self, request_str: &str) -> HTTPResponse {
pub async fn route(&self, request_str: &str, config: Config) -> HTTPResponse {
let request = HTTPRequest::from(request_str);
let target = request.start_line.get_target();
match HTTP_METHODS.get(target.as_str()) {
Some(f) => f(request).await,
Some(f) => f(request, config).await,
None => HTTPResponse::as_404(),
}
}
@@ -89,12 +193,59 @@ pub const ROUTER: Router = Router {};
#[tokio::test]
async fn test_route() {
use super::HTTPStatusCode;
let router: &Router = &ROUTER;
let config: Config = Config::default();
let request_str = "POST /get/ HTTP/1.1\r\n\r\n";
let response: HTTPResponse = router.route(request_str).await;
let response: HTTPResponse = router.route(request_str, config).await;
assert_eq!(
HTTPStatusCode::Http400,
response.status_line.get_status_code()
);
}
#[test]
fn test_config() {
use std::env;
let root_path = env::var("CARGO_MANIFEST_DIR").unwrap();
// TODO: path::Path should be better
let config_path = format!("{}/{}/{}/{}", root_path, "tests", "data", "config.ini");
let mut config = Ini::new();
let _r = config.load(config_path);
let router_config = Config::try_from(config);
assert!(router_config.is_ok());
}
#[test]
fn test_bad_config() {
use std::env;
let root_path = env::var("CARGO_MANIFEST_DIR").unwrap();
// TODO: path::Path should be better
let config_path = format!("{}/{}/{}/{}", root_path, "tests", "data", "bad_config.ini");
let mut config = Ini::new();
let _r = config.load(config_path);
let router_config = Config::try_from(config);
assert!(router_config.is_err());
}
#[test]
fn test_bad_config_path() {
use std::env;
let root_path = env::var("CARGO_MANIFEST_DIR").unwrap();
// TODO: path::Path should be better
let config_path = format!("{}/{}/{}/{}", root_path, "tests", "data", "con.ini");
let mut config = Ini::new();
let result = config.load(config_path);
assert!(result.is_err());
}
+42 -7
View File
@@ -1,33 +1,68 @@
mod http;
mod stores;
use clap::Parser;
use configparser::ini::Ini;
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::{TcpListener, TcpStream},
};
use http::ROUTER;
use http::{Config, ROUTER};
const SERVER_URL: &str = "127.0.0.1:9000";
#[derive(Parser)]
#[clap(author, version, about, long_about = None)]
struct Cli {
/// config filepath (.ini)
config: String,
}
#[tokio::main]
async fn main() {
let listener = TcpListener::bind(SERVER_URL).await.unwrap();
println!("server is listening on '{}'", SERVER_URL);
let args = Cli::parse();
let mut config = Ini::new();
match config.load(args.config) {
Ok(c) => c,
Err(e) => {
eprintln!("error while loading the config file, err={}", e);
std::process::exit(1);
}
};
let server_url = config.get("server", "url").unwrap_or("".to_string());
let listener = {
match TcpListener::bind(&server_url).await {
Ok(t) => {
println!("server is listening on '{}'", server_url);
t
}
Err(e) => {
eprintln!("error occurred while initializing tcp listener err={}", e);
std::process::exit(1);
}
}
};
let router_config: Config = if let Ok(c) = Config::try_from(config) {
c
} else {
std::process::exit(1);
};
loop {
let (stream, _) = listener.accept().await.unwrap();
handle_connection(stream).await;
handle_connection(stream, router_config.clone()).await;
}
}
/// parses the incoming request (partial spec implementation) and build an HTTP response
async fn handle_connection(mut stream: TcpStream) {
async fn handle_connection(mut stream: TcpStream, config: Config) {
let mut buffer: [u8; 1024] = [0; 1024];
let n = stream.read(&mut buffer).await.unwrap();
let request_string = std::str::from_utf8(&buffer[0..n]).unwrap();
let response = ROUTER.route(request_string).await;
let response = ROUTER.route(request_string, config).await;
let response_str: String = response.into();
stream.write(response_str.as_bytes()).await.unwrap();