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}
43
44/// The operator name when `OPERATOR_NAME` is unset: neutral, because the
45/// crate does not know who runs it.
46pub const DEFAULT_OPERATOR_NAME: &str = "this integration proxy";
47
48/// Where GitHub Pages serves this repository's `overlays/` folder. Every
49/// overlay URL in the dated catalogs under `overlays/catalog/` starts with
50/// this prefix.
51pub const OVERLAYS_PAGES_BASE: &str = "https://ontola.github.io/atomic-plugins/overlays/";
52
53/// The default dated catalog's path under `overlays/`, for tests that read
54/// the checked-in copy; `default_catalog_is_the_published_checked_in_catalog`
55/// keeps it equal to [`DEFAULT_CATALOG_PATH`]'s.
56#[cfg(test)]
57pub const DEFAULT_CATALOG_FILE: &str = "catalog/2026-10-02-auth-profiles.json";
58
59/// `overlays/catalog/2026-10-02-auth-profiles.json` as GitHub Pages publishes it from this
60/// repository's `main`, used when `CATALOG_PATH` is not set. Unlike the
61/// unversioned catalog this replaced, its dated file and selected overlay
62/// revisions are immutable; the proxy reads it once, at startup. Shared with
63/// tests that need to validate the exact catalog the application would load
64/// by default (they read the checked-in copy; see `Catalog::load_checked_in`).
65pub const DEFAULT_CATALOG_PATH: &str =
66    "https://ontola.github.io/atomic-plugins/overlays/catalog/2026-10-02-auth-profiles.json";
67
68/// Reads a required environment variable and rejects it if unset or blank,
69/// so a blank `.env` value fails configuration explicitly instead of being
70/// silently accepted (e.g. as a reproducible empty secret).
71fn require_env(name: &str) -> Result<String, String> {
72    match env::var(name) {
73        Ok(value) if !value.is_empty() => Ok(value),
74        _ => Err(format!("{name} must be set")),
75    }
76}
77
78fn list(value: &str) -> Vec<String> {
79    value
80        .split(',')
81        .map(str::trim)
82        .filter(|s| !s.is_empty())
83        .map(str::to_owned)
84        .collect()
85}
86
87/// `BASE_URL` must be an absolute http(s) URL without credentials, query or
88/// fragment: it is the signed origin, so anything ambiguous is refused at
89/// startup rather than failing every signature later.
90pub(crate) fn validate_base_url(value: &str) -> Result<String, String> {
91    let url = Url::parse(value).map_err(|_| "BASE_URL must be an absolute URL".to_string())?;
92    if !matches!(url.scheme(), "https" | "http")
93        || url.host_str().is_none()
94        || !url.username().is_empty()
95        || url.password().is_some()
96        || url.query().is_some()
97        || url.fragment().is_some()
98    {
99        return Err(
100            "BASE_URL must be an http(s) URL without credentials, query or fragment".into(),
101        );
102    }
103    Ok(value.trim_end_matches('/').to_owned())
104}
105
106/// `OPERATOR_NAME`, trimmed; unset or blank means [`DEFAULT_OPERATOR_NAME`].
107pub(crate) fn operator_name(value: Option<&str>) -> String {
108    match value.map(str::trim) {
109        Some(name) if !name.is_empty() => name.to_owned(),
110        _ => DEFAULT_OPERATOR_NAME.to_owned(),
111    }
112}
113
114/// `OPERATOR_URL`, if set: an absolute http(s) URL without credentials. It is
115/// rendered as a link, so anything else (`javascript:`, a relative path) is
116/// refused at startup.
117pub(crate) fn validate_operator_url(value: Option<&str>) -> Result<Option<String>, String> {
118    let Some(value) = value.map(str::trim).filter(|value| !value.is_empty()) else {
119        return Ok(None);
120    };
121    let url = Url::parse(value)
122        .map_err(|_| "OPERATOR_URL must be an absolute http(s) URL".to_string())?;
123    if !matches!(url.scheme(), "https" | "http")
124        || url.host_str().is_none()
125        || !url.username().is_empty()
126        || url.password().is_some()
127    {
128        return Err("OPERATOR_URL must be an http(s) URL without credentials".into());
129    }
130    Ok(Some(url.to_string()))
131}
132
133/// `host[:port]` of an http(s) URL, the port only when it is not the
134/// scheme's default. Falls back to the input when it does not parse.
135pub(crate) fn public_host(base_url: &str) -> String {
136    match Url::parse(base_url) {
137        Ok(url) => match (url.host_str(), url.port()) {
138            (Some(host), Some(port)) => format!("{host}:{port}"),
139            (Some(host), None) => host.to_owned(),
140            _ => base_url.to_owned(),
141        },
142        Err(_) => base_url.to_owned(),
143    }
144}
145
146impl Config {
147    pub fn from_env() -> Result<Self, String> {
148        let base_url = validate_base_url(
149            &env::var("BASE_URL").unwrap_or_else(|_| "http://localhost:8080".to_string()),
150        )?;
151        let port = env::var("PORT")
152            .ok()
153            .and_then(|p| p.parse().ok())
154            .unwrap_or(8080);
155        // An empty SESSION_SECRET is treated as unset, so it triggers random
156        // key generation instead of being hashed into a reproducible,
157        // guessable cookie-encryption key.
158        let session_secret = env::var("SESSION_SECRET")
159            .ok()
160            .filter(|value| !value.is_empty());
161        let catalog_path =
162            env::var("CATALOG_PATH").unwrap_or_else(|_| DEFAULT_CATALOG_PATH.to_string());
163        let database_url = require_env("DATABASE_URL").map_err(|_| {
164            "DATABASE_URL must be set for connections and replay protection".to_string()
165        })?;
166        let encryption_key = require_env("ENCRYPTION_KEY")?;
167        let revoked_subjects = list(&env::var("REVOKED_SUBJECTS").unwrap_or_default());
168        let allowed_agents = env::var("ALLOWED_AGENTS")
169            .ok()
170            .filter(|value| !value.trim().is_empty())
171            .map(|value| list(&value));
172        let operator_name = operator_name(env::var("OPERATOR_NAME").ok().as_deref());
173        let operator_url = validate_operator_url(env::var("OPERATOR_URL").ok().as_deref())?;
174
175        Ok(Self {
176            base_url,
177            port,
178            session_secret,
179            catalog_path,
180            database_url,
181            encryption_key,
182            revoked_subjects,
183            allowed_agents,
184            operator_name,
185            operator_url,
186        })
187    }
188
189    /// The origin (`scheme://host[:port]`) of [`Config::base_url`]: a
190    /// capability's required `aud`.
191    pub fn public_origin(&self) -> String {
192        Url::parse(&self.base_url)
193            .map(|url| url.origin().ascii_serialization())
194            .unwrap_or_else(|_| self.base_url.clone())
195    }
196
197    /// `host[:port]` of [`Config::base_url`], as the consent page shows it.
198    pub fn public_host(&self) -> String {
199        public_host(&self.base_url)
200    }
201
202    /// OAuth callback and credential variable names are deterministic from the
203    /// catalog platform name, e.g. `google-calendar` becomes
204    /// `OAUTH_GOOGLE_CALENDAR_CLIENT_ID` and `/oauth/google-calendar/callback`.
205    pub fn provider_env_prefix(provider: &str) -> Result<String, String> {
206        if provider.is_empty()
207            || !provider
208                .bytes()
209                .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
210        {
211            return Err(
212                "provider names may contain only lowercase letters, digits, and hyphens"
213                    .to_string(),
214            );
215        }
216        Ok(format!(
217            "OAUTH_{}",
218            provider.replace('-', "_").to_ascii_uppercase()
219        ))
220    }
221}
222
223#[cfg(test)]
224mod tests {
225    use super::*;
226
227    #[test]
228    fn provider_names_produce_predictable_environment_prefixes() {
229        assert_eq!(
230            Config::provider_env_prefix("google-calendar").unwrap(),
231            "OAUTH_GOOGLE_CALENDAR"
232        );
233        assert!(Config::provider_env_prefix("Google Calendar").is_err());
234    }
235
236    #[test]
237    fn require_env_rejects_missing_and_blank_values() {
238        let name = "INTEGRATION_PROXY_TEST_REQUIRE_ENV_VAR";
239        env::remove_var(name);
240        assert!(require_env(name).is_err());
241        env::set_var(name, "");
242        assert!(require_env(name).is_err());
243        env::set_var(name, "a-value");
244        assert_eq!(require_env(name).unwrap(), "a-value");
245        env::remove_var(name);
246    }
247
248    #[test]
249    fn base_url_is_the_signed_origin_and_must_be_unambiguous() {
250        assert_eq!(
251            validate_base_url("https://proxy.example/").unwrap(),
252            "https://proxy.example"
253        );
254        assert_eq!(
255            validate_base_url("http://localhost:8080").unwrap(),
256            "http://localhost:8080"
257        );
258        for invalid in [
259            "proxy.example",
260            "ftp://proxy.example",
261            "https://u:p@proxy.example",
262            "https://proxy.example?x=1",
263            "https://proxy.example#x",
264        ] {
265            assert!(validate_base_url(invalid).is_err(), "{invalid}");
266        }
267        let config = Config {
268            base_url: "https://proxy.example:8443/prefix".into(),
269            port: 0,
270            session_secret: None,
271            catalog_path: String::new(),
272            database_url: String::new(),
273            encryption_key: String::new(),
274            revoked_subjects: vec![],
275            allowed_agents: None,
276            operator_name: DEFAULT_OPERATOR_NAME.into(),
277            operator_url: None,
278        };
279        assert_eq!(config.public_origin(), "https://proxy.example:8443");
280        assert_eq!(config.public_host(), "proxy.example:8443");
281        assert_eq!(public_host("https://proxy.example"), "proxy.example");
282        assert_eq!(public_host("http://127.0.0.1:8080"), "127.0.0.1:8080");
283    }
284
285    #[test]
286    fn operator_name_defaults_to_a_neutral_phrase() {
287        assert_eq!(operator_name(None), DEFAULT_OPERATOR_NAME);
288        assert_eq!(operator_name(Some("  ")), DEFAULT_OPERATOR_NAME);
289        assert_eq!(operator_name(Some(" Atomic Data ")), "Atomic Data");
290    }
291
292    #[test]
293    fn operator_url_is_optional_and_must_be_a_plain_http_url() {
294        assert_eq!(validate_operator_url(None).unwrap(), None);
295        assert_eq!(validate_operator_url(Some(" ")).unwrap(), None);
296        assert_eq!(
297            validate_operator_url(Some("https://atomic.place")).unwrap(),
298            Some("https://atomic.place/".into())
299        );
300        for invalid in [
301            "atomic.place",
302            "javascript:alert(1)",
303            "data:text/html,x",
304            "https://u:p@atomic.place",
305        ] {
306            assert!(validate_operator_url(Some(invalid)).is_err(), "{invalid}");
307        }
308    }
309
310    #[test]
311    fn lists_are_comma_separated_and_trimmed() {
312        assert_eq!(list(" a, b ,,c "), vec!["a", "b", "c"]);
313        assert!(list("").is_empty());
314    }
315}