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 pub operator_name: String,
39 pub operator_url: Option<String>,
42}
43
44pub const DEFAULT_OPERATOR_NAME: &str = "this integration proxy";
47
48pub const OVERLAYS_PAGES_BASE: &str = "https://ontola.github.io/atomic-plugins/overlays/";
51
52pub const DEFAULT_CATALOG_PATH: &str =
59 "https://ontola.github.io/atomic-plugins/overlays/catalog/2026-10-02.json";
60
61fn require_env(name: &str) -> Result<String, String> {
65 match env::var(name) {
66 Ok(value) if !value.is_empty() => Ok(value),
67 _ => Err(format!("{name} must be set")),
68 }
69}
70
71fn list(value: &str) -> Vec<String> {
72 value
73 .split(',')
74 .map(str::trim)
75 .filter(|s| !s.is_empty())
76 .map(str::to_owned)
77 .collect()
78}
79
80pub(crate) fn validate_base_url(value: &str) -> Result<String, String> {
84 let url = Url::parse(value).map_err(|_| "BASE_URL must be an absolute URL".to_string())?;
85 if !matches!(url.scheme(), "https" | "http")
86 || url.host_str().is_none()
87 || !url.username().is_empty()
88 || url.password().is_some()
89 || url.query().is_some()
90 || url.fragment().is_some()
91 {
92 return Err(
93 "BASE_URL must be an http(s) URL without credentials, query or fragment".into(),
94 );
95 }
96 Ok(value.trim_end_matches('/').to_owned())
97}
98
99pub(crate) fn operator_name(value: Option<&str>) -> String {
101 match value.map(str::trim) {
102 Some(name) if !name.is_empty() => name.to_owned(),
103 _ => DEFAULT_OPERATOR_NAME.to_owned(),
104 }
105}
106
107pub(crate) fn validate_operator_url(value: Option<&str>) -> Result<Option<String>, String> {
111 let Some(value) = value.map(str::trim).filter(|value| !value.is_empty()) else {
112 return Ok(None);
113 };
114 let url = Url::parse(value)
115 .map_err(|_| "OPERATOR_URL must be an absolute http(s) URL".to_string())?;
116 if !matches!(url.scheme(), "https" | "http")
117 || url.host_str().is_none()
118 || !url.username().is_empty()
119 || url.password().is_some()
120 {
121 return Err("OPERATOR_URL must be an http(s) URL without credentials".into());
122 }
123 Ok(Some(url.to_string()))
124}
125
126pub(crate) fn public_host(base_url: &str) -> String {
129 match Url::parse(base_url) {
130 Ok(url) => match (url.host_str(), url.port()) {
131 (Some(host), Some(port)) => format!("{host}:{port}"),
132 (Some(host), None) => host.to_owned(),
133 _ => base_url.to_owned(),
134 },
135 Err(_) => base_url.to_owned(),
136 }
137}
138
139impl Config {
140 pub fn from_env() -> Result<Self, String> {
141 let base_url = validate_base_url(
142 &env::var("BASE_URL").unwrap_or_else(|_| "http://localhost:8080".to_string()),
143 )?;
144 let port = env::var("PORT")
145 .ok()
146 .and_then(|p| p.parse().ok())
147 .unwrap_or(8080);
148 let session_secret = env::var("SESSION_SECRET")
152 .ok()
153 .filter(|value| !value.is_empty());
154 let catalog_path =
155 env::var("CATALOG_PATH").unwrap_or_else(|_| DEFAULT_CATALOG_PATH.to_string());
156 let database_url = require_env("DATABASE_URL").map_err(|_| {
157 "DATABASE_URL must be set for connections and replay protection".to_string()
158 })?;
159 let encryption_key = require_env("ENCRYPTION_KEY")?;
160 let revoked_subjects = list(&env::var("REVOKED_SUBJECTS").unwrap_or_default());
161 let allowed_agents = env::var("ALLOWED_AGENTS")
162 .ok()
163 .filter(|value| !value.trim().is_empty())
164 .map(|value| list(&value));
165 let operator_name = operator_name(env::var("OPERATOR_NAME").ok().as_deref());
166 let operator_url = validate_operator_url(env::var("OPERATOR_URL").ok().as_deref())?;
167
168 Ok(Self {
169 base_url,
170 port,
171 session_secret,
172 catalog_path,
173 database_url,
174 encryption_key,
175 revoked_subjects,
176 allowed_agents,
177 operator_name,
178 operator_url,
179 })
180 }
181
182 pub fn public_origin(&self) -> String {
185 Url::parse(&self.base_url)
186 .map(|url| url.origin().ascii_serialization())
187 .unwrap_or_else(|_| self.base_url.clone())
188 }
189
190 pub fn public_host(&self) -> String {
192 public_host(&self.base_url)
193 }
194
195 pub fn provider_env_prefix(provider: &str) -> Result<String, String> {
199 if provider.is_empty()
200 || !provider
201 .bytes()
202 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
203 {
204 return Err(
205 "provider names may contain only lowercase letters, digits, and hyphens"
206 .to_string(),
207 );
208 }
209 Ok(format!(
210 "OAUTH_{}",
211 provider.replace('-', "_").to_ascii_uppercase()
212 ))
213 }
214}
215
216#[cfg(test)]
217mod tests {
218 use super::*;
219
220 #[test]
221 fn provider_names_produce_predictable_environment_prefixes() {
222 assert_eq!(
223 Config::provider_env_prefix("google-calendar").unwrap(),
224 "OAUTH_GOOGLE_CALENDAR"
225 );
226 assert!(Config::provider_env_prefix("Google Calendar").is_err());
227 }
228
229 #[test]
230 fn require_env_rejects_missing_and_blank_values() {
231 let name = "INTEGRATION_PROXY_TEST_REQUIRE_ENV_VAR";
232 env::remove_var(name);
233 assert!(require_env(name).is_err());
234 env::set_var(name, "");
235 assert!(require_env(name).is_err());
236 env::set_var(name, "a-value");
237 assert_eq!(require_env(name).unwrap(), "a-value");
238 env::remove_var(name);
239 }
240
241 #[test]
242 fn base_url_is_the_signed_origin_and_must_be_unambiguous() {
243 assert_eq!(
244 validate_base_url("https://proxy.example/").unwrap(),
245 "https://proxy.example"
246 );
247 assert_eq!(
248 validate_base_url("http://localhost:8080").unwrap(),
249 "http://localhost:8080"
250 );
251 for invalid in [
252 "proxy.example",
253 "ftp://proxy.example",
254 "https://u:p@proxy.example",
255 "https://proxy.example?x=1",
256 "https://proxy.example#x",
257 ] {
258 assert!(validate_base_url(invalid).is_err(), "{invalid}");
259 }
260 let config = Config {
261 base_url: "https://proxy.example:8443/prefix".into(),
262 port: 0,
263 session_secret: None,
264 catalog_path: String::new(),
265 database_url: String::new(),
266 encryption_key: String::new(),
267 revoked_subjects: vec![],
268 allowed_agents: None,
269 operator_name: DEFAULT_OPERATOR_NAME.into(),
270 operator_url: None,
271 };
272 assert_eq!(config.public_origin(), "https://proxy.example:8443");
273 assert_eq!(config.public_host(), "proxy.example:8443");
274 assert_eq!(public_host("https://proxy.example"), "proxy.example");
275 assert_eq!(public_host("http://127.0.0.1:8080"), "127.0.0.1:8080");
276 }
277
278 #[test]
279 fn operator_name_defaults_to_a_neutral_phrase() {
280 assert_eq!(operator_name(None), DEFAULT_OPERATOR_NAME);
281 assert_eq!(operator_name(Some(" ")), DEFAULT_OPERATOR_NAME);
282 assert_eq!(operator_name(Some(" Atomic Data ")), "Atomic Data");
283 }
284
285 #[test]
286 fn operator_url_is_optional_and_must_be_a_plain_http_url() {
287 assert_eq!(validate_operator_url(None).unwrap(), None);
288 assert_eq!(validate_operator_url(Some(" ")).unwrap(), None);
289 assert_eq!(
290 validate_operator_url(Some("https://atomic.place")).unwrap(),
291 Some("https://atomic.place/".into())
292 );
293 for invalid in [
294 "atomic.place",
295 "javascript:alert(1)",
296 "data:text/html,x",
297 "https://u:p@atomic.place",
298 ] {
299 assert!(validate_operator_url(Some(invalid)).is_err(), "{invalid}");
300 }
301 }
302
303 #[test]
304 fn lists_are_comma_separated_and_trimmed() {
305 assert_eq!(list(" a, b ,,c "), vec!["a", "b", "c"]);
306 assert!(list("").is_empty());
307 }
308}