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