generated from visoftsolutions/ksox-template
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* first steps * monolith architecture * prettier in github workflow * kubernetes setup * envs * basic jwt impl * basic jwt tests * fix clippy * cargo fmt * add KSOX_SERVER_JWT_SECRET env to workflows
- Loading branch information
1 parent
cf7a7e6
commit e29919a
Showing
32 changed files
with
586 additions
and
40 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,5 @@ | ||
# Envs | ||
**/envs/ | ||
**/*.env | ||
**/*.local | ||
**/*.cargo | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,2 +1,25 @@ | ||
# ksox-template | ||
|
||
The KSOX Project | ||
|
||
#### `./k8s/patches/dev/envs/config.env`: | ||
|
||
``` | ||
SURREAL_BIND=0.0.0.0:80 | ||
``` | ||
|
||
#### `./k8s/patches/dev/envs/secrets.env`: | ||
|
||
``` | ||
SURREAL_USER=surrealuser | ||
SURREAL_PASS=surrealp4ssword | ||
``` | ||
|
||
#### `./.cargo/config.toml`: | ||
|
||
``` | ||
[env] | ||
KSOX_SERVER_SURREALDB_URL = "http://surrealdb.test/" | ||
KSOX_SERVER_REDIS_URL = "redis://redis.test/" | ||
KSOX_SERVER_API_BIND = "0.0.0.0:8080" | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
[package] | ||
name = "api" | ||
edition.workspace = true | ||
version.workspace = true | ||
authors.workspace = true | ||
description.workspace = true | ||
|
||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html | ||
|
||
[dependencies] | ||
axum.workspace = true | ||
chrono.workspace = true | ||
futures.workspace = true | ||
hyper.workspace = true | ||
jsonwebtoken.workspace = true | ||
once_cell.workspace = true | ||
proptest.workspace = true | ||
ring.workspace = true | ||
seq-macro.workspace = true | ||
serde.workspace = true | ||
shutdown = { version = "0.1.0", path = "../crates/shutdown" } | ||
surrealdb.workspace = true | ||
thiserror.workspace = true | ||
tokio.workspace = true | ||
tokio-stream.workspace = true | ||
tower.workspace = true | ||
tracing.workspace = true | ||
tracing-subscriber.workspace = true | ||
url.workspace = true |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
use axum::{ | ||
response::{IntoResponse, Response}, | ||
Json, | ||
}; | ||
use hyper::StatusCode; | ||
use serde::{Deserialize, Serialize}; | ||
|
||
#[derive(Debug, thiserror::Error)] | ||
pub enum ApiError { | ||
#[error("parse address error")] | ||
AddressParse(#[from] std::net::AddrParseError), | ||
|
||
#[error("axum server error")] | ||
Hyper(#[from] hyper::Error), | ||
|
||
#[error("tracing setup error")] | ||
Tracing(#[from] tracing::subscriber::SetGlobalDefaultError), | ||
} | ||
|
||
#[derive(Debug, Deserialize, Serialize)] | ||
struct AuthErrorResponse { | ||
error: String, | ||
} | ||
#[derive(Debug)] | ||
pub enum AuthError { | ||
WrongCredentials, | ||
InvalidToken, | ||
} | ||
impl IntoResponse for AuthError { | ||
fn into_response(self) -> Response { | ||
let (status, error_message) = match self { | ||
AuthError::WrongCredentials => (StatusCode::UNAUTHORIZED, "Wrong credentials"), | ||
AuthError::InvalidToken => (StatusCode::BAD_REQUEST, "Invalid token"), | ||
}; | ||
let body = Json(AuthErrorResponse { | ||
error: error_message.to_string(), | ||
}); | ||
(status, body).into_response() | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,79 @@ | ||
use axum::{ | ||
async_trait, | ||
extract::FromRequestParts, | ||
headers::{authorization::Bearer, Authorization}, | ||
http::request::Parts, | ||
RequestPartsExt, TypedHeader, | ||
}; | ||
use chrono::Utc; | ||
use jsonwebtoken::{ | ||
decode, encode, Algorithm, DecodingKey, EncodingKey, Header, TokenData, Validation, | ||
}; | ||
use once_cell::sync::Lazy; | ||
use serde::{Deserialize, Serialize}; | ||
|
||
use crate::errors::AuthError; | ||
|
||
pub static KEYS: Lazy<Keys> = Lazy::new(|| { | ||
let secret = | ||
std::env::var("KSOX_SERVER_JWT_SECRET").expect("KSOX_SERVER_JWT_SECRET must be set"); | ||
Keys::new(secret.as_bytes()) | ||
}); | ||
pub struct Keys { | ||
pub decoding: DecodingKey, | ||
pub encoding: EncodingKey, | ||
} | ||
impl Keys { | ||
fn new(secret: &[u8]) -> Self { | ||
Self { | ||
decoding: DecodingKey::from_secret(secret), | ||
encoding: EncodingKey::from_secret(secret), | ||
} | ||
} | ||
} | ||
|
||
pub trait JwtEncodeDecode<T> { | ||
fn decode(token: &str) -> jsonwebtoken::errors::Result<TokenData<T>>; | ||
fn encode(&self) -> jsonwebtoken::errors::Result<String>; | ||
} | ||
|
||
#[derive(Debug, Serialize, Deserialize)] | ||
pub struct Claims { | ||
pub sub: String, | ||
pub exp: usize, | ||
} | ||
impl JwtEncodeDecode<Self> for Claims { | ||
fn decode(token: &str) -> jsonwebtoken::errors::Result<TokenData<Self>> { | ||
decode::<Claims>(token, &KEYS.decoding, &Validation::new(Algorithm::HS256)) | ||
} | ||
fn encode(&self) -> jsonwebtoken::errors::Result<String> { | ||
encode(&Header::new(Algorithm::HS256), self, &KEYS.encoding) | ||
} | ||
} | ||
|
||
#[async_trait] | ||
impl<S> FromRequestParts<S> for Claims | ||
where | ||
S: Send + Sync, | ||
{ | ||
type Rejection = AuthError; | ||
|
||
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> { | ||
// Extract the token from the authorization header | ||
let TypedHeader(Authorization(bearer)) = parts | ||
.extract::<TypedHeader<Authorization<Bearer>>>() | ||
.await | ||
.map_err(|_| AuthError::InvalidToken)?; | ||
// Decode the user data | ||
|
||
let token_data = Claims::decode(bearer.token()).map_err(|_| AuthError::InvalidToken)?; | ||
|
||
if token_data.claims.exp | ||
<= usize::try_from(Utc::now().timestamp()).map_err(|_| AuthError::WrongCredentials)? | ||
{ | ||
return Err(AuthError::WrongCredentials); | ||
} | ||
|
||
Ok(token_data.claims) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
mod api_test; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
use axum::{body::Body, http::Request}; | ||
use chrono::Utc; | ||
use futures::executor::block_on; | ||
use hyper::StatusCode; | ||
use proptest::prelude::*; | ||
use seq_macro::seq; | ||
use tower::ServiceExt; | ||
|
||
use crate::{ | ||
app::get_app, | ||
jwt::{Claims, JwtEncodeDecode}, | ||
}; | ||
|
||
seq!(N in 0..15 { | ||
proptest! { | ||
#[test] | ||
fn test_me_endpoint~N(s in "[a-zA-Z0-9]{256}") { | ||
let app = get_app(); | ||
let jwt = Claims { | ||
sub: s.to_owned(), | ||
exp: usize::try_from(Utc::now().timestamp()).unwrap() + 60, | ||
}; | ||
let request = Request::builder() | ||
.method("GET") | ||
.uri("/me") | ||
.header("Authorization", format!("Bearer {}", jwt.encode().unwrap())) | ||
.body(Body::empty()) | ||
.unwrap(); | ||
|
||
let resp = block_on(async { app.oneshot(request).await.unwrap() }); | ||
let (parts, body) = resp.into_parts(); | ||
let bytes = block_on(hyper::body::to_bytes(body)).unwrap(); | ||
let body_str = String::from_utf8(bytes.to_vec()).expect("Response body is not a valid UTF-8 string"); | ||
|
||
assert_eq!(parts.status, StatusCode::OK); | ||
assert_eq!(body_str, s); | ||
} | ||
} | ||
}); |
Oops, something went wrong.