Skip to content

Commit

Permalink
Update application configuration and add server settings
Browse files Browse the repository at this point in the history
The application was updated to include a configuration loader and multiple server settings were added. The changes include the adjustment of authnz-rs v0.1.0 to v0.2.0 in Cargo.toml, environment variable exports in README.md, and usage of TLS and port specifications in src/main.rs. Additional library dependencies have also been included to support the changes.
  • Loading branch information
arkavo-com committed Jul 14, 2024
1 parent ca4b9b3 commit e84f938
Show file tree
Hide file tree
Showing 4 changed files with 114 additions and 9 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,6 @@ Cargo.lock

/target
/.idea
/apple-app-site-association.json
/fullchain.pem
/privkey.pem
18 changes: 15 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,16 +1,28 @@
# https://doc.rust-lang.org/cargo/reference/manifest.html
[package]
name = "authnz-rs"
version = "0.1.0"
version = "0.2.0"
edition = "2021"
license = "BSD-2"

# export RUSTFLAGS="-C target-cpu=native"
# cargo build --release
[profile.release]
opt-level = 3
lto = true
codegen-units = 1
# cargo flamegraph
#debug = true

[dependencies]
tokio = { version = "1.38.0", features = ["rt", "rt-multi-thread", "macros"] }
tokio = { version = "1.38.0", features = ["rt", "rt-multi-thread", "macros", "fs"] }
tokio-native-tls = "0.3.1"
axum = { version="0.7.5", features = ["http2", "tokio"] }
axum-server = { version = "0.6.0", features = ["tls-rustls"] }
webauthn-rs = { version="0.5.0", features = ["danger-allow-state-serialisation"] }
tower = { version="0.4.13", features = ["full"] }
tower-sessions = "0.12.2"
thiserror = "1.0.62"
log = "0.4.22"
serde = { version = "1.0.204", features = ["derive"] }
serde = { version = "1.0.204", features = ["derive"] }
serde_json = "1.0.120"
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,10 @@
# authnz-rs
Authentication and Entitlement WebAuthn and Smart Contract

## Usage

```env
export PORT=8443
export TLS_CERT_PATH=/path/to/fullchain.pem
export TLS_KEY_PATH=/path/to/privkey.pem
```
94 changes: 88 additions & 6 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
use std::collections::HashMap;
use std::env;
use std::path::PathBuf;
use std::sync::Arc;

use axum::{Extension, Router};
use axum::http::StatusCode;
use axum::response::IntoResponse;
use axum::routing::post;
use tokio::sync::Mutex;
use axum::routing::{get, post};
use axum_server::tls_rustls::RustlsConfig;
use tokio::sync::{Mutex, RwLock};
use tower::ServiceBuilder;
use tower_sessions::{Expiry, MemoryStore, SessionManagerLayer};
use tower_sessions::cookie::SameSite;
Expand All @@ -18,6 +21,21 @@ mod authn;

#[tokio::main]
async fn main() {
// Load configuration
let settings = load_config().unwrap();
// Load and cache the apple-app-site-association.json file
let apple_app_site_association = load_apple_app_site_association().await;
// Set up TLS if not disabled
let tls_config = if settings.tls_enabled {
Some(
RustlsConfig::from_pem_file(
PathBuf::from(settings.tls_cert_path),
PathBuf::from(settings.tls_key_path),
).await.unwrap()
)
} else {
None
};
// Create the app
let app_state = AppState::new();
let session_store = MemoryStore::default();
Expand All @@ -31,15 +49,25 @@ async fn main() {
);
// build our application with a route
let app = Router::<()>::new()
.route("/register_start/:username", post(start_register))
.route("/.well-known/apple-app-site-association", get(serve_apple_app_site_association))
.route("/challenge/:username", get(start_register))
.route("/register_finish", post(finish_register))
.route("/login_start/:username", post(start_authentication))
.route("/login_finish", post(finish_authentication))
.layer(Extension(app_state))
.layer(session_service)
.layer(Extension(apple_app_site_association))
.fallback(handler_404);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
let listener = std::net::TcpListener::bind(format!("0.0.0.0:{}", settings.port)).unwrap();
println!("Listening on: 0.0.0.0:{}", settings.port);
if let Some(tls_config) = tls_config {
axum_server::from_tcp_rustls(listener, tls_config)
.serve(app.into_make_service())
.await
.unwrap();
} else {
axum_server::from_tcp(listener);
}
}

#[derive(Clone)]
Expand Down Expand Up @@ -85,4 +113,58 @@ pub struct AccountData {

async fn handler_404() -> impl IntoResponse {
(StatusCode::NOT_FOUND, StatusCode::NOT_FOUND.canonical_reason().unwrap())
}
}

#[derive(Debug, Clone)]
struct ServerSettings {
port: u16,
tls_enabled: bool,
tls_cert_path: String,
tls_key_path: String,
_enable_timing_logs: bool,
}

fn load_config() -> Result<ServerSettings, Box<dyn std::error::Error>> {
let current_dir = env::current_dir()?;

Ok(ServerSettings {
port: env::var("PORT")
.unwrap_or_else(|_| "8080".to_string())
.parse()?,
tls_enabled: env::var("TLS_CERT_PATH").is_ok(),
tls_cert_path: env::var("TLS_CERT_PATH").unwrap_or_else(|_| {
current_dir
.join("fullchain.pem")
.to_str()
.unwrap()
.to_string()
}),
tls_key_path: env::var("TLS_KEY_PATH").unwrap_or_else(|_| {
current_dir
.join("privkey.pem")
.to_str()
.unwrap()
.to_string()
}),
_enable_timing_logs: env::var("ENABLE_TIMING_LOGS")
.unwrap_or_else(|_| "false".to_string())
.parse()
.unwrap_or(false),
})
}

async fn load_apple_app_site_association() -> Arc<RwLock<serde_json::Value>> {
let content = tokio::fs::read_to_string("apple-app-site-association.json")
.await
.expect("Failed to read apple-app-site-association.json");
let json: serde_json::Value = serde_json::from_str(&content)
.expect("Failed to parse apple-app-site-association.json");
Arc::new(RwLock::new(json))
}

async fn serve_apple_app_site_association(
Extension(apple_app_site_association): Extension<Arc<RwLock<serde_json::Value>>>,
) -> impl IntoResponse {
let json = apple_app_site_association.read().await;
axum::Json(json.clone())
}

0 comments on commit e84f938

Please sign in to comment.