1use eyre::Result;
2use serde::{Deserialize, Serialize};
3use std::collections::BTreeMap;
4
5pub const DEFAULT_MAX_TURNS: usize = 100;
6
7pub const DEFAULT_AGGREGATOR_MAX_TOKENS: u64 = 16_384;
10
11#[derive(Serialize, Deserialize)]
12#[serde(deny_unknown_fields)]
13pub struct Config {
14 #[serde(skip_serializing_if = "Option::is_none")]
15 pub defaults: Option<DefaultsConfig>,
16 pub aggregator: AggregatorConfig,
17 pub reviewer: Vec<ReviewerConfig>,
18 #[serde(skip_serializing_if = "Option::is_none")]
21 pub presets: Option<BTreeMap<String, PresetConfig>>,
22}
23
24#[derive(Serialize, Deserialize)]
26#[serde(deny_unknown_fields)]
27pub struct PresetConfig {
28 pub prompt: String,
29}
30
31#[derive(Serialize, Deserialize)]
32#[serde(deny_unknown_fields)]
33pub struct DefaultsConfig {
34 #[serde(skip_serializing_if = "Option::is_none")]
35 pub debate: Option<bool>,
36 #[serde(skip_serializing_if = "Option::is_none")]
37 pub alloy: Option<bool>,
38 #[serde(skip_serializing_if = "Option::is_none")]
39 pub max_turns: Option<usize>,
40 #[serde(skip_serializing_if = "Option::is_none")]
41 pub compact_threshold: Option<u64>,
42 #[serde(skip_serializing_if = "Option::is_none")]
43 pub log_trajectories: Option<bool>,
44 #[serde(skip_serializing_if = "Option::is_none")]
47 pub presets: Option<Vec<String>>,
48}
49
50#[derive(Serialize, Deserialize)]
51#[serde(deny_unknown_fields)]
52pub struct AggregatorConfig {
53 #[serde(default)]
54 pub model: String,
55 pub provider: ProviderType,
56 #[serde(skip_serializing_if = "Option::is_none")]
57 pub base_url: Option<String>,
58 #[serde(skip_serializing_if = "Option::is_none")]
59 pub api_key_env: Option<String>,
60 #[serde(skip_serializing_if = "Option::is_none")]
61 pub max_tokens: Option<u64>,
62 #[serde(skip_serializing_if = "Option::is_none")]
63 pub auth: Option<String>,
64 #[serde(skip_serializing_if = "Option::is_none")]
66 pub azure_scope: Option<String>,
67 #[serde(skip_serializing_if = "Option::is_none")]
69 pub azure_credentials: Option<String>,
70}
71
72#[derive(Serialize, Deserialize)]
73#[serde(deny_unknown_fields)]
74pub struct ReviewerConfig {
75 #[serde(default)]
76 pub name: String,
77 #[serde(default)]
78 pub model: String,
79 pub provider: ProviderType,
80 #[serde(skip_serializing_if = "Option::is_none")]
81 pub base_url: Option<String>,
82 #[serde(skip_serializing_if = "Option::is_none")]
83 pub api_key_env: Option<String>,
84 #[serde(skip_serializing_if = "Option::is_none")]
86 pub max_tokens: Option<u64>,
87 #[serde(skip_serializing_if = "Option::is_none")]
88 pub compact_threshold: Option<u64>,
89 #[serde(skip_serializing_if = "Option::is_none")]
90 pub auth: Option<String>,
91 #[serde(skip_serializing_if = "Option::is_none")]
93 pub azure_scope: Option<String>,
94 #[serde(skip_serializing_if = "Option::is_none")]
96 pub azure_credentials: Option<String>,
97}
98
99pub(crate) struct ClientSettings<'a> {
103 pub(crate) provider: &'a ProviderType,
104 pub(crate) auth: Option<&'a str>,
105 pub(crate) base_url: Option<&'a str>,
106 pub(crate) api_key_env: Option<&'a str>,
107 pub(crate) azure_scope: Option<&'a str>,
108 pub(crate) azure_credentials: Option<&'a str>,
109}
110
111impl<'a> From<&'a ReviewerConfig> for ClientSettings<'a> {
112 fn from(reviewer: &'a ReviewerConfig) -> Self {
113 Self {
114 provider: &reviewer.provider,
115 auth: reviewer.auth.as_deref(),
116 base_url: reviewer.base_url.as_deref(),
117 api_key_env: reviewer.api_key_env.as_deref(),
118 azure_scope: reviewer.azure_scope.as_deref(),
119 azure_credentials: reviewer.azure_credentials.as_deref(),
120 }
121 }
122}
123
124impl<'a> From<&'a AggregatorConfig> for ClientSettings<'a> {
125 fn from(agg: &'a AggregatorConfig) -> Self {
126 Self {
127 provider: &agg.provider,
128 auth: agg.auth.as_deref(),
129 base_url: agg.base_url.as_deref(),
130 api_key_env: agg.api_key_env.as_deref(),
131 azure_scope: agg.azure_scope.as_deref(),
132 azure_credentials: agg.azure_credentials.as_deref(),
133 }
134 }
135}
136
137#[derive(Serialize, Deserialize)]
138pub enum ProviderType {
139 #[serde(rename = "anthropic", alias = "anthropic_compatible")]
140 Anthropic,
141 #[serde(rename = "gemini")]
142 Gemini,
143 #[serde(rename = "openai", alias = "openai_compatible")]
144 OpenAi,
145 #[serde(rename = "openrouter")]
146 OpenRouter,
147}
148
149impl ProviderType {
150 #[cfg(feature = "antigravity")]
152 pub fn is_gemini(&self) -> bool {
153 matches!(self, ProviderType::Gemini)
154 }
155}
156
157impl Config {
158 pub fn validate(&self) -> Result<()> {
159 if self.reviewer.is_empty() {
160 eyre::bail!("no reviewers configured");
161 }
162
163 self.validate_alloy(self.default_alloy())?;
164
165 validate_free_model(
166 "[aggregator]",
167 &self.aggregator.provider,
168 &self.aggregator.model,
169 )?;
170
171 validate_auth(
175 "[aggregator]",
176 &self.aggregator.provider,
177 &self.aggregator.auth,
178 self.aggregator.base_url.as_deref(),
179 self.aggregator.api_key_env.as_deref(),
180 self.aggregator.azure_credentials.as_deref(),
181 )?;
182
183 if let Some(env) = required_env_var(ClientSettings::from(&self.aggregator)) {
184 check_env_var(env)
185 .map_err(|_| eyre::eyre!("[aggregator]: env var {env} is not set"))?;
186 }
187
188 for reviewer in &self.reviewer {
189 let reviewer_label = match reviewer.name.is_empty() {
190 true => "reviewer <unnamed>".to_string(),
191 false => format!("reviewer {}", reviewer.name),
192 };
193 validate_free_model(&reviewer_label, &reviewer.provider, &reviewer.model)?;
194 validate_auth(
195 &reviewer_label,
196 &reviewer.provider,
197 &reviewer.auth,
198 reviewer.base_url.as_deref(),
199 reviewer.api_key_env.as_deref(),
200 reviewer.azure_credentials.as_deref(),
201 )?;
202 if let Some(env) = required_env_var(ClientSettings::from(reviewer)) {
203 check_env_var(env).map_err(|_| {
204 eyre::eyre!("reviewer {}: env var {env} is not set", reviewer.name)
205 })?;
206 }
207 if reviewer.compact_threshold == Some(0) {
208 eyre::bail!(
209 "reviewer {}: compact_threshold must be greater than 0",
210 reviewer.name
211 );
212 }
213 if reviewer.max_tokens == Some(0) {
214 eyre::bail!(
215 "reviewer {}: max_tokens must be greater than 0",
216 reviewer.name
217 );
218 }
219 }
220
221 if self.aggregator.max_tokens == Some(0) {
222 eyre::bail!("[aggregator].max_tokens must be greater than 0");
223 }
224
225 if self.defaults.as_ref().and_then(|d| d.compact_threshold) == Some(0) {
226 eyre::bail!("[defaults].compact_threshold must be greater than 0");
227 }
228
229 validate_presets(self.presets.as_ref())?;
230
231 Ok(())
232 }
233
234 pub fn default_debate(&self) -> bool {
235 self.defaults
236 .as_ref()
237 .and_then(|d| d.debate)
238 .unwrap_or(true)
239 }
240
241 pub fn validate_alloy(&self, alloy: bool) -> Result<()> {
242 if alloy && self.reviewer.len() < 2 {
243 eyre::bail!(
244 "--alloy requires at least 2 reviewers, found {}",
245 self.reviewer.len()
246 );
247 }
248 Ok(())
249 }
250
251 pub fn default_alloy(&self) -> bool {
252 self.defaults
253 .as_ref()
254 .and_then(|d| d.alloy)
255 .unwrap_or(false)
256 }
257
258 pub fn max_turns(&self, override_max_turns: Option<usize>) -> Result<usize> {
259 match override_max_turns {
260 Some(max_turns) => Ok(max_turns),
261 None => self.default_max_turns(),
262 }
263 }
264
265 pub fn default_max_turns(&self) -> Result<usize> {
266 let max_turns = self
267 .defaults
268 .as_ref()
269 .and_then(|d| d.max_turns)
270 .unwrap_or(DEFAULT_MAX_TURNS);
271
272 if max_turns == 0 {
273 eyre::bail!("[defaults].max_turns must be greater than 0");
274 }
275
276 Ok(max_turns)
277 }
278
279 pub fn default_compact_threshold(&self) -> Option<u64> {
280 self.defaults.as_ref().and_then(|d| d.compact_threshold)
281 }
282
283 pub fn log_trajectories(&self) -> bool {
284 self.defaults
285 .as_ref()
286 .and_then(|d| d.log_trajectories)
287 .unwrap_or(false)
288 }
289
290 pub fn aggregator_max_tokens(&self) -> u64 {
291 self.aggregator
292 .max_tokens
293 .unwrap_or(DEFAULT_AGGREGATOR_MAX_TOKENS)
294 }
295
296 pub fn reviewer_compact_threshold(&self, reviewer: &ReviewerConfig) -> Option<u64> {
297 reviewer
298 .compact_threshold
299 .or(self.default_compact_threshold())
300 }
301}
302
303fn validate_presets(presets: Option<&BTreeMap<String, PresetConfig>>) -> Result<()> {
304 let presets = match presets {
305 Some(presets) => presets,
306 None => return Ok(()),
307 };
308 for (name, preset) in presets {
309 if name.trim().is_empty() {
310 eyre::bail!("[presets]: preset names must contain non-whitespace content");
311 }
312 if name != name.trim() {
315 eyre::bail!("[presets.{name:?}]: preset names must not have surrounding whitespace");
316 }
317 if name.chars().any(char::is_control) {
320 eyre::bail!("[presets.{name:?}]: preset names must not contain control characters");
321 }
322 if preset.prompt.trim().is_empty() {
323 eyre::bail!("[presets.{name}].prompt must contain non-whitespace content");
324 }
325 }
326 Ok(())
327}
328
329fn validate_free_model(label: &str, provider: &ProviderType, model: &str) -> Result<()> {
330 if model == "free" && !matches!(provider, ProviderType::OpenRouter) {
331 eyre::bail!("{label}: model = \"free\" is only supported with provider = \"openrouter\"");
332 }
333
334 Ok(())
335}
336
337fn validate_auth(
338 label: &str,
339 provider: &ProviderType,
340 auth: &Option<String>,
341 base_url: Option<&str>,
342 api_key_env: Option<&str>,
343 azure_credentials: Option<&str>,
344) -> Result<()> {
345 match (provider, auth.as_deref()) {
346 (_, None) => Ok(()),
348 (ProviderType::Gemini, Some("oauth")) => {
349 eyre::bail!(
350 "{label}: auth = \"oauth\" has been removed — use auth = \"agy-keyring\" (see README) or unset `auth` to use GEMINI_API_KEY"
351 );
352 }
353 (ProviderType::Gemini, Some("agy-keyring")) => {
356 if !cfg!(feature = "antigravity") {
357 eyre::bail!(
358 "{label}: auth = \"agy-keyring\" requires building nitpicker with `--features antigravity`"
359 );
360 }
361 Ok(())
362 }
363 (ProviderType::Gemini, Some(other)) => {
364 eyre::bail!(
365 "{label}: unknown auth value \"{other}\" — expected \"agy-keyring\" or unset"
366 );
367 }
368 (ProviderType::OpenAi | ProviderType::Anthropic, Some("azure-ad")) => {
371 if !cfg!(feature = "azure") {
372 eyre::bail!(
373 "{label}: auth = \"azure-ad\" requires building nitpicker with `--features azure`"
374 );
375 }
376 validate_azure_fields(label, base_url, azure_credentials)
377 }
378 (_, Some("azure-ad")) => {
379 eyre::bail!(
380 "{label}: auth = \"azure-ad\" is only supported with provider \"openai\" or \"anthropic\""
381 );
382 }
383 (ProviderType::OpenAi, Some("codex")) => {
388 if base_url.is_some() {
389 eyre::bail!(
390 "{label}: auth = \"codex\" ignores `base_url` (requests always go to the Codex endpoint) — remove it"
391 );
392 }
393 if api_key_env.is_some() {
394 eyre::bail!(
395 "{label}: auth = \"codex\" ignores `api_key_env` (the token comes from ~/.codex/auth.json) — remove it"
396 );
397 }
398 Ok(())
399 }
400 (_, Some("codex")) => {
401 eyre::bail!("{label}: auth = \"codex\" is only supported with provider \"openai\"");
402 }
403 (_, Some(other)) => {
406 eyre::bail!("{label}: unknown auth value \"{other}\"");
407 }
408 }
409}
410
411fn validate_azure_fields(
415 label: &str,
416 base_url: Option<&str>,
417 azure_credentials: Option<&str>,
418) -> Result<()> {
419 if base_url.map(str::trim).filter(|u| !u.is_empty()).is_none() {
420 eyre::bail!(
421 "{label}: auth = \"azure-ad\" requires a non-empty `base_url` (the Azure Foundry endpoint)"
422 );
423 }
424 match azure_credentials {
429 Some(mode) => validate_azure_credentials_mode(label, "azure_credentials", mode)?,
430 None => {
431 if let Ok(env_mode) = std::env::var("AZURE_TOKEN_CREDENTIALS") {
432 validate_azure_credentials_mode(label, "AZURE_TOKEN_CREDENTIALS", &env_mode)?;
433 }
434 }
435 }
436 Ok(())
437}
438
439fn validate_azure_credentials_mode(label: &str, source: &str, mode: &str) -> Result<()> {
444 let normalized = mode.trim().to_ascii_lowercase();
445 if !normalized.is_empty() && !matches!(normalized.as_str(), "dev" | "prod" | "auto") {
446 eyre::bail!(
447 "{label}: unknown {source} value \"{mode}\" — expected \"dev\", \"prod\", or unset (\"auto\")"
448 );
449 }
450 Ok(())
451}
452
453fn check_env_var(name: &str) -> Result<(), std::env::VarError> {
454 if name == "GEMINI_API_KEY" {
456 if std::env::var("GEMINI_API_KEY").is_ok() || std::env::var("GOOGLE_AI_API_KEY").is_ok() {
457 return Ok(());
458 }
459 return Err(std::env::VarError::NotPresent);
460 }
461 std::env::var(name).map(|_| ())
462}
463
464fn is_local_server(base_url: Option<&str>) -> bool {
465 base_url
466 .map(|u| u.starts_with("http://localhost") || u.starts_with("http://127.0.0.1"))
467 .unwrap_or(false)
468}
469
470fn required_env_var<'a>(settings: ClientSettings<'a>) -> Option<&'a str> {
471 if matches!(settings.provider, ProviderType::Gemini) && is_gemini_proxy_auth(settings.auth) {
472 return None;
473 }
474 if is_azure_ad_auth(settings.auth) {
475 return None;
476 }
477 if is_codex_auth(settings.auth) {
478 return None;
479 }
480 if is_local_server(settings.base_url) {
481 return None;
482 }
483 if let Some(env) = settings.api_key_env {
484 return Some(env);
485 }
486 default_env_var(settings.provider)
487}
488
489fn is_gemini_proxy_auth(auth: Option<&str>) -> bool {
490 matches!(auth, Some("agy-keyring"))
491}
492
493pub fn is_azure_ad_auth(auth: Option<&str>) -> bool {
496 matches!(auth, Some("azure-ad"))
497}
498
499pub fn is_codex_auth(auth: Option<&str>) -> bool {
501 matches!(auth, Some("codex"))
502}
503
504fn default_env_var(provider: &ProviderType) -> Option<&'static str> {
505 match provider {
506 ProviderType::Anthropic => Some("ANTHROPIC_API_KEY"),
507 ProviderType::Gemini => Some("GEMINI_API_KEY"),
508 ProviderType::OpenAi => Some("OPENAI_API_KEY"),
509 ProviderType::OpenRouter => Some("OPENROUTER_API_KEY"),
510 }
511}
512
513#[cfg(test)]
514mod tests {
515 use super::*;
516
517 const FOUNDRY_URL: &str = "https://res.services.ai.azure.com/openai/v1";
518
519 #[test]
520 fn azure_ad_auth_detection() {
521 assert!(is_azure_ad_auth(Some("azure-ad")));
522 assert!(!is_azure_ad_auth(Some("agy-keyring")));
523 assert!(!is_azure_ad_auth(None));
524 }
525
526 #[test]
527 fn validate_auth_rejects_azure_ad_on_unsupported_providers() {
528 let auth = Some("azure-ad".to_string());
529 assert!(validate_auth("[t]", &ProviderType::Gemini, &auth, None, None, None).is_err());
530 assert!(validate_auth("[t]", &ProviderType::OpenRouter, &auth, None, None, None).is_err());
531 }
532
533 #[test]
534 fn validate_auth_azure_ad_on_supported_providers() {
535 let auth = Some("azure-ad".to_string());
536 let creds = Some("auto");
539 let openai = validate_auth(
540 "[t]",
541 &ProviderType::OpenAi,
542 &auth,
543 Some(FOUNDRY_URL),
544 None,
545 creds,
546 );
547 let anthropic = validate_auth(
548 "[t]",
549 &ProviderType::Anthropic,
550 &auth,
551 Some(FOUNDRY_URL),
552 None,
553 creds,
554 );
555 if cfg!(feature = "azure") {
558 assert!(openai.is_ok());
559 assert!(anthropic.is_ok());
560 } else {
561 assert!(openai.is_err());
562 assert!(anthropic.is_err());
563 }
564 }
565
566 #[test]
567 fn validate_auth_allows_unset_and_known_values() {
568 assert!(validate_auth("[t]", &ProviderType::OpenAi, &None, None, None, None).is_ok());
569 let agy = validate_auth(
572 "[t]",
573 &ProviderType::Gemini,
574 &Some("agy-keyring".to_string()),
575 None,
576 None,
577 None,
578 );
579 if cfg!(feature = "antigravity") {
580 assert!(agy.is_ok());
581 } else {
582 assert!(agy.is_err());
583 }
584 }
585
586 #[test]
587 fn validate_auth_codex_rejects_ignored_fields() {
588 let auth = Some("codex".to_string());
589 assert!(validate_auth("[t]", &ProviderType::OpenAi, &auth, None, None, None).is_ok());
591 assert!(
593 validate_auth(
594 "[t]",
595 &ProviderType::OpenAi,
596 &auth,
597 Some("https://example.com"),
598 None,
599 None,
600 )
601 .is_err()
602 );
603 assert!(
604 validate_auth(
605 "[t]",
606 &ProviderType::OpenAi,
607 &auth,
608 None,
609 Some("MY_KEY"),
610 None,
611 )
612 .is_err()
613 );
614 }
615
616 #[test]
617 fn codex_auth_detection() {
618 assert!(is_codex_auth(Some("codex")));
619 assert!(!is_codex_auth(Some("azure-ad")));
620 assert!(!is_codex_auth(None));
621 }
622
623 #[test]
624 fn validate_auth_codex_only_on_openai() {
625 let auth = Some("codex".to_string());
626 assert!(validate_auth("[t]", &ProviderType::OpenAi, &auth, None, None, None).is_ok());
627 assert!(validate_auth("[t]", &ProviderType::Anthropic, &auth, None, None, None).is_err());
628 assert!(validate_auth("[t]", &ProviderType::Gemini, &auth, None, None, None).is_err());
629 assert!(validate_auth("[t]", &ProviderType::OpenRouter, &auth, None, None, None).is_err());
630 }
631
632 fn config_with(reviewer_max_tokens: Option<u64>, aggregator_max_tokens: Option<u64>) -> Config {
634 Config {
635 defaults: None,
636 aggregator: AggregatorConfig {
637 model: "gpt-5.4".to_string(),
638 provider: ProviderType::OpenAi,
639 base_url: None,
640 api_key_env: None,
641 max_tokens: aggregator_max_tokens,
642 auth: Some("codex".to_string()),
643 azure_scope: None,
644 azure_credentials: None,
645 },
646 reviewer: vec![ReviewerConfig {
647 name: "r".to_string(),
648 model: "gpt-5.4".to_string(),
649 provider: ProviderType::OpenAi,
650 base_url: None,
651 api_key_env: None,
652 max_tokens: reviewer_max_tokens,
653 compact_threshold: None,
654 auth: Some("codex".to_string()),
655 azure_scope: None,
656 azure_credentials: None,
657 }],
658 presets: None,
659 }
660 }
661
662 #[test]
664 fn zero_max_tokens_is_rejected_on_both_entities() {
665 assert!(config_with(None, None).validate().is_ok());
666 assert!(config_with(Some(0), None).validate().is_err());
667 assert!(config_with(None, Some(0)).validate().is_err());
668 }
669
670 #[test]
671 fn codex_auth_requires_no_env_var() {
672 let reviewer = ReviewerConfig {
673 name: "r".to_string(),
674 model: "gpt-5.4".to_string(),
675 provider: ProviderType::OpenAi,
676 base_url: None,
677 api_key_env: None,
678 max_tokens: None,
679 compact_threshold: None,
680 auth: Some("codex".to_string()),
681 azure_scope: None,
682 azure_credentials: None,
683 };
684 assert_eq!(required_env_var(ClientSettings::from(&reviewer)), None);
685 let agg = AggregatorConfig {
686 model: "gpt-5.4".to_string(),
687 provider: ProviderType::OpenAi,
688 base_url: None,
689 api_key_env: None,
690 max_tokens: None,
691 auth: Some("codex".to_string()),
692 azure_scope: None,
693 azure_credentials: None,
694 };
695 assert_eq!(required_env_var(ClientSettings::from(&agg)), None);
696 }
697
698 #[test]
703 fn required_env_var_branch_table_and_precedence() {
704 fn provider(name: &str) -> ProviderType {
705 match name {
706 "anthropic" => ProviderType::Anthropic,
707 "gemini" => ProviderType::Gemini,
708 "openai" => ProviderType::OpenAi,
709 "openrouter" => ProviderType::OpenRouter,
710 other => panic!("unknown provider in table: {other}"),
711 }
712 }
713
714 #[rustfmt::skip]
717 let rows = [
718 ("gemini", Some("agy-keyring"), None, None, None),
719 ("gemini", Some("agy-keyring"), None, Some("EXPLICIT"), None),
720 ("openai", Some("agy-keyring"), None, None, Some("OPENAI_API_KEY")),
722 ("openai", Some("azure-ad"), Some("https://f.example/v1"), Some("EXPLICIT"), None),
723 ("openai", Some("codex"), None, Some("EXPLICIT"), None),
724 ("openai", None, Some("http://localhost:1234/v1"), Some("EXPLICIT"), None),
725 ("openai", None, Some("http://127.0.0.1:1234/v1"), None, None),
726 ("anthropic", None, Some("https://gw.example"), Some("EXPLICIT"), Some("EXPLICIT")),
728 ("anthropic", None, None, None, Some("ANTHROPIC_API_KEY")),
729 ("gemini", None, None, None, Some("GEMINI_API_KEY")),
730 ("openai", None, None, None, Some("OPENAI_API_KEY")),
731 ("openrouter", None, None, None, Some("OPENROUTER_API_KEY")),
732 ];
733
734 for (name, auth, base_url, api_key_env, expected) in rows {
735 let reviewer = ReviewerConfig {
736 name: String::new(),
737 model: String::new(),
738 provider: provider(name),
739 base_url: base_url.map(str::to_string),
740 api_key_env: api_key_env.map(str::to_string),
741 max_tokens: None,
742 compact_threshold: None,
743 auth: auth.map(str::to_string),
744 azure_scope: None,
745 azure_credentials: None,
746 };
747 let agg = AggregatorConfig {
748 model: String::new(),
749 provider: provider(name),
750 base_url: base_url.map(str::to_string),
751 api_key_env: api_key_env.map(str::to_string),
752 max_tokens: None,
753 auth: auth.map(str::to_string),
754 azure_scope: None,
755 azure_credentials: None,
756 };
757 for (role, settings) in [
758 ("reviewer", ClientSettings::from(&reviewer)),
759 ("aggregator", ClientSettings::from(&agg)),
760 ] {
761 assert_eq!(
762 required_env_var(settings),
763 expected,
764 "{role}: {name} auth={auth:?} base_url={base_url:?} api_key_env={api_key_env:?}"
765 );
766 }
767 }
768 }
769
770 #[test]
771 fn validate_auth_rejects_unknown_value_on_non_gemini() {
772 let typo = Some("azure_ad".to_string());
774 assert!(
775 validate_auth(
776 "[t]",
777 &ProviderType::OpenAi,
778 &typo,
779 Some(FOUNDRY_URL),
780 None,
781 None
782 )
783 .is_err()
784 );
785 assert!(validate_auth("[t]", &ProviderType::Anthropic, &typo, None, None, None).is_err());
786 }
787
788 #[cfg(feature = "azure")]
789 #[test]
790 fn validate_auth_azure_ad_requires_base_url() {
791 let auth = Some("azure-ad".to_string());
792 assert!(validate_auth("[t]", &ProviderType::OpenAi, &auth, None, None, None).is_err());
796 assert!(validate_auth("[t]", &ProviderType::OpenAi, &auth, Some(""), None, None).is_err());
797 assert!(
798 validate_auth(
799 "[t]",
800 &ProviderType::OpenAi,
801 &auth,
802 Some(FOUNDRY_URL),
803 None,
804 Some("auto")
805 )
806 .is_ok()
807 );
808 }
809
810 #[test]
811 fn validate_azure_credentials_mode_rejects_unknown_only() {
812 assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "dev").is_ok());
814 assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "PROD").is_ok());
815 assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "auto").is_ok());
816 assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "").is_ok());
818 assert!(validate_azure_credentials_mode("[t]", "azure_credentials", " ").is_ok());
819 let err = validate_azure_credentials_mode("[t]", "AZURE_TOKEN_CREDENTIALS", "bogus")
822 .unwrap_err()
823 .to_string();
824 assert!(err.contains("AZURE_TOKEN_CREDENTIALS"), "got: {err}");
825 assert!(err.contains("bogus"), "got: {err}");
826 }
827
828 #[cfg(feature = "azure")]
829 #[test]
830 fn validate_auth_azure_ad_validates_credentials() {
831 let auth = Some("azure-ad".to_string());
832 let ok = |creds| {
833 validate_auth(
834 "[t]",
835 &ProviderType::OpenAi,
836 &auth,
837 Some(FOUNDRY_URL),
838 None,
839 creds,
840 )
841 .is_ok()
842 };
843 assert!(ok(Some("auto")));
848 assert!(ok(Some("dev")));
849 assert!(ok(Some("PROD"))); assert!(ok(Some("auto")));
851 assert!(
852 validate_auth(
853 "[t]",
854 &ProviderType::OpenAi,
855 &auth,
856 Some(FOUNDRY_URL),
857 None,
858 Some("deve")
859 )
860 .is_err()
861 );
862 }
863
864 #[test]
868 fn preset_tables_reject_blank_and_padded_names_and_blank_prompts() {
869 let table = |name: &str, prompt: &str| {
870 let mut presets = BTreeMap::new();
871 presets.insert(
872 name.to_string(),
873 PresetConfig {
874 prompt: prompt.to_string(),
875 },
876 );
877 presets
878 };
879 assert!(validate_presets(None).is_ok());
880 assert!(validate_presets(Some(&table("tone", "review the docs"))).is_ok());
881 assert!(validate_presets(Some(&table(" tone", "review the docs"))).is_err());
882 assert!(validate_presets(Some(&table(" ", "review the docs"))).is_err());
883 assert!(validate_presets(Some(&table("tone", " "))).is_err());
884 }
885
886 #[test]
889 fn preset_tables_reject_control_bytes_in_names() {
890 let table = |name: &str| {
891 let mut presets = BTreeMap::new();
892 presets.insert(
893 name.to_string(),
894 PresetConfig {
895 prompt: "review the docs".to_string(),
896 },
897 );
898 presets
899 };
900 for name in [
901 "esc\u{1b}]0;pwn\u{7}",
902 "csi\u{9b}31m",
903 "tab\tname",
904 "nl\nname",
905 ] {
906 let err = validate_presets(Some(&table(name))).expect_err("control bytes rejected");
907 assert!(
908 format!("{err:#}").contains("control characters"),
909 "wrong error for {name:?}: {err:#}"
910 );
911 }
912 }
913}