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    /// `WEBHOOKS_ENABLED` and the webhook inbox's limits. Off by default.
51    pub webhooks: WebhookConfig,
52    /// Registered public device clients and the owner approval bridge. Disabled by default.
53    pub device: crate::device::DeviceConfig,
54}
55
56/// The webhook inbox (ontola/atomic-plugins#369). Off unless
57/// `WEBHOOKS_ENABLED=true`: then, and only then, the proxy creates the inbox
58/// tables and runs the inbox sweeper. No webhook route is mounted yet.
59#[derive(Clone, Debug, PartialEq, Eq)]
60#[non_exhaustive]
61pub struct WebhookConfig {
62    /// Discard verified provider bodies after extracting routing metadata.
63    /// WEBHOOK_NOTIFICATIONS_ONLY=true stores only a fixed change hint.
64    pub notifications_only: bool,
65    /// `WEBHOOKS_ENABLED`: `true` turns the inbox on; unset, empty or
66    /// `false` leaves it off. Anything else stops the proxy at startup.
67    pub enabled: bool,
68    /// `WEBHOOK_INBOX_MAX_BYTES`: the deployment's inbox budget in bytes,
69    /// payloads plus the stated per-row overhead. Defaults to
70    /// [`DEFAULT_WEBHOOK_INBOX_MAX_BYTES`] (1 GiB).
71    pub inbox_max_bytes: i64,
72    /// `WEBHOOK_INGRESS_LIMIT_PER_ENDPOINT`: failed verifications one
73    /// existing endpoint counts per minute, per instance; over it, further
74    /// ones get `429` instead of `401`. A delivery that verifies is never
75    /// refused for it. Default 600.
76    pub ingress_per_endpoint_per_minute: u32,
77    /// `WEBHOOK_INGRESS_LIMIT_PER_NETWORK`: refusals one client network (as
78    /// `TRUST_FORWARDED_FOR` finds it) may cause per minute, per instance
79    /// (not `400` or `408`). Over it, its requests for ids that name no
80    /// endpoint get `429`, and at most 2 requests of networks over their
81    /// limit may wait for or hold the lookup slot at a time. Default 120.
82    pub ingress_per_network_per_minute: u32,
83    /// `WEBHOOK_SUBSCRIBE_LIMIT_PER_OWNER`: subscription requests per
84    /// connection owner per hour, per instance, counted before the access
85    /// check reaches the provider. Default 20.
86    pub subscribe_per_owner_per_hour: u32,
87}
88
89impl Default for WebhookConfig {
90    fn default() -> Self {
91        Self {
92            notifications_only: false,
93            enabled: false,
94            inbox_max_bytes: DEFAULT_WEBHOOK_INBOX_MAX_BYTES,
95            ingress_per_endpoint_per_minute: 600,
96            ingress_per_network_per_minute: 120,
97            subscribe_per_owner_per_hour: 20,
98        }
99    }
100}
101
102/// The largest value of a webhook rate limit.
103const MAX_WEBHOOK_LIMIT: u32 = 100_000;
104
105fn webhook_limit(name: &str, value: Option<&str>, default: u32) -> Result<u32, String> {
106    match value.map(str::trim) {
107        None | Some("") => Ok(default),
108        Some(value) => match value.parse::<u32>() {
109            Ok(limit) if (1..=MAX_WEBHOOK_LIMIT).contains(&limit) => Ok(limit),
110            _ => Err(format!(
111                "{name} must be a whole number from 1 to {MAX_WEBHOOK_LIMIT}"
112            )),
113        },
114    }
115}
116
117/// The deployment inbox budget when `WEBHOOK_INBOX_MAX_BYTES` is unset: the
118/// plan's 1 GiB pilot value.
119pub const DEFAULT_WEBHOOK_INBOX_MAX_BYTES: i64 = 1 << 30;
120
121/// The smallest `WEBHOOK_INBOX_MAX_BYTES` accepted: the owner budget
122/// (256 MiB), so one owner's limit can always be reached before the
123/// deployment's.
124const MIN_WEBHOOK_INBOX_MAX_BYTES: i64 = 256 << 20;
125
126/// The webhook variables as read from the environment, by name.
127pub(crate) type WebhookVariables<'a> = &'a dyn Fn(&str) -> Option<String>;
128
129#[cfg(test)]
130pub(crate) fn webhook_config(
131    enabled: Option<&str>,
132    inbox_max_bytes: Option<&str>,
133) -> Result<WebhookConfig, String> {
134    webhook_config_with(enabled, inbox_max_bytes, &|_| None)
135}
136
137/// [`webhook_config`] plus the rate limits, read only when the inbox is on.
138pub(crate) fn webhook_config_with(
139    enabled: Option<&str>,
140    inbox_max_bytes: Option<&str>,
141    variable: WebhookVariables<'_>,
142) -> Result<WebhookConfig, String> {
143    let enabled = match enabled.map(str::trim) {
144        None | Some("") | Some("false") => false,
145        Some("true") => true,
146        Some(_) => return Err("WEBHOOKS_ENABLED must be true or false".into()),
147    };
148    // Read only when the inbox is on: off, the variable is ignored.
149    let inbox_max_bytes = match inbox_max_bytes.map(str::trim).filter(|_| enabled) {
150        None | Some("") => DEFAULT_WEBHOOK_INBOX_MAX_BYTES,
151        Some(value) => match value.parse::<i64>() {
152            Ok(bytes) if bytes >= MIN_WEBHOOK_INBOX_MAX_BYTES => bytes,
153            _ => {
154                return Err(format!(
155                    "WEBHOOK_INBOX_MAX_BYTES must be a whole number of bytes, at least {MIN_WEBHOOK_INBOX_MAX_BYTES}"
156                ))
157            }
158        },
159    };
160    let defaults = WebhookConfig::default();
161    let limit = |name: &str, default: u32| {
162        if enabled {
163            webhook_limit(name, variable(name).as_deref(), default)
164        } else {
165            Ok(default)
166        }
167    };
168    let notifications_only = match variable("WEBHOOK_NOTIFICATIONS_ONLY")
169        .as_deref()
170        .map(str::trim)
171    {
172        None | Some("") | Some("false") => false,
173        Some("true") => true,
174        Some(_) => return Err("WEBHOOK_NOTIFICATIONS_ONLY must be true or false".into()),
175    };
176    Ok(WebhookConfig {
177        notifications_only,
178        enabled,
179        inbox_max_bytes,
180        ingress_per_endpoint_per_minute: limit(
181            "WEBHOOK_INGRESS_LIMIT_PER_ENDPOINT",
182            defaults.ingress_per_endpoint_per_minute,
183        )?,
184        ingress_per_network_per_minute: limit(
185            "WEBHOOK_INGRESS_LIMIT_PER_NETWORK",
186            defaults.ingress_per_network_per_minute,
187        )?,
188        subscribe_per_owner_per_hour: limit(
189            "WEBHOOK_SUBSCRIBE_LIMIT_PER_OWNER",
190            defaults.subscribe_per_owner_per_hour,
191        )?,
192    })
193}
194
195/// The key checks one client network may make per platform and hour when
196/// `KEY_CHECK_LIMIT_PER_HOUR` is unset. A person entering a key makes one to
197/// three.
198pub const DEFAULT_KEY_CHECK_LIMIT_PER_HOUR: u32 = 20;
199
200/// Which client address the key-check limit counts against
201/// (`TRUST_FORWARDED_FOR`).
202#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
203#[non_exhaustive]
204pub enum TrustForwardedFor {
205    /// `none`: the TCP peer address; every `X-Forwarded-For` is ignored.
206    /// Right when nothing sits in front of the proxy, and the default.
207    #[default]
208    None,
209    /// `heroku`, or its synonym `rightmost`: the right-most
210    /// `X-Forwarded-For` entry, the one the proxy in front appended (Heroku's
211    /// router does; so do Caddy and nginx with
212    /// `$proxy_add_x_forwarded_for`); everything to its left came from the
213    /// client and is ignored. Only right when every request reaches the
214    /// proxy through exactly one such proxy: without it a client can write
215    /// that entry itself.
216    RightMost,
217}
218
219impl std::str::FromStr for TrustForwardedFor {
220    type Err = String;
221
222    fn from_str(value: &str) -> Result<Self, String> {
223        match value.trim() {
224            "" | "none" => Ok(Self::None),
225            "heroku" | "rightmost" => Ok(Self::RightMost),
226            _ => Err("TRUST_FORWARDED_FOR must be `none`, `heroku` or `rightmost`".into()),
227        }
228    }
229}
230
231/// The highest `KEY_CHECK_LIMIT_PER_HOUR` accepted. Each check may scan the
232/// network's slots, so a huge limit makes every key check slow (2,000,000
233/// took 640 ms per insert); `0` is the way to turn the limit off.
234pub const MAX_KEY_CHECK_LIMIT_PER_HOUR: u32 = 10_000;
235
236/// `KEY_CHECK_LIMIT_PER_HOUR`: unset or blank means
237/// [`DEFAULT_KEY_CHECK_LIMIT_PER_HOUR`], `0` means no limit; anything but a
238/// whole number from 0 to [`MAX_KEY_CHECK_LIMIT_PER_HOUR`] is refused at
239/// startup.
240pub(crate) fn key_check_limit(value: Option<&str>) -> Result<u32, String> {
241    let invalid = || {
242        format!(
243            "KEY_CHECK_LIMIT_PER_HOUR must be a whole number from 0 (no limit) to {MAX_KEY_CHECK_LIMIT_PER_HOUR}"
244        )
245    };
246    match value.map(str::trim) {
247        None | Some("") => Ok(DEFAULT_KEY_CHECK_LIMIT_PER_HOUR),
248        Some(value) => match value.parse::<u32>() {
249            Ok(limit) if limit <= MAX_KEY_CHECK_LIMIT_PER_HOUR => Ok(limit),
250            _ => Err(invalid()),
251        },
252    }
253}
254
255/// The operator name when `OPERATOR_NAME` is unset: neutral, because the
256/// crate does not know who runs it.
257pub const DEFAULT_OPERATOR_NAME: &str = "this integration proxy";
258
259/// Where GitHub Pages serves this repository's `overlays/` folder. Every
260/// overlay URL in the dated catalogs under `overlays/catalog/` starts with
261/// this prefix.
262pub const OVERLAYS_PAGES_BASE: &str = "https://ontola.github.io/atomic-plugins/overlays/";
263
264/// The default dated catalog's path under `overlays/`, for tests that read
265/// the checked-in copy; `default_catalog_is_the_published_checked_in_catalog`
266/// keeps it equal to [`DEFAULT_CATALOG_PATH`]'s.
267#[cfg(test)]
268pub const DEFAULT_CATALOG_FILE: &str = "catalog/2026-10-29-google-keep-writes.json";
269
270/// `overlays/catalog/2026-10-29-google-keep-writes.json` as GitHub Pages publishes it from this
271/// repository's `main`, used when `CATALOG_PATH` is not set. Unlike the
272/// unversioned catalog this replaced, its dated file and selected overlay
273/// revisions are immutable; the proxy reads it once, at startup. Shared with
274/// tests that need to validate the exact catalog the application would load
275/// by default (they read the checked-in copy; see `Catalog::load_checked_in`).
276pub const DEFAULT_CATALOG_PATH: &str =
277    "https://ontola.github.io/atomic-plugins/overlays/catalog/2026-10-29-google-keep-writes.json";
278
279/// Reads a required environment variable and rejects it if unset or blank,
280/// so a blank `.env` value fails configuration explicitly instead of being
281/// silently accepted (e.g. as a reproducible empty secret).
282fn require_env(name: &str) -> Result<String, String> {
283    match env::var(name) {
284        Ok(value) if !value.is_empty() => Ok(value),
285        _ => Err(format!("{name} must be set")),
286    }
287}
288
289fn list(value: &str) -> Vec<String> {
290    value
291        .split(',')
292        .map(str::trim)
293        .filter(|s| !s.is_empty())
294        .map(str::to_owned)
295        .collect()
296}
297
298/// `BASE_URL` must be an absolute http(s) URL without credentials, query or
299/// fragment: it is the signed origin, so anything ambiguous is refused at
300/// startup rather than failing every signature later.
301pub(crate) fn validate_base_url(value: &str) -> Result<String, String> {
302    let url = Url::parse(value).map_err(|_| "BASE_URL must be an absolute URL".to_string())?;
303    if !matches!(url.scheme(), "https" | "http")
304        || url.host_str().is_none()
305        || !url.username().is_empty()
306        || url.password().is_some()
307        || url.query().is_some()
308        || url.fragment().is_some()
309    {
310        return Err(
311            "BASE_URL must be an http(s) URL without credentials, query or fragment".into(),
312        );
313    }
314    Ok(value.trim_end_matches('/').to_owned())
315}
316
317/// `OPERATOR_NAME`, trimmed; unset or blank means [`DEFAULT_OPERATOR_NAME`].
318pub(crate) fn operator_name(value: Option<&str>) -> String {
319    match value.map(str::trim) {
320        Some(name) if !name.is_empty() => name.to_owned(),
321        _ => DEFAULT_OPERATOR_NAME.to_owned(),
322    }
323}
324
325/// `OPERATOR_URL`, if set: an absolute http(s) URL without credentials. It is
326/// rendered as a link, so anything else (`javascript:`, a relative path) is
327/// refused at startup.
328pub(crate) fn validate_operator_url(value: Option<&str>) -> Result<Option<String>, String> {
329    let Some(value) = value.map(str::trim).filter(|value| !value.is_empty()) else {
330        return Ok(None);
331    };
332    let url = Url::parse(value)
333        .map_err(|_| "OPERATOR_URL must be an absolute http(s) URL".to_string())?;
334    if !matches!(url.scheme(), "https" | "http")
335        || url.host_str().is_none()
336        || !url.username().is_empty()
337        || url.password().is_some()
338    {
339        return Err("OPERATOR_URL must be an http(s) URL without credentials".into());
340    }
341    Ok(Some(url.to_string()))
342}
343
344/// `host[:port]` of an http(s) URL, the port only when it is not the
345/// scheme's default. Falls back to the input when it does not parse.
346pub(crate) fn public_host(base_url: &str) -> String {
347    match Url::parse(base_url) {
348        Ok(url) => match (url.host_str(), url.port()) {
349            (Some(host), Some(port)) => format!("{host}:{port}"),
350            (Some(host), None) => host.to_owned(),
351            _ => base_url.to_owned(),
352        },
353        Err(_) => base_url.to_owned(),
354    }
355}
356
357impl Config {
358    pub fn from_env() -> Result<Self, String> {
359        let base_url = validate_base_url(
360            &env::var("BASE_URL").unwrap_or_else(|_| "http://localhost:8080".to_string()),
361        )?;
362        let port = env::var("PORT")
363            .ok()
364            .and_then(|p| p.parse().ok())
365            .unwrap_or(8080);
366        // An empty SESSION_SECRET is treated as unset, so it triggers random
367        // key generation instead of being hashed into a reproducible,
368        // guessable cookie-encryption key.
369        let session_secret = env::var("SESSION_SECRET")
370            .ok()
371            .filter(|value| !value.is_empty());
372        let catalog_path =
373            env::var("CATALOG_PATH").unwrap_or_else(|_| DEFAULT_CATALOG_PATH.to_string());
374        let database_url = require_env("DATABASE_URL").map_err(|_| {
375            "DATABASE_URL must be set for connections and replay protection".to_string()
376        })?;
377        let encryption_key = require_env("ENCRYPTION_KEY")?;
378        let revoked_subjects = list(&env::var("REVOKED_SUBJECTS").unwrap_or_default());
379        let allowed_agents = env::var("ALLOWED_AGENTS")
380            .ok()
381            .filter(|value| !value.trim().is_empty())
382            .map(|value| list(&value));
383        let operator_name = operator_name(env::var("OPERATOR_NAME").ok().as_deref());
384        let operator_url = validate_operator_url(env::var("OPERATOR_URL").ok().as_deref())?;
385        let key_check_limit_per_hour =
386            key_check_limit(env::var("KEY_CHECK_LIMIT_PER_HOUR").ok().as_deref())?;
387        let trust_forwarded_for = env::var("TRUST_FORWARDED_FOR")
388            .unwrap_or_default()
389            .parse()?;
390        let webhooks = webhook_config_with(
391            env::var("WEBHOOKS_ENABLED").ok().as_deref(),
392            env::var("WEBHOOK_INBOX_MAX_BYTES").ok().as_deref(),
393            &|name| env::var(name).ok(),
394        )?;
395
396        Ok(Self {
397            base_url,
398            port,
399            session_secret,
400            catalog_path,
401            database_url,
402            encryption_key,
403            revoked_subjects,
404            allowed_agents,
405            operator_name,
406            operator_url,
407            key_check_limit_per_hour,
408            trust_forwarded_for,
409            webhooks,
410            device: crate::device::DeviceConfig::from_env()?,
411        })
412    }
413
414    /// The origin (`scheme://host[:port]`) of [`Config::base_url`]: a
415    /// capability's required `aud`.
416    pub fn public_origin(&self) -> String {
417        Url::parse(&self.base_url)
418            .map(|url| url.origin().ascii_serialization())
419            .unwrap_or_else(|_| self.base_url.clone())
420    }
421
422    /// `host[:port]` of [`Config::base_url`], as the consent page shows it.
423    pub fn public_host(&self) -> String {
424        public_host(&self.base_url)
425    }
426
427    /// OAuth callback and credential variable names are deterministic from the
428    /// catalog platform name, e.g. `google-calendar` becomes
429    /// `OAUTH_GOOGLE_CALENDAR_CLIENT_ID` and `/oauth/google-calendar/callback`.
430    pub fn provider_env_prefix(provider: &str) -> Result<String, String> {
431        if provider.is_empty()
432            || !provider
433                .bytes()
434                .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
435        {
436            return Err(
437                "provider names may contain only lowercase letters, digits, and hyphens"
438                    .to_string(),
439            );
440        }
441        Ok(format!(
442            "OAUTH_{}",
443            provider.replace('-', "_").to_ascii_uppercase()
444        ))
445    }
446}
447
448#[cfg(test)]
449mod tests {
450    use super::*;
451
452    #[test]
453    fn provider_names_produce_predictable_environment_prefixes() {
454        assert_eq!(
455            Config::provider_env_prefix("google-calendar").unwrap(),
456            "OAUTH_GOOGLE_CALENDAR"
457        );
458        assert!(Config::provider_env_prefix("Google Calendar").is_err());
459    }
460
461    #[test]
462    fn require_env_rejects_missing_and_blank_values() {
463        let name = "INTEGRATION_PROXY_TEST_REQUIRE_ENV_VAR";
464        env::remove_var(name);
465        assert!(require_env(name).is_err());
466        env::set_var(name, "");
467        assert!(require_env(name).is_err());
468        env::set_var(name, "a-value");
469        assert_eq!(require_env(name).unwrap(), "a-value");
470        env::remove_var(name);
471    }
472
473    #[test]
474    fn base_url_is_the_signed_origin_and_must_be_unambiguous() {
475        assert_eq!(
476            validate_base_url("https://proxy.example/").unwrap(),
477            "https://proxy.example"
478        );
479        assert_eq!(
480            validate_base_url("http://localhost:8080").unwrap(),
481            "http://localhost:8080"
482        );
483        for invalid in [
484            "proxy.example",
485            "ftp://proxy.example",
486            "https://u:p@proxy.example",
487            "https://proxy.example?x=1",
488            "https://proxy.example#x",
489        ] {
490            assert!(validate_base_url(invalid).is_err(), "{invalid}");
491        }
492        let config = Config {
493            base_url: "https://proxy.example:8443/prefix".into(),
494            port: 0,
495            session_secret: None,
496            catalog_path: String::new(),
497            database_url: String::new(),
498            encryption_key: String::new(),
499            revoked_subjects: vec![],
500            allowed_agents: None,
501            operator_name: DEFAULT_OPERATOR_NAME.into(),
502            operator_url: None,
503            key_check_limit_per_hour: 0,
504            trust_forwarded_for: TrustForwardedFor::None,
505            webhooks: WebhookConfig::default(),
506            device: Default::default(),
507        };
508        assert_eq!(config.public_origin(), "https://proxy.example:8443");
509        assert_eq!(config.public_host(), "proxy.example:8443");
510        assert_eq!(public_host("https://proxy.example"), "proxy.example");
511        assert_eq!(public_host("http://127.0.0.1:8080"), "127.0.0.1:8080");
512    }
513
514    #[test]
515    fn webhooks_are_off_unless_enabled_explicitly() {
516        assert_eq!(
517            webhook_config(None, None).unwrap(),
518            WebhookConfig::default()
519        );
520        assert!(!WebhookConfig::default().enabled);
521        assert_eq!(WebhookConfig::default().inbox_max_bytes, 1 << 30);
522        assert!(!webhook_config(Some(""), None).unwrap().enabled);
523        assert!(!webhook_config(Some("false"), None).unwrap().enabled);
524        assert!(webhook_config(Some("true"), None).unwrap().enabled);
525        for invalid in ["1", "yes", "TRUE", "on"] {
526            assert!(webhook_config(Some(invalid), None).is_err(), "{invalid}");
527        }
528        assert_eq!(
529            webhook_config(Some("true"), Some("536870912"))
530                .unwrap()
531                .inbox_max_bytes,
532            512 << 20
533        );
534        for invalid in ["0", "-1", "1e9", "268435455", "lots"] {
535            assert!(
536                webhook_config(Some("true"), Some(invalid)).is_err(),
537                "{invalid}"
538            );
539            // Off, the budget is not read at all.
540            assert_eq!(
541                webhook_config(None, Some(invalid)).unwrap(),
542                WebhookConfig::default()
543            );
544        }
545    }
546
547    #[test]
548    fn webhook_rate_limits_are_bounded_and_read_only_when_enabled() {
549        let vars = |pairs: &'static [(&'static str, &'static str)]| {
550            move |name: &str| {
551                pairs
552                    .iter()
553                    .find(|(k, _)| *k == name)
554                    .map(|(_, v)| v.to_string())
555            }
556        };
557        let config = webhook_config_with(Some("true"), None, &|_| None).unwrap();
558        assert_eq!(
559            (
560                config.ingress_per_endpoint_per_minute,
561                config.ingress_per_network_per_minute,
562                config.subscribe_per_owner_per_hour
563            ),
564            (600, 120, 20)
565        );
566        let set = vars(&[
567            ("WEBHOOK_INGRESS_LIMIT_PER_ENDPOINT", "1000"),
568            ("WEBHOOK_INGRESS_LIMIT_PER_NETWORK", "30"),
569            ("WEBHOOK_SUBSCRIBE_LIMIT_PER_OWNER", "5"),
570        ]);
571        let config = webhook_config_with(Some("true"), None, &set).unwrap();
572        assert_eq!(config.ingress_per_endpoint_per_minute, 1000);
573        assert_eq!(config.ingress_per_network_per_minute, 30);
574        assert_eq!(config.subscribe_per_owner_per_hour, 5);
575        for invalid in ["0", "-1", "100001", "lots", "1.5"] {
576            let bad = move |name: &str| {
577                (name == "WEBHOOK_INGRESS_LIMIT_PER_NETWORK").then(|| invalid.to_string())
578            };
579            assert!(
580                webhook_config_with(Some("true"), None, &bad).is_err(),
581                "{invalid}"
582            );
583            // Off, nothing is read.
584            assert_eq!(
585                webhook_config_with(None, None, &bad).unwrap(),
586                WebhookConfig::default()
587            );
588        }
589    }
590
591    #[test]
592    fn operator_name_defaults_to_a_neutral_phrase() {
593        assert_eq!(operator_name(None), DEFAULT_OPERATOR_NAME);
594        assert_eq!(operator_name(Some("  ")), DEFAULT_OPERATOR_NAME);
595        assert_eq!(operator_name(Some(" Atomic Data ")), "Atomic Data");
596    }
597
598    #[test]
599    fn operator_url_is_optional_and_must_be_a_plain_http_url() {
600        assert_eq!(validate_operator_url(None).unwrap(), None);
601        assert_eq!(validate_operator_url(Some(" ")).unwrap(), None);
602        assert_eq!(
603            validate_operator_url(Some("https://atomic.place")).unwrap(),
604            Some("https://atomic.place/".into())
605        );
606        for invalid in [
607            "atomic.place",
608            "javascript:alert(1)",
609            "data:text/html,x",
610            "https://u:p@atomic.place",
611        ] {
612            assert!(validate_operator_url(Some(invalid)).is_err(), "{invalid}");
613        }
614    }
615
616    #[test]
617    fn the_key_check_limit_defaults_to_twenty_and_zero_turns_it_off() {
618        assert_eq!(key_check_limit(None).unwrap(), 20);
619        assert_eq!(key_check_limit(Some(" ")).unwrap(), 20);
620        assert_eq!(key_check_limit(Some("0")).unwrap(), 0);
621        assert_eq!(key_check_limit(Some(" 50 ")).unwrap(), 50);
622        assert_eq!(key_check_limit(Some("10000")).unwrap(), 10_000);
623        for invalid in ["-1", "twenty", "1.5", "10001", "2000000", "99999999999"] {
624            let error = key_check_limit(Some(invalid)).unwrap_err();
625            assert!(
626                error.contains("0 (no limit) to 10000"),
627                "{invalid}: {error}"
628            );
629        }
630    }
631
632    #[test]
633    fn forwarded_for_is_trusted_only_when_named() {
634        assert_eq!("".parse(), Ok(TrustForwardedFor::None));
635        assert_eq!("none".parse(), Ok(TrustForwardedFor::None));
636        assert_eq!(" heroku ".parse(), Ok(TrustForwardedFor::RightMost));
637        assert_eq!("rightmost".parse(), Ok(TrustForwardedFor::RightMost));
638        for invalid in ["Heroku", "true", "all", "x-forwarded-for"] {
639            assert!(invalid.parse::<TrustForwardedFor>().is_err(), "{invalid}");
640        }
641    }
642
643    #[test]
644    fn lists_are_comma_separated_and_trimmed() {
645        assert_eq!(list(" a, b ,,c "), vec!["a", "b", "c"]);
646        assert!(list("").is_empty());
647    }
648}