Skip to content

Commit

Permalink
Enable the use of .env for setting runtime variables alongside CLI pa…
Browse files Browse the repository at this point in the history
…rams. Also accept a list of CORS allowed origin URLs instead of hardcoding them.
  • Loading branch information
jhodapp committed Dec 12, 2024
1 parent db15a71 commit f9f4ce5
Show file tree
Hide file tree
Showing 5 changed files with 36 additions and 5 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ EXPOSE 4000

# Default command starts an interactive bash shell
# Set ENTRYPOINT to default to run the Rust binary with arguments
ENTRYPOINT ["/bin/bash", "-c", "/usr/local/bin/refactor_platform_rs -l DEBUG -i \"$SERVICE_INTERFACE\" -p \"$SERVICE_PORT\" -d \"$DATABASE_URL\""]
ENTRYPOINT ["/bin/bash", "-c", "/usr/local/bin/refactor_platform_rs"]

# Default CMD allows overriding with custom commands
CMD ["bash"]
1 change: 1 addition & 0 deletions service/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ features = [

[dependencies]
clap = { version = "4.5.20", features = ["cargo", "derive", "env"] }
dotenvy = "0.15"
log = "0.4.22"
simplelog = { version = "0.12.2", features = ["paris"] }
serde = { version = "1.0.210", features = ["derive"] }
Expand Down
19 changes: 17 additions & 2 deletions service/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use clap::builder::TypedValueParser as _;
use clap::Parser;
use dotenvy::dotenv;
use log::LevelFilter;
use semver::{BuildMetadata, Prerelease, Version};
use serde::Deserialize;
Expand All @@ -26,6 +27,16 @@ pub struct ApiVersion {
#[derive(Clone, Debug, Parser)]
#[command(author, version, about, long_about = None)]
pub struct Config {
/// A list of full CORS origin URLs that allowed to receive server responses.
#[arg(
long,
env,
value_delimiter = ',',
use_value_delimiter = true,
default_value = "http://localhost:3000,https://localhost:3000"
)]
pub allowed_origins: Vec<String>,

/// Set the current semantic version of the endpoint API to expose to clients. All
/// endpoints not contained in the specified version will not be exposed by the router.
#[arg(short, long, env, default_value = DEFAULT_API_VERSION,
Expand All @@ -44,17 +55,18 @@ pub struct Config {
database_uri: Option<String>,

/// The host interface to listen for incoming connections
#[arg(short, long, default_value = "127.0.0.1")]
#[arg(short, long, env, default_value = "127.0.0.1")]
pub interface: Option<String>,

/// The host TCP port to listen for incoming connections
#[arg(short, long, default_value_t = 4000)]
#[arg(short, long, env, default_value_t = 4000)]
pub port: u16,

/// Set the log level verbosity threshold (level) to control what gets displayed on console output
#[arg(
short,
long,
env,
default_value_t = LevelFilter::Warn,
value_parser = clap::builder::PossibleValuesParser::new(["OFF", "ERROR", "WARN", "INFO", "DEBUG", "TRACE"])
.map(|s| s.parse::<LevelFilter>().unwrap()),
Expand All @@ -70,6 +82,9 @@ impl Default for Config {

impl Config {
pub fn new() -> Self {
// Load .env file first
dotenv().ok();
// Then parse the command line parameters and flags
Config::parse()
}

Expand Down
18 changes: 16 additions & 2 deletions web/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
use axum::http::{header::CONTENT_TYPE, HeaderName, HeaderValue, Method};
use axum::http::{
header::{AUTHORIZATION, CONTENT_TYPE},
HeaderName, HeaderValue, Method,
};
use axum_login::{
tower_sessions::{Expiry, SessionManagerLayer},
AuthManagerLayerBuilder,
Expand Down Expand Up @@ -60,6 +63,15 @@ pub async fn init_server(app_state: AppState) -> Result<()> {
info!("Server starting... listening for connections on http://{host}:{port}");

let listener = TcpListener::bind(listen_addr).await.unwrap();
// Convert the type of the allow_origins Vec into a HeaderValue that the CorsLayer accepts
let allowed_origins = app_state
.config
.allowed_origins
.iter()
.filter_map(|origin| origin.parse().ok())
.collect::<Vec<HeaderValue>>();
debug!("allowed_origins: {:#?}", allowed_origins);

let cors_layer = CorsLayer::new()
.allow_methods([
Method::DELETE,
Expand All @@ -72,10 +84,12 @@ pub async fn init_server(app_state: AppState) -> Result<()> {
// Allow and expose the X-Version header across origins
.allow_headers([
ApiVersion::field_name().parse::<HeaderName>().unwrap(),
AUTHORIZATION,
CONTENT_TYPE,
])
.expose_headers([ApiVersion::field_name().parse::<HeaderName>().unwrap()])
.allow_origin("http://localhost:3000".parse::<HeaderValue>().unwrap());
.allow_private_network(true)
.allow_origin(allowed_origins);

axum::serve(
listener,
Expand Down

0 comments on commit f9f4ce5

Please sign in to comment.