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