1use std::env;
2use url::Url;
3
4#[derive(Clone)]
11pub struct Config {
12 pub base_url: String,
18 pub port: u16,
19 pub session_secret: Option<String>,
23 pub catalog_path: String,
25 pub database_url: String,
28 pub encryption_key: String,
30 pub revoked_subjects: Vec<String>,
33 pub allowed_agents: Option<Vec<String>>,
36 pub operator_name: String,
39 pub operator_url: Option<String>,
42 pub key_check_limit_per_hour: u32,
47 pub trust_forwarded_for: TrustForwardedFor,
50 pub webhooks: WebhookConfig,
52 pub device: crate::device::DeviceConfig,
54}
55
56#[derive(Clone, Debug, PartialEq, Eq)]
60#[non_exhaustive]
61pub struct WebhookConfig {
62 pub notifications_only: bool,
65 pub enabled: bool,
68 pub inbox_max_bytes: i64,
72 pub ingress_per_endpoint_per_minute: u32,
77 pub ingress_per_network_per_minute: u32,
83 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
102const 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
117pub const DEFAULT_WEBHOOK_INBOX_MAX_BYTES: i64 = 1 << 30;
120
121const MIN_WEBHOOK_INBOX_MAX_BYTES: i64 = 256 << 20;
125
126pub(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
137pub(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 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
195pub const DEFAULT_KEY_CHECK_LIMIT_PER_HOUR: u32 = 20;
199
200#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
203#[non_exhaustive]
204pub enum TrustForwardedFor {
205 #[default]
208 None,
209 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
231pub const MAX_KEY_CHECK_LIMIT_PER_HOUR: u32 = 10_000;
235
236pub(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
255pub const DEFAULT_OPERATOR_NAME: &str = "this integration proxy";
258
259pub const OVERLAYS_PAGES_BASE: &str = "https://ontola.github.io/atomic-plugins/overlays/";
263
264#[cfg(test)]
268pub const DEFAULT_CATALOG_FILE: &str = "catalog/2026-10-29-google-keep-writes.json";
269
270pub const DEFAULT_CATALOG_PATH: &str =
277 "https://ontola.github.io/atomic-plugins/overlays/catalog/2026-10-29-google-keep-writes.json";
278
279fn 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
298pub(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
317pub(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
325pub(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
344pub(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 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 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 pub fn public_host(&self) -> String {
424 public_host(&self.base_url)
425 }
426
427 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 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 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}