1use std::net::SocketAddr;
4use std::path::PathBuf;
5use std::time::Duration;
6
7#[derive(Debug, Clone)]
8pub struct Config {
9 pub bind: SocketAddr,
10 pub api_keys: Vec<String>,
11 pub allowed_origins: Vec<String>,
12 pub rate_limit: (u32, Duration),
14 pub wait_max: Duration,
18 pub wait_default: Duration,
19 pub webhook_max: Duration,
23 pub webhook_secret: Option<String>,
24 pub webhook_allow_private: bool,
25 pub database: Option<PathBuf>,
27 pub database_url: Option<String>,
30 pub instance_id: String,
33 pub health_sync_every: Duration,
36 pub maintenance_every: Duration,
38}
39
40fn default_instance_id() -> String {
42 env(&["HOSTNAME"]).unwrap_or_else(|| format!("il-{:08x}", rand::random::<u32>()))
43}
44
45impl Default for Config {
46 fn default() -> Self {
47 Config {
48 bind: "127.0.0.1:8080".parse().unwrap(),
49 api_keys: Vec::new(),
50 allowed_origins: Vec::new(),
51 rate_limit: (30, Duration::from_secs(60)),
52 wait_max: Duration::from_secs(25),
53 wait_default: Duration::from_secs(25),
54 webhook_max: Duration::from_secs(600),
55 webhook_secret: None,
56 webhook_allow_private: false,
57 database: None,
58 database_url: None,
59 instance_id: default_instance_id(),
60 health_sync_every: Duration::from_secs(5),
61 maintenance_every: Duration::from_secs(30),
62 }
63 }
64}
65
66pub const ENV: &[(&str, &str)] = &[
69 (
70 "INTERLOPER_API_KEYS",
71 "Comma-separated API keys; required (the server refuses to start open).",
72 ),
73 (
74 "INTERLOPER_BIND",
75 "Listen address (default 127.0.0.1:8080). PORT, if set instead, binds 0.0.0.0:PORT.",
76 ),
77 (
78 "INTERLOPER_ALLOWED_ORIGINS",
79 "Comma-separated CORS origins; unset sends no CORS headers.",
80 ),
81 (
82 "INTERLOPER_RATE_LIMIT",
83 "Requests per window per client, e.g. 30/60s (default).",
84 ),
85 (
86 "INTERLOPER_WAIT_DEFAULT",
87 "Seconds `wait` holds when the caller gives no timeout (default 25).",
88 ),
89 (
90 "INTERLOPER_WAIT_MAX",
91 "Ceiling in seconds on any `wait` (default 25).",
92 ),
93 (
94 "INTERLOPER_WEBHOOK_MAX",
95 "Ceiling in seconds a webhook waits for mail (default 600).",
96 ),
97 (
98 "INTERLOPER_WEBHOOK_SECRET",
99 "HMAC-SHA256 key; deliveries carry x-interloper-signature: sha256=...",
100 ),
101 (
102 "INTERLOPER_WEBHOOK_ALLOW_PRIVATE",
103 "1/true allows webhooks to private/loopback hosts (testing only).",
104 ),
105 (
106 "INTERLOPER_DATABASE",
107 "SQLite file for issued addresses; unset keeps them in memory.",
108 ),
109 (
110 "INTERLOPER_DATABASE_URL",
111 "Postgres URL: shared address store plus fleet health sync; TLS per ?sslmode= (verified). Excludes INTERLOPER_DATABASE.",
112 ),
113 (
114 "INTERLOPER_INSTANCE_ID",
115 "This instance's name in fleet health rows (default $HOSTNAME).",
116 ),
117 (
118 "INTERLOPER_HEALTH_SYNC_SECONDS",
119 "Fleet health sync interval (default 5).",
120 ),
121];
122
123fn env(names: &[&str]) -> Option<String> {
124 names
125 .iter()
126 .find_map(|k| std::env::var(k).ok().filter(|v| !v.trim().is_empty()))
127}
128
129fn csv(v: Option<String>) -> Vec<String> {
130 v.map(|s| {
131 s.split(',')
132 .map(|x| x.trim().to_string())
133 .filter(|x| !x.is_empty())
134 .collect()
135 })
136 .unwrap_or_default()
137}
138
139fn secs(names: &[&str], default: Duration) -> Result<Duration, String> {
140 match env(names) {
141 None => Ok(default),
142 Some(v) => match v.trim().parse::<u64>() {
143 Ok(n) if n >= 1 => Ok(Duration::from_secs(n)),
144 _ => Err(format!(
145 "{} must be a whole number of seconds >= 1, got {v:?}",
146 names[0]
147 )),
148 },
149 }
150}
151
152pub fn parse_rate(s: &str) -> Result<(u32, Duration), String> {
154 let (n, per) = s
155 .split_once('/')
156 .ok_or_else(|| format!("rate limit {s:?} is not N/unit"))?;
157 let n: u32 = n
158 .trim()
159 .parse()
160 .map_err(|_| format!("rate limit {s:?} is not N/unit"))?;
161 let window = match per.trim() {
162 "second" | "s" => Duration::from_secs(1),
163 "minute" | "m" => Duration::from_secs(60),
164 "hour" | "h" => Duration::from_secs(3600),
165 "day" | "d" => Duration::from_secs(86400),
166 other => return Err(format!("unknown rate-limit unit {other:?}")),
167 };
168 if n == 0 {
169 return Err("rate limit must allow at least one request".into());
170 }
171 Ok((n, window))
172}
173
174impl Config {
175 pub fn from_env() -> Result<Self, String> {
177 let d = Config::default();
178 let bind = match env(&["INTERLOPER_BIND", "BIND"]) {
179 Some(b) => b
180 .parse()
181 .map_err(|e| format!("INTERLOPER_BIND {b:?}: {e}"))?,
182 None => match env(&["PORT"]) {
185 Some(p) => std::net::SocketAddr::from((
186 [0, 0, 0, 0],
187 p.trim()
188 .parse::<u16>()
189 .map_err(|e| format!("PORT {p:?}: {e}"))?,
190 )),
191 None => d.bind,
192 },
193 };
194 let rate_limit = match env(&["INTERLOPER_RATE_LIMIT", "RATE_LIMIT"]) {
195 Some(r) => parse_rate(&r)?,
196 None => d.rate_limit,
197 };
198 let allow_private = env(&["INTERLOPER_WEBHOOK_ALLOW_PRIVATE", "WEBHOOK_ALLOW_PRIVATE"])
199 .is_some_and(|v| matches!(v.trim(), "1" | "true" | "yes"));
200 let database = env(&["INTERLOPER_DATABASE", "DATABASE_PATH"]).map(PathBuf::from);
201 let database_url = env(&["INTERLOPER_DATABASE_URL", "COWBIRD_DATABASE_URL"]);
202 if database.is_some() && database_url.is_some() {
203 return Err(
205 "set INTERLOPER_DATABASE (SQLite) or INTERLOPER_DATABASE_URL (Postgres), not both"
206 .into(),
207 );
208 }
209 Ok(Config {
210 bind,
211 api_keys: csv(env(&["INTERLOPER_API_KEYS", "API_KEYS"])),
212 allowed_origins: csv(env(&["INTERLOPER_ALLOWED_ORIGINS", "ALLOWED_ORIGINS"])),
213 rate_limit,
214 wait_max: secs(&["INTERLOPER_WAIT_MAX", "WAIT_MAX"], d.wait_max)?,
215 wait_default: secs(&["INTERLOPER_WAIT_DEFAULT", "WAIT_DEFAULT"], d.wait_default)?,
216 webhook_max: secs(&["INTERLOPER_WEBHOOK_MAX", "WEBHOOK_MAX"], d.webhook_max)?,
217 webhook_secret: env(&["INTERLOPER_WEBHOOK_SECRET", "WEBHOOK_SECRET"]),
218 webhook_allow_private: allow_private,
219 database,
220 database_url,
221 instance_id: env(&["INTERLOPER_INSTANCE_ID", "INSTANCE_ID"]).unwrap_or(d.instance_id),
222 health_sync_every: secs(
223 &["INTERLOPER_HEALTH_SYNC_SECONDS", "HEALTH_FLUSH_SECONDS"],
224 d.health_sync_every,
225 )?,
226 maintenance_every: d.maintenance_every,
227 })
228 }
229
230 pub fn clamp_wait(&self, requested: Option<u64>) -> Duration {
232 requested
233 .map_or(self.wait_default, Duration::from_secs)
234 .min(self.wait_max)
235 }
236
237 pub fn clamp_webhook(&self, requested: Option<u64>) -> Duration {
238 requested
239 .map_or(self.webhook_max, Duration::from_secs)
240 .min(self.webhook_max)
241 }
242}
243
244#[cfg(test)]
245mod tests {
246 use super::*;
247
248 #[test]
249 fn rates() {
250 assert_eq!(
251 parse_rate("30/minute").unwrap(),
252 (30, Duration::from_secs(60))
253 );
254 assert!(parse_rate("0/minute").is_err());
255 assert!(parse_rate("thirty").is_err());
256 }
257
258 #[test]
259 fn clamps_are_separate() {
260 let c = Config::default();
261 assert_eq!(c.clamp_wait(Some(9999)), c.wait_max);
262 assert_eq!(c.clamp_wait(None), c.wait_default);
263 assert_eq!(c.clamp_webhook(Some(300)), Duration::from_secs(300));
264 assert_eq!(c.clamp_webhook(None), c.webhook_max);
265 }
266
267 #[test]
268 fn every_setting_read_is_documented() {
269 let src = include_str!("config.rs");
270 let documented: Vec<&str> = ENV.iter().map(|(n, _)| *n).collect();
271 let re = interloper::regex::Regex::new(r#""(INTERLOPER_[A-Z_]+)""#).unwrap();
272 for c in re.captures_iter(src) {
273 let name = &c[1];
274 assert!(
275 documented.contains(&name),
276 "{name} is read but not in config::ENV"
277 );
278 }
279 }
280}