use std::env;
use url::Url;
#[derive(Clone)]
pub struct Config {
pub base_url: String,
pub port: u16,
pub session_secret: Option<String>,
pub catalog_path: String,
pub database_url: String,
pub encryption_key: String,
pub revoked_subjects: Vec<String>,
pub allowed_agents: Option<Vec<String>>,
pub operator_name: String,
pub operator_url: Option<String>,
pub key_check_limit_per_hour: u32,
pub trust_forwarded_for: TrustForwardedFor,
}
pub const DEFAULT_KEY_CHECK_LIMIT_PER_HOUR: u32 = 20;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum TrustForwardedFor {
#[default]
None,
RightMost,
}
impl std::str::FromStr for TrustForwardedFor {
type Err = String;
fn from_str(value: &str) -> Result<Self, String> {
match value.trim() {
"" | "none" => Ok(Self::None),
"heroku" | "rightmost" => Ok(Self::RightMost),
_ => Err("TRUST_FORWARDED_FOR must be `none`, `heroku` or `rightmost`".into()),
}
}
}
pub const MAX_KEY_CHECK_LIMIT_PER_HOUR: u32 = 10_000;
pub(crate) fn key_check_limit(value: Option<&str>) -> Result<u32, String> {
let invalid = || {
format!(
"KEY_CHECK_LIMIT_PER_HOUR must be a whole number from 0 (no limit) to {MAX_KEY_CHECK_LIMIT_PER_HOUR}"
)
};
match value.map(str::trim) {
None | Some("") => Ok(DEFAULT_KEY_CHECK_LIMIT_PER_HOUR),
Some(value) => match value.parse::<u32>() {
Ok(limit) if limit <= MAX_KEY_CHECK_LIMIT_PER_HOUR => Ok(limit),
_ => Err(invalid()),
},
}
}
pub const DEFAULT_OPERATOR_NAME: &str = "this integration proxy";
pub const OVERLAYS_PAGES_BASE: &str = "https://ontola.github.io/atomic-plugins/overlays/";
#[cfg(test)]
pub const DEFAULT_CATALOG_FILE: &str = "catalog/2026-10-02-auth-profiles.json";
pub const DEFAULT_CATALOG_PATH: &str =
"https://ontola.github.io/atomic-plugins/overlays/catalog/2026-10-02-auth-profiles.json";
fn require_env(name: &str) -> Result<String, String> {
match env::var(name) {
Ok(value) if !value.is_empty() => Ok(value),
_ => Err(format!("{name} must be set")),
}
}
fn list(value: &str) -> Vec<String> {
value
.split(',')
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_owned)
.collect()
}
pub(crate) fn validate_base_url(value: &str) -> Result<String, String> {
let url = Url::parse(value).map_err(|_| "BASE_URL must be an absolute URL".to_string())?;
if !matches!(url.scheme(), "https" | "http")
|| url.host_str().is_none()
|| !url.username().is_empty()
|| url.password().is_some()
|| url.query().is_some()
|| url.fragment().is_some()
{
return Err(
"BASE_URL must be an http(s) URL without credentials, query or fragment".into(),
);
}
Ok(value.trim_end_matches('/').to_owned())
}
pub(crate) fn operator_name(value: Option<&str>) -> String {
match value.map(str::trim) {
Some(name) if !name.is_empty() => name.to_owned(),
_ => DEFAULT_OPERATOR_NAME.to_owned(),
}
}
pub(crate) fn validate_operator_url(value: Option<&str>) -> Result<Option<String>, String> {
let Some(value) = value.map(str::trim).filter(|value| !value.is_empty()) else {
return Ok(None);
};
let url = Url::parse(value)
.map_err(|_| "OPERATOR_URL must be an absolute http(s) URL".to_string())?;
if !matches!(url.scheme(), "https" | "http")
|| url.host_str().is_none()
|| !url.username().is_empty()
|| url.password().is_some()
{
return Err("OPERATOR_URL must be an http(s) URL without credentials".into());
}
Ok(Some(url.to_string()))
}
pub(crate) fn public_host(base_url: &str) -> String {
match Url::parse(base_url) {
Ok(url) => match (url.host_str(), url.port()) {
(Some(host), Some(port)) => format!("{host}:{port}"),
(Some(host), None) => host.to_owned(),
_ => base_url.to_owned(),
},
Err(_) => base_url.to_owned(),
}
}
impl Config {
pub fn from_env() -> Result<Self, String> {
let base_url = validate_base_url(
&env::var("BASE_URL").unwrap_or_else(|_| "http://localhost:8080".to_string()),
)?;
let port = env::var("PORT")
.ok()
.and_then(|p| p.parse().ok())
.unwrap_or(8080);
let session_secret = env::var("SESSION_SECRET")
.ok()
.filter(|value| !value.is_empty());
let catalog_path =
env::var("CATALOG_PATH").unwrap_or_else(|_| DEFAULT_CATALOG_PATH.to_string());
let database_url = require_env("DATABASE_URL").map_err(|_| {
"DATABASE_URL must be set for connections and replay protection".to_string()
})?;
let encryption_key = require_env("ENCRYPTION_KEY")?;
let revoked_subjects = list(&env::var("REVOKED_SUBJECTS").unwrap_or_default());
let allowed_agents = env::var("ALLOWED_AGENTS")
.ok()
.filter(|value| !value.trim().is_empty())
.map(|value| list(&value));
let operator_name = operator_name(env::var("OPERATOR_NAME").ok().as_deref());
let operator_url = validate_operator_url(env::var("OPERATOR_URL").ok().as_deref())?;
let key_check_limit_per_hour =
key_check_limit(env::var("KEY_CHECK_LIMIT_PER_HOUR").ok().as_deref())?;
let trust_forwarded_for = env::var("TRUST_FORWARDED_FOR")
.unwrap_or_default()
.parse()?;
Ok(Self {
base_url,
port,
session_secret,
catalog_path,
database_url,
encryption_key,
revoked_subjects,
allowed_agents,
operator_name,
operator_url,
key_check_limit_per_hour,
trust_forwarded_for,
})
}
pub fn public_origin(&self) -> String {
Url::parse(&self.base_url)
.map(|url| url.origin().ascii_serialization())
.unwrap_or_else(|_| self.base_url.clone())
}
pub fn public_host(&self) -> String {
public_host(&self.base_url)
}
pub fn provider_env_prefix(provider: &str) -> Result<String, String> {
if provider.is_empty()
|| !provider
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
{
return Err(
"provider names may contain only lowercase letters, digits, and hyphens"
.to_string(),
);
}
Ok(format!(
"OAUTH_{}",
provider.replace('-', "_").to_ascii_uppercase()
))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn provider_names_produce_predictable_environment_prefixes() {
assert_eq!(
Config::provider_env_prefix("google-calendar").unwrap(),
"OAUTH_GOOGLE_CALENDAR"
);
assert!(Config::provider_env_prefix("Google Calendar").is_err());
}
#[test]
fn require_env_rejects_missing_and_blank_values() {
let name = "INTEGRATION_PROXY_TEST_REQUIRE_ENV_VAR";
env::remove_var(name);
assert!(require_env(name).is_err());
env::set_var(name, "");
assert!(require_env(name).is_err());
env::set_var(name, "a-value");
assert_eq!(require_env(name).unwrap(), "a-value");
env::remove_var(name);
}
#[test]
fn base_url_is_the_signed_origin_and_must_be_unambiguous() {
assert_eq!(
validate_base_url("https://proxy.example/").unwrap(),
"https://proxy.example"
);
assert_eq!(
validate_base_url("http://localhost:8080").unwrap(),
"http://localhost:8080"
);
for invalid in [
"proxy.example",
"ftp://proxy.example",
"https://u:p@proxy.example",
"https://proxy.example?x=1",
"https://proxy.example#x",
] {
assert!(validate_base_url(invalid).is_err(), "{invalid}");
}
let config = Config {
base_url: "https://proxy.example:8443/prefix".into(),
port: 0,
session_secret: None,
catalog_path: String::new(),
database_url: String::new(),
encryption_key: String::new(),
revoked_subjects: vec![],
allowed_agents: None,
operator_name: DEFAULT_OPERATOR_NAME.into(),
operator_url: None,
key_check_limit_per_hour: 0,
trust_forwarded_for: TrustForwardedFor::None,
};
assert_eq!(config.public_origin(), "https://proxy.example:8443");
assert_eq!(config.public_host(), "proxy.example:8443");
assert_eq!(public_host("https://proxy.example"), "proxy.example");
assert_eq!(public_host("http://127.0.0.1:8080"), "127.0.0.1:8080");
}
#[test]
fn operator_name_defaults_to_a_neutral_phrase() {
assert_eq!(operator_name(None), DEFAULT_OPERATOR_NAME);
assert_eq!(operator_name(Some(" ")), DEFAULT_OPERATOR_NAME);
assert_eq!(operator_name(Some(" Atomic Data ")), "Atomic Data");
}
#[test]
fn operator_url_is_optional_and_must_be_a_plain_http_url() {
assert_eq!(validate_operator_url(None).unwrap(), None);
assert_eq!(validate_operator_url(Some(" ")).unwrap(), None);
assert_eq!(
validate_operator_url(Some("https://atomic.place")).unwrap(),
Some("https://atomic.place/".into())
);
for invalid in [
"atomic.place",
"javascript:alert(1)",
"data:text/html,x",
"https://u:p@atomic.place",
] {
assert!(validate_operator_url(Some(invalid)).is_err(), "{invalid}");
}
}
#[test]
fn the_key_check_limit_defaults_to_twenty_and_zero_turns_it_off() {
assert_eq!(key_check_limit(None).unwrap(), 20);
assert_eq!(key_check_limit(Some(" ")).unwrap(), 20);
assert_eq!(key_check_limit(Some("0")).unwrap(), 0);
assert_eq!(key_check_limit(Some(" 50 ")).unwrap(), 50);
assert_eq!(key_check_limit(Some("10000")).unwrap(), 10_000);
for invalid in ["-1", "twenty", "1.5", "10001", "2000000", "99999999999"] {
let error = key_check_limit(Some(invalid)).unwrap_err();
assert!(
error.contains("0 (no limit) to 10000"),
"{invalid}: {error}"
);
}
}
#[test]
fn forwarded_for_is_trusted_only_when_named() {
assert_eq!("".parse(), Ok(TrustForwardedFor::None));
assert_eq!("none".parse(), Ok(TrustForwardedFor::None));
assert_eq!(" heroku ".parse(), Ok(TrustForwardedFor::RightMost));
assert_eq!("rightmost".parse(), Ok(TrustForwardedFor::RightMost));
for invalid in ["Heroku", "true", "all", "x-forwarded-for"] {
assert!(invalid.parse::<TrustForwardedFor>().is_err(), "{invalid}");
}
}
#[test]
fn lists_are_comma_separated_and_trimmed() {
assert_eq!(list(" a, b ,,c "), vec!["a", "b", "c"]);
assert!(list("").is_empty());
}
}