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