use eyre::Result;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
pub const DEFAULT_MAX_TURNS: usize = 100;
pub const DEFAULT_AGGREGATOR_MAX_TOKENS: u64 = 16_384;
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
#[serde(skip_serializing_if = "Option::is_none")]
pub defaults: Option<DefaultsConfig>,
pub aggregator: AggregatorConfig,
pub reviewer: Vec<ReviewerConfig>,
#[serde(skip_serializing_if = "Option::is_none")]
pub presets: Option<BTreeMap<String, PresetConfig>>,
}
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PresetConfig {
pub prompt: String,
}
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DefaultsConfig {
#[serde(skip_serializing_if = "Option::is_none")]
pub debate: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub alloy: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub fallback: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub max_turns: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub compact_threshold: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub log_trajectories: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub presets: Option<Vec<String>>,
}
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AggregatorConfig {
#[serde(default)]
pub model: String,
pub provider: ProviderType,
#[serde(skip_serializing_if = "Option::is_none")]
pub base_url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub api_key_env: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub max_tokens: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub auth: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub azure_scope: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub azure_credentials: Option<String>,
}
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ReviewerConfig {
#[serde(default)]
pub name: String,
#[serde(default)]
pub model: String,
pub provider: ProviderType,
#[serde(skip_serializing_if = "Option::is_none")]
pub base_url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub api_key_env: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub max_tokens: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub compact_threshold: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub auth: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub azure_scope: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub azure_credentials: Option<String>,
}
pub(crate) struct ClientSettings<'a> {
pub(crate) provider: &'a ProviderType,
pub(crate) auth: Option<&'a str>,
pub(crate) base_url: Option<&'a str>,
pub(crate) api_key_env: Option<&'a str>,
pub(crate) azure_scope: Option<&'a str>,
pub(crate) azure_credentials: Option<&'a str>,
}
impl<'a> From<&'a ReviewerConfig> for ClientSettings<'a> {
fn from(reviewer: &'a ReviewerConfig) -> Self {
Self {
provider: &reviewer.provider,
auth: reviewer.auth.as_deref(),
base_url: reviewer.base_url.as_deref(),
api_key_env: reviewer.api_key_env.as_deref(),
azure_scope: reviewer.azure_scope.as_deref(),
azure_credentials: reviewer.azure_credentials.as_deref(),
}
}
}
impl<'a> From<&'a AggregatorConfig> for ClientSettings<'a> {
fn from(agg: &'a AggregatorConfig) -> Self {
Self {
provider: &agg.provider,
auth: agg.auth.as_deref(),
base_url: agg.base_url.as_deref(),
api_key_env: agg.api_key_env.as_deref(),
azure_scope: agg.azure_scope.as_deref(),
azure_credentials: agg.azure_credentials.as_deref(),
}
}
}
#[derive(Serialize, Deserialize)]
pub enum ProviderType {
#[serde(rename = "anthropic", alias = "anthropic_compatible")]
Anthropic,
#[serde(rename = "gemini")]
Gemini,
#[serde(rename = "openai", alias = "openai_compatible")]
OpenAi,
#[serde(rename = "openrouter")]
OpenRouter,
}
impl ProviderType {
#[cfg(feature = "antigravity")]
pub fn is_gemini(&self) -> bool {
matches!(self, ProviderType::Gemini)
}
}
impl Config {
pub fn validate(&self) -> Result<()> {
self.validate_structure()?;
self.validate_credentials()
}
pub fn validate_structure(&self) -> Result<()> {
if self.reviewer.is_empty() {
eyre::bail!("no reviewers configured");
}
self.validate_alloy(self.default_alloy())?;
self.validate_fallback(self.default_fallback())?;
validate_free_model(
"[aggregator]",
&self.aggregator.provider,
&self.aggregator.model,
)?;
validate_auth(
"[aggregator]",
&self.aggregator.provider,
&self.aggregator.auth,
self.aggregator.base_url.as_deref(),
self.aggregator.api_key_env.as_deref(),
self.aggregator.azure_credentials.as_deref(),
)?;
for reviewer in &self.reviewer {
let reviewer_label = match reviewer.name.is_empty() {
true => "reviewer <unnamed>".to_string(),
false => format!("reviewer {}", reviewer.name),
};
validate_free_model(&reviewer_label, &reviewer.provider, &reviewer.model)?;
validate_auth(
&reviewer_label,
&reviewer.provider,
&reviewer.auth,
reviewer.base_url.as_deref(),
reviewer.api_key_env.as_deref(),
reviewer.azure_credentials.as_deref(),
)?;
if reviewer.compact_threshold == Some(0) {
eyre::bail!(
"reviewer {}: compact_threshold must be greater than 0",
reviewer.name
);
}
if reviewer.max_tokens == Some(0) {
eyre::bail!(
"reviewer {}: max_tokens must be greater than 0",
reviewer.name
);
}
}
if self.aggregator.max_tokens == Some(0) {
eyre::bail!("[aggregator].max_tokens must be greater than 0");
}
if self.defaults.as_ref().and_then(|d| d.compact_threshold) == Some(0) {
eyre::bail!("[defaults].compact_threshold must be greater than 0");
}
validate_presets(self.presets.as_ref())?;
Ok(())
}
pub fn default_debate(&self) -> bool {
self.defaults
.as_ref()
.and_then(|d| d.debate)
.unwrap_or(true)
}
pub fn validate_alloy(&self, alloy: bool) -> Result<()> {
if alloy && self.reviewer.len() < 2 {
eyre::bail!(
"--alloy requires at least 2 reviewers, found {}",
self.reviewer.len()
);
}
Ok(())
}
pub fn validate_credentials(&self) -> Result<()> {
if let Some(env) = required_env_var(ClientSettings::from(&self.aggregator)) {
check_env_var(env)
.map_err(|_| eyre::eyre!("[aggregator]: env var {env} is not set"))?;
}
for reviewer in &self.reviewer {
if let Some(env) = required_env_var(ClientSettings::from(reviewer)) {
check_env_var(env).map_err(|_| {
eyre::eyre!("reviewer {}: env var {env} is not set", reviewer.name)
})?;
}
}
Ok(())
}
pub fn default_alloy(&self) -> bool {
self.defaults
.as_ref()
.and_then(|d| d.alloy)
.unwrap_or(false)
}
pub fn validate_fallback(&self, fallback: bool) -> Result<()> {
if fallback && self.reviewer.len() < 2 {
eyre::bail!(
"fallback = true / --fallback requires at least 2 reviewers, found {}",
self.reviewer.len()
);
}
Ok(())
}
pub fn default_fallback(&self) -> bool {
self.defaults
.as_ref()
.and_then(|d| d.fallback)
.unwrap_or(false)
}
pub fn max_turns(&self, override_max_turns: Option<usize>) -> Result<usize> {
match override_max_turns {
Some(max_turns) => Ok(max_turns),
None => self.default_max_turns(),
}
}
pub fn default_max_turns(&self) -> Result<usize> {
let max_turns = self
.defaults
.as_ref()
.and_then(|d| d.max_turns)
.unwrap_or(DEFAULT_MAX_TURNS);
if max_turns == 0 {
eyre::bail!("[defaults].max_turns must be greater than 0");
}
Ok(max_turns)
}
pub fn default_compact_threshold(&self) -> Option<u64> {
self.defaults.as_ref().and_then(|d| d.compact_threshold)
}
pub fn log_trajectories(&self) -> bool {
self.defaults
.as_ref()
.and_then(|d| d.log_trajectories)
.unwrap_or(false)
}
pub fn aggregator_max_tokens(&self) -> u64 {
self.aggregator
.max_tokens
.unwrap_or(DEFAULT_AGGREGATOR_MAX_TOKENS)
}
pub fn reviewer_compact_threshold(&self, reviewer: &ReviewerConfig) -> Option<u64> {
reviewer
.compact_threshold
.or(self.default_compact_threshold())
}
}
fn validate_presets(presets: Option<&BTreeMap<String, PresetConfig>>) -> Result<()> {
let presets = match presets {
Some(presets) => presets,
None => return Ok(()),
};
for (name, preset) in presets {
if name.trim().is_empty() {
eyre::bail!("[presets]: preset names must contain non-whitespace content");
}
if name != name.trim() {
eyre::bail!("[presets.{name:?}]: preset names must not have surrounding whitespace");
}
if name.chars().any(char::is_control) {
eyre::bail!("[presets.{name:?}]: preset names must not contain control characters");
}
if preset.prompt.trim().is_empty() {
eyre::bail!("[presets.{name}].prompt must contain non-whitespace content");
}
}
Ok(())
}
fn validate_free_model(label: &str, provider: &ProviderType, model: &str) -> Result<()> {
if model == "free" && !matches!(provider, ProviderType::OpenRouter) {
eyre::bail!("{label}: model = \"free\" is only supported with provider = \"openrouter\"");
}
Ok(())
}
fn validate_auth(
label: &str,
provider: &ProviderType,
auth: &Option<String>,
base_url: Option<&str>,
api_key_env: Option<&str>,
azure_credentials: Option<&str>,
) -> Result<()> {
match (provider, auth.as_deref()) {
(_, None) => Ok(()),
(ProviderType::Gemini, Some("oauth")) => {
eyre::bail!(
"{label}: auth = \"oauth\" has been removed — use auth = \"agy-keyring\" (see README) or unset `auth` to use GEMINI_API_KEY"
);
}
(ProviderType::Gemini, Some("agy-keyring")) => {
if !cfg!(feature = "antigravity") {
eyre::bail!(
"{label}: auth = \"agy-keyring\" requires building nitpicker with `--features antigravity`"
);
}
Ok(())
}
(ProviderType::Gemini, Some(other)) => {
eyre::bail!(
"{label}: unknown auth value \"{other}\" — expected \"agy-keyring\" or unset"
);
}
(ProviderType::OpenAi | ProviderType::Anthropic, Some("azure-ad")) => {
if !cfg!(feature = "azure") {
eyre::bail!(
"{label}: auth = \"azure-ad\" requires building nitpicker with `--features azure`"
);
}
validate_azure_fields(label, base_url, azure_credentials)
}
(_, Some("azure-ad")) => {
eyre::bail!(
"{label}: auth = \"azure-ad\" is only supported with provider \"openai\" or \"anthropic\""
);
}
(ProviderType::OpenAi, Some("codex")) => {
if base_url.is_some() {
eyre::bail!(
"{label}: auth = \"codex\" ignores `base_url` (requests always go to the Codex endpoint) — remove it"
);
}
if api_key_env.is_some() {
eyre::bail!(
"{label}: auth = \"codex\" ignores `api_key_env` (the token comes from ~/.codex/auth.json) — remove it"
);
}
Ok(())
}
(_, Some("codex")) => {
eyre::bail!("{label}: auth = \"codex\" is only supported with provider \"openai\"");
}
(_, Some(other)) => {
eyre::bail!("{label}: unknown auth value \"{other}\"");
}
}
}
fn validate_azure_fields(
label: &str,
base_url: Option<&str>,
azure_credentials: Option<&str>,
) -> Result<()> {
if base_url.map(str::trim).filter(|u| !u.is_empty()).is_none() {
eyre::bail!(
"{label}: auth = \"azure-ad\" requires a non-empty `base_url` (the Azure Foundry endpoint)"
);
}
match azure_credentials {
Some(mode) => validate_azure_credentials_mode(label, "azure_credentials", mode)?,
None => {
if let Ok(env_mode) = std::env::var("AZURE_TOKEN_CREDENTIALS") {
validate_azure_credentials_mode(label, "AZURE_TOKEN_CREDENTIALS", &env_mode)?;
}
}
}
Ok(())
}
fn validate_azure_credentials_mode(label: &str, source: &str, mode: &str) -> Result<()> {
let normalized = mode.trim().to_ascii_lowercase();
if !normalized.is_empty() && !matches!(normalized.as_str(), "dev" | "prod" | "auto") {
eyre::bail!(
"{label}: unknown {source} value \"{mode}\" — expected \"dev\", \"prod\", or unset (\"auto\")"
);
}
Ok(())
}
fn check_env_var(name: &str) -> Result<(), std::env::VarError> {
if name == "GEMINI_API_KEY" {
if std::env::var("GEMINI_API_KEY").is_ok() || std::env::var("GOOGLE_AI_API_KEY").is_ok() {
return Ok(());
}
return Err(std::env::VarError::NotPresent);
}
std::env::var(name).map(|_| ())
}
fn is_local_server(base_url: Option<&str>) -> bool {
base_url
.map(|u| u.starts_with("http://localhost") || u.starts_with("http://127.0.0.1"))
.unwrap_or(false)
}
fn required_env_var<'a>(settings: ClientSettings<'a>) -> Option<&'a str> {
if matches!(settings.provider, ProviderType::Gemini) && is_gemini_proxy_auth(settings.auth) {
return None;
}
if is_azure_ad_auth(settings.auth) {
return None;
}
if is_codex_auth(settings.auth) {
return None;
}
if is_local_server(settings.base_url) {
return None;
}
if let Some(env) = settings.api_key_env {
return Some(env);
}
default_env_var(settings.provider)
}
fn is_gemini_proxy_auth(auth: Option<&str>) -> bool {
matches!(auth, Some("agy-keyring"))
}
pub fn is_azure_ad_auth(auth: Option<&str>) -> bool {
matches!(auth, Some("azure-ad"))
}
pub fn is_codex_auth(auth: Option<&str>) -> bool {
matches!(auth, Some("codex"))
}
fn default_env_var(provider: &ProviderType) -> Option<&'static str> {
match provider {
ProviderType::Anthropic => Some("ANTHROPIC_API_KEY"),
ProviderType::Gemini => Some("GEMINI_API_KEY"),
ProviderType::OpenAi => Some("OPENAI_API_KEY"),
ProviderType::OpenRouter => Some("OPENROUTER_API_KEY"),
}
}
#[cfg(test)]
mod tests {
use super::*;
const FOUNDRY_URL: &str = "https://res.services.ai.azure.com/openai/v1";
#[test]
fn azure_ad_auth_detection() {
assert!(is_azure_ad_auth(Some("azure-ad")));
assert!(!is_azure_ad_auth(Some("agy-keyring")));
assert!(!is_azure_ad_auth(None));
}
#[test]
fn validate_auth_rejects_azure_ad_on_unsupported_providers() {
let auth = Some("azure-ad".to_string());
assert!(validate_auth("[t]", &ProviderType::Gemini, &auth, None, None, None).is_err());
assert!(validate_auth("[t]", &ProviderType::OpenRouter, &auth, None, None, None).is_err());
}
#[test]
fn validate_auth_azure_ad_on_supported_providers() {
let auth = Some("azure-ad".to_string());
let creds = Some("auto");
let openai = validate_auth(
"[t]",
&ProviderType::OpenAi,
&auth,
Some(FOUNDRY_URL),
None,
creds,
);
let anthropic = validate_auth(
"[t]",
&ProviderType::Anthropic,
&auth,
Some(FOUNDRY_URL),
None,
creds,
);
if cfg!(feature = "azure") {
assert!(openai.is_ok());
assert!(anthropic.is_ok());
} else {
assert!(openai.is_err());
assert!(anthropic.is_err());
}
}
#[test]
fn validate_auth_allows_unset_and_known_values() {
assert!(validate_auth("[t]", &ProviderType::OpenAi, &None, None, None, None).is_ok());
let agy = validate_auth(
"[t]",
&ProviderType::Gemini,
&Some("agy-keyring".to_string()),
None,
None,
None,
);
if cfg!(feature = "antigravity") {
assert!(agy.is_ok());
} else {
assert!(agy.is_err());
}
}
#[test]
fn validate_auth_codex_rejects_ignored_fields() {
let auth = Some("codex".to_string());
assert!(validate_auth("[t]", &ProviderType::OpenAi, &auth, None, None, None).is_ok());
assert!(
validate_auth(
"[t]",
&ProviderType::OpenAi,
&auth,
Some("https://example.com"),
None,
None,
)
.is_err()
);
assert!(
validate_auth(
"[t]",
&ProviderType::OpenAi,
&auth,
None,
Some("MY_KEY"),
None,
)
.is_err()
);
}
#[test]
fn codex_auth_detection() {
assert!(is_codex_auth(Some("codex")));
assert!(!is_codex_auth(Some("azure-ad")));
assert!(!is_codex_auth(None));
}
#[test]
fn validate_auth_codex_only_on_openai() {
let auth = Some("codex".to_string());
assert!(validate_auth("[t]", &ProviderType::OpenAi, &auth, None, None, None).is_ok());
assert!(validate_auth("[t]", &ProviderType::Anthropic, &auth, None, None, None).is_err());
assert!(validate_auth("[t]", &ProviderType::Gemini, &auth, None, None, None).is_err());
assert!(validate_auth("[t]", &ProviderType::OpenRouter, &auth, None, None, None).is_err());
}
fn config_with(reviewer_max_tokens: Option<u64>, aggregator_max_tokens: Option<u64>) -> Config {
Config {
defaults: None,
aggregator: AggregatorConfig {
model: "gpt-5.4".to_string(),
provider: ProviderType::OpenAi,
base_url: None,
api_key_env: None,
max_tokens: aggregator_max_tokens,
auth: Some("codex".to_string()),
azure_scope: None,
azure_credentials: None,
},
reviewer: vec![ReviewerConfig {
name: "r".to_string(),
model: "gpt-5.4".to_string(),
provider: ProviderType::OpenAi,
base_url: None,
api_key_env: None,
max_tokens: reviewer_max_tokens,
compact_threshold: None,
auth: Some("codex".to_string()),
azure_scope: None,
azure_credentials: None,
}],
presets: None,
}
}
#[test]
fn zero_max_tokens_is_rejected_on_both_entities() {
assert!(config_with(None, None).validate().is_ok());
assert!(config_with(Some(0), None).validate().is_err());
assert!(config_with(None, Some(0)).validate().is_err());
}
#[test]
fn fallback_default_is_opt_in_and_requires_a_next_reviewer() {
let mut config = config_with(None, None);
assert!(!config.default_fallback());
config.defaults = Some(DefaultsConfig {
debate: None,
alloy: None,
fallback: Some(true),
max_turns: None,
compact_threshold: None,
log_trajectories: None,
presets: None,
});
assert!(config.default_fallback());
assert!(config.validate().is_err());
config.reviewer.push(ReviewerConfig {
name: "r2".to_string(),
model: "gpt-5.4".to_string(),
provider: ProviderType::OpenAi,
base_url: None,
api_key_env: None,
max_tokens: None,
compact_threshold: None,
auth: Some("codex".to_string()),
azure_scope: None,
azure_credentials: None,
});
assert!(config.validate().is_ok());
}
#[test]
fn structural_validation_defers_missing_route_credentials() {
let mut config = config_with(None, None);
config.aggregator.auth = None;
config.aggregator.api_key_env =
Some("NITPICKER_TEST_MISSING_AGGREGATOR_CREDENTIAL_FOR_FALLBACK_7C51".to_string());
assert!(config.validate_structure().is_ok());
let err = config.validate_credentials().unwrap_err();
assert!(format!("{err:#}").contains("env var"));
assert!(config.validate().is_err());
}
#[test]
fn codex_auth_requires_no_env_var() {
let reviewer = ReviewerConfig {
name: "r".to_string(),
model: "gpt-5.4".to_string(),
provider: ProviderType::OpenAi,
base_url: None,
api_key_env: None,
max_tokens: None,
compact_threshold: None,
auth: Some("codex".to_string()),
azure_scope: None,
azure_credentials: None,
};
assert_eq!(required_env_var(ClientSettings::from(&reviewer)), None);
let agg = AggregatorConfig {
model: "gpt-5.4".to_string(),
provider: ProviderType::OpenAi,
base_url: None,
api_key_env: None,
max_tokens: None,
auth: Some("codex".to_string()),
azure_scope: None,
azure_credentials: None,
};
assert_eq!(required_env_var(ClientSettings::from(&agg)), None);
}
#[test]
fn required_env_var_branch_table_and_precedence() {
fn provider(name: &str) -> ProviderType {
match name {
"anthropic" => ProviderType::Anthropic,
"gemini" => ProviderType::Gemini,
"openai" => ProviderType::OpenAi,
"openrouter" => ProviderType::OpenRouter,
other => panic!("unknown provider in table: {other}"),
}
}
#[rustfmt::skip]
let rows = [
("gemini", Some("agy-keyring"), None, None, None),
("gemini", Some("agy-keyring"), None, Some("EXPLICIT"), None),
("openai", Some("agy-keyring"), None, None, Some("OPENAI_API_KEY")),
("openai", Some("azure-ad"), Some("https://f.example/v1"), Some("EXPLICIT"), None),
("openai", Some("codex"), None, Some("EXPLICIT"), None),
("openai", None, Some("http://localhost:1234/v1"), Some("EXPLICIT"), None),
("openai", None, Some("http://127.0.0.1:1234/v1"), None, None),
("anthropic", None, Some("https://gw.example"), Some("EXPLICIT"), Some("EXPLICIT")),
("anthropic", None, None, None, Some("ANTHROPIC_API_KEY")),
("gemini", None, None, None, Some("GEMINI_API_KEY")),
("openai", None, None, None, Some("OPENAI_API_KEY")),
("openrouter", None, None, None, Some("OPENROUTER_API_KEY")),
];
for (name, auth, base_url, api_key_env, expected) in rows {
let reviewer = ReviewerConfig {
name: String::new(),
model: String::new(),
provider: provider(name),
base_url: base_url.map(str::to_string),
api_key_env: api_key_env.map(str::to_string),
max_tokens: None,
compact_threshold: None,
auth: auth.map(str::to_string),
azure_scope: None,
azure_credentials: None,
};
let agg = AggregatorConfig {
model: String::new(),
provider: provider(name),
base_url: base_url.map(str::to_string),
api_key_env: api_key_env.map(str::to_string),
max_tokens: None,
auth: auth.map(str::to_string),
azure_scope: None,
azure_credentials: None,
};
for (role, settings) in [
("reviewer", ClientSettings::from(&reviewer)),
("aggregator", ClientSettings::from(&agg)),
] {
assert_eq!(
required_env_var(settings),
expected,
"{role}: {name} auth={auth:?} base_url={base_url:?} api_key_env={api_key_env:?}"
);
}
}
}
#[test]
fn validate_auth_rejects_unknown_value_on_non_gemini() {
let typo = Some("azure_ad".to_string());
assert!(
validate_auth(
"[t]",
&ProviderType::OpenAi,
&typo,
Some(FOUNDRY_URL),
None,
None
)
.is_err()
);
assert!(validate_auth("[t]", &ProviderType::Anthropic, &typo, None, None, None).is_err());
}
#[cfg(feature = "azure")]
#[test]
fn validate_auth_azure_ad_requires_base_url() {
let auth = Some("azure-ad".to_string());
assert!(validate_auth("[t]", &ProviderType::OpenAi, &auth, None, None, None).is_err());
assert!(validate_auth("[t]", &ProviderType::OpenAi, &auth, Some(""), None, None).is_err());
assert!(
validate_auth(
"[t]",
&ProviderType::OpenAi,
&auth,
Some(FOUNDRY_URL),
None,
Some("auto")
)
.is_ok()
);
}
#[test]
fn validate_azure_credentials_mode_rejects_unknown_only() {
assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "dev").is_ok());
assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "PROD").is_ok());
assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "auto").is_ok());
assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "").is_ok());
assert!(validate_azure_credentials_mode("[t]", "azure_credentials", " ").is_ok());
let err = validate_azure_credentials_mode("[t]", "AZURE_TOKEN_CREDENTIALS", "bogus")
.unwrap_err()
.to_string();
assert!(err.contains("AZURE_TOKEN_CREDENTIALS"), "got: {err}");
assert!(err.contains("bogus"), "got: {err}");
}
#[cfg(feature = "azure")]
#[test]
fn validate_auth_azure_ad_validates_credentials() {
let auth = Some("azure-ad".to_string());
let ok = |creds| {
validate_auth(
"[t]",
&ProviderType::OpenAi,
&auth,
Some(FOUNDRY_URL),
None,
creds,
)
.is_ok()
};
assert!(ok(Some("auto")));
assert!(ok(Some("dev")));
assert!(ok(Some("PROD"))); assert!(ok(Some("auto")));
assert!(
validate_auth(
"[t]",
&ProviderType::OpenAi,
&auth,
Some(FOUNDRY_URL),
None,
Some("deve")
)
.is_err()
);
}
#[test]
fn preset_tables_reject_blank_and_padded_names_and_blank_prompts() {
let table = |name: &str, prompt: &str| {
let mut presets = BTreeMap::new();
presets.insert(
name.to_string(),
PresetConfig {
prompt: prompt.to_string(),
},
);
presets
};
assert!(validate_presets(None).is_ok());
assert!(validate_presets(Some(&table("tone", "review the docs"))).is_ok());
assert!(validate_presets(Some(&table(" tone", "review the docs"))).is_err());
assert!(validate_presets(Some(&table(" ", "review the docs"))).is_err());
assert!(validate_presets(Some(&table("tone", " "))).is_err());
}
#[test]
fn preset_tables_reject_control_bytes_in_names() {
let table = |name: &str| {
let mut presets = BTreeMap::new();
presets.insert(
name.to_string(),
PresetConfig {
prompt: "review the docs".to_string(),
},
);
presets
};
for name in [
"esc\u{1b}]0;pwn\u{7}",
"csi\u{9b}31m",
"tab\tname",
"nl\nname",
] {
let err = validate_presets(Some(&table(name))).expect_err("control bytes rejected");
assert!(
format!("{err:#}").contains("control characters"),
"wrong error for {name:?}: {err:#}"
);
}
}
}