1use std::env;
5use std::num::NonZeroU32;
6
7use firstpass_core::{Config as RoutingConfig, Mode, PriceTable, RoutingMode};
8
9const DEFAULT_PROMPT_SALT: &str = "firstpass-dev-salt";
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
27pub enum ReceiptsMode {
28 #[default]
30 BestEffort,
31 Durable,
34}
35
36#[derive(Debug, Clone)]
38pub struct ProxyConfig {
39 pub bind: String,
41 pub upstream_anthropic: String,
43 pub upstream_openai: String,
45 pub upstream_gemini: String,
48 pub db_path: String,
50 pub tenant_id: String,
54 pub require_auth: bool,
58 pub tenant_keys: crate::tenant_auth::TenantKeys,
67 pub prompt_salt: String,
69 pub mode: Mode,
71 pub routing: Option<RoutingConfig>,
74 pub prices: PriceTable,
76 pub max_concurrency: usize,
80 pub tenant_rate_per_sec: Option<NonZeroU32>,
84 pub receipts_mode: ReceiptsMode,
87 pub default_routing_mode: RoutingMode,
91}
92
93const DEFAULT_MAX_CONCURRENCY: usize = 512;
95
96#[derive(Debug, thiserror::Error)]
98pub enum ConfigError {
99 #[error(
101 "FIRSTPASS_MODE={0:?} is not a known mode; set `observe` or `enforce`, or leave it unset"
102 )]
103 UnsupportedMode(String),
104
105 #[error("FIRSTPASS_RECEIPTS={0:?} is not valid; set `best_effort` (default) or `durable`")]
107 UnsupportedReceiptsMode(String),
108
109 #[error(
111 "FIRSTPASS_MODE_PROFILE={0:?} is not a known routing mode; \
112 valid: observe|cost|balanced|quality|latency|max"
113 )]
114 UnsupportedModeProfile(String),
115
116 #[error("routing config error: {0}")]
118 Config(String),
119
120 #[error("tenant auth config error: {0}")]
123 Auth(#[from] crate::tenant_auth::AuthConfigError),
124}
125
126impl ProxyConfig {
127 pub fn from_env() -> Result<Self, ConfigError> {
133 let routing_toml = match env::var("FIRSTPASS_CONFIG").ok() {
137 Some(path) => Some(
138 std::fs::read_to_string(&path)
139 .map_err(|e| ConfigError::Config(format!("reading {path}: {e}")))?,
140 ),
141 None => None,
142 };
143 let tenant_keys_json = match env::var("FIRSTPASS_TENANT_KEYS").ok() {
147 Some(path) => Some(
148 std::fs::read_to_string(&path)
149 .map_err(|e| ConfigError::Config(format!("reading {path}: {e}")))?,
150 ),
151 None => None,
152 };
153 Self::from_lookup(|key| match key {
154 "FIRSTPASS_CONFIG_TOML" => routing_toml.clone(),
155 "FIRSTPASS_TENANT_KEYS_JSON" => env::var(key).ok().or_else(|| tenant_keys_json.clone()),
156 other => env::var(other).ok(),
157 })
158 }
159
160 pub fn from_lookup(lookup: impl Fn(&str) -> Option<String>) -> Result<Self, ConfigError> {
168 let bind = lookup("FIRSTPASS_BIND").unwrap_or_else(|| "127.0.0.1:8080".to_owned());
169 let upstream_anthropic = lookup("FIRSTPASS_UPSTREAM_ANTHROPIC")
170 .unwrap_or_else(|| "https://api.anthropic.com".to_owned());
171 let upstream_openai = lookup("FIRSTPASS_UPSTREAM_OPENAI")
172 .unwrap_or_else(|| "https://api.openai.com".to_owned());
173 let upstream_gemini = lookup("FIRSTPASS_UPSTREAM_GEMINI")
174 .unwrap_or_else(|| "https://generativelanguage.googleapis.com".to_owned());
175 let db_path = lookup("FIRSTPASS_DB").unwrap_or_else(|| "firstpass.db".to_owned());
176 let tenant_id = lookup("FIRSTPASS_TENANT").unwrap_or_else(|| "default".to_owned());
177 let prompt_salt = lookup("FIRSTPASS_PROMPT_SALT").unwrap_or_else(|| {
178 tracing::warn!(
179 "FIRSTPASS_PROMPT_SALT is unset — using the built-in dev default; \
180 set a real secret before handling production traffic"
181 );
182 DEFAULT_PROMPT_SALT.to_owned()
183 });
184 let mode_str = lookup("FIRSTPASS_MODE").unwrap_or_else(|| "observe".to_owned());
185 let mode = match mode_str.as_str() {
186 "observe" => Mode::Observe,
187 "enforce" => Mode::Enforce,
188 other => return Err(ConfigError::UnsupportedMode(other.to_owned())),
189 };
190 let routing = match lookup("FIRSTPASS_CONFIG_TOML") {
191 Some(toml) => {
192 Some(RoutingConfig::parse(&toml).map_err(|e| ConfigError::Config(e.to_string()))?)
193 }
194 None => None,
195 };
196 let max_concurrency = match lookup("FIRSTPASS_MAX_CONCURRENCY") {
197 Some(s) => s.parse().map_err(|e| {
198 ConfigError::Config(format!("FIRSTPASS_MAX_CONCURRENCY={s:?}: {e}"))
199 })?,
200 None => DEFAULT_MAX_CONCURRENCY,
201 };
202
203 let require_auth = lookup("FIRSTPASS_REQUIRE_AUTH")
206 .map(|s| {
207 matches!(
208 s.trim().to_ascii_lowercase().as_str(),
209 "1" | "true" | "yes" | "on"
210 )
211 })
212 .unwrap_or(false);
213 let tenant_keys = match lookup("FIRSTPASS_TENANT_KEYS_JSON") {
214 Some(json) => crate::tenant_auth::TenantKeys::from_json(&json)?,
215 None => crate::tenant_auth::TenantKeys::default(),
216 };
217 if require_auth && tenant_keys.is_empty() {
218 tracing::warn!(
219 "FIRSTPASS_REQUIRE_AUTH is on but no tenant keys are configured — every request \
220 will be rejected with 401 until FIRSTPASS_TENANT_KEYS is set"
221 );
222 }
223
224 let tenant_rate_per_sec = match lookup("FIRSTPASS_TENANT_RATE_PER_SEC") {
226 Some(s) => Some(s.trim().parse::<NonZeroU32>().map_err(|e| {
227 ConfigError::Config(format!("FIRSTPASS_TENANT_RATE_PER_SEC={s:?}: {e}"))
228 })?),
229 None => None,
230 };
231
232 let receipts_mode = match lookup("FIRSTPASS_RECEIPTS").as_deref() {
234 None | Some("best_effort") => ReceiptsMode::BestEffort,
235 Some("durable") => ReceiptsMode::Durable,
236 Some(other) => {
237 return Err(ConfigError::UnsupportedReceiptsMode(other.to_owned()));
238 }
239 };
240
241 let default_routing_mode = match lookup("FIRSTPASS_MODE_PROFILE").as_deref() {
243 None | Some("balanced") => RoutingMode::Balanced,
244 Some("observe") => RoutingMode::Observe,
245 Some("cost") => RoutingMode::Cost,
246 Some("quality") => RoutingMode::Quality,
247 Some("latency") => RoutingMode::Latency,
248 Some("max") => RoutingMode::Max,
249 Some(other) => {
250 return Err(ConfigError::UnsupportedModeProfile(other.to_owned()));
251 }
252 };
253
254 Ok(Self {
255 bind,
256 upstream_anthropic,
257 upstream_openai,
258 upstream_gemini,
259 db_path,
260 tenant_id,
261 require_auth,
262 tenant_keys,
263 prompt_salt,
264 mode,
265 prices: {
266 let mut prices = PriceTable::defaults();
269 if let Some(cfg) = routing.as_ref() {
270 for p in &cfg.price_defs {
271 prices = prices.with_override(
272 p.model.clone(),
273 firstpass_core::ModelPrice {
274 input_per_mtok: p.input_per_mtok,
275 output_per_mtok: p.output_per_mtok,
276 },
277 );
278 }
279 }
280 prices
281 },
282 routing,
283 max_concurrency,
284 tenant_rate_per_sec,
285 receipts_mode,
286 default_routing_mode,
287 })
288 }
289}
290
291#[cfg(test)]
292mod tests {
293 use super::*;
294
295 #[test]
296 fn defaults_are_sane_when_unset() {
297 let cfg = ProxyConfig::from_lookup(|_| None).unwrap();
298 assert_eq!(cfg.bind, "127.0.0.1:8080");
299 assert_eq!(cfg.upstream_anthropic, "https://api.anthropic.com");
300 assert_eq!(
301 cfg.upstream_gemini,
302 "https://generativelanguage.googleapis.com"
303 );
304 assert_eq!(cfg.db_path, "firstpass.db");
305 assert_eq!(cfg.tenant_id, "default");
306 assert_eq!(cfg.prompt_salt, DEFAULT_PROMPT_SALT);
307 assert_eq!(cfg.mode, Mode::Observe);
308 assert_eq!(cfg.max_concurrency, DEFAULT_MAX_CONCURRENCY);
309 }
310
311 #[test]
312 fn max_concurrency_is_parsed_from_env() {
313 let cfg = ProxyConfig::from_lookup(|key| {
314 (key == "FIRSTPASS_MAX_CONCURRENCY").then(|| "64".to_owned())
315 })
316 .unwrap();
317 assert_eq!(cfg.max_concurrency, 64);
318 }
319
320 #[test]
321 fn bad_max_concurrency_is_an_error() {
322 let result = ProxyConfig::from_lookup(|key| {
323 (key == "FIRSTPASS_MAX_CONCURRENCY").then(|| "not-a-number".to_owned())
324 });
325 assert!(matches!(result, Err(ConfigError::Config(_))));
326 }
327
328 #[test]
329 fn overrides_are_applied() {
330 let cfg = ProxyConfig::from_lookup(|key| match key {
331 "FIRSTPASS_BIND" => Some("0.0.0.0:9090".to_owned()),
332 "FIRSTPASS_TENANT" => Some("acme".to_owned()),
333 _ => None,
334 })
335 .unwrap();
336 assert_eq!(cfg.bind, "0.0.0.0:9090");
337 assert_eq!(cfg.tenant_id, "acme");
338 }
339
340 #[test]
341 fn enforce_mode_is_accepted() {
342 let cfg =
343 ProxyConfig::from_lookup(|key| (key == "FIRSTPASS_MODE").then(|| "enforce".to_owned()))
344 .unwrap();
345 assert_eq!(cfg.mode, Mode::Enforce);
346 }
347
348 #[test]
349 fn unknown_mode_is_rejected() {
350 let result =
351 ProxyConfig::from_lookup(|key| (key == "FIRSTPASS_MODE").then(|| "banana".to_owned()));
352 assert!(matches!(result, Err(ConfigError::UnsupportedMode(m)) if m == "banana"));
353 }
354
355 #[test]
356 fn routing_config_parses_inline() {
357 let toml = r#"
358[[route]]
359match = { task_kind = "code_edit" }
360mode = "enforce"
361ladder = ["anthropic/claude-haiku-4-5", "anthropic/claude-sonnet-5"]
362gates = ["non-empty"]
363"#;
364 let cfg = ProxyConfig::from_lookup(|key| match key {
365 "FIRSTPASS_CONFIG_TOML" => Some(toml.to_owned()),
366 _ => None,
367 })
368 .unwrap();
369 let routing = cfg.routing.expect("routing config present");
370 assert_eq!(routing.routes.len(), 1);
371 assert_eq!(routing.routes[0].mode, Mode::Enforce);
372 }
373
374 #[test]
375 fn bad_routing_config_is_an_error() {
376 let result = ProxyConfig::from_lookup(|key| match key {
377 "FIRSTPASS_CONFIG_TOML" => Some("this is not valid = = toml".to_owned()),
378 _ => None,
379 });
380 assert!(matches!(result, Err(ConfigError::Config(_))));
381 }
382
383 #[test]
384 fn receipts_mode_defaults_to_best_effort() {
385 let cfg = ProxyConfig::from_lookup(|_| None).unwrap();
386 assert_eq!(cfg.receipts_mode, ReceiptsMode::BestEffort);
387 }
388
389 #[test]
390 fn receipts_mode_durable_is_accepted() {
391 let cfg =
392 ProxyConfig::from_lookup(|k| (k == "FIRSTPASS_RECEIPTS").then(|| "durable".to_owned()))
393 .unwrap();
394 assert_eq!(cfg.receipts_mode, ReceiptsMode::Durable);
395 }
396
397 #[test]
398 fn receipts_mode_best_effort_explicit_is_accepted() {
399 let cfg = ProxyConfig::from_lookup(|k| {
400 (k == "FIRSTPASS_RECEIPTS").then(|| "best_effort".to_owned())
401 })
402 .unwrap();
403 assert_eq!(cfg.receipts_mode, ReceiptsMode::BestEffort);
404 }
405
406 #[test]
407 fn receipts_mode_unknown_is_rejected() {
408 let result = ProxyConfig::from_lookup(|k| {
409 (k == "FIRSTPASS_RECEIPTS").then(|| "never_drop".to_owned())
410 });
411 assert!(
412 matches!(result, Err(ConfigError::UnsupportedReceiptsMode(m)) if m == "never_drop")
413 );
414 }
415
416 #[test]
417 fn default_routing_mode_is_balanced() {
418 let cfg = ProxyConfig::from_lookup(|_| None).unwrap();
419 assert_eq!(cfg.default_routing_mode, RoutingMode::Balanced);
420 }
421
422 #[test]
423 fn firstpass_mode_profile_is_parsed() {
424 let cfg = ProxyConfig::from_lookup(|k| {
425 (k == "FIRSTPASS_MODE_PROFILE").then(|| "quality".to_owned())
426 })
427 .unwrap();
428 assert_eq!(cfg.default_routing_mode, RoutingMode::Quality);
429 }
430
431 #[test]
432 fn unknown_mode_profile_is_rejected() {
433 let result = ProxyConfig::from_lookup(|k| {
434 (k == "FIRSTPASS_MODE_PROFILE").then(|| "turbo".to_owned())
435 });
436 assert!(matches!(result, Err(ConfigError::UnsupportedModeProfile(m)) if m == "turbo"));
437 }
438
439 #[test]
440 fn price_overrides_reach_the_price_table() {
441 let toml = "[[route]]\nmatch = {}\nmode = \"observe\"\nladder = [\"anthropic/claude-haiku-4-5\"]\n\n[[price]]\nmodel = \"anthropic/claude-haiku-4-5\"\ninput_per_mtok = 2.0\noutput_per_mtok = 10.0\n";
442 let cfg = ProxyConfig::from_lookup(|k| match k {
443 "FIRSTPASS_CONFIG_TOML" => Some(toml.to_owned()),
444 _ => None,
445 })
446 .unwrap();
447 let cost = cfg
449 .prices
450 .cost_usd("anthropic/claude-haiku-4-5", 1000, 1000)
451 .unwrap();
452 assert!((cost - 0.012).abs() < 1e-9, "override must win: {cost}");
453 }
454}