Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable the use of .env for setting runtime variables and non-static setting of CORS allow_origins #86

Merged
merged 6 commits into from
Dec 14, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 -l $LOG_LEVEL_FILTER -i \"$BACKEND_INTERFACE\" -p \"$BACKEND_PORT\" -d \"$DATABASE_URL\" --allowed_origins=\"$ALLOWED_ORIGINS\""]

# Default CMD allows overriding with custom commands
CMD ["bash"]
8 changes: 4 additions & 4 deletions docker-compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,10 @@ services:
POSTGRES_HOST: postgres # Set PostgreSQL host to "postgres" service
POSTGRES_PORT: ${POSTGRES_PORT} # Set PostgreSQL port from environment variable
DATABASE_URL: postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@postgres:${POSTGRES_PORT}/${POSTGRES_DB} # Configure database URL
SERVICE_PORT: ${SERVICE_PORT} # Set service port from environment variable
SERVICE_INTERFACE: ${SERVICE_INTERFACE} # Set service interface from environment variable
PORT: ${BACKEND_PORT} # Set service port from environment variable
INTERFACE: ${BACKEND_INTERFACE} # Set service interface from environment variable
ports:
- "${SERVICE_PORT}:${SERVICE_PORT}" # Map host port to container's service port
- "${BACKEND_PORT}:${BACKEND_PORT}" # Map host port to container's service port
depends_on:
- postgres # Ensure postgres service starts before rust-app
networks:
Expand All @@ -50,7 +50,7 @@ services:
dockerfile: Dockerfile
target: runner # Use runner target
ports:
- "${NEXTJS_FRONTEND_PORT}:${NEXTJS_FRONTEND_PORT}" # Map host port to frontend container's service port
- "${FRONTEND_PORT}:${FRONTEND_PORT}" # Map host port to frontend container's service port
depends_on:
- rust-app # Ensure postgres service starts before rust-app

Expand Down
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
19 changes: 17 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 All @@ -22,6 +25,7 @@ pub(crate) mod extractors;
mod router;

pub async fn init_server(app_state: AppState) -> Result<()> {
info!("Connecting to DB with URI: {}", app_state.config.database_uri());
// Session layer
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if it would make sense to change this to debug! so we don't log the URI in production? Thinking more of down the line if we are using like an AWS database. Not really sure if the URI itself would contain any sensitive information but just a thought.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great question, I actually had it as debug originally but I messed up the order in my mind. I'm going to switch this to TRACE so that it only shows up when we really want it to. And at some point we may even decide that this is not even necessary.

let session_store = PostgresStore::new(
app_state
Expand Down Expand Up @@ -60,6 +64,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>>();
info!("allowed_origins: {:#?}", allowed_origins);

let cors_layer = CorsLayer::new()
.allow_methods([
Method::DELETE,
Expand All @@ -72,10 +85,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
Loading