Skip to main content

atomic_integration_proxy/
config.rs

1use std::env;
2use url::Url;
3
4/// Runtime configuration, loaded entirely from environment variables so the
5/// server itself stays container-friendly.
6///
7/// Issue #54 removed the tenant concept. `APP_AUTH_*`, `SERVER_SECRET` and
8/// the other tenant-era variables are no longer read; leaving them set is
9/// harmless.
10#[derive(Clone)]
11pub struct Config {
12    /// Public URL the proxy is reachable at, e.g. `https://auth.example.com`.
13    /// Used for OAuth redirect URLs, and as the origin of the URL covered by
14    /// every Atomic v2 request signature and of a capability's `aud`. It must
15    /// be exactly what clients use: behind TLS termination the proxy cannot
16    /// tell its public scheme or host from the request.
17    pub base_url: String,
18    pub port: u16,
19    /// Secret used to encrypt the short-lived consent and OAuth-binding
20    /// cookies. If unset, a random key is generated at startup, so a consent
21    /// screen open during a restart has to be started again.
22    pub session_secret: Option<String>,
23    /// Local file or immutable HTTPS URL listing the pinned OADs and overlays.
24    pub catalog_path: String,
25    /// PostgreSQL: connections, delegations, runtimes, handoffs and the
26    /// single-use record of signed requests.
27    pub database_url: String,
28    /// Base64url-encoded 32-byte key for sealed provider credentials.
29    pub encryption_key: String,
30    /// `REVOKED_SUBJECTS`: comma-separated agent ids (any accepted spelling)
31    /// refused by the default access policy.
32    pub revoked_subjects: Vec<String>,
33    /// `ALLOWED_AGENTS`: when set, comma-separated agent ids; the default
34    /// access policy admits only these owners.
35    pub allowed_agents: Option<Vec<String>>,
36    /// `OPERATOR_NAME`: who runs this proxy, as the landing and consent pages
37    /// name them. Defaults to [`DEFAULT_OPERATOR_NAME`] when unset or blank.
38    pub operator_name: String,
39    /// `OPERATOR_URL`: optional absolute http(s) link for the operator's
40    /// name on those pages.
41    pub operator_url: Option<String>,
42    /// `KEY_CHECK_LIMIT_PER_HOUR`: the most API key or token checks the
43    /// consent form makes for one client network and platform in any hour.
44    /// Defaults to [`DEFAULT_KEY_CHECK_LIMIT_PER_HOUR`]; `0` turns the limit
45    /// off.
46    pub key_check_limit_per_hour: u32,
47    /// `TRUST_FORWARDED_FOR`: where the client address of that limit comes
48    /// from. Defaults to [`TrustForwardedFor::None`].
49    pub trust_forwarded_for: TrustForwardedFor,
50}
51
52/// The key checks one client network may make per platform and hour when
53/// `KEY_CHECK_LIMIT_PER_HOUR` is unset. A person entering a key makes one to
54/// three.
55pub const DEFAULT_KEY_CHECK_LIMIT_PER_HOUR: u32 = 20;
56
57/// Which client address the key-check limit counts against
58/// (`TRUST_FORWARDED_FOR`).
59#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
60#[non_exhaustive]
61pub enum TrustForwardedFor {
62    /// `none`: the TCP peer address; every `X-Forwarded-For` is ignored.
63    /// Right when nothing sits in front of the proxy, and the default.
64    #[default]
65    None,
66    /// `heroku`, or its synonym `rightmost`: the right-most
67    /// `X-Forwarded-For` entry, the one the proxy in front appended (Heroku's
68    /// router does; so do Caddy and nginx with
69    /// `$proxy_add_x_forwarded_for`); everything to its left came from the
70    /// client and is ignored. Only right when every request reaches the
71    /// proxy through exactly one such proxy: without it a client can write
72    /// that entry itself.
73    RightMost,
74}
75
76impl std::str::FromStr for TrustForwardedFor {
77    type Err = String;
78
79    fn from_str(value: &str) -> Result<Self, String> {
80        match value.trim() {
81            "" | "none" => Ok(Self::None),
82            "heroku" | "rightmost" => Ok(Self::RightMost),
83            _ => Err("TRUST_FORWARDED_FOR must be `none`, `heroku` or `rightmost`".into()),
84        }
85    }
86}
87
88/// The highest `KEY_CHECK_LIMIT_PER_HOUR` accepted. Each check may scan the
89/// network's slots, so a huge limit makes every key check slow (2,000,000
90/// took 640 ms per insert); `0` is the way to turn the limit off.
91pub const MAX_KEY_CHECK_LIMIT_PER_HOUR: u32 = 10_000;
92
93/// `KEY_CHECK_LIMIT_PER_HOUR`: unset or blank means
94/// [`DEFAULT_KEY_CHECK_LIMIT_PER_HOUR`], `0` means no limit; anything but a
95/// whole number from 0 to [`MAX_KEY_CHECK_LIMIT_PER_HOUR`] is refused at
96/// startup.
97pub(crate) fn key_check_limit(value: Option<&str>) -> Result<u32, String> {
98    let invalid = || {
99        format!(
100            "KEY_CHECK_LIMIT_PER_HOUR must be a whole number from 0 (no limit) to {MAX_KEY_CHECK_LIMIT_PER_HOUR}"
101        )
102    };
103    match value.map(str::trim) {
104        None | Some("") => Ok(DEFAULT_KEY_CHECK_LIMIT_PER_HOUR),
105        Some(value) => match value.parse::<u32>() {
106            Ok(limit) if limit <= MAX_KEY_CHECK_LIMIT_PER_HOUR => Ok(limit),
107            _ => Err(invalid()),
108        },
109    }
110}
111
112/// The operator name when `OPERATOR_NAME` is unset: neutral, because the
113/// crate does not know who runs it.
114pub const DEFAULT_OPERATOR_NAME: &str = "this integration proxy";
115
116/// Where GitHub Pages serves this repository's `overlays/` folder. Every
117/// overlay URL in the dated catalogs under `overlays/catalog/` starts with
118/// this prefix.
119pub const OVERLAYS_PAGES_BASE: &str = "https://ontola.github.io/atomic-plugins/overlays/";
120
121/// The default dated catalog's path under `overlays/`, for tests that read
122/// the checked-in copy; `default_catalog_is_the_published_checked_in_catalog`
123/// keeps it equal to [`DEFAULT_CATALOG_PATH`]'s.
124#[cfg(test)]
125pub const DEFAULT_CATALOG_FILE: &str = "catalog/2026-10-02-auth-profiles.json";
126
127/// `overlays/catalog/2026-10-02-auth-profiles.json` as GitHub Pages publishes it from this
128/// repository's `main`, used when `CATALOG_PATH` is not set. Unlike the
129/// unversioned catalog this replaced, its dated file and selected overlay
130/// revisions are immutable; the proxy reads it once, at startup. Shared with
131/// tests that need to validate the exact catalog the application would load
132/// by default (they read the checked-in copy; see `Catalog::load_checked_in`).
133pub const DEFAULT_CATALOG_PATH: &str =
134    "https://ontola.github.io/atomic-plugins/overlays/catalog/2026-10-02-auth-profiles.json";
135
136/// Reads a required environment variable and rejects it if unset or blank,
137/// so a blank `.env` value fails configuration explicitly instead of being
138/// silently accepted (e.g. as a reproducible empty secret).
139fn require_env(name: &str) -> Result<String, String> {
140    match env::var(name) {
141        Ok(value) if !value.is_empty() => Ok(value),
142        _ => Err(format!("{name} must be set")),
143    }
144}
145
146fn list(value: &str) -> Vec<String> {
147    value
148        .split(',')
149        .map(str::trim)
150        .filter(|s| !s.is_empty())
151        .map(str::to_owned)
152        .collect()
153}
154
155/// `BASE_URL` must be an absolute http(s) URL without credentials, query or
156/// fragment: it is the signed origin, so anything ambiguous is refused at
157/// startup rather than failing every signature later.
158pub(crate) fn validate_base_url(value: &str) -> Result<String, String> {
159    let url = Url::parse(value).map_err(|_| "BASE_URL must be an absolute URL".to_string())?;
160    if !matches!(url.scheme(), "https" | "http")
161        || url.host_str().is_none()
162        || !url.username().is_empty()
163        || url.password().is_some()
164        || url.query().is_some()
165        || url.fragment().is_some()
166    {
167        return Err(
168            "BASE_URL must be an http(s) URL without credentials, query or fragment".into(),
169        );
170    }
171    Ok(value.trim_end_matches('/').to_owned())
172}
173
174/// `OPERATOR_NAME`, trimmed; unset or blank means [`DEFAULT_OPERATOR_NAME`].
175pub(crate) fn operator_name(value: Option<&str>) -> String {
176    match value.map(str::trim) {
177        Some(name) if !name.is_empty() => name.to_owned(),
178        _ => DEFAULT_OPERATOR_NAME.to_owned(),
179    }
180}
181
182/// `OPERATOR_URL`, if set: an absolute http(s) URL without credentials. It is
183/// rendered as a link, so anything else (`javascript:`, a relative path) is
184/// refused at startup.
185pub(crate) fn validate_operator_url(value: Option<&str>) -> Result<Option<String>, String> {
186    let Some(value) = value.map(str::trim).filter(|value| !value.is_empty()) else {
187        return Ok(None);
188    };
189    let url = Url::parse(value)
190        .map_err(|_| "OPERATOR_URL must be an absolute http(s) URL".to_string())?;
191    if !matches!(url.scheme(), "https" | "http")
192        || url.host_str().is_none()
193        || !url.username().is_empty()
194        || url.password().is_some()
195    {
196        return Err("OPERATOR_URL must be an http(s) URL without credentials".into());
197    }
198    Ok(Some(url.to_string()))
199}
200
201/// `host[:port]` of an http(s) URL, the port only when it is not the
202/// scheme's default. Falls back to the input when it does not parse.
203pub(crate) fn public_host(base_url: &str) -> String {
204    match Url::parse(base_url) {
205        Ok(url) => match (url.host_str(), url.port()) {
206            (Some(host), Some(port)) => format!("{host}:{port}"),
207            (Some(host), None) => host.to_owned(),
208            _ => base_url.to_owned(),
209        },
210        Err(_) => base_url.to_owned(),
211    }
212}
213
214impl Config {
215    pub fn from_env() -> Result<Self, String> {
216        let base_url = validate_base_url(
217            &env::var("BASE_URL").unwrap_or_else(|_| "http://localhost:8080".to_string()),
218        )?;
219        let port = env::var("PORT")
220            .ok()
221            .and_then(|p| p.parse().ok())
222            .unwrap_or(8080);
223        // An empty SESSION_SECRET is treated as unset, so it triggers random
224        // key generation instead of being hashed into a reproducible,
225        // guessable cookie-encryption key.
226        let session_secret = env::var("SESSION_SECRET")
227            .ok()
228            .filter(|value| !value.is_empty());
229        let catalog_path =
230            env::var("CATALOG_PATH").unwrap_or_else(|_| DEFAULT_CATALOG_PATH.to_string());
231        let database_url = require_env("DATABASE_URL").map_err(|_| {
232            "DATABASE_URL must be set for connections and replay protection".to_string()
233        })?;
234        let encryption_key = require_env("ENCRYPTION_KEY")?;
235        let revoked_subjects = list(&env::var("REVOKED_SUBJECTS").unwrap_or_default());
236        let allowed_agents = env::var("ALLOWED_AGENTS")
237            .ok()
238            .filter(|value| !value.trim().is_empty())
239            .map(|value| list(&value));
240        let operator_name = operator_name(env::var("OPERATOR_NAME").ok().as_deref());
241        let operator_url = validate_operator_url(env::var("OPERATOR_URL").ok().as_deref())?;
242        let key_check_limit_per_hour =
243            key_check_limit(env::var("KEY_CHECK_LIMIT_PER_HOUR").ok().as_deref())?;
244        let trust_forwarded_for = env::var("TRUST_FORWARDED_FOR")
245            .unwrap_or_default()
246            .parse()?;
247
248        Ok(Self {
249            base_url,
250            port,
251            session_secret,
252            catalog_path,
253            database_url,
254            encryption_key,
255            revoked_subjects,
256            allowed_agents,
257            operator_name,
258            operator_url,
259            key_check_limit_per_hour,
260            trust_forwarded_for,
261        })
262    }
263
264    /// The origin (`scheme://host[:port]`) of [`Config::base_url`]: a
265    /// capability's required `aud`.
266    pub fn public_origin(&self) -> String {
267        Url::parse(&self.base_url)
268            .map(|url| url.origin().ascii_serialization())
269            .unwrap_or_else(|_| self.base_url.clone())
270    }
271
272    /// `host[:port]` of [`Config::base_url`], as the consent page shows it.
273    pub fn public_host(&self) -> String {
274        public_host(&self.base_url)
275    }
276
277    /// OAuth callback and credential variable names are deterministic from the
278    /// catalog platform name, e.g. `google-calendar` becomes
279    /// `OAUTH_GOOGLE_CALENDAR_CLIENT_ID` and `/oauth/google-calendar/callback`.
280    pub fn provider_env_prefix(provider: &str) -> Result<String, String> {
281        if provider.is_empty()
282            || !provider
283                .bytes()
284                .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
285        {
286            return Err(
287                "provider names may contain only lowercase letters, digits, and hyphens"
288                    .to_string(),
289            );
290        }
291        Ok(format!(
292            "OAUTH_{}",
293            provider.replace('-', "_").to_ascii_uppercase()
294        ))
295    }
296}
297
298#[cfg(test)]
299mod tests {
300    use super::*;
301
302    #[test]
303    fn provider_names_produce_predictable_environment_prefixes() {
304        assert_eq!(
305            Config::provider_env_prefix("google-calendar").unwrap(),
306            "OAUTH_GOOGLE_CALENDAR"
307        );
308        assert!(Config::provider_env_prefix("Google Calendar").is_err());
309    }
310
311    #[test]
312    fn require_env_rejects_missing_and_blank_values() {
313        let name = "INTEGRATION_PROXY_TEST_REQUIRE_ENV_VAR";
314        env::remove_var(name);
315        assert!(require_env(name).is_err());
316        env::set_var(name, "");
317        assert!(require_env(name).is_err());
318        env::set_var(name, "a-value");
319        assert_eq!(require_env(name).unwrap(), "a-value");
320        env::remove_var(name);
321    }
322
323    #[test]
324    fn base_url_is_the_signed_origin_and_must_be_unambiguous() {
325        assert_eq!(
326            validate_base_url("https://proxy.example/").unwrap(),
327            "https://proxy.example"
328        );
329        assert_eq!(
330            validate_base_url("http://localhost:8080").unwrap(),
331            "http://localhost:8080"
332        );
333        for invalid in [
334            "proxy.example",
335            "ftp://proxy.example",
336            "https://u:p@proxy.example",
337            "https://proxy.example?x=1",
338            "https://proxy.example#x",
339        ] {
340            assert!(validate_base_url(invalid).is_err(), "{invalid}");
341        }
342        let config = Config {
343            base_url: "https://proxy.example:8443/prefix".into(),
344            port: 0,
345            session_secret: None,
346            catalog_path: String::new(),
347            database_url: String::new(),
348            encryption_key: String::new(),
349            revoked_subjects: vec![],
350            allowed_agents: None,
351            operator_name: DEFAULT_OPERATOR_NAME.into(),
352            operator_url: None,
353            key_check_limit_per_hour: 0,
354            trust_forwarded_for: TrustForwardedFor::None,
355        };
356        assert_eq!(config.public_origin(), "https://proxy.example:8443");
357        assert_eq!(config.public_host(), "proxy.example:8443");
358        assert_eq!(public_host("https://proxy.example"), "proxy.example");
359        assert_eq!(public_host("http://127.0.0.1:8080"), "127.0.0.1:8080");
360    }
361
362    #[test]
363    fn operator_name_defaults_to_a_neutral_phrase() {
364        assert_eq!(operator_name(None), DEFAULT_OPERATOR_NAME);
365        assert_eq!(operator_name(Some("  ")), DEFAULT_OPERATOR_NAME);
366        assert_eq!(operator_name(Some(" Atomic Data ")), "Atomic Data");
367    }
368
369    #[test]
370    fn operator_url_is_optional_and_must_be_a_plain_http_url() {
371        assert_eq!(validate_operator_url(None).unwrap(), None);
372        assert_eq!(validate_operator_url(Some(" ")).unwrap(), None);
373        assert_eq!(
374            validate_operator_url(Some("https://atomic.place")).unwrap(),
375            Some("https://atomic.place/".into())
376        );
377        for invalid in [
378            "atomic.place",
379            "javascript:alert(1)",
380            "data:text/html,x",
381            "https://u:p@atomic.place",
382        ] {
383            assert!(validate_operator_url(Some(invalid)).is_err(), "{invalid}");
384        }
385    }
386
387    #[test]
388    fn the_key_check_limit_defaults_to_twenty_and_zero_turns_it_off() {
389        assert_eq!(key_check_limit(None).unwrap(), 20);
390        assert_eq!(key_check_limit(Some(" ")).unwrap(), 20);
391        assert_eq!(key_check_limit(Some("0")).unwrap(), 0);
392        assert_eq!(key_check_limit(Some(" 50 ")).unwrap(), 50);
393        assert_eq!(key_check_limit(Some("10000")).unwrap(), 10_000);
394        for invalid in ["-1", "twenty", "1.5", "10001", "2000000", "99999999999"] {
395            let error = key_check_limit(Some(invalid)).unwrap_err();
396            assert!(
397                error.contains("0 (no limit) to 10000"),
398                "{invalid}: {error}"
399            );
400        }
401    }
402
403    #[test]
404    fn forwarded_for_is_trusted_only_when_named() {
405        assert_eq!("".parse(), Ok(TrustForwardedFor::None));
406        assert_eq!("none".parse(), Ok(TrustForwardedFor::None));
407        assert_eq!(" heroku ".parse(), Ok(TrustForwardedFor::RightMost));
408        assert_eq!("rightmost".parse(), Ok(TrustForwardedFor::RightMost));
409        for invalid in ["Heroku", "true", "all", "x-forwarded-for"] {
410            assert!(invalid.parse::<TrustForwardedFor>().is_err(), "{invalid}");
411        }
412    }
413
414    #[test]
415    fn lists_are_comma_separated_and_trimmed() {
416        assert_eq!(list(" a, b ,,c "), vec!["a", "b", "c"]);
417        assert!(list("").is_empty());
418    }
419}