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}
37
38/// Where GitHub Pages serves this repository's `overlays/` folder. Every
39/// overlay URL in `overlays/catalog.json` starts with this prefix.
40pub const OVERLAYS_PAGES_BASE: &str = "https://ontola.github.io/atomic-plugins/overlays/";
41
42/// `overlays/catalog.json` as GitHub Pages publishes it from this
43/// repository's `main`, used when `CATALOG_PATH` is not set. Unlike the
44/// commit-pinned `raw.githubusercontent.com` URLs this replaced, it changes
45/// whenever `main` changes; the proxy reads it once, at startup. Shared with
46/// tests that need to validate the exact catalog the application would load
47/// by default (they read the checked-in copy; see `Catalog::load_checked_in`).
48pub const DEFAULT_CATALOG_PATH: &str =
49    "https://ontola.github.io/atomic-plugins/overlays/catalog.json";
50
51/// Reads a required environment variable and rejects it if unset or blank,
52/// so a blank `.env` value fails configuration explicitly instead of being
53/// silently accepted (e.g. as a reproducible empty secret).
54fn require_env(name: &str) -> Result<String, String> {
55    match env::var(name) {
56        Ok(value) if !value.is_empty() => Ok(value),
57        _ => Err(format!("{name} must be set")),
58    }
59}
60
61fn list(value: &str) -> Vec<String> {
62    value
63        .split(',')
64        .map(str::trim)
65        .filter(|s| !s.is_empty())
66        .map(str::to_owned)
67        .collect()
68}
69
70/// `BASE_URL` must be an absolute http(s) URL without credentials, query or
71/// fragment: it is the signed origin, so anything ambiguous is refused at
72/// startup rather than failing every signature later.
73pub(crate) fn validate_base_url(value: &str) -> Result<String, String> {
74    let url = Url::parse(value).map_err(|_| "BASE_URL must be an absolute URL".to_string())?;
75    if !matches!(url.scheme(), "https" | "http")
76        || url.host_str().is_none()
77        || !url.username().is_empty()
78        || url.password().is_some()
79        || url.query().is_some()
80        || url.fragment().is_some()
81    {
82        return Err(
83            "BASE_URL must be an http(s) URL without credentials, query or fragment".into(),
84        );
85    }
86    Ok(value.trim_end_matches('/').to_owned())
87}
88
89impl Config {
90    pub fn from_env() -> Result<Self, String> {
91        let base_url = validate_base_url(
92            &env::var("BASE_URL").unwrap_or_else(|_| "http://localhost:8080".to_string()),
93        )?;
94        let port = env::var("PORT")
95            .ok()
96            .and_then(|p| p.parse().ok())
97            .unwrap_or(8080);
98        // An empty SESSION_SECRET is treated as unset, so it triggers random
99        // key generation instead of being hashed into a reproducible,
100        // guessable cookie-encryption key.
101        let session_secret = env::var("SESSION_SECRET")
102            .ok()
103            .filter(|value| !value.is_empty());
104        let catalog_path =
105            env::var("CATALOG_PATH").unwrap_or_else(|_| DEFAULT_CATALOG_PATH.to_string());
106        let database_url = require_env("DATABASE_URL").map_err(|_| {
107            "DATABASE_URL must be set for connections and replay protection".to_string()
108        })?;
109        let encryption_key = require_env("ENCRYPTION_KEY")?;
110        let revoked_subjects = list(&env::var("REVOKED_SUBJECTS").unwrap_or_default());
111        let allowed_agents = env::var("ALLOWED_AGENTS")
112            .ok()
113            .filter(|value| !value.trim().is_empty())
114            .map(|value| list(&value));
115
116        Ok(Self {
117            base_url,
118            port,
119            session_secret,
120            catalog_path,
121            database_url,
122            encryption_key,
123            revoked_subjects,
124            allowed_agents,
125        })
126    }
127
128    /// The origin (`scheme://host[:port]`) of [`Config::base_url`]: a
129    /// capability's required `aud`.
130    pub fn public_origin(&self) -> String {
131        Url::parse(&self.base_url)
132            .map(|url| url.origin().ascii_serialization())
133            .unwrap_or_else(|_| self.base_url.clone())
134    }
135
136    /// OAuth callback and credential variable names are deterministic from the
137    /// catalog platform name, e.g. `google-calendar` becomes
138    /// `OAUTH_GOOGLE_CALENDAR_CLIENT_ID` and `/oauth/google-calendar/callback`.
139    pub fn provider_env_prefix(provider: &str) -> Result<String, String> {
140        if provider.is_empty()
141            || !provider
142                .bytes()
143                .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
144        {
145            return Err(
146                "provider names may contain only lowercase letters, digits, and hyphens"
147                    .to_string(),
148            );
149        }
150        Ok(format!(
151            "OAUTH_{}",
152            provider.replace('-', "_").to_ascii_uppercase()
153        ))
154    }
155}
156
157#[cfg(test)]
158mod tests {
159    use super::*;
160
161    #[test]
162    fn provider_names_produce_predictable_environment_prefixes() {
163        assert_eq!(
164            Config::provider_env_prefix("google-calendar").unwrap(),
165            "OAUTH_GOOGLE_CALENDAR"
166        );
167        assert!(Config::provider_env_prefix("Google Calendar").is_err());
168    }
169
170    #[test]
171    fn require_env_rejects_missing_and_blank_values() {
172        let name = "INTEGRATION_PROXY_TEST_REQUIRE_ENV_VAR";
173        env::remove_var(name);
174        assert!(require_env(name).is_err());
175        env::set_var(name, "");
176        assert!(require_env(name).is_err());
177        env::set_var(name, "a-value");
178        assert_eq!(require_env(name).unwrap(), "a-value");
179        env::remove_var(name);
180    }
181
182    #[test]
183    fn base_url_is_the_signed_origin_and_must_be_unambiguous() {
184        assert_eq!(
185            validate_base_url("https://proxy.example/").unwrap(),
186            "https://proxy.example"
187        );
188        assert_eq!(
189            validate_base_url("http://localhost:8080").unwrap(),
190            "http://localhost:8080"
191        );
192        for invalid in [
193            "proxy.example",
194            "ftp://proxy.example",
195            "https://u:p@proxy.example",
196            "https://proxy.example?x=1",
197            "https://proxy.example#x",
198        ] {
199            assert!(validate_base_url(invalid).is_err(), "{invalid}");
200        }
201        let config = Config {
202            base_url: "https://proxy.example:8443/prefix".into(),
203            port: 0,
204            session_secret: None,
205            catalog_path: String::new(),
206            database_url: String::new(),
207            encryption_key: String::new(),
208            revoked_subjects: vec![],
209            allowed_agents: None,
210        };
211        assert_eq!(config.public_origin(), "https://proxy.example:8443");
212    }
213
214    #[test]
215    fn lists_are_comma_separated_and_trimmed() {
216        assert_eq!(list(" a, b ,,c "), vec!["a", "b", "c"]);
217        assert!(list("").is_empty());
218    }
219}