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 enabled: bool,
65 pub inbox_max_bytes: i64,
69 pub ingress_per_endpoint_per_minute: u32,
74 pub ingress_per_network_per_minute: u32,
80 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
98const 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
113pub const DEFAULT_WEBHOOK_INBOX_MAX_BYTES: i64 = 1 << 30;
116
117const MIN_WEBHOOK_INBOX_MAX_BYTES: i64 = 256 << 20;
121
122pub(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
133pub(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 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
182pub const DEFAULT_KEY_CHECK_LIMIT_PER_HOUR: u32 = 20;
186
187#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
190#[non_exhaustive]
191pub enum TrustForwardedFor {
192 #[default]
195 None,
196 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
218pub const MAX_KEY_CHECK_LIMIT_PER_HOUR: u32 = 10_000;
222
223pub(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
242pub const DEFAULT_OPERATOR_NAME: &str = "this integration proxy";
245
246pub const OVERLAYS_PAGES_BASE: &str = "https://ontola.github.io/atomic-plugins/overlays/";
250
251#[cfg(test)]
255pub const DEFAULT_CATALOG_FILE: &str = "catalog/2026-10-29-google-keep-writes.json";
256
257pub const DEFAULT_CATALOG_PATH: &str =
264 "https://ontola.github.io/atomic-plugins/overlays/catalog/2026-10-29-google-keep-writes.json";
265
266fn 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
285pub(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
304pub(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
312pub(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
331pub(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 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 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 pub fn public_host(&self) -> String {
411 public_host(&self.base_url)
412 }
413
414 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 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 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}