Skip to content

Commit

Permalink
Merge pull request #86 from refactor-group/tweak_cors_policy_for_dev_…
Browse files Browse the repository at this point in the history
…and_prod
  • Loading branch information
jhodapp authored Dec 14, 2024
2 parents db15a71 + 9552805 commit 1808420
Show file tree
Hide file tree
Showing 7 changed files with 93 additions and 21 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 -l \"$BACKEND_LOG_FILTER_LEVEL\" -i \"$BACKEND_INTERFACE\" -p \"$BACKEND_PORT\" -d \"$DATABASE_URL\" --allowed-origins=$BACKEND_ALLOWED_ORIGINS"]

# Default CMD allows overriding with custom commands
CMD ["bash"]
10 changes: 6 additions & 4 deletions docker-compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,12 @@ 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
BACKEND_PORT: ${BACKEND_PORT} # Set service port from environment variable
BACKEND_INTERFACE: ${BACKEND_INTERFACE} # Set service interface from environment variable
BACKEND_ALLOWED_ORIGINS: ${BACKEND_ALLOWED_ORIGINS}
BACKEND_LOG_FILTER_LEVEL: ${BACKEND_LOG_FILTER_LEVEL}
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 +52,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
54 changes: 45 additions & 9 deletions docs/runbooks/Container-README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,14 @@ POSTGRES_HOST=postgres
POSTGRES_PORT=5432
POSTGRES_SCHEMA=refactor_platform
DATABASE_URL=postgres://$POSTGRES_USER:$POSTGRES_PASSWORD@$POSTGRES_HOST:$POSTGRES_PORT/$POSTGRES_DB
SERVICE_PORT=4000
SERVICE_INTERFACE=0.0.0.0
BACKEND_PORT=4000
BACKEND_INTERFACE=0.0.0.0
BACKEND_ALLOWED_ORIGINS="http://localhost:3000,https://localhost:3000"
FRONTEND_PORT=3000
USERNAME=appuser
USER_UID=1000
USER_GID=1000
CONTAINER_NAME=refactor-platform
PLATFORM=linux/arm64
```

Expand All @@ -62,11 +65,14 @@ POSTGRES_HOST=postgres.example.com
POSTGRES_SCHEMA=refactor_platform
DATABASE_URL=postgres://$POSTGRES_USER:$POSTGRES_PASSWORD@$POSTGRES_HOST:$POSTGRES_PORT/$POSTGRES_DB
POSTGRES_PORT=5432
SERVICE_PORT=4000
SERVICE_INTERFACE=0.0.0.0
BACKEND_PORT=4000
BACKEND_INTERFACE=0.0.0.0
BACKEND_ALLOWED_ORIGINS="http://localhost:3000,https://localhost:3000"
FRONTEND_PORT=3000
USERNAME=remote_appuser
USER_UID=1001
USER_GID=1001
CONTAINER_NAME=refactor-platform
PLATFORM=linux/arm64
```

Expand All @@ -78,6 +84,7 @@ The `docker-compose.yaml` file uses environment variables defined in your `.env`
services:
postgres:
image: postgres:17
container_name: postgres
environment:
POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
Expand All @@ -86,27 +93,56 @@ services:
- "${POSTGRES_PORT}:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
- ./migration/src/setup.sql:/docker-entrypoint-initdb.d/0-setup.sql
- ./migration/src/refactor_platform_rs.sql:/docker-entrypoint-initdb.d/1-refactor_plaform_rs.sql
- ./migration/src/setup_default_user.sql:/docker-entrypoint-initdb.d/2-setup_default_user.sql
networks:
- backend_network

rust-app:
image: rust-backend
build:
context: .
dockerfile: Dockerfile
target: runtime
platform: ${PLATFORM}
container_name: ${CONTAINER_NAME}
environment:
POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
POSTGRES_DB: ${POSTGRES_DB}
POSTGRES_HOST: ${POSTGRES_HOST}
POSTGRES_SCHEMA: ${POSTGRES_SCHEMA}
POSTGRES_HOST: postgres
POSTGRES_PORT: ${POSTGRES_PORT}
DATABASE_URL: ${POSTGRES_HOST}://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_DB}
SERVICE_PORT: ${SERVICE_PORT}
DATABASE_URL: postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@postgres:${POSTGRES_PORT}/${POSTGRES_DB}
BACKEND_PORT: ${BACKEND_PORT}
BACKEND_INTERFACE: ${BACKEND_INTERFACE}
BACKEND_ALLOWED_ORIGINS: ${BACKEND_ALLOWED_ORIGINS}
BACKEND_LOG_FILTER_LEVEL: ${BACKEND_LOG_FILTER_LEVEL}
ports:
- "${SERVICE_PORT}:4000"
- "${BACKEND_PORT}:${BACKEND_PORT}"
depends_on:
- postgres
networks:
- backend_network
command: ["sh", "-c", "sleep 5 && /usr/local/bin/refactor_platform_rs"]

nextjs-app:
build:
context: https://github.com/refactor-group/refactor-platform-fe.git#main
dockerfile: Dockerfile
target: runner
ports:
- "${FRONTEND_PORT}:${FRONTEND_PORT}"
depends_on:
- rust-app

networks:
backend_network:
driver: bridge

volumes:
postgres_data:
postgres_data
```
---
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
27 changes: 22 additions & 5 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,10 @@ 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
let session_store = PostgresStore::new(
app_state
Expand Down Expand Up @@ -53,13 +60,21 @@ pub async fn init_server(app_state: AppState) -> Result<()> {
// These will probably come from app_state.config (command line)
let host = app_state.config.interface.as_ref().unwrap();
let port = app_state.config.port;
let server_url = format!("{host}:{port}");
info!("Server starting... listening for connections on http://{host}:{port}");

let server_url = format!("{host}:{port}");
let listen_addr = SocketAddr::from_str(&server_url).unwrap();

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 +87,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 1808420

Please sign in to comment.