atomic_integration_proxy/
config.rs1use 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}
37
38pub const OVERLAYS_PAGES_BASE: &str = "https://ontola.github.io/atomic-plugins/overlays/";
41
42pub const DEFAULT_CATALOG_PATH: &str =
49 "https://ontola.github.io/atomic-plugins/overlays/catalog.json";
50
51fn 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
70pub(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 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 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 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}