use sea_orm::DatabaseConnection;
use std::env;
/// Runtime configuration, sourced entirely from the environment so the same
/// binary works across local, container, and CI without a config file.
#[derive(Debug, Clone)]
pub struct Config {
/// Display name shown in templates (title, nav brand, theme key).
pub app_name: String,
pub database_url: String,
pub bind_address: String,
pub session_duration_hours: i64,
pub registration_token_duration_days: i64,
/// Run pending migrations on startup.
pub auto_migrate: bool,
/// Open sign-up: `/register` creates an account without an invite
/// (still unverified until the emailed link is followed). Invites work
/// either way.
pub registration_enabled: bool,
/// Open sign-up's abuse guards (`REGISTRATION_PER_IP_PER_DAY`,
/// `REGISTRATION_MIN_FILL_SECS`, `REGISTRATION_UNVERIFIED_TTL_DAYS`).
pub registration: crate::registration::Guards,
/// Minimum trust level required to mint NEW tags (Discourse default: 3).
/// Lower-tier users can still apply existing tags. Staff always can.
pub min_trust_to_create_tag: i32,
/// Absolute origin the app is reached at (no trailing slash): the base of
/// email-verification links and of the default OIDC redirect URI. When it
/// is https the session cookie is also marked `Secure`.
pub public_url: String,
/// "Sign in with NEIAM" and any other OIDC providers (neiam-auth). Off
/// unless `OIDC_ENABLED=true`; see the README.
pub oidc: neiam_auth::OidcProviders,
/// `OIDC_PASSWORD_LOGIN` (default true). When false the password form is
/// hidden and `POST /auth/login` is refused.
pub password_login: bool,
/// mail-prism (`MAIL_PRISM_URL` + `MAIL_PRISM_API_KEY`). Unset: mail is
/// only logged (development).
pub mail_prism_url: Option<String>,
pub mail_prism_api_key: Option<String>,
/// From address; must equal the mail-prism application address. Unset:
/// mail-prism uses the application's own address.
pub mail_from_address: Option<String>,
pub mail_from_name: String,
/// Lifetime of an email-verification link.
pub email_verification_ttl_hours: i64,
/// Unverified accounts can read but not post, reply, react, bookmark or
/// tag. `REQUIRE_EMAIL_VERIFICATION=false` turns the gate off.
pub require_email_verification: bool,
/// Trust level needed to flag a post (`MIN_TRUST_TO_FLAG`, default 1).
pub min_trust_to_flag: i32,
/// Reverse proxies whose `X-Forwarded-For` is believed
/// (`TRUSTED_PROXIES`, comma-separated CIDRs or `none`; default loopback
/// and the private ranges, [`crate::client_ip::DEFAULT_TRUSTED`]).
pub trusted_proxies: crate::client_ip::TrustedProxies,
/// How long client addresses are kept (`IP_RETENTION_DAYS`, default 180).
pub ip_retention_days: i64,
/// Signs `/out` destinations (`LINK_SECRET`; a fixed development value
/// when unset, which is fine until links are posted publicly).
pub link_secret: String,
/// When flags hide a post pending review (`FLAG_HIDE_RATIO`, default
/// 0.1; `FLAG_HIDE_MIN_FLAGS`, default 2; `FLAG_HIDE_ENOUGH_FLAGS`,
/// default 10). See [`crate::policy::FlagThreshold`].
pub flag_threshold: crate::policy::FlagThreshold,
/// `MAX_POST_CHARS` and the `LAMENESS_*` filter.
pub lameness: crate::lameness::Config,
}
impl Config {
pub fn from_env() -> Self {
let bind_address = env::var("BIND_ADDRESS").unwrap_or_else(|_| "0.0.0.0:3000".to_string());
let public_url = env_present("PUBLIC_URL")
.unwrap_or_else(|| default_public_url(&bind_address))
.trim_end_matches('/')
.to_string();
let app_name = env::var("APP_NAME").unwrap_or_else(|_| "recourse".to_string());
Config {
oidc: neiam_auth::OidcProviders::from_env_with_public_url(&public_url),
password_login: parse_bool("OIDC_PASSWORD_LOGIN", true),
mail_prism_url: env_present("MAIL_PRISM_URL").map(|s| s.trim_end_matches('/').to_string()),
mail_prism_api_key: env_present("MAIL_PRISM_API_KEY"),
mail_from_address: env_present("MAIL_FROM_ADDRESS"),
mail_from_name: env_present("MAIL_FROM_NAME").unwrap_or_else(|| app_name.clone()),
email_verification_ttl_hours: env::var("EMAIL_VERIFICATION_TTL_HOURS")
.ok()
.and_then(|v| v.parse().ok())
.filter(|h: &i64| *h > 0)
.unwrap_or(48),
require_email_verification: parse_bool("REQUIRE_EMAIL_VERIFICATION", true),
public_url,
app_name,
database_url: env::var("DATABASE_URL").unwrap_or_else(|_| {
// Host port 5439 (not 5432) — 5432 is commonly taken by other
// local Postgres containers. Matches compose.yml's mapping.
"postgres://recourse_user:recourse_password@localhost:5439/recourse".to_string()
}),
bind_address,
session_duration_hours: env::var("SESSION_DURATION_HOURS")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(24),
registration_token_duration_days: env::var("REGISTRATION_TOKEN_DURATION_DAYS")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(7),
auto_migrate: env::var("AUTO_MIGRATE")
.map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on"))
.unwrap_or(true),
registration_enabled: env::var("REGISTRATION_ENABLED")
.map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on"))
.unwrap_or(false),
registration: crate::registration::Guards::from_env(),
trusted_proxies: match env::var("TRUSTED_PROXIES") {
Ok(v) => crate::client_ip::TrustedProxies::parse(&v)
.unwrap_or_else(|e| panic!("TRUSTED_PROXIES: {e}")),
Err(_) => Default::default(),
},
link_secret: env_present("LINK_SECRET").unwrap_or_else(|| DEV_LINK_SECRET.to_string()),
ip_retention_days: env::var("IP_RETENTION_DAYS")
.ok()
.and_then(|v| v.parse().ok())
.filter(|d: &i64| *d >= 1)
.unwrap_or(180),
min_trust_to_flag: env::var("MIN_TRUST_TO_FLAG")
.ok()
.and_then(|v| v.parse().ok())
.map(|n: i32| n.clamp(0, 4))
.unwrap_or(1),
lameness: crate::lameness::Config::from_env(),
flag_threshold: crate::policy::FlagThreshold {
ratio: env::var("FLAG_HIDE_RATIO")
.ok()
.and_then(|v| v.parse().ok())
.filter(|r: &f64| *r > 0.0 && *r <= 1.0)
.unwrap_or(0.1),
min_flags: env::var("FLAG_HIDE_MIN_FLAGS")
.ok()
.and_then(|v| v.parse().ok())
.filter(|n: &u64| *n >= 1)
.unwrap_or(2),
enough_flags: env::var("FLAG_HIDE_ENOUGH_FLAGS")
.ok()
.and_then(|v| v.parse().ok())
.filter(|n: &u64| *n >= 1)
.unwrap_or(10),
},
min_trust_to_create_tag: env::var("MIN_TRUST_TO_CREATE_TAG")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(3),
}
}
}
impl Config {
/// Mark the session cookie `Secure` when the app is served over https.
pub fn secure_cookies(&self) -> bool {
self.public_url.starts_with("https://")
}
/// Whether mail actually goes out (mail-prism configured) rather than
/// only being logged.
pub fn mail_configured(&self) -> bool {
self.mail_prism_url.is_some() && self.mail_prism_api_key.is_some()
}
}
/// A set, non-blank environment variable (blank counts as unset).
fn env_present(key: &str) -> Option<String> {
env::var(key).ok().map(|v| v.trim().to_string()).filter(|v| !v.is_empty())
}
fn parse_bool(key: &str, default: bool) -> bool {
env::var(key)
.map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on"))
.unwrap_or(default)
}
/// `http://localhost:<port>` from a bind address like `0.0.0.0:3000`.
/// `LINK_SECRET` when unset: links still work, but anyone who reads this
/// can sign an `/out` link, so production sets its own.
pub const DEV_LINK_SECRET: &str = "recourse-dev-link-secret-change-me";
fn default_public_url(bind_address: &str) -> String {
let port = bind_address.rsplit(':').next().unwrap_or("3000");
format!("http://localhost:{port}")
}
pub async fn create_db_connection(database_url: &str) -> Result<DatabaseConnection, sea_orm::DbErr> {
sea_orm::Database::connect(database_url).await
}
neiam
/recourse
public · Issues · Pulls · Labels · Forks · Compare · Actions queued · Badges · Packages
⭐
Log in to mark this repository.
8.8 KiB · text
History
60fbb92