Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
24447dff9d | ||
|
|
e9a3b44d31 | ||
|
|
78e06756e2 | ||
|
|
900dcebcad | ||
|
|
0cc5169664 | ||
|
|
02b6fb3b33 | ||
|
|
b933853a13 | ||
|
|
8d3651d6fc | ||
|
|
1d2924b7ef | ||
|
|
91e80cfbf4 | ||
|
|
b1cb4dec23 | ||
|
|
5a638fd354 | ||
|
|
17a098ef89 | ||
|
|
45c9112af2 | ||
|
|
74e8d58b5c | ||
|
|
df321ec555 | ||
|
|
a5986f1f28 | ||
|
|
e02849ca8e | ||
|
|
b73add00c5 | ||
|
|
6c79c3d708 | ||
|
|
baa8595a4a | ||
|
|
7336933642 | ||
|
|
6166310283 | ||
|
|
7073a4b88e | ||
|
|
808cd3ee77 | ||
|
|
88c2e99aa8 | ||
|
|
0856b7b6b2 |
@@ -4,3 +4,4 @@ simple-auth
|
||||
|
||||
tests/python/__pycache__
|
||||
tests/bash/response.txt
|
||||
tests/data/*.ini
|
||||
|
||||
Generated
+137
-8
@@ -169,6 +169,12 @@ version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "349a06037c7bf932dd7e7d1f653678b2038b9ad46a74102f1fc7bd7872678cce"
|
||||
|
||||
[[package]]
|
||||
name = "base64"
|
||||
version = "0.13.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8"
|
||||
|
||||
[[package]]
|
||||
name = "base64ct"
|
||||
version = "1.5.2"
|
||||
@@ -297,6 +303,17 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "colored"
|
||||
version = "2.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b3616f750b84d8f0de8a58bda93e08e2a81ad3f523089b05f1dffecab48c6cbd"
|
||||
dependencies = [
|
||||
"atty",
|
||||
"lazy_static",
|
||||
"winapi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "concurrent-queue"
|
||||
version = "1.2.4"
|
||||
@@ -781,7 +798,7 @@ dependencies = [
|
||||
"libc",
|
||||
"log",
|
||||
"wasi",
|
||||
"windows-sys",
|
||||
"windows-sys 0.36.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -842,6 +859,15 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num_threads"
|
||||
version = "0.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2819ce041d2ee131036f4fc9d6ae7ae125a3a40e97ba64d04fe799ad9dabbb44"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.15.0"
|
||||
@@ -902,7 +928,7 @@ dependencies = [
|
||||
"libc",
|
||||
"redox_syscall",
|
||||
"smallvec",
|
||||
"windows-sys",
|
||||
"windows-sys 0.36.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1205,19 +1231,36 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "simple-auth"
|
||||
version = "0.1.0"
|
||||
version = "0.3.0"
|
||||
dependencies = [
|
||||
"async-std",
|
||||
"async-trait",
|
||||
"base64",
|
||||
"clap",
|
||||
"configparser",
|
||||
"json",
|
||||
"jwt-simple",
|
||||
"lazy_static",
|
||||
"log",
|
||||
"regex",
|
||||
"serde",
|
||||
"simple_logger",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "simple_logger"
|
||||
version = "4.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e190a521c2044948158666916d9e872cbb9984f755e9bb3b5b75a836205affcd"
|
||||
dependencies = [
|
||||
"atty",
|
||||
"colored",
|
||||
"log",
|
||||
"time",
|
||||
"windows-sys 0.42.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "slab"
|
||||
version = "0.4.7"
|
||||
@@ -1327,6 +1370,35 @@ dependencies = [
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "time"
|
||||
version = "0.3.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a561bf4617eebd33bca6434b988f39ed798e527f51a1e797d0ee4f61c0a38376"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"libc",
|
||||
"num_threads",
|
||||
"serde",
|
||||
"time-core",
|
||||
"time-macros",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "time-core"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2e153e1f1acaef8acc537e68b44906d2db6436e2b35ac2c6b42640fff91f00fd"
|
||||
|
||||
[[package]]
|
||||
name = "time-macros"
|
||||
version = "0.2.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d967f99f534ca7e495c575c62638eebc2898a8c84c119b89e250477bc4ba16b2"
|
||||
dependencies = [
|
||||
"time-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tokio"
|
||||
version = "1.21.2"
|
||||
@@ -1520,43 +1592,100 @@ version = "0.36.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ea04155a16a59f9eab786fe12a4a450e75cdb175f9e0d80da1e17db09f55b8d2"
|
||||
dependencies = [
|
||||
"windows_aarch64_msvc",
|
||||
"windows_i686_gnu",
|
||||
"windows_i686_msvc",
|
||||
"windows_x86_64_gnu",
|
||||
"windows_x86_64_msvc",
|
||||
"windows_aarch64_msvc 0.36.1",
|
||||
"windows_i686_gnu 0.36.1",
|
||||
"windows_i686_msvc 0.36.1",
|
||||
"windows_x86_64_gnu 0.36.1",
|
||||
"windows_x86_64_msvc 0.36.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.42.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5a3e1820f08b8513f676f7ab6c1f99ff312fb97b553d30ff4dd86f9f15728aa7"
|
||||
dependencies = [
|
||||
"windows_aarch64_gnullvm",
|
||||
"windows_aarch64_msvc 0.42.0",
|
||||
"windows_i686_gnu 0.42.0",
|
||||
"windows_i686_msvc 0.42.0",
|
||||
"windows_x86_64_gnu 0.42.0",
|
||||
"windows_x86_64_gnullvm",
|
||||
"windows_x86_64_msvc 0.42.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_gnullvm"
|
||||
version = "0.42.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "41d2aa71f6f0cbe00ae5167d90ef3cfe66527d6f613ca78ac8024c3ccab9a19e"
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_msvc"
|
||||
version = "0.36.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9bb8c3fd39ade2d67e9874ac4f3db21f0d710bee00fe7cab16949ec184eeaa47"
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_msvc"
|
||||
version = "0.42.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dd0f252f5a35cac83d6311b2e795981f5ee6e67eb1f9a7f64eb4500fbc4dcdb4"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_gnu"
|
||||
version = "0.36.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "180e6ccf01daf4c426b846dfc66db1fc518f074baa793aa7d9b9aaeffad6a3b6"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_gnu"
|
||||
version = "0.42.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fbeae19f6716841636c28d695375df17562ca208b2b7d0dc47635a50ae6c5de7"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_msvc"
|
||||
version = "0.36.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e2e7917148b2812d1eeafaeb22a97e4813dfa60a3f8f78ebe204bcc88f12f024"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_msvc"
|
||||
version = "0.42.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "84c12f65daa39dd2babe6e442988fc329d6243fdce47d7d2d155b8d874862246"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnu"
|
||||
version = "0.36.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4dcd171b8776c41b97521e5da127a2d86ad280114807d0b2ab1e462bc764d9e1"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnu"
|
||||
version = "0.42.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bf7b1b21b5362cbc318f686150e5bcea75ecedc74dd157d874d754a2ca44b0ed"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnullvm"
|
||||
version = "0.42.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09d525d2ba30eeb3297665bd434a54297e4170c7f1a44cad4ef58095b4cd2028"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_msvc"
|
||||
version = "0.36.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c811ca4a8c853ef420abd8592ba53ddbbac90410fab6903b3e79972a631f7680"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_msvc"
|
||||
version = "0.42.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f40009d85759725a34da6d89a94e63d7bdc50a862acf0dbc7c8e488f1edcb6f5"
|
||||
|
||||
[[package]]
|
||||
name = "zeroize"
|
||||
version = "1.5.7"
|
||||
|
||||
+8
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "simple-auth"
|
||||
version = "0.1.0"
|
||||
version = "0.3.1"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
@@ -12,6 +12,9 @@ regex = "1"
|
||||
tokio = { version = "1.21.1", features = ["full"] }
|
||||
async-trait = "0.1.57"
|
||||
jwt-simple = "0.11.1"
|
||||
simple_logger = "4.0.0"
|
||||
log = "0.4.17"
|
||||
base64 = "0.13.1"
|
||||
|
||||
# useful for tests (embedded files should be delete in release ?)
|
||||
#rust-embed="6.4.1"
|
||||
@@ -27,3 +30,7 @@ features = ["derive"]
|
||||
[dependencies.async-std]
|
||||
version = "1.6"
|
||||
features = ["attributes"]
|
||||
|
||||
[dependencies.serde]
|
||||
version = "1.0"
|
||||
features = ["derive"]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# simple-auth
|
||||
|
||||
A little web server providing JWT token for auth auser.
|
||||
A little web server providing JWT token for auth user.
|
||||
|
||||
## Build
|
||||
```bash
|
||||
@@ -13,7 +13,7 @@ cargo build --release
|
||||
The store represents the credentials. For now, this a `.txt` file with plain passwords. You have to create one like:
|
||||
```txt
|
||||
# acts as a comment (only on a start line)
|
||||
<username>:<password>
|
||||
<email>:<password>
|
||||
```
|
||||
**WARN**: the file should have a chmod to **600**.
|
||||
|
||||
@@ -45,9 +45,19 @@ expiration_time = 2 # in hours
|
||||
```bash
|
||||
./simple-auth <ini_path>
|
||||
|
||||
curl http://<ip>:<port>/get/ -d '{"username":"<user>", "password":"<password>"}'
|
||||
# get a JWT
|
||||
curl http://<ip>:<port>/get/ -d '{"email":"<email>", "password":"<password>"}'
|
||||
# should returned
|
||||
{"token":"<header>.<payload>.<signature>"}
|
||||
|
||||
# validate a JWT
|
||||
curl http://<ip>:<port>/validate/ -d '{"token":"<header>.<payload>.<signature>"}'
|
||||
# should returned (if valid)
|
||||
{"valid":"true"}
|
||||
|
||||
# get the public key for local validation
|
||||
curl http://<ip>:<port>/pubkey/
|
||||
{"pubkey":"<b64_encoded_public_key>"}
|
||||
```
|
||||
|
||||
## Test
|
||||
@@ -58,7 +68,13 @@ cargo test
|
||||
```
|
||||
|
||||
### integration tests
|
||||
* run the server locally or remotly (the URL must be changed if needed in `curling.bash` and `test_requests.py`)
|
||||
* do the **configuration** step for your env tests
|
||||
* set the following env variables:
|
||||
```bash
|
||||
export SIMPLE_AUTH_URL="http://<url>:<port>"
|
||||
export SIMPLE_AUTH_PUB_KEY="<path_to_pem_pub_key>" # DO NOT USE THE ONE IN PRODUCTION !
|
||||
```
|
||||
* run the server (if no one is running remotly)
|
||||
* run curl tests
|
||||
```bash
|
||||
cd tests/bash/
|
||||
@@ -75,7 +91,7 @@ source venv/bin/activate
|
||||
pip install -r requirements
|
||||
|
||||
# launch the tests
|
||||
python -m unitest
|
||||
python -m unittest
|
||||
```
|
||||
|
||||
## Documentation
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
use configparser::ini::Ini;
|
||||
use std::str::FromStr;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Config {
|
||||
pub jwt_exp_time: u64,
|
||||
pub jwt_issuer: String,
|
||||
pub jwt_priv_key: String,
|
||||
pub jwt_pub_key: String,
|
||||
pub 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) => {
|
||||
log::error!(
|
||||
"unable to convert JWT expiration time into u64 details={}",
|
||||
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 {
|
||||
log::error!("invalid config parameter: JWT expiration time is negative or equals to 0");
|
||||
return false;
|
||||
}
|
||||
|
||||
if self.jwt_issuer == "" {
|
||||
log::error!("invalid config parameter: JWT issuer is empty");
|
||||
return false;
|
||||
}
|
||||
|
||||
if self.jwt_pub_key == "" {
|
||||
log::error!("invalid config parameter: JWT public key file path is empty");
|
||||
return false;
|
||||
}
|
||||
|
||||
if self.jwt_priv_key == "" {
|
||||
log::error!("invalid config parameter: JWT private key file path is empty");
|
||||
return false;
|
||||
}
|
||||
|
||||
if self.filestore_path == "" {
|
||||
log::error!("invalid config parameter: filestore path is empty");
|
||||
return false;
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_config() {
|
||||
use std::env;
|
||||
|
||||
let root_path = env::var("CARGO_MANIFEST_DIR").unwrap();
|
||||
|
||||
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();
|
||||
|
||||
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();
|
||||
|
||||
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());
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
//! provides `Config` struct to load and validate `.ini` file
|
||||
mod config;
|
||||
|
||||
pub use config::Config;
|
||||
@@ -0,0 +1,93 @@
|
||||
use json;
|
||||
use std::collections::HashMap;
|
||||
|
||||
const JSON_DELIMITER: &'static str = ",";
|
||||
|
||||
/// `HashMap` wrapper, represents the JSON response body
|
||||
pub struct HTTPMessage {
|
||||
message: HashMap<String, String>,
|
||||
}
|
||||
|
||||
impl Default for HTTPMessage {
|
||||
fn default() -> Self {
|
||||
HTTPMessage {
|
||||
message: HashMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// try to convert `HTTPMessage` in `json::JsonValue`
|
||||
impl TryInto<json::JsonValue> for HTTPMessage {
|
||||
type Error = String;
|
||||
fn try_into(self) -> Result<json::JsonValue, Self::Error> {
|
||||
let message = format!(r#"{{{}}}"#, self.build_json());
|
||||
match json::parse(&message) {
|
||||
Ok(r) => Ok(r),
|
||||
Err(e) => Err(format!(
|
||||
"unable to parse the HTTPMessage correctly: {}, err={}",
|
||||
message, e
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HTTPMessage {
|
||||
pub fn put(&mut self, key: &str, value: &str) {
|
||||
self.message.insert(key.to_string(), value.to_string());
|
||||
}
|
||||
|
||||
/// associated function to build an HTTPMessage error
|
||||
pub fn error(message: &str) -> Option<json::JsonValue> {
|
||||
let mut http_message = HTTPMessage::default();
|
||||
http_message.put("error", message);
|
||||
|
||||
match message.try_into() {
|
||||
Ok(m) => Some(m),
|
||||
Err(e) => {
|
||||
eprintln!(
|
||||
"unable to parse the message: {} into JSON, err={}",
|
||||
message, e
|
||||
);
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// loops over all the HashMap keys, builds a JSON key value for each one and join them with `JSON_DELIMITER`
|
||||
fn build_json(self) -> String {
|
||||
let unstruct: Vec<String> = self
|
||||
.message
|
||||
.keys()
|
||||
.map(|k| format!(r#""{}":{:?}"#, k, self.message.get(k).unwrap()))
|
||||
.collect();
|
||||
let joined = unstruct.join(JSON_DELIMITER);
|
||||
joined
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_message() {
|
||||
let mut http_message = HTTPMessage::default();
|
||||
http_message.put("email", "toto@toto.fr");
|
||||
http_message.put("password", "tata");
|
||||
|
||||
let mut json_result: Result<json::JsonValue, String> = http_message.try_into();
|
||||
assert!(json_result.is_ok());
|
||||
|
||||
let mut json = json_result.unwrap();
|
||||
assert!(json.has_key("email"));
|
||||
assert!(json.has_key("password"));
|
||||
|
||||
let empty_http_message = HTTPMessage::default();
|
||||
json_result = empty_http_message.try_into();
|
||||
assert!(json_result.is_ok());
|
||||
|
||||
json = json_result.unwrap();
|
||||
assert_eq!("{}", json.dump().to_string());
|
||||
|
||||
let mut bad_http_message = HTTPMessage::default();
|
||||
bad_http_message.put("\"", "");
|
||||
|
||||
json_result = bad_http_message.try_into();
|
||||
assert!(json_result.is_err());
|
||||
}
|
||||
+4
-2
@@ -1,9 +1,11 @@
|
||||
//! http module includes tools to parse an HTTP request and build and HTTP response
|
||||
|
||||
pub mod message;
|
||||
pub mod request;
|
||||
pub mod response;
|
||||
pub mod router;
|
||||
|
||||
pub use request::HTTPRequest;
|
||||
pub use message::HTTPMessage;
|
||||
pub use request::{HTTPRequest, HTTPVersion};
|
||||
pub use response::{HTTPResponse, HTTPStatusCode};
|
||||
pub use router::{Config, ROUTER};
|
||||
pub use router::ROUTER;
|
||||
|
||||
+58
-12
@@ -8,6 +8,8 @@ use lazy_static::lazy_static;
|
||||
use regex::Regex;
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use crate::utils::extract_json_value;
|
||||
|
||||
type RequestParts = (String, VecDeque<String>, String);
|
||||
|
||||
const HTTP_REQUEST_SEPARATOR: &'static str = "\r\n";
|
||||
@@ -105,7 +107,6 @@ impl Default for HTTPStartLine {
|
||||
fn default() -> Self {
|
||||
HTTPStartLine {
|
||||
method: "".to_string(),
|
||||
|
||||
target: "".to_string(),
|
||||
version: HTTPVersion::Unknown,
|
||||
}
|
||||
@@ -142,10 +143,7 @@ impl TryFrom<String> for HTTPBody {
|
||||
let body = body.replace(NULL_CHAR, "");
|
||||
match json::parse(&body) {
|
||||
Ok(v) => Ok(HTTPBody::new(v)),
|
||||
Err(e) => Err(format!(
|
||||
"error occurred during request body parsing err={}",
|
||||
e
|
||||
)),
|
||||
Err(e) => Err(format!("during request body parsing details={}", e)),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -155,6 +153,8 @@ impl TryFrom<String> for HTTPBody {
|
||||
pub struct HTTPRequest {
|
||||
pub start_line: HTTPStartLine,
|
||||
pub body: Option<HTTPBody>,
|
||||
// includes the client IP + port (should be in the headers)
|
||||
pub addr: String,
|
||||
}
|
||||
|
||||
impl HTTPRequest {
|
||||
@@ -189,27 +189,46 @@ impl HTTPRequest {
|
||||
let start_line = HTTPStartLine::parse(&rp.0);
|
||||
match start_line {
|
||||
Ok(v) => request.start_line = v,
|
||||
Err(e) => eprintln!("error occurred while parsing start_line err={}", e),
|
||||
Err(e) => log::error!("while parsing start_line details={}", e),
|
||||
}
|
||||
|
||||
let body = HTTPBody::try_from(rp.2);
|
||||
match body {
|
||||
Ok(v) => request.body = Some(v),
|
||||
Err(e) => eprintln!("error occurred during body parsing err={}", e),
|
||||
Err(e) => log::warn!("{}", e),
|
||||
}
|
||||
|
||||
return Ok(request);
|
||||
}
|
||||
Err(e) => {
|
||||
return Err(format!("error occurred getting request parts err={}", e));
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// retrieve value in `HTTPBody` (returns None if empty or does not exist)
|
||||
pub fn get_body_value(&self, key: &str) -> Option<String> {
|
||||
match self.body {
|
||||
Some(ref b) => match &b.data {
|
||||
json::JsonValue::Object(d) => extract_json_value(&d, key),
|
||||
_ => None,
|
||||
},
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_method(&self) -> String {
|
||||
self.start_line.method.clone()
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn is_valid(&self) -> bool {
|
||||
return self.start_line.is_valid();
|
||||
}
|
||||
|
||||
pub fn set_addr(&mut self, addr: String) {
|
||||
self.addr = addr;
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for HTTPRequest {
|
||||
@@ -217,6 +236,7 @@ impl Default for HTTPRequest {
|
||||
HTTPRequest {
|
||||
start_line: HTTPStartLine::default(),
|
||||
body: None,
|
||||
addr: "".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -225,8 +245,8 @@ impl From<&str> for HTTPRequest {
|
||||
fn from(request: &str) -> Self {
|
||||
match Self::parse(request) {
|
||||
Ok(v) => v,
|
||||
Err(v) => {
|
||||
eprintln!("{}", format!("[ERR]: {v}"));
|
||||
Err(e) => {
|
||||
log::error!("{}", e);
|
||||
return HTTPRequest::default();
|
||||
}
|
||||
}
|
||||
@@ -239,15 +259,17 @@ fn test_request() {
|
||||
start_line: String,
|
||||
body: Option<String>,
|
||||
is_valid: bool,
|
||||
has_token: bool,
|
||||
}
|
||||
|
||||
let test_cases: [(String, Expect); 11] = [
|
||||
let test_cases: [(String, Expect); 12] = [
|
||||
(
|
||||
"POST /get/ HTTP/1.1\r\n\r\n".to_string(),
|
||||
Expect {
|
||||
start_line: "POST /get/ HTTP/1.1".to_string(),
|
||||
body: None,
|
||||
is_valid: true,
|
||||
has_token: false,
|
||||
},
|
||||
),
|
||||
(
|
||||
@@ -256,6 +278,7 @@ fn test_request() {
|
||||
start_line: "POST /refresh/ HTTP/2".to_string(),
|
||||
body: None,
|
||||
is_valid: true,
|
||||
has_token: false,
|
||||
},
|
||||
),
|
||||
(
|
||||
@@ -264,6 +287,7 @@ fn test_request() {
|
||||
start_line: "POST /validate/ HTTP/1.0".to_string(),
|
||||
body: None,
|
||||
is_valid: true,
|
||||
has_token: false,
|
||||
},
|
||||
),
|
||||
(
|
||||
@@ -272,6 +296,7 @@ fn test_request() {
|
||||
start_line: "GET / HTTP/1.1".to_string(),
|
||||
body: None,
|
||||
is_valid: true,
|
||||
has_token: false,
|
||||
},
|
||||
),
|
||||
// intentionally add HTTP with no version number
|
||||
@@ -281,6 +306,7 @@ fn test_request() {
|
||||
start_line: " UNKNOWN".to_string(),
|
||||
body: None,
|
||||
is_valid: false,
|
||||
has_token: false,
|
||||
},
|
||||
),
|
||||
(
|
||||
@@ -289,6 +315,7 @@ fn test_request() {
|
||||
start_line: " UNKNOWN".to_string(),
|
||||
body: None,
|
||||
is_valid: false,
|
||||
has_token: false
|
||||
}
|
||||
),
|
||||
(
|
||||
@@ -297,6 +324,7 @@ fn test_request() {
|
||||
start_line: " UNKNOWN".to_string(),
|
||||
body: None,
|
||||
is_valid: false,
|
||||
has_token: false
|
||||
}
|
||||
),
|
||||
(
|
||||
@@ -305,6 +333,7 @@ fn test_request() {
|
||||
start_line: "fjlqskjd /oks?id=65 HTTP/2".to_string(),
|
||||
body: None,
|
||||
is_valid: true,
|
||||
has_token: false
|
||||
}
|
||||
),
|
||||
(
|
||||
@@ -313,6 +342,7 @@ fn test_request() {
|
||||
start_line: " UNKNOWN".to_string(),
|
||||
body: None,
|
||||
is_valid: false,
|
||||
has_token: false,
|
||||
}
|
||||
),
|
||||
(
|
||||
@@ -321,6 +351,7 @@ fn test_request() {
|
||||
start_line: " UNKNOWN".to_string(),
|
||||
body: Some(r#"{"access_token":"AAAAAAAAAAAA.BBBBBBBBBB.CCCCCCCCCC","refresh_token": "DDDDDDDDDDD.EEEEEEEEEEE.FFFFF"}"#.to_string()),
|
||||
is_valid: false,
|
||||
has_token: false
|
||||
}
|
||||
),
|
||||
(
|
||||
@@ -329,15 +360,25 @@ fn test_request() {
|
||||
start_line: "POST /refresh/ HTTP/1.1".to_string(),
|
||||
body: Some(r#"{"access_token":"toto","refresh_token":"tutu"}"#.to_string()),
|
||||
is_valid: true,
|
||||
has_token: false
|
||||
}
|
||||
),
|
||||
(
|
||||
format!("{}\r\nuselessheaders\r\n{}", "POST /get/ HTTP/1.1", r#"{"token": "toto", "refresh_token": "tutu"}"#),
|
||||
Expect {
|
||||
start_line: "POST /get/ HTTP/1.1".to_string(),
|
||||
body: Some(r#"{"token":"toto","refresh_token":"tutu"}"#.to_string()),
|
||||
is_valid: true,
|
||||
has_token: true
|
||||
}
|
||||
),
|
||||
];
|
||||
|
||||
for (request, expect) in test_cases {
|
||||
let http_request = HTTPRequest::from(request.as_str());
|
||||
println!("{:?}", http_request);
|
||||
assert_eq!(expect.is_valid, http_request.is_valid());
|
||||
|
||||
let token = http_request.get_body_value("token");
|
||||
let start_line: String = http_request.start_line.into();
|
||||
assert_eq!(expect.start_line, start_line);
|
||||
|
||||
@@ -347,6 +388,11 @@ fn test_request() {
|
||||
}
|
||||
None => continue,
|
||||
}
|
||||
|
||||
match expect.has_token {
|
||||
true => assert!(token.is_some()),
|
||||
false => assert!(token.is_none()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+33
-6
@@ -2,7 +2,7 @@
|
||||
//! it will build an HTTPResponse corresponding to the HTTP message specs. see: https://developer.mozilla.org/en-US/docs/Web/HTTP/Messages
|
||||
//! NOTE: only few parts of the specification has been implemented
|
||||
|
||||
use crate::http::request::HTTPVersion;
|
||||
use super::{HTTPMessage, HTTPVersion};
|
||||
use json;
|
||||
|
||||
#[derive(Debug, PartialEq, Clone)]
|
||||
@@ -92,13 +92,19 @@ impl Into<String> for HTTPResponse {
|
||||
}
|
||||
|
||||
impl HTTPResponse {
|
||||
pub fn as_500() -> Self {
|
||||
pub fn as_500(message: Option<json::JsonValue>) -> Self {
|
||||
let mut response = Self::default();
|
||||
|
||||
response
|
||||
.status_line
|
||||
.set_status_code(HTTPStatusCode::Http500);
|
||||
response.body = json::parse(r#"{"error": "unexpected error occurred"}"#).unwrap();
|
||||
|
||||
response.body = {
|
||||
match message {
|
||||
Some(m) => m,
|
||||
None => json::parse(r#"{"error": "unexpected error occurred"}"#).unwrap(),
|
||||
}
|
||||
};
|
||||
|
||||
response
|
||||
}
|
||||
@@ -119,9 +125,11 @@ impl HTTPResponse {
|
||||
status_line: HTTPStatusLine::default(),
|
||||
body: json::parse(r#"{"error": "invalid credentials"}"#).unwrap(),
|
||||
};
|
||||
|
||||
response
|
||||
.status_line
|
||||
.set_status_code(HTTPStatusCode::Http403);
|
||||
|
||||
response
|
||||
}
|
||||
|
||||
@@ -130,16 +138,35 @@ impl HTTPResponse {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
// TODO: need to be adjust to accept `json::JsonValue`
|
||||
pub fn as_200(token: String) -> Self {
|
||||
pub fn as_200(message: Option<json::JsonValue>) -> Self {
|
||||
let mut response = Self::default();
|
||||
|
||||
response
|
||||
.status_line
|
||||
.set_status_code(HTTPStatusCode::Http200);
|
||||
|
||||
response.body = json::parse(format!(r#"{{"token": "{}"}}"#, token).as_str()).unwrap();
|
||||
response.body = {
|
||||
match message {
|
||||
Some(m) => m,
|
||||
None => json::parse(r#"{"status": "ok"}"#).unwrap(),
|
||||
}
|
||||
};
|
||||
|
||||
response
|
||||
}
|
||||
|
||||
/// builds an HTTP 200 response with the generated JWT
|
||||
pub fn send_token(token: &str) -> Self {
|
||||
let mut http_message = HTTPMessage::default();
|
||||
http_message.put("token", token);
|
||||
|
||||
let message = {
|
||||
match http_message.try_into() {
|
||||
Ok(m) => m,
|
||||
Err(_e) => json::parse(r#"{"token": "error.generation.token"}"#).unwrap(),
|
||||
}
|
||||
};
|
||||
|
||||
HTTPResponse::as_200(Some(message))
|
||||
}
|
||||
}
|
||||
|
||||
+105
-195
@@ -1,189 +1,143 @@
|
||||
//! router aims to handle correctly the request corresponding to the target
|
||||
//! it implements all the logic to build an `HTTPResponse`
|
||||
|
||||
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;
|
||||
use std::str::FromStr;
|
||||
use base64;
|
||||
use json;
|
||||
|
||||
type FuturePinned<HTTPResponse> = Pin<Box<dyn Future<Output = HTTPResponse>>>;
|
||||
type Handler = fn(HTTPRequest, Config) -> FuturePinned<HTTPResponse>;
|
||||
use super::{HTTPMessage, HTTPRequest, HTTPResponse};
|
||||
use crate::config::Config;
|
||||
use crate::jwt::JWTSigner;
|
||||
use crate::stores::{FileStore, Store};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Config {
|
||||
jwt_exp_time: u64,
|
||||
jwt_issuer: String,
|
||||
jwt_priv_key: String,
|
||||
jwt_pub_key: String,
|
||||
filestore_path: String,
|
||||
// TODO: must be mapped with corresponding handler
|
||||
const GET_ROUTE: &'static str = "/get/";
|
||||
const VALIDATE_ROUTE: &'static str = "/validate/";
|
||||
const PUBKEY_ROUTE: &'static str = "/pubkey/";
|
||||
|
||||
async fn handle_get(request: HTTPRequest, config: Config, method: &str) -> HTTPResponse {
|
||||
if method.trim().to_lowercase() != "post" {
|
||||
return HTTPResponse::as_400();
|
||||
}
|
||||
|
||||
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 {
|
||||
let mut store = FileStore::new(config.filestore_path);
|
||||
let mut store = FileStore::new(config.filestore_path.clone());
|
||||
match &request.body {
|
||||
Some(ref b) => {
|
||||
let is_auth = store.is_auth(&b.get_data()).await;
|
||||
if !is_auth {
|
||||
let credentials = store.is_auth(&b.get_data()).await;
|
||||
if credentials.is_none() {
|
||||
return HTTPResponse::as_403();
|
||||
}
|
||||
|
||||
let priv_key_content = {
|
||||
match std::fs::read_to_string(config.jwt_priv_key) {
|
||||
Ok(c) => c,
|
||||
let jwt_signer = {
|
||||
match JWTSigner::new(config).await {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
eprintln!("error while reading JWT priv key content err={}", e);
|
||||
"".to_string()
|
||||
let message = HTTPMessage::error(&e);
|
||||
return HTTPResponse::as_500(message);
|
||||
}
|
||||
}
|
||||
};
|
||||
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.sign(claims) {
|
||||
Ok(token) => HTTPResponse::as_200(token),
|
||||
// TODO: set the error in the message body
|
||||
match jwt_signer.sign(credentials.unwrap().email) {
|
||||
Ok(t) => HTTPResponse::send_token(&t),
|
||||
Err(e) => {
|
||||
eprintln!("error occurred while signing the token err={}", e);
|
||||
return HTTPResponse::as_500();
|
||||
let message = HTTPMessage::error(&e);
|
||||
return HTTPResponse::as_500(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
None => HTTPResponse::as_400(),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// validates the token by checking:
|
||||
/// * expiration time
|
||||
fn handle_validate(request: HTTPRequest, _config: Config) -> FuturePinned<HTTPResponse> {
|
||||
Box::pin(async move {
|
||||
match &request.body {
|
||||
Some(ref _b) => {
|
||||
// TODO: impl the JWT validation
|
||||
HTTPResponse::as_200("header.payload.signature".to_string())
|
||||
}
|
||||
None => HTTPResponse::as_400(),
|
||||
}
|
||||
})
|
||||
/// * signature
|
||||
async fn handle_validate(request: HTTPRequest, config: Config, method: &str) -> HTTPResponse {
|
||||
if request.get_method().trim().to_lowercase() != method {
|
||||
return HTTPResponse::as_400();
|
||||
}
|
||||
|
||||
lazy_static! {
|
||||
/// defines the map between the URL and its associated callback
|
||||
/// each authorized targets must implement a function returning `FuturePinned<HTTPResponse>`
|
||||
// TODO: a macro should be implemented to mask the implementation details
|
||||
static ref HTTP_METHODS: HashMap<&'static str, Handler> =
|
||||
HashMap::from(
|
||||
[
|
||||
("/get/", handle_get as Handler),
|
||||
("/validate/", handle_validate as Handler)
|
||||
]
|
||||
);
|
||||
let token = {
|
||||
match request.get_body_value("token") {
|
||||
Some(t) => t,
|
||||
None => {
|
||||
let mut message = HTTPMessage::default();
|
||||
message.put("valid", "false");
|
||||
message.put("reason", "no token provided in the request body");
|
||||
let json = message.try_into().unwrap();
|
||||
|
||||
return HTTPResponse::as_200(Some(json));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let jwt_signer = {
|
||||
match JWTSigner::new(config).await {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
let message = HTTPMessage::error(&e);
|
||||
let json = message.try_into().unwrap();
|
||||
return HTTPResponse::as_500(Some(json));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let mut message = HTTPMessage::default();
|
||||
match jwt_signer.validate(&token) {
|
||||
Ok(()) => {
|
||||
message.put("valid", "true");
|
||||
}
|
||||
Err(e) => {
|
||||
message.put("valid", "false");
|
||||
message.put("reason", &e);
|
||||
}
|
||||
}
|
||||
|
||||
let json: json::JsonValue = message.try_into().unwrap();
|
||||
HTTPResponse::as_200(Some(json))
|
||||
}
|
||||
|
||||
/// returns the JWT public key in base64 encoded
|
||||
async fn handle_public_key(request: HTTPRequest, config: Config, method: &str) -> HTTPResponse {
|
||||
if request.get_method().trim().to_lowercase() != method {
|
||||
return HTTPResponse::as_400();
|
||||
}
|
||||
|
||||
let jwt_signer = {
|
||||
match JWTSigner::new(config).await {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
let message = HTTPMessage::error(&e);
|
||||
let json = message.try_into().unwrap();
|
||||
return HTTPResponse::as_500(Some(json));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let public_key = jwt_signer.get_public_key();
|
||||
|
||||
let mut message = HTTPMessage::default();
|
||||
message.put("pubkey", &base64::encode(public_key));
|
||||
|
||||
let json = message.try_into().unwrap();
|
||||
HTTPResponse::as_200(Some(json))
|
||||
}
|
||||
|
||||
pub struct Router;
|
||||
|
||||
impl Router {
|
||||
pub async fn route(&self, request_str: &str, config: Config) -> HTTPResponse {
|
||||
let request = HTTPRequest::from(request_str);
|
||||
/// routes the request to the corresponding handling method
|
||||
pub async fn route(&self, request_str: &str, addr: String, config: Config) -> HTTPResponse {
|
||||
let mut request = HTTPRequest::from(request_str);
|
||||
request.set_addr(addr);
|
||||
|
||||
let target = request.start_line.get_target();
|
||||
|
||||
match HTTP_METHODS.get(target.as_str()) {
|
||||
Some(f) => f(request, config).await,
|
||||
None => HTTPResponse::as_404(),
|
||||
match target.as_str() {
|
||||
GET_ROUTE => handle_get(request, config, "post").await,
|
||||
VALIDATE_ROUTE => handle_validate(request, config, "post").await,
|
||||
PUBKEY_ROUTE => handle_public_key(request, config, "get").await,
|
||||
_ => HTTPResponse::as_404(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -199,53 +153,9 @@ async fn test_route() {
|
||||
let config: Config = Config::default();
|
||||
let request_str = "POST /get/ HTTP/1.1\r\n\r\n";
|
||||
|
||||
let response: HTTPResponse = router.route(request_str, config).await;
|
||||
let response: HTTPResponse = router.route(request_str, "".to_string(), 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());
|
||||
}
|
||||
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
use crate::config::Config;
|
||||
use jwt_simple::common::VerificationOptions;
|
||||
use jwt_simple::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashSet;
|
||||
use tokio::fs;
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct JWTCustomClaims {
|
||||
email: String,
|
||||
}
|
||||
|
||||
pub struct JWTSigner {
|
||||
private_key: String,
|
||||
public_key: String,
|
||||
issuer: String,
|
||||
exp_time: u64,
|
||||
}
|
||||
|
||||
impl JWTSigner {
|
||||
// NOTE: could be included in a Trait: `TryFrom` but difficult to handle with async
|
||||
pub async fn new(config: Config) -> Result<Self, String> {
|
||||
let mut jwt_signer = JWTSigner {
|
||||
private_key: "".to_string(),
|
||||
public_key: "".to_string(),
|
||||
issuer: config.jwt_issuer,
|
||||
exp_time: config.jwt_exp_time,
|
||||
};
|
||||
|
||||
match fs::read_to_string(config.jwt_priv_key).await {
|
||||
Ok(c) => {
|
||||
jwt_signer.private_key = c;
|
||||
}
|
||||
Err(e) => {
|
||||
return Err(format!("unable to read the private key details={}", e));
|
||||
}
|
||||
}
|
||||
|
||||
match fs::read_to_string(config.jwt_pub_key).await {
|
||||
Ok(c) => {
|
||||
jwt_signer.public_key = c;
|
||||
}
|
||||
Err(e) => {
|
||||
return Err(format!("unable to read the public key details={}", e));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(jwt_signer)
|
||||
}
|
||||
|
||||
fn get_verification_options(&self) -> VerificationOptions {
|
||||
let mut verification_options = VerificationOptions::default();
|
||||
|
||||
let mut issuers: HashSet<String> = HashSet::new();
|
||||
issuers.insert(self.issuer.clone());
|
||||
verification_options.allowed_issuers = Some(issuers);
|
||||
|
||||
verification_options
|
||||
}
|
||||
|
||||
/// builds and signs the token
|
||||
pub fn sign(&self, email: String) -> Result<String, String> {
|
||||
let jwt_key = {
|
||||
match RS384KeyPair::from_pem(&self.private_key) {
|
||||
Ok(k) => k,
|
||||
Err(e) => {
|
||||
return Err(format!("unable to load the private key details={}", e));
|
||||
}
|
||||
}
|
||||
};
|
||||
let mut claims = Claims::with_custom_claims(
|
||||
JWTCustomClaims { email },
|
||||
Duration::from_hours(self.exp_time),
|
||||
);
|
||||
claims.issuer = Some(self.issuer.clone());
|
||||
|
||||
match jwt_key.sign(claims) {
|
||||
Ok(token) => Ok(token),
|
||||
Err(e) => {
|
||||
return Err(format!("unable to sign the token details={}", e));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn validate(&self, token: &str) -> Result<(), String> {
|
||||
let verification_options = self.get_verification_options();
|
||||
match RS384PublicKey::from_pem(&self.public_key) {
|
||||
Ok(key) => {
|
||||
if let Err(e) =
|
||||
key.verify_token::<NoCustomClaims>(token, Some(verification_options))
|
||||
{
|
||||
return Err(format!("token validation failed details={}", e));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => Err(format!(
|
||||
"token validation failed, can't read the public key details={}",
|
||||
e
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_public_key(&self) -> String {
|
||||
self.public_key.clone()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_signer() {
|
||||
use configparser::ini::Ini;
|
||||
use std::env;
|
||||
|
||||
let root_path = env::var("CARGO_MANIFEST_DIR").unwrap();
|
||||
|
||||
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());
|
||||
|
||||
let jwt_signer = JWTSigner::new(router_config.unwrap());
|
||||
assert!(jwt_signer.await.is_ok());
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
//! simple module to read `.pem` files and sign the token
|
||||
mod jwt;
|
||||
|
||||
pub use jwt::JWTSigner;
|
||||
+44
-14
@@ -1,14 +1,19 @@
|
||||
mod config;
|
||||
mod http;
|
||||
mod jwt;
|
||||
mod stores;
|
||||
mod utils;
|
||||
|
||||
use clap::Parser;
|
||||
use configparser::ini::Ini;
|
||||
use tokio::{
|
||||
io::{AsyncReadExt, AsyncWriteExt},
|
||||
net::{TcpListener, TcpStream},
|
||||
time::{timeout, Duration},
|
||||
};
|
||||
|
||||
use http::{Config, ROUTER};
|
||||
use config::Config;
|
||||
use http::ROUTER;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[clap(author, version, about, long_about = None)]
|
||||
@@ -19,13 +24,14 @@ struct Cli {
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
simple_logger::init_with_level(log::Level::Info).unwrap();
|
||||
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);
|
||||
log::error!("error while loading the config file details={}", e);
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
@@ -34,37 +40,61 @@ async fn main() {
|
||||
let listener = {
|
||||
match TcpListener::bind(&server_url).await {
|
||||
Ok(t) => {
|
||||
println!("server is listening on '{}'", server_url);
|
||||
log::info!("server is listening on '{}'", server_url);
|
||||
t
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("error occurred while initializing tcp listener err={}", e);
|
||||
log::error!("while initializing tcp listener details={}", e);
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let router_config: Config = if let Ok(c) = Config::try_from(config) {
|
||||
c
|
||||
} else {
|
||||
let router_config: Config = {
|
||||
match Config::try_from(config) {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
log::error!("unable to load the configuration details={}", e);
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
loop {
|
||||
let (stream, _) = listener.accept().await.unwrap();
|
||||
handle_connection(stream, router_config.clone()).await;
|
||||
let (stream, addr) = listener.accept().await.unwrap();
|
||||
let conf = router_config.clone();
|
||||
tokio::spawn(handle_connection(stream, addr.to_string(), conf.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
/// parses the incoming request (partial spec implementation) and build an HTTP response
|
||||
async fn handle_connection(mut stream: TcpStream, config: Config) {
|
||||
let mut buffer: [u8; 1024] = [0; 1024];
|
||||
let n = stream.read(&mut buffer).await.unwrap();
|
||||
async fn handle_connection(mut stream: TcpStream, addr: String, config: Config) {
|
||||
log::info!("client connected: {}", addr);
|
||||
|
||||
let request_string = std::str::from_utf8(&buffer[0..n]).unwrap();
|
||||
let response = ROUTER.route(request_string, config).await;
|
||||
let mut message = vec![];
|
||||
let mut buffer: [u8; 1024] = [0; 1024];
|
||||
|
||||
let duration = Duration::from_millis(5);
|
||||
|
||||
// loop until the message is read
|
||||
// the stream can be fragmented so, using a timeout (5ms should be far enough) for the future for completion
|
||||
// after the timeout, the message is "considered" as entirely read
|
||||
loop {
|
||||
match timeout(duration, stream.read(&mut buffer)).await {
|
||||
Ok(v) => {
|
||||
let n = v.unwrap();
|
||||
message.extend_from_slice(&buffer[0..n]);
|
||||
}
|
||||
Err(_e) => break,
|
||||
}
|
||||
}
|
||||
|
||||
let request_string = std::str::from_utf8(&message).unwrap();
|
||||
let response = ROUTER.route(request_string, addr.clone(), config).await;
|
||||
let response_str: String = response.into();
|
||||
|
||||
stream.write(response_str.as_bytes()).await.unwrap();
|
||||
stream.flush().await.unwrap();
|
||||
|
||||
log::info!("connection closed: {}", addr);
|
||||
}
|
||||
|
||||
+19
-16
@@ -41,46 +41,47 @@ impl FileStore {
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!(
|
||||
"error occurred while reading store file: {}, err={:?}",
|
||||
self.path, e
|
||||
);
|
||||
log::error!("while reading store file: {}, details={:?}", self.path, e);
|
||||
}
|
||||
}
|
||||
self.credentials = credentials;
|
||||
}
|
||||
|
||||
/// checks if the credentials exist in the `FileStore`
|
||||
fn auth(&self, username: String, password: String) -> bool {
|
||||
fn auth(&self, email: String, password: String) -> Option<Credentials> {
|
||||
let credentials: Vec<&Credentials> = self
|
||||
.credentials
|
||||
.iter()
|
||||
.filter(|x| x.username == username && x.password == password)
|
||||
.filter(|x| x.email == email && x.password == password)
|
||||
.collect();
|
||||
if credentials.len() == 1 {
|
||||
return true;
|
||||
// no need to store the password again
|
||||
return Some(Credentials::new(
|
||||
credentials[0].email.clone(),
|
||||
"".to_string(),
|
||||
));
|
||||
}
|
||||
false
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Store for FileStore {
|
||||
async fn is_auth(&mut self, data: &json::JsonValue) -> bool {
|
||||
async fn is_auth(&mut self, data: &json::JsonValue) -> Option<Credentials> {
|
||||
// ensure that the store file already exists even after its instanciation
|
||||
if !Path::new(&self.path).is_file() {
|
||||
eprintln!("{} path referencing file store does not exist", self.path);
|
||||
return false;
|
||||
log::error!("{} path referencing file store does not exist", self.path);
|
||||
return None;
|
||||
}
|
||||
|
||||
let credentials = Credentials::from(data);
|
||||
if credentials.is_empty() {
|
||||
eprintln!("unable to parse the credentials correctly from the incoming request");
|
||||
return false;
|
||||
log::error!("unable to parse the credentials correctly from the incoming request");
|
||||
return None;
|
||||
}
|
||||
|
||||
self.parse_contents().await;
|
||||
self.auth(credentials.username, credentials.password)
|
||||
self.auth(credentials.email, credentials.password)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,6 +95,8 @@ async fn test_store() {
|
||||
|
||||
let mut store = FileStore::new(store_path);
|
||||
|
||||
let data = json::parse(r#"{"username": "toto", "password": "tata"}"#).unwrap();
|
||||
assert_eq!(store.is_auth(&data).await, true);
|
||||
let data = json::parse(r#"{"email": "toto@toto.fr", "password": "tata"}"#).unwrap();
|
||||
let credentials = store.is_auth(&data).await;
|
||||
assert_eq!(false, credentials.is_none());
|
||||
assert_eq!(credentials.unwrap().email, "toto@toto.fr");
|
||||
}
|
||||
|
||||
+1
-1
@@ -8,4 +8,4 @@ mod file;
|
||||
mod store;
|
||||
|
||||
pub use file::FileStore;
|
||||
pub use store::Store;
|
||||
pub use store::{Credentials, Store};
|
||||
|
||||
+10
-20
@@ -1,36 +1,26 @@
|
||||
use async_trait::async_trait;
|
||||
use json;
|
||||
use json::object::Object;
|
||||
|
||||
use crate::utils::extract_json_value;
|
||||
|
||||
#[async_trait]
|
||||
pub trait Store {
|
||||
async fn is_auth(&mut self, data: &json::JsonValue) -> bool;
|
||||
}
|
||||
|
||||
/// extracts `String` json value from a key
|
||||
fn extract_json_value(data: &Object, key: &str) -> String {
|
||||
if let Some(u) = data.get(key) {
|
||||
match u.as_str() {
|
||||
Some(s) => return s.to_string(),
|
||||
None => return "".to_string(),
|
||||
}
|
||||
};
|
||||
"".to_string()
|
||||
async fn is_auth(&mut self, data: &json::JsonValue) -> Option<Credentials>;
|
||||
}
|
||||
|
||||
#[derive(Default, Debug)]
|
||||
pub struct Credentials {
|
||||
pub username: String,
|
||||
pub email: String,
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
impl Credentials {
|
||||
pub fn new(username: String, password: String) -> Self {
|
||||
Credentials { username, password }
|
||||
pub fn new(email: String, password: String) -> Self {
|
||||
Credentials { email, password }
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.username == "" || self.password == ""
|
||||
self.email == "" || self.password == ""
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,8 +29,8 @@ impl From<&json::JsonValue> for Credentials {
|
||||
let mut credentials = Credentials::default();
|
||||
match data {
|
||||
json::JsonValue::Object(ref d) => {
|
||||
credentials.username = extract_json_value(&d, "username");
|
||||
credentials.password = extract_json_value(&d, "password");
|
||||
credentials.email = extract_json_value(&d, "email").unwrap_or("".to_string());
|
||||
credentials.password = extract_json_value(&d, "password").unwrap_or("".to_string());
|
||||
}
|
||||
_ => return credentials,
|
||||
}
|
||||
@@ -60,7 +50,7 @@ fn test_credentials() {
|
||||
is_empty: true
|
||||
},
|
||||
Expect {
|
||||
data: json::parse(r#"{"username":"toto","password": "tata"}"#).unwrap(),
|
||||
data: json::parse(r#"{"email":"toto@toto.fr","password": "tata"}"#).unwrap(),
|
||||
is_empty: false
|
||||
}
|
||||
];
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
//! includes utility function, that's all !
|
||||
mod utils;
|
||||
|
||||
pub use utils::extract_json_value;
|
||||
@@ -0,0 +1,30 @@
|
||||
use json::object::Object;
|
||||
|
||||
/// extracts JSON value from a key
|
||||
pub fn extract_json_value(data: &Object, key: &str) -> Option<String> {
|
||||
match data.get(key) {
|
||||
Some(u) => match u.as_str() {
|
||||
Some(s) => return Some(s.to_string()),
|
||||
None => None,
|
||||
},
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_json_value() {
|
||||
let test_cases: [(json::JsonValue, bool, bool); 3] = [
|
||||
(json::parse(r#"{"test": ""}"#).unwrap(), true, true),
|
||||
(json::parse(r#"{}"#).unwrap(), true, false),
|
||||
(json::parse(r#"[]"#).unwrap(), false, false),
|
||||
];
|
||||
|
||||
for (value, is_valid, has_key) in test_cases {
|
||||
match value {
|
||||
json::JsonValue::Object(d) => {
|
||||
assert_eq!(has_key, extract_json_value(&d, "test").is_some());
|
||||
}
|
||||
_ => assert!(!is_valid),
|
||||
}
|
||||
}
|
||||
}
|
||||
+17
-1
@@ -6,7 +6,12 @@
|
||||
#
|
||||
#######################################
|
||||
|
||||
URL="https://dev.thegux.fr"
|
||||
URL=${SIMPLE_AUTH_URL}
|
||||
if [ -z ${URL} ]
|
||||
then
|
||||
echo "[WARN]: SIMPLE_AUTH_URL is empty, set to http://localhost:5555"
|
||||
URL="http://localhost:5555"
|
||||
fi
|
||||
|
||||
for i in {0..10}
|
||||
do
|
||||
@@ -34,3 +39,14 @@ do
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
|
||||
for i in {0..10}
|
||||
do
|
||||
http_response=$(curl -s -o response.txt -w "%{http_code}" ${URL}/pubkey/)
|
||||
if [ $http_response != "200" ]
|
||||
then
|
||||
echo "bad http status code : ${http_response}, expect 400"
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# this a test password storage with password in clear
|
||||
# need to be updated in the future to encrypt or hash the password
|
||||
# <username>:<password>
|
||||
toto:tata
|
||||
# <email>:<password>
|
||||
toto@toto.fr:tata
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
attrs==22.1.0
|
||||
black==22.8.0
|
||||
certifi==2022.9.14
|
||||
cffi==1.15.1
|
||||
charset-normalizer==2.1.1
|
||||
click==8.1.3
|
||||
cryptography==38.0.1
|
||||
idna==3.4
|
||||
iniconfig==1.1.1
|
||||
mypy-extensions==0.4.3
|
||||
@@ -11,7 +13,10 @@ pathspec==0.10.1
|
||||
platformdirs==2.5.2
|
||||
pluggy==1.0.0
|
||||
py==1.11.0
|
||||
pycparser==2.21
|
||||
PyJWT==2.5.0
|
||||
pyparsing==3.0.9
|
||||
requests==2.28.1
|
||||
tomli==2.0.1
|
||||
types-cryptography==3.3.23
|
||||
urllib3==1.26.12
|
||||
|
||||
@@ -1,41 +1,75 @@
|
||||
import base64
|
||||
import jwt
|
||||
import os
|
||||
import requests
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from unittest import TestCase
|
||||
|
||||
URL = "https://dev.thegux.fr"
|
||||
URL = os.getenv("SIMPLE_AUTH_URL", "http://127.0.0.1:5555")
|
||||
PUB_KEY_PATH = os.getenv("SIMPLE_AUTH_PUB_KEY", "")
|
||||
|
||||
|
||||
class TestResponse(TestCase):
|
||||
def test_get_target(self):
|
||||
def setUp(self):
|
||||
with open(PUB_KEY_PATH, "r") as f:
|
||||
self.pub_key = f.read()
|
||||
|
||||
def test_get_target(self, pubkey=None):
|
||||
resp = requests.post(
|
||||
URL + "/get/", json={"username": "toto", "password": "tata"}
|
||||
URL + "/get/", json={"email": "toto@toto.fr", "password": "tata"}
|
||||
)
|
||||
self.assertEqual(resp.status_code, 200, "bad status code returned")
|
||||
self.assertIsNotNone(resp.json(), "response data can't be empty")
|
||||
|
||||
token = resp.json()["token"]
|
||||
jwt_decoded = jwt.decode(token, options={"verify_signature": False})
|
||||
jwt_decoded = jwt.decode(
|
||||
token,
|
||||
pubkey or self.pub_key,
|
||||
algorithms=["RS384"],
|
||||
options={
|
||||
"verify_signature": True,
|
||||
"verify_claims": True,
|
||||
"verify_iss": True,
|
||||
},
|
||||
)
|
||||
self.assertEqual("thegux.fr", jwt_decoded["iss"])
|
||||
self.assertEqual("toto@toto.fr", jwt_decoded["email"])
|
||||
|
||||
jwt_exp = datetime.fromtimestamp(jwt_decoded["exp"])
|
||||
jwt_iat = datetime.fromtimestamp(jwt_decoded["iat"])
|
||||
date_exp = datetime.strptime(str(jwt_exp - jwt_iat), "%H:%M:%S")
|
||||
self.assertEqual(2, date_exp.hour)
|
||||
return token
|
||||
|
||||
def test_validate_target(self):
|
||||
def test_validate_target_no_token(self):
|
||||
resp = requests.post(
|
||||
URL + "/validate/", json={"username": "toto", "password": "tata"}
|
||||
URL + "/validate/", json={"username": "toto@toto.fr", "password": "tata"}
|
||||
)
|
||||
self.assertEqual(resp.status_code, 200, "bad status code returned")
|
||||
self.assertIsNotNone(resp.json(), "response data can't be empty")
|
||||
self.assertEqual(resp.json()["valid"], "false", "bad status returned")
|
||||
self.assertEqual(resp.json()["reason"], "no token provided in the request body")
|
||||
|
||||
def test_validate_target_empty_token(self):
|
||||
resp = requests.post(URL + "/validate/", json={"tutu": "tutu", "token": ""})
|
||||
self.assertEqual(resp.status_code, 200, "bad status code returned")
|
||||
self.assertIsNotNone(resp.json(), "response data can't be empty")
|
||||
self.assertEqual(resp.json()["valid"], "false", "bad status returned")
|
||||
self.assertEqual(
|
||||
resp.json()["token"], "header.payload.signature", "bad status returned"
|
||||
resp.json()["reason"],
|
||||
"token validation failed details=JWT compact encoding error",
|
||||
)
|
||||
|
||||
# TODO: must be updated after implmenting `/refresh/` url handler
|
||||
def test_validate_target(self):
|
||||
token = self.test_get_target()
|
||||
|
||||
resp = requests.post(URL + "/validate/", json={"token": token})
|
||||
self.assertEqual(resp.status_code, 200, "bad status code returned")
|
||||
self.assertIsNotNone(resp.json(), "response data can't be empty")
|
||||
self.assertEqual(resp.json()["valid"], "true", "bad status returned")
|
||||
|
||||
# TODO: must be updated after implementing `/refresh/` url handler
|
||||
def test_refresh_target(self):
|
||||
resp = requests.post(
|
||||
URL + "/refresh/", json={"username": "toto", "password": "tata"}
|
||||
@@ -59,10 +93,8 @@ class TestResponse(TestCase):
|
||||
)
|
||||
|
||||
def test_bad_credentials(self):
|
||||
resp = requests.post(
|
||||
URL + "/get/", json={"username": "tutu", "password": "titi"}
|
||||
)
|
||||
self.assertEqual(resp.status_code, 403, "bas status code returned")
|
||||
resp = requests.post(URL + "/get/", json={"email": "tutu", "password": "titi"})
|
||||
self.assertEqual(resp.status_code, 403, "bad status code returned")
|
||||
self.assertIsNotNone(resp.json(), "response data must not be empty")
|
||||
self.assertEqual(
|
||||
resp.json()["error"],
|
||||
@@ -81,3 +113,26 @@ class TestResponse(TestCase):
|
||||
"the url requested does not exist",
|
||||
"invalid error message returned",
|
||||
)
|
||||
|
||||
def test_get_pubkey(self):
|
||||
resp = requests.get(URL + "/pubkey/")
|
||||
self.assertEqual(resp.status_code, 200, "bad status code returned")
|
||||
self.assertIsNotNone(resp.json(), "response data must not be empty")
|
||||
self.assertIsNotNone(resp.json()["pubkey"], "invalid error message returned")
|
||||
|
||||
b64_pubkey = base64.b64decode(resp.json()["pubkey"])
|
||||
self.assertIsNotNone(b64_pubkey, "public key b64 decoded can't be empty")
|
||||
b64_pubkey_decoded = b64_pubkey.decode()
|
||||
self.assertIn("-BEGIN PUBLIC KEY-", b64_pubkey_decoded)
|
||||
|
||||
self.test_get_target(b64_pubkey_decoded)
|
||||
|
||||
def test_get_pubkey_bad_method(self):
|
||||
resp = requests.post(URL + "/pubkey/", json={"tutu": "toto"})
|
||||
self.assertEqual(resp.status_code, 400, "bad status code returned")
|
||||
self.assertIsNotNone(resp.json(), "response data must not be empty")
|
||||
self.assertEqual(
|
||||
resp.json()["error"],
|
||||
"the incoming request is not valid",
|
||||
"invalid error message returned",
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user