use std::path::{Path, PathBuf};
use anyhow::{Context, bail};
use serde::{Deserialize, Serialize};
use serde_yaml_ng::{Mapping, Value};
mod binary;
pub mod credentials;
mod document;
pub mod go_url;
mod sanitize;
mod schema;
mod text;
mod timestamp;
mod trusted;
mod validate;
pub use binary::{PLAIN as PLAIN_SCALAR, double_quoted as yaml_double_quoted};
pub use document::{ConfigDocument, archive_comments, credential_error, is_v8_layout, v8_group_error, v8_layout_error};
pub use schema::validate as validate_config_fields;
pub use schema::{coerce_typed_scalars, go_bool, go_int};
pub use timestamp::{AsJson, TAG as TIMESTAMP_TAG};
pub fn parse_yaml(text: &str) -> Result<Value, serde_yaml_ng::Error> {
let text = text.strip_prefix('\u{feff}').unwrap_or(text);
let parse = |text: &str| serde_yaml_ng::from_str::<Value>(text);
let err = if may_resolve(text) {
None
} else {
match parse(text) {
Ok(value) if !needs_scan(&value) => return Ok(value),
Ok(_) => None,
Err(err) => Some(err),
}
};
let as_is = |err: Option<serde_yaml_ng::Error>| err.map_or_else(|| parse(text), Err);
let Ok(scalars) = binary::plain_scalars(text) else {
return as_is(err);
};
let mut out = String::with_capacity(text.len());
let mut last = 0;
for plain in scalars.into_iter().filter(|p| p.timestamp_tag.is_none()) {
let read = std::str::from_utf8(&plain.value)
.ok()
.and_then(|s| go_read(s, plain.key));
let (Some(read), Some(before)) = (read, text.get(last..plain.span.start)) else {
continue;
};
out.push_str(before);
out.push_str(&read);
last = plain.span.end;
}
if last == 0 {
return as_is(err);
}
out.push_str(&text[last.min(text.len())..]);
parse(&out)
}
pub fn yaml_string(value: &Value) -> Result<String, serde_yaml_ng::Error> {
let text = serde_yaml_ng::to_string(value)?;
if !may_resolve(&text) && !needs_scan(value) {
return Ok(text);
}
let Ok(scalars) = binary::plain_scalars(&text) else {
return Ok(text);
};
let mut out = String::with_capacity(text.len() + 2);
let mut last = 0;
for plain in scalars {
if let Some(tag) = plain.timestamp_tag {
out.push_str(&text[last..tag]);
out.push_str(&text[plain.span.clone()]);
last = plain.span.end;
continue;
}
let flagged = std::str::from_utf8(&plain.value).ok().and_then(|s| go_read(s, false));
if flagged.is_none() {
continue;
}
out.push_str(&text[last..plain.span.start]);
out.push('"');
out.push_str(&text[plain.span.clone()]);
out.push('"');
last = plain.span.end;
}
out.push_str(&text[last..]);
Ok(out)
}
fn may_resolve(text: &str) -> bool {
let zero = |w: &[u8]| w[0] == b'0' && (w[1].is_ascii_digit() || matches!(w[1], b'b' | b'o' | b'X' | b'O' | b'B'));
text.contains('_')
|| text.as_bytes().starts_with(b"0")
|| text
.as_bytes()
.windows(3)
.any(|w| zero(&w[1..]) && !(w[0].is_ascii_alphanumeric() || w[0] == b'.'))
}
fn needs_scan(value: &Value) -> bool {
match value {
Value::String(s) => timestamp::go_timestamp(s).is_some(),
Value::Number(n) => n.as_i64().is_none() && n.as_u64().is_some(),
Value::Sequence(items) => items.iter().any(needs_scan),
Value::Mapping(m) => m.iter().any(|(k, v)| needs_scan(k) || needs_scan(v)),
Value::Tagged(t) => t.tag == timestamp::TAG || needs_scan(&t.value),
_ => false,
}
}
fn go_read(scalar: &str, key: bool) -> Option<String> {
if !key && let Some(time) = timestamp::go_timestamp(scalar) {
return Some(format!("!<{}> {time}", timestamp::TAG));
}
let unsigned = scalar.strip_prefix(['+', '-']).unwrap_or(scalar).as_bytes();
let leading_zero = unsigned.first() == Some(&b'0')
&& unsigned
.get(1)
.is_some_and(|b| b.is_ascii_digit() || matches!(b, b'b' | b'o' | b'X' | b'O' | b'B'));
if scalar.contains('_') || leading_zero {
(!key)
.then(|| go_resolved(scalar))
.flatten()
.or_else(|| go_big_integer(scalar, key))
} else {
go_big_integer(scalar, key)
}
}
fn go_resolved(text: &str) -> Option<String> {
let plain = text.replace('_', "");
let float = |s: &str| {
let f = go_yaml_float(s)?;
Some(format!("{f:e}"))
};
match text.as_bytes().first()? {
b'.' => {
let bytes = text.as_bytes();
let between_digits = bytes.iter().enumerate().all(|(i, &b)| {
b != b'_'
|| (i > 0 && bytes[i - 1].is_ascii_digit() && bytes.get(i + 1).is_some_and(u8::is_ascii_digit))
});
if between_digits { float(&plain) } else { None }
}
b'0'..=b'9' | b'+' | b'-' => {
let negative = plain.starts_with('-');
let signed = plain.starts_with(['+', '-']);
let unsigned = plain.strip_prefix(['+', '-']).unwrap_or(&plain);
let (radix, digits) = match unsigned.get(..2) {
Some("0x" | "0X") => (16, &unsigned[2..]),
Some("0o" | "0O") => (8, &unsigned[2..]),
Some("0b" | "0B") => (2, &unsigned[2..]),
_ if unsigned.len() > 1 && unsigned.starts_with('0') => (8, &unsigned[1..]),
_ => (10, unsigned),
};
if !digits.is_empty() && digits.chars().all(|c| c.is_digit(radix)) {
if let Ok(n) = u64::from_str_radix(digits, radix) {
if negative && n <= 1 << 63 {
return Some(format!("-{n}"));
}
if !negative && (n <= i64::MAX as u64 || !signed) {
return Some(n.to_string());
}
if !negative && unsigned.as_bytes().get(1).is_some_and(u8::is_ascii_alphabetic) {
return Some(format!("'{text}'"));
}
}
}
if let Some(f) = float(&plain) {
return Some(f);
}
let (radix, rest) = match plain.get(..2)? {
"0b" => (2, &plain[2..]),
"0o" => (8, &plain[2..]),
_ => return None,
};
let n = i64::from_str_radix(rest, radix).map(|n| n.to_string());
let unsigned = || {
(!rest.starts_with('+'))
.then(|| u64::from_str_radix(rest, radix).ok())
.flatten()
};
n.ok().or_else(|| unsigned().map(|n| n.to_string()))
}
_ => None,
}
}
fn go_yaml_float(s: &str) -> Option<f64> {
let digits = |s: &str| s.len() - s.trim_start_matches(|c: char| c.is_ascii_digit()).len();
let rest = s.strip_prefix(['+', '-']).unwrap_or(s);
let (mantissa, exponent) = match rest.find(['e', 'E']) {
Some(at) => (&rest[..at], Some(&rest[at + 1..])),
None => (rest, None),
};
let mantissa_ok = match mantissa.split_once('.') {
Some(("", frac)) => !frac.is_empty() && digits(frac) == frac.len(),
Some((int, frac)) => !int.is_empty() && digits(int) == int.len() && digits(frac) == frac.len(),
None => !mantissa.is_empty() && digits(mantissa) == mantissa.len(),
};
let exponent_ok = exponent.is_none_or(|e| {
let e = e.strip_prefix(['+', '-']).unwrap_or(e);
!e.is_empty() && digits(e) == e.len()
});
if !(mantissa_ok && exponent_ok) {
return None;
}
s.parse::<f64>().ok().filter(|f| f.is_finite())
}
fn go_big_integer(text: &str, key: bool) -> Option<String> {
let negative = text.starts_with('-');
let unsigned = text.strip_prefix(['+', '-']).unwrap_or(text);
let (radix, digits) = match unsigned.get(..2) {
Some("0x" | "0X") => (16, &unsigned[2..]),
Some("0o" | "0O") => (8, &unsigned[2..]),
Some("0b" | "0B") => (2, &unsigned[2..]),
_ => (10, unsigned),
};
if digits.is_empty() || (radix == 10 && digits.len() > 1 && digits.starts_with('0')) {
return None;
}
let magnitude = u128::from_str_radix(digits, radix).ok()?;
if negative && magnitude > 1 << 127 {
return None;
}
let fits = if negative {
i64::from_str_radix(&format!("-{digits}"), radix).is_ok()
} else if text.starts_with('+') && !key {
i64::from_str_radix(digits, radix).is_ok()
} else {
u64::from_str_radix(digits, radix).is_ok()
};
if fits {
return None;
}
Some(if radix == 10 {
format!("{:e}", text.parse::<f64>().ok()?)
} else {
format!("'{text}'")
})
}
pub fn yaml_value(text: &str) -> anyhow::Result<Value> {
let mut value = parse_yaml(text)?;
timestamp::refuse_wide_offsets(&value)?;
binary::decode(text, &mut value, None, binary::Mode::File)?;
Ok(value)
}
pub fn config_value(text: &str) -> anyhow::Result<Value> {
let mut value = parse_yaml(text)?;
timestamp::refuse_wide_offsets(&value)?;
binary::decode(text, &mut value, Some(&[]), binary::Mode::File)?;
Ok(value)
}
fn plugin_configs(text: &str, root: &Mapping) -> Value {
if !lookup(root, "plugins.configs").is_some_and(|c| c.as_mapping().is_some_and(|m| !m.is_empty())) {
return Value::Null;
}
let raw = || {
let mut value = parse_yaml(text)?;
binary::decode(text, &mut value, Some(&[]), binary::Mode::Plugins)?;
expand_merges(&mut value)?;
anyhow::Ok(value)
};
match raw() {
Ok(v) => v
.get("plugins")
.and_then(|p| p.get("configs"))
.cloned()
.unwrap_or(Value::Null),
Err(e) => {
static WARNED: std::sync::Mutex<u64> = std::sync::Mutex::new(0);
let hash = {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
text.hash(&mut h);
h.finish()
};
let mut warned = WARNED.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if *warned != hash {
*warned = hash;
tracing::warn!("plugin configs keep their parsed values: {e:#}");
}
Value::Null
}
}
}
pub fn body_value(text: &str, keys: &[&str]) -> anyhow::Result<Value> {
fn keep_written(literal: &mut Value, parsed: Value) {
match (literal, parsed) {
(Value::Mapping(l), Value::Mapping(p)) => {
for ((_, l), (_, p)) in l.iter_mut().zip(p) {
keep_written(l, p);
}
}
(Value::Sequence(l), Value::Sequence(p)) => {
for (l, p) in l.iter_mut().zip(p) {
keep_written(l, p);
}
}
(l @ Value::String(_), p @ (Value::Number(_) | Value::Bool(_)))
if l.as_str() == Some(go_string(&p).as_str()) =>
{
*l = p;
}
_ => {}
}
}
let parsed = parse_yaml(text)?;
let mut value = parsed.clone();
binary::decode(text, &mut value, Some(keys), binary::Mode::Body)?;
keep_written(&mut value, parsed);
Ok(value)
}
const MERGE_NOT_MAPS: &str = "yaml: map merge requires map or sequence of maps as the value";
pub fn expand_merges(value: &mut Value) -> anyhow::Result<()> {
match value {
Value::Mapping(map) => {
for (_, child) in map.iter_mut() {
expand_merges(child)?;
}
if let Some(merge) = map.shift_remove("<<") {
let sources: Vec<Mapping> = match untagged(merge) {
Value::Mapping(m) => vec![m],
Value::Sequence(items) => items
.into_iter()
.map(|item| match untagged(item) {
Value::Mapping(m) => Ok(m),
_ => Err(anyhow::anyhow!(MERGE_NOT_MAPS)),
})
.collect::<anyhow::Result<_>>()?,
_ => bail!(MERGE_NOT_MAPS),
};
for source in sources {
for (key, item) in source {
map.entry(key).or_insert(item);
}
}
}
}
Value::Sequence(items) => {
for item in items {
expand_merges(item)?;
}
}
Value::Tagged(tagged) => expand_merges(&mut tagged.value)?,
_ => {}
}
Ok(())
}
fn untagged(value: Value) -> Value {
match value {
Value::Tagged(tagged) => untagged(tagged.value),
other => other,
}
}
pub use trusted::{TrustedProxies, go_trim_space};
pub use validate::{catalog_sources as validate_catalog_sources, go_is_abs, parse_duration};
pub const DEFAULT_PORT: u16 = 8317;
pub const DEFAULT_AUTH_DIR: &str = "~/.cli-proxy-api";
#[derive(Clone, PartialEq, Eq)]
pub struct Config {
pub host: String,
pub port: u16,
pub api_keys: Vec<String>,
pub trusted_proxies: Vec<String>,
pub auth_dir: PathBuf,
pub routing: RoutingConfig,
pub management: ManagementConfig,
pub document: Value,
pub oauth_only: std::collections::BTreeSet<String>,
pub plugin_configs: Value,
pub derived: Derived,
}
#[derive(Default)]
pub struct Derived(std::sync::Mutex<Vec<std::sync::Arc<dyn std::any::Any + Send + Sync>>>);
impl Clone for Derived {
fn clone(&self) -> Self {
Self::default()
}
}
impl PartialEq for Derived {
fn eq(&self, _: &Self) -> bool {
true
}
}
impl Eq for Derived {}
impl Config {
pub fn catalog_sources(&self) -> [String; 3] {
["catalog", "codex-catalog", "devin-catalog"].map(|name| {
self.document
.get("models")
.and_then(|models| models.get(name))
.filter(|v| !v.is_null())
.map(go_string)
.unwrap_or_default()
})
}
pub fn derived<T: std::any::Any + Send + Sync>(&self, init: impl FnOnce(&Config) -> T) -> std::sync::Arc<T> {
let find = |slots: &[std::sync::Arc<dyn std::any::Any + Send + Sync>]| {
slots.iter().find_map(|v| v.clone().downcast::<T>().ok())
};
let lock = || self.derived.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(found) = find(&lock()) {
return found;
}
let value = std::sync::Arc::new(init(self));
let mut slots = lock();
if let Some(found) = find(&slots) {
return found;
}
slots.push(value.clone());
value
}
}
impl std::fmt::Debug for Config {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Config")
.field("host", &self.host)
.field("port", &self.port)
.field("routing", &self.routing)
.finish_non_exhaustive()
}
}
fn de_go_string<'de, D: serde::Deserializer<'de>>(d: D) -> Result<String, D::Error> {
Ok(go_string(&Value::deserialize(d)?))
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(default, rename_all = "kebab-case")]
pub struct RoutingConfig {
#[serde(deserialize_with = "de_go_string")]
pub strategy: String,
pub force_model_prefix: bool,
pub session_affinity: bool,
#[serde(deserialize_with = "de_go_string")]
pub session_affinity_ttl: String,
pub session_affinity_subagents: Option<bool>,
pub retry: RetryConfig,
pub cooldown: CooldownConfig,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(default, rename_all = "kebab-case")]
pub struct RetryConfig {
pub request_retry: i64,
pub max_retry_credentials: i64,
pub max_retry_interval: i64,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(default, rename_all = "kebab-case")]
pub struct CooldownConfig {
pub disable_cooling: bool,
pub save_cooldown_status: bool,
pub transient_error_cooldown_seconds: i64,
#[serde(deserialize_with = "de_go_string", skip_serializing_if = "String::is_empty")]
pub max_trusted_cooldown: String,
}
#[derive(Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(default, rename_all = "kebab-case")]
pub struct ManagementConfig {
pub allow_remote: bool,
#[serde(deserialize_with = "de_go_string")]
pub secret_key: String,
pub disable_control_panel: bool,
pub disable_auto_update_panel: bool,
#[serde(deserialize_with = "de_go_string")]
pub panel_github_repository: String,
}
impl std::fmt::Debug for ManagementConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ManagementConfig")
.field("allow_remote", &self.allow_remote)
.field("disable_control_panel", &self.disable_control_panel)
.finish_non_exhaustive()
}
}
impl Default for Config {
fn default() -> Self {
Self::parse("{}").expect("empty mapping is valid")
}
}
fn persist_secret_hash(path: &Path, text: &str, hash: &str) -> anyhow::Result<()> {
ConfigDocument::write(path, &with_secret_hash(text, hash)?)
}
fn with_secret_hash(text: &str, hash: &str) -> anyhow::Result<String> {
let text = text.strip_prefix('\u{feff}').unwrap_or(text);
let expanded = |t: &str| -> anyhow::Result<Value> {
let mut root: Value = parse_yaml(t)?;
expand_merges(&mut root)?;
Ok(root)
};
let mut want = expanded(text)?;
let mapping = want.as_mapping().context("config must be a mapping")?;
let v8 = lookup(mapping, "management.secret-key").is_some();
let parent = if v8 { "management" } else { "remote-management" };
let literal = parse_yaml(text)
.ok()
.and_then(|raw| raw.get(parent)?.as_mapping()?.get("secret-key").cloned())
.is_some();
let in_place = literal.then(|| {
let file: yaml_edit::YamlFile = text.parse().ok()?;
file.document()?.get_mapping(parent)?.set("secret-key", hash);
Some(file.to_string())
});
want.get_mut(parent)
.and_then(Value::as_mapping_mut)
.context("management must be a mapping")?
.insert(Value::from("secret-key"), Value::from(hash));
let updated = match in_place.flatten().filter(|t| expanded(t).is_ok_and(|v| v == want)) {
Some(t) => t,
None => {
let t = yaml_string(&want)?;
fn plain_keys(v: &Value) -> bool {
match v {
Value::Mapping(m) => m.iter().all(|(k, v)| matches!(k, Value::String(_)) && plain_keys(v)),
Value::Sequence(items) => items.iter().all(plain_keys),
Value::Tagged(_) => false,
_ => true,
}
}
let tagged = yaml_edit::lex(text)
.iter()
.any(|(kind, _)| *kind == yaml_edit::SyntaxKind::TAG);
anyhow::ensure!(
!tagged && plain_keys(&want),
"rewriting the config file would change the text of another setting"
);
let others = |t: &str| -> anyhow::Result<Value> {
let mut tree = scalar_texts(t)?;
expand_merges(&mut tree)?;
if let Some(m) = tree.get_mut(parent).and_then(Value::as_mapping_mut) {
m.remove("secret-key");
}
Ok(tree)
};
anyhow::ensure!(
others(text)? == others(&t)?,
"rewriting the config file would change the text of another setting"
);
t
}
};
let stored = scalar_texts(&updated).ok().map(|tree| effective_secret(&tree));
anyhow::ensure!(stored.as_deref() == Some(hash), "secret key not updated");
Ok(updated)
}
pub fn prepare_for_upload(path: &Path) -> anyhow::Result<()> {
let text = String::from_utf8(std::fs::read(path)?).context("failed to parse config file")?;
let prepared = prepared_for_upload(&text)?;
if prepared != text {
ConfigDocument::write(path, &prepared).context("failed to write prepared config file")?;
}
Ok(())
}
fn prepared_for_upload(text: &str) -> anyhow::Result<String> {
decode(text, Decode::Upload).context("failed to parse config file")?;
anyhow::ensure!(
!text.contains(['\u{85}', '\u{2028}', '\u{2029}']),
"the config file contains a Unicode line separator yaml-edit cannot read"
);
let mut tree = scalar_texts(text).context("failed to parse config file")?;
expand_merges(&mut tree).context("failed to parse config file")?;
let mut secret = effective_secret(&tree).into_bytes();
if !secret.is_empty() && binary_secret(text, &tree)? {
secret = binary::go_base64(&secret)
.context("failed to parse config file: yaml: !!binary value contains invalid base64 data")?;
}
let mut prepared = text.to_owned();
if !secret.is_empty() && !looks_like_bcrypt(&secret) {
anyhow::ensure!(
secret.len() <= 72,
"failed to hash remote management key: bcrypt: password length exceeds 72 bytes"
);
let hash = bcrypt::hash(&secret, 10).context("failed to hash remote management key")?;
prepared = with_secret_hash(text, &hash).context("failed to update remote management key")?;
}
if let Some(cleaned) = ConfigDocument::without_conflicts(&prepared)? {
prepared = cleaned;
}
let mut plaintexts: Vec<String> = String::from_utf8(secret).into_iter().collect();
for path in ["remote-management.secret-key", "management.secret-key"] {
if let Some(Value::String(value)) = tree.as_mapping().and_then(|m| lookup(m, path)) {
plaintexts.push(value.clone());
}
}
plaintexts.retain(|p| !p.is_empty() && !is_bcrypt(p));
if !plaintexts.is_empty() {
let doc = scalar_texts(&prepared).context("failed to parse prepared config")?;
if plaintexts.iter().any(|p| scalar_exists(&doc, p)) {
bail!(
"plaintext remote management key is still present elsewhere in the config file, for example through a YAML anchor or as another setting's value"
);
}
}
Ok(prepared)
}
fn effective_secret(tree: &Value) -> String {
let root = tree.as_mapping();
let at = |path| root.and_then(|m| lookup(m, path));
match at("management.secret-key").or_else(|| at("remote-management.secret-key")) {
Some(Value::String(s)) => s.clone(),
_ => String::new(),
}
}
fn binary_secret(text: &str, tree: &Value) -> anyhow::Result<bool> {
let v8 = tree
.as_mapping()
.and_then(|m| lookup(m, "management.secret-key"))
.is_some();
let parent = if v8 { "management" } else { "remote-management" };
let unresolved = || anyhow::anyhow!("the management key's YAML tag cannot be resolved for upload");
let file: yaml_edit::YamlFile = text.parse().map_err(|_| unresolved())?;
let tokens = yaml_edit::lex(text);
let directives = tokens
.iter()
.any(|(kind, token)| *kind == yaml_edit::SyntaxKind::DIRECTIVE && token.starts_with("%TAG"));
let binary = |raw: &str| -> anyhow::Result<bool> {
anyhow::ensure!(!directives, unresolved());
let tag = if let Some(uri) = raw.strip_prefix("!<").and_then(|t| t.strip_suffix('>')) {
uri.to_owned()
} else if let Some(suffix) = raw.strip_prefix("!!") {
format!("tag:yaml.org,2002:{suffix}")
} else if raw[1..].contains('!') {
anyhow::bail!(unresolved());
} else {
raw.to_owned()
};
let mut bytes = Vec::with_capacity(tag.len());
let mut rest = tag.as_bytes();
while let Some((&b, tail)) = rest.split_first() {
if b == b'%' {
let hex = tail.get(..2).and_then(|h| std::str::from_utf8(h).ok());
bytes.push(
hex.and_then(|h| u8::from_str_radix(h, 16).ok())
.ok_or_else(unresolved)?,
);
rest = &tail[2..];
} else {
bytes.push(b);
rest = tail;
}
}
Ok(bytes == b"tag:yaml.org,2002:binary" || bytes == b"!!binary")
};
match file.document().and_then(|d| d.get_mapping(parent)?.get("secret-key")) {
Some(yaml_edit::YamlNode::TaggedNode(node)) => binary(&node.tag().ok_or_else(unresolved)?),
Some(yaml_edit::YamlNode::Scalar(_)) => Ok(false),
_ => {
for (kind, token) in &tokens {
if *kind == yaml_edit::SyntaxKind::TAG && binary(token).unwrap_or(true) {
anyhow::bail!(unresolved());
}
}
Ok(false)
}
}
}
fn scalar_texts(text: &str) -> anyhow::Result<Value> {
use serde::de::{DeserializeSeed, Deserializer, IgnoredAny, MapAccess, SeqAccess, Visitor};
struct Shaped<'a>(&'a Value);
struct Entries<'a>(&'a Mapping);
struct Items<'a>(&'a [Value]);
impl<'de> DeserializeSeed<'de> for Shaped<'_> {
type Value = Value;
fn deserialize<D: Deserializer<'de>>(self, d: D) -> Result<Value, D::Error> {
match self.0 {
Value::Mapping(map) => d.deserialize_map(Entries(map)),
Value::Sequence(items) => d.deserialize_seq(Items(items)),
Value::Null => IgnoredAny::deserialize(d).map(|_| Value::Null),
Value::Tagged(tagged) if tagged.tag == timestamp::TAG => String::deserialize(d).map(Value::String),
Value::Tagged(tagged) => d.deserialize_any(Untagged(&tagged.value)),
_ => String::deserialize(d).map(Value::String),
}
}
}
struct Untagged<'a>(&'a Value);
impl<'de> Visitor<'de> for Untagged<'_> {
type Value = Value;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("a tagged node")
}
fn visit_enum<A: serde::de::EnumAccess<'de>>(self, access: A) -> Result<Value, A::Error> {
use serde::de::VariantAccess as _;
let (IgnoredAny, variant) = access.variant()?;
match self.0 {
Value::Mapping(_) | Value::Sequence(_) => variant.newtype_variant_seed(Shaped(self.0)),
_ => variant.newtype_variant::<String>().map(Value::String),
}
}
}
impl<'de> Visitor<'de> for Entries<'_> {
type Value = Value;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("a mapping")
}
fn visit_map<A: MapAccess<'de>>(self, mut access: A) -> Result<Value, A::Error> {
let mut out = Mapping::new();
for (key, value) in self.0 {
access.next_key::<IgnoredAny>()?;
out.insert(key.clone(), access.next_value_seed(Shaped(value))?);
}
Ok(Value::Mapping(out))
}
}
impl<'de> Visitor<'de> for Items<'_> {
type Value = Value;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("a sequence")
}
fn visit_seq<A: SeqAccess<'de>>(self, mut access: A) -> Result<Value, A::Error> {
let mut out = Vec::with_capacity(self.0.len());
for item in self.0 {
out.push(access.next_element_seed(Shaped(item))?.unwrap_or(Value::Null));
}
Ok(Value::Sequence(out))
}
}
use serde::Deserialize as _;
let text = text.strip_prefix('\u{feff}').unwrap_or(text);
let shape: Value = parse_yaml(text)?;
Ok(Shaped(&shape).deserialize(serde_yaml_ng::Deserializer::from_str(text))?)
}
fn scalar_exists(node: &Value, value: &str) -> bool {
match node {
Value::Mapping(map) => map.values().any(|v| scalar_exists(v, value)),
Value::Sequence(items) => items.iter().any(|v| scalar_exists(v, value)),
Value::String(text) => text == value,
_ => false,
}
}
#[derive(Clone, Copy, PartialEq)]
enum Decode {
Load,
Payload,
Upload,
}
fn decode(text: &str, mode: Decode) -> anyhow::Result<(Mapping, ConfigDocument)> {
let mut parsed = config_value(text)?;
expand_merges(&mut parsed)?;
let root = match parsed {
Value::Null if text.trim().is_empty() => Mapping::new(),
Value::Mapping(m) => m,
_ => bail!("config must be a mapping"),
};
validate_shape(&root)?;
let credentials = if mode == Decode::Upload {
v8_group_error(&root)
} else {
credential_error(&root)
};
if let Some(e) = credentials {
bail!(e);
}
let mut document = ConfigDocument::from_mapping(root.clone())?;
document.coerce_typed_scalars();
schema::validate(document.value(), false)
.and_then(|()| validate::decoded(document.value()))
.map_err(|e| {
if mode == Decode::Payload {
anyhow::anyhow!("parse config payload: {e}")
} else {
e
}
})?;
Ok((root, document))
}
impl Config {
pub fn load(path: &Path) -> anyhow::Result<Self> {
Self::load_text(path, &std::fs::read_to_string(path)?)
}
pub fn load_text(path: &Path, text: &str) -> anyhow::Result<Self> {
let mut config = Self::parse(text)?;
if !config.management.secret_key.is_empty() && !is_bcrypt(&config.management.secret_key) {
let hash = bcrypt::hash(&config.management.secret_key, 10)?;
let _ = persist_secret_hash(path, text, &hash);
config.management.secret_key = hash.clone();
if let Some(management) = config.document.get_mut("management").and_then(Value::as_mapping_mut) {
management.insert(Value::from("secret-key"), Value::from(hash));
}
}
Ok(config)
}
pub fn parse_payload(text: &str) -> anyhow::Result<Self> {
Self::parse_as(text, Decode::Payload)
}
pub fn parse(text: &str) -> anyhow::Result<Self> {
Self::parse_as(text, Decode::Load)
}
fn parse_as(text: &str, mode: Decode) -> anyhow::Result<Self> {
let (root, document) = decode(text, mode)?;
let canonical = document.value().as_mapping().expect("document is a mapping");
let routing = decode_section::<RoutingConfig>(canonical, "routing")?;
let mut routing = routing;
routing.retry.max_retry_credentials = routing.retry.max_retry_credentials.max(0);
let management = decode_section::<ManagementConfig>(canonical, "management")?;
let pick = |v8: &str, legacy: &str| lookup(&root, v8).or_else(|| lookup(&root, legacy));
let host = string_or_empty(pick("server.host", "host"), "server.host")?;
let port = match pick("server.port", "port") {
None | Some(Value::Null) => 0,
Some(v) => go_int(v)
.and_then(|p| u16::try_from(p).ok())
.context("server.port must be an integer port number")?,
};
let legacy_keys = lookup(&root, "api-keys").filter(|v| !v.is_mapping());
let api_keys = match lookup(&root, "access.api-keys").or(legacy_keys) {
None | Some(Value::Null) => Vec::new(),
Some(Value::Sequence(seq)) => seq
.iter()
.map(|k| {
k.as_str()
.map(str::to_owned)
.context("access.api-keys must be a list of strings")
})
.collect::<anyhow::Result<_>>()?,
Some(_) => bail!("access.api-keys must be a list of strings"),
};
let auth_dir = string_or_empty(pick("oauth.auth-dir", "auth-dir"), "oauth.auth-dir")?;
let trusted_proxies: Vec<String> = match lookup(canonical, "server.trusted-proxies") {
Some(Value::Sequence(seq)) => seq.iter().map(go_string).collect(),
_ => Vec::new(),
};
trusted::validate(&trusted_proxies)?;
validate::go_custom(document.value())?;
let oauth_only = schema::oauth_only_paths(&Value::Mapping(root.clone()));
let plugin_configs = plugin_configs(text, &root);
Ok(Config {
host,
port,
api_keys: normalize_keys(api_keys),
trusted_proxies,
auth_dir: resolve_auth_dir(&auth_dir),
routing,
management,
document: document.into_value(),
oauth_only,
plugin_configs,
derived: Derived::default(),
})
}
pub fn allow_open_access(&self) -> bool {
self.document
.get("access")
.and_then(|a| a.get("allow-open-access"))
.and_then(Value::as_bool)
.unwrap_or(false)
}
pub fn max_request_body_bytes(&self) -> Option<u64> {
let value = self.document.get("server")?.get("max-request-body-bytes")?;
u64::try_from(go_int(value)?).ok().filter(|&n| n > 0)
}
pub fn for_api_key(&self) -> std::borrow::Cow<'_, Config> {
if self.oauth_only.is_empty() {
return std::borrow::Cow::Borrowed(self);
}
let mut view = self.clone();
for path in &self.oauth_only {
schema::zero_at(&mut view.document, path);
}
view.oauth_only.clear();
std::borrow::Cow::Owned(view)
}
}
pub fn is_bcrypt(key: &str) -> bool {
looks_like_bcrypt(key.as_bytes())
}
fn looks_like_bcrypt(key: &[u8]) -> bool {
key.len() > 4 && [b"$2a$", b"$2b$", b"$2y$"].iter().any(|p| key.starts_with(*p))
}
fn decode_section<T: serde::de::DeserializeOwned + Default>(root: &Mapping, name: &str) -> anyhow::Result<T> {
match lookup(root, name) {
None | Some(Value::Null) => Ok(T::default()),
Some(value) => Ok(serde_yaml_ng::from_value(null_scalars_to_zero(value.clone()))?),
}
}
fn null_scalars_to_zero(mut value: Value) -> Value {
if let Value::Mapping(ref mut map) = value {
map.retain(|_, v| !v.is_null());
for (_, v) in map {
*v = null_scalars_to_zero(v.clone());
}
}
value
}
fn validate_shape(root: &Mapping) -> anyhow::Result<()> {
if let Some(e) = document::shape_error(root) {
bail!(e);
}
if let Some(version) = lookup(root, "config-version")
&& version.as_u64() != Some(8)
{
bail!("unsupported config-version (expected 8)");
}
Ok(())
}
fn lookup<'a>(root: &'a Mapping, path: &str) -> Option<&'a Value> {
let mut parts = path.split('.');
let mut cur = root.get(parts.next()?)?;
for part in parts {
cur = cur.as_mapping()?.get(part)?;
}
Some(cur)
}
pub fn go_string(value: &Value) -> String {
match value {
Value::String(s) => s.clone(),
Value::Number(n) => n.to_string(),
Value::Bool(b) => b.to_string(),
_ => String::new(),
}
}
fn string_or_empty(value: Option<&Value>, name: &str) -> anyhow::Result<String> {
match value {
None | Some(Value::Null) => Ok(String::new()),
Some(Value::String(s)) => Ok(s.clone()),
Some(v @ (Value::Number(_) | Value::Bool(_))) => Ok(go_string(v)),
Some(_) => bail!("{name} must be a string"),
}
}
fn normalize_keys(keys: Vec<String>) -> Vec<String> {
let mut out: Vec<String> = Vec::with_capacity(keys.len());
for key in keys {
let key = key.trim();
if !key.is_empty() && !out.iter().any(|k| k == key) {
out.push(key.to_owned());
}
}
out
}
fn resolve_auth_dir(dir: &str) -> PathBuf {
let dir = if dir.is_empty() { DEFAULT_AUTH_DIR } else { dir };
let (Some(rest), Some(home)) = (dir.strip_prefix('~'), std::env::var_os("HOME")) else {
return PathBuf::from(dir);
};
let rest = rest.trim_start_matches(['/', '\\']).replace('\\', "/");
if rest.is_empty() {
PathBuf::from(home)
} else {
PathBuf::from(home).join(rest)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(unix)]
#[test]
fn prepare_for_upload_refuses_a_file_it_cannot_write() {
use std::os::unix::fs::PermissionsExt as _;
let dir = std::env::temp_dir().join(format!("cpa-prepare-ro-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("config.yaml");
let content = "remote-management:\n secret-key: upload-plaintext-secret\n";
std::fs::write(&path, content).unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o400)).unwrap();
if std::fs::OpenOptions::new().write(true).open(&path).is_err() {
assert!(prepare_for_upload(&path).is_err());
assert_eq!(std::fs::read_to_string(&path).unwrap(), content);
}
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
std::fs::remove_dir_all(&dir).unwrap();
}
fn home() -> PathBuf {
PathBuf::from(std::env::var("HOME").unwrap())
}
#[test]
fn v8_wins_by_presence_even_when_null_or_empty() {
let cfg = Config::parse(
"port: 9000\napi-keys: [legacy]\nauth-dir: /legacy\nhost: legacyhost\n\
server: {port: 9100, host: null}\naccess: {api-keys: []}\noauth: {auth-dir: /v8}\n\
remote-management: {allow-remote: true}\nmanagement: {allow-remote: false, disable-auto-update-panel: true}\n",
)
.unwrap();
assert_eq!(cfg.port, 9100);
assert_eq!(cfg.host, "", "present null beats legacy");
assert!(cfg.api_keys.is_empty(), "present empty list beats legacy");
assert_eq!(cfg.auth_dir, PathBuf::from("/v8"));
assert!(!cfg.management.allow_remote, "present false beats legacy");
assert!(cfg.management.disable_auto_update_panel);
let cfg = Config::parse("api-keys: [legacy]\naccess: {api-keys: null}\n").unwrap();
assert!(cfg.api_keys.is_empty(), "present null list beats legacy");
}
#[test]
fn worker_threads_is_a_known_int() {
let doc = |text: &str| serde_yaml_ng::from_str::<serde_yaml_ng::Value>(text).unwrap();
validate_config_fields(&doc("config-version: 8\nworker-threads: 3\n"), true).unwrap();
assert!(validate_config_fields(&doc("worker-threads: many\n"), true).is_err());
assert!(validate_config_fields(&doc("worker-thread: 3\n"), true).is_err());
}
#[test]
fn legacy_spellings_still_work() {
let cfg = Config::parse("host: 127.0.0.1\nport: 9000\napi-keys: [' a ', a, '', b]\nauth-dir: /x\n").unwrap();
assert_eq!((cfg.host.as_str(), cfg.port), ("127.0.0.1", 9000));
assert_eq!(cfg.api_keys, ["a", "b"]);
assert_eq!(cfg.auth_dir, PathBuf::from("/x"));
}
#[test]
fn null_or_scalar_parents_are_rejected() {
for (yaml, want) in [
("access: null\n", "access must be a mapping"),
("access: [a]\n", "access must be a mapping"),
("server: 5\n", "server must be a mapping"),
("oauth:\n providers: null\n", "oauth.providers must be a mapping"),
("config-version: 7\n", "unsupported config-version (expected 8)"),
("- a\n", "config must be a mapping"),
] {
assert_eq!(Config::parse(yaml).unwrap_err().to_string(), want, "{yaml:?}");
}
assert!(
Config::parse("routing: null\nconfig-version: 8\n").is_ok(),
"routing: null means defaults"
);
}
#[test]
fn image_generation_mode_reads_go_spellings() {
let mode = |yaml: &str| {
Config::parse(&format!("multimedia:\n disable-image-generation: {yaml}\n"))
.map(|c| c.document["multimedia"]["disable-image-generation"].clone())
.map_err(|e| e.to_string())
};
assert_eq!(mode("' Off '"), Ok(Value::Bool(false)));
assert_eq!(mode("~"), Ok(Value::Bool(false)));
assert_eq!(mode("YES"), Ok(Value::Bool(true)));
assert_eq!(mode("' Chat'"), Ok(Value::from("chat")));
assert_eq!(
mode("\"\\u00dc\\u0001\""),
Err(
"invalid disable-image-generation value \"\u{fc}\\x01\" (allowed: true, false, chat, passthrough)"
.into()
)
);
}
#[test]
fn v8_upstream_key_map_is_not_client_keys() {
let cfg = Config::parse("api-keys:\n claude:\n - keys: [{api-key: fake-key}]\n").unwrap();
assert!(cfg.api_keys.is_empty());
for yaml in [
"api-keys: {claude: [{api-key: fake-key}]}",
"api-keys: {claude: null}",
"api-keys: {claude: [{keys: null}]}",
"api-keys: {claude: [{weight: 2, keys: []}]}",
"api-keys: {claude: [{keys: [{base-url: https://example.invalid}]}]}",
"api-keys: {claude: [{keys: [{weight: 1000001}]}]}",
] {
assert!(Config::parse(yaml).is_err(), "{yaml}");
}
assert!(Config::parse("api-keys: {claude: [{keys: [{weight: 0}]}]}").is_ok());
}
#[test]
fn scheduler_legacy_keys_and_v8_presence_share_one_typed_view() {
let cfg = Config::parse(
"request-retry: 7\nmax-retry-credentials: -2\nmax-retry-interval: 41\n\
disable-cooling: true\nsave-cooldown-status: true\n\
transient-error-cooldown-seconds: -3\nforce-model-prefix: true\n\
routing:\n strategy: fill-first\n session-affinity: true\n\
\x20 session-affinity-ttl: 37m\n session-affinity-subagents: false\n\
\x20 retry: {request-retry: 0}\n cooldown: {disable-cooling: false}\n",
)
.unwrap();
assert_eq!(cfg.routing.strategy, "fill-first");
assert!(cfg.routing.force_model_prefix && cfg.routing.session_affinity);
assert_eq!(cfg.routing.session_affinity_ttl, "37m");
assert_eq!(cfg.routing.session_affinity_subagents, Some(false));
assert_eq!(cfg.routing.retry.request_retry, 0);
assert_eq!(cfg.routing.retry.max_retry_credentials, 0);
assert_eq!(cfg.routing.retry.max_retry_interval, 41);
assert!(!cfg.routing.cooldown.disable_cooling);
assert!(cfg.routing.cooldown.save_cooldown_status);
assert_eq!(cfg.routing.cooldown.transient_error_cooldown_seconds, -3);
for (yaml, expect) in [("0", "0"), ("90m", "90m")] {
let text = format!("routing:\n cooldown:\n max-trusted-cooldown: {yaml}\n");
let cfg = Config::parse(&text).unwrap();
assert_eq!(cfg.routing.cooldown.max_trusted_cooldown, expect);
assert!(ConfigDocument::parse(&text).unwrap().archive_unknown().is_empty());
}
assert!(Config::parse("routing: {cooldown: {max-trusted-cooldown: [1]}}").is_err());
let empty = Config::default();
assert_eq!(empty.routing, RoutingConfig::default());
assert_eq!(empty.routing.session_affinity_subagents, None);
let null = Config::parse("request-retry: 7\nrouting: {retry: {request-retry: null}}\n").unwrap();
assert_eq!(null.routing.retry.request_retry, 0);
}
#[test]
fn compaction_section_is_known_to_the_schema() {
let text = "compaction:\n summary-max-tokens: 16384\n summary-reasoning-effort: low\n";
assert!(Config::parse(text).is_ok());
assert!(ConfigDocument::parse(text).unwrap().archive_unknown().is_empty());
assert!(Config::parse("compaction: {summary-max-tokens: [1]}").is_err());
}
#[test]
fn legacy_session_date_pin_days_migrates() {
let doc = ConfigDocument::parse("claude: {tool-search: true, session-date-pin-days: 3}\n").unwrap();
assert!(doc.value().get("claude").is_none(), "{:?}", doc.value());
assert_eq!(doc.value()["upstream"]["claude"]["session-date-pin-days"], 3);
}
#[test]
fn shared_upstream_layouts_agree_and_migrate() {
let keys = "api-keys: {codex: [{base-url: https://example.invalid, keys: [{api-key: test-key, disable-codex-cloaking: false}]}]}\n";
let codex = "{disable-codex-cloaking: true, stream-bootstrap-buffering: true, stream-bootstrap-timeout: 10s, orphan-delegation-compatibility: true, model-level-cooling: true, response-steering: true";
let headers = "{user-agent: client-agent, package-version: 1.2.3, runtime-version: v22.1.0, os: Linux, arch: arm64, timeout: '123', timezone: Asia/Shanghai, stabilize-device-profile: true}";
let oauth = "oauth: {auth-dir: client-auth, auth-auto-refresh-workers: 3, providers: {codex: {header-defaults: {user-agent: oauth-agent, beta-features: oauth-beta}}}}\n";
let legacy = format!(
"auth-dir: client-auth\nauth-auto-refresh-workers: 3\ncodex: {codex}}}\nclaude: {{model-level-cooling: true}}\nclaude-code: {{disable-cloaking-model-list: true}}\ndisable-claude-cloak-mode: true\nclaude-header-defaults: {headers}\nxai: {{inject-x-search: true}}\n{oauth}{keys}"
);
let canonical = format!(
"upstream:\n codex: {codex}}}\n claude:\n model-level-cooling: true\n disable-cloaking-model-list: true\n disable-claude-cloak-mode: true\n header-defaults: {headers}\n xai: {{inject-x-search: true}}\n{oauth}{keys}"
);
let historical = format!(
"oauth:\n auth-dir: client-auth\n auth-auto-refresh-workers: 3\n providers:\n codex: {codex}, header-defaults: {{user-agent: oauth-agent, beta-features: oauth-beta}}}}\n claude:\n model-level-cooling: true\n claude-code: {{disable-cloaking-model-list: true}}\n disable-claude-cloak-mode: true\n header-defaults: {headers}\n xai: {{inject-x-search: true}}\n{keys}"
);
let expected = Config::parse(&canonical).unwrap().document;
assert_eq!(
expected["upstream"]["claude"]["header-defaults"]["timezone"],
"Asia/Shanghai"
);
for raw in [&legacy, &canonical, &historical] {
let doc = ConfigDocument::parse(raw).unwrap();
schema::validate(doc.value(), true).unwrap();
for alias in ["codex", "claude", "claude-code", "xai", "claude-header-defaults"] {
assert!(doc.value().get(alias).is_none(), "{alias} survived: {raw}");
}
let providers = &doc.value()["oauth"]["providers"];
assert!(
providers.get("claude").is_none() && providers.get("xai").is_none(),
"{raw}"
);
let codex = providers["codex"].as_mapping().unwrap();
assert_eq!(
codex.keys().collect::<Vec<_>>(),
[&Value::from("header-defaults")],
"{raw}"
);
for text in [raw.to_string(), doc.yaml().unwrap()] {
let cfg = Config::parse(&text).unwrap();
for view in [&cfg, &*cfg.for_api_key()] {
assert_eq!(view.document["upstream"], expected["upstream"], "{text}");
assert_eq!(view.document["oauth"]["auth-auto-refresh-workers"], 3);
let key = &view.document["api-keys"]["codex"][0]["keys"][0];
assert_eq!(key["disable-codex-cloaking"], Value::Bool(false));
}
let user_agent =
|c: &Config| c.document["oauth"]["providers"]["codex"]["header-defaults"]["user-agent"].clone();
assert_eq!(user_agent(&cfg), "oauth-agent");
assert_eq!(user_agent(&cfg.for_api_key()), "");
}
}
}
#[test]
fn shared_upstream_presence_wins_and_empty_containers_move() {
for value in ["false", "null"] {
let raw = format!(
"codex: {{response-steering: true}}\noauth: {{providers: {{codex: {{response-steering: true}}, claude: {{header-defaults: {{user-agent: historical-agent, stabilize-device-profile: true}}}}}}}}\nupstream: {{codex: {{response-steering: {value}}}, claude: {{header-defaults: {{user-agent: '', stabilize-device-profile: {value}}}}}}}\n"
);
let cfg = Config::parse(&raw).unwrap();
let upstream = &cfg.document["upstream"];
assert_ne!(upstream["codex"]["response-steering"], Value::Bool(true), "{raw}");
assert_eq!(upstream["claude"]["header-defaults"]["user-agent"], "", "{raw}");
assert_ne!(
upstream["claude"]["header-defaults"]["stabilize-device-profile"],
Value::Bool(true)
);
schema::validate(ConfigDocument::parse(&raw).unwrap().value(), true).unwrap();
}
for (historical, current) in [
(
"oauth.providers.claude.header-defaults",
"upstream.claude.header-defaults",
),
("oauth.providers.claude.claude-code", "upstream.claude"),
("oauth.providers.claude", "upstream.claude"),
("oauth.providers.xai", "upstream.xai"),
] {
for value in ["{}", "null"] {
let parts: Vec<&str> = historical.split('.').collect();
let raw = parts
.iter()
.rev()
.fold(value.to_owned(), |inner, key| format!("{{{key}: {inner}}}"));
let doc = ConfigDocument::parse(&raw).unwrap();
schema::validate(doc.value(), true).unwrap();
assert!(lookup(doc.value().as_mapping().unwrap(), historical).is_none(), "{raw}");
assert!(lookup(doc.value().as_mapping().unwrap(), current).is_some(), "{raw}");
}
}
let cfg = Config::parse(
"claude: {disable-cloaking-model-list: true, model-level-cooling: true}\nclaude-code: {disable-cloaking-model-list: false, model-level-cooling: true}\n",
)
.unwrap();
let claude = &cfg.document["upstream"]["claude"];
assert_eq!(claude["disable-cloaking-model-list"], Value::Bool(false));
assert_eq!(claude["model-level-cooling"], Value::Bool(true));
assert_eq!(cfg.document["claude"]["disable-cloaking-model-list"], Value::Bool(true));
assert_eq!(cfg.document["claude-code"]["model-level-cooling"], Value::Bool(true));
let cfg = Config::parse("claude-code: {model-level-cooling: true}\n").unwrap();
assert!(cfg.document.get("upstream").is_none(), "{:?}", cfg.document);
for legacy in ["claude: null\n", "claude-code: {}\n"] {
let doc = ConfigDocument::parse(legacy).unwrap();
assert_eq!(
doc.value()["upstream"]["claude"],
Value::Mapping(Mapping::new()),
"{legacy}"
);
assert!(doc.value().get("claude").is_none() && doc.value().get("claude-code").is_none());
}
let err = Config::parse("oauth: {providers: {xai: true}}\n").unwrap_err();
assert_eq!(err.to_string(), "oauth.providers.xai must be a mapping");
}
#[test]
fn v8_layout_is_recognised_by_version_sections_and_paths() {
for (raw, v8) in [
("request-retry: 3\ncodex: {response-steering: true}\n", false),
(
"routing: {strategy: fill-first}\nplugins: {configs: {example: {enabled: true}}}\nquota-exceeded: {switch-project: true}\nclient: {codex: {enable-apply-patch: true}}\napi-keys: [client-key]\n",
false,
),
("codex: {optimize-multi-agent-v2: true}\n", false),
("config-version: 8\nrequest-retry: 3\n", true),
("oauth: {providers: {codex: {response-steering: true}}}\n", true),
("server: {}\n", true),
("upstream: {xai: {inject-x-search: false}}\n", true),
("api-keys: {}\n", true),
("request-retry: 3\nrouting: {retry: {max-retry-credentials: 2}}\n", true),
("routing: {retry: {}}\n", true),
("providers: {codex: {optimize-multi-agent-v2: true}}\n", true),
("client: {codex: {optimize-multi-agent-v2: false}}\n", true),
] {
let value: Value = serde_yaml_ng::from_str(raw).unwrap();
assert_eq!(is_v8_layout(&value), v8, "{raw}");
}
}
#[test]
fn defaults_match_go_loader() {
let cfg = Config::parse("").unwrap();
assert_eq!((cfg.port, cfg.host.as_str()), (0, ""));
assert_eq!(cfg.auth_dir, home().join(".cli-proxy-api"));
assert_eq!(
Config::parse("auth-dir: ''\n").unwrap().auth_dir,
home().join(".cli-proxy-api")
);
assert_eq!(resolve_auth_dir("~"), home());
assert_eq!(resolve_auth_dir("~other/x"), home().join("other/x"));
assert_eq!(resolve_auth_dir("/abs"), PathBuf::from("/abs"));
}
#[test]
fn yaml_literals_scale_linearly() {
let time = |n: usize| {
let params: Vec<String> = (0..n).map(|i| format!("k{i}: 1.50")).collect();
let text = format!(
"x: &a 1\nrequests: {{payload: {{override: [{{models: [{{name: 0x1F}}], params: {{{}}}}}]}}}}\n",
params.join(", ")
);
(0..3)
.map(|_| {
let start = std::time::Instant::now();
let doc = config_value(&text).unwrap();
let rule = &doc["requests"]["payload"]["override"][0];
assert_eq!(rule["models"][0]["name"], Value::from("0x1F"));
assert_eq!(rule["params"][format!("k{}", n - 1).as_str()], Value::from(1.5));
start.elapsed()
})
.min()
.unwrap()
};
let (small, large) = (time(1000), time(16000));
let ratio = large.as_secs_f64() / small.as_secs_f64().max(1e-9);
assert!(
ratio < 64.0,
"16x the entries took {ratio:.0}x the time ({small:?} to {large:?})"
);
}
#[test]
fn unused_number_aliases_do_not_expand_too_far() {
let numbers: Vec<String> = (0..1024).map(|i| i.to_string()).collect();
let text = format!(
"a: &l [{}]\nb: [{}]\noauth-excluded-models: {{c: *l}}\n",
numbers.join(", "),
vec!["*l"; 1024].join(", ")
);
let doc = config_value(&text).unwrap();
assert_eq!(doc["b"][1023][1023], Value::from(1023));
assert_eq!(doc["oauth-excluded-models"]["c"][7], Value::from("7"));
}
#[test]
fn dropped_alias_copies_are_bounded() {
let numbers = vec!["0"; 2049].join(", ");
let text = format!("x: &x [{numbers}]\nzz-ignored: [{}]\n", vec!["*x"; 2048].join(", "));
let err = config_value(&text).unwrap_err();
assert_eq!(err.to_string(), "config YAML aliases expand too far");
}
#[test]
fn written_numbers_do_not_count_toward_the_alias_limit() {
let numbers = vec!["0"; (1 << 20) + 1].join(", ");
let doc = config_value(&format!(
"x: &l [{numbers}]
oauth-excluded-models: {{c: [{numbers}]}}
"
))
.unwrap();
assert_eq!(doc["x"][1 << 20], Value::from(0));
assert_eq!(doc["oauth-excluded-models"]["c"][1 << 20], Value::from("0"));
}
#[test]
fn integers_beyond_64_bits_read_as_in_go() {
let token = "123456789012345678901234567890";
let cfg = Config::parse(&format!("server:\n github-token: {token}\n")).unwrap();
assert_eq!(cfg.document["server"]["github-token"].as_str(), Some(token));
assert_eq!(
body_value(token, &["server", "github-token"]).unwrap(),
Value::from(token)
);
let any = yaml_value("x: [18446744073709551616, -9223372036854775809, 0x1FFFFFFFFFFFFFFFFF]\n").unwrap();
let want: Vec<Value> = vec![
1.8446744073709552e19.into(),
(-9.223372036854776e18).into(),
"0x1FFFFFFFFFFFFFFFFF".into(),
];
assert_eq!(any["x"].as_sequence().unwrap(), &want);
let cfg = Config::parse(&format!("plugins: {{configs: {{p: {{n: {token}}}}}}}\n")).unwrap();
let Value::Tagged(n) = &cfg.plugin_configs["p"]["n"] else {
panic!("{:?}", cfg.plugin_configs)
};
assert_eq!(n.value, Value::from(token));
let many = yaml_value(&format!("x: [{}]\n", vec!["-18446744073709551616"; 100].join(", "))).unwrap();
assert!(
many["x"]
.as_sequence()
.unwrap()
.iter()
.all(|v| v.as_f64() == Some(-1.8446744073709552e19))
);
for text in [
"a: &n 18446744073709551616\nb: *n\n",
"a: &n\n 18446744073709551616\nb: *n\n",
] {
let anchored = yaml_value(text).unwrap();
assert_eq!(anchored["b"].as_f64(), Some(1.8446744073709552e19), "{text}");
}
let huge = format!("1{}", "0".repeat(400));
for other in [huge.as_str(), "01000000000000000000000"] {
let both = yaml_value(&format!("x: [18446744073709551616, {other}]\n")).unwrap();
assert_eq!(
both["x"][1],
yaml_value(&format!("x: {other}\n")).unwrap()["x"],
"{other}"
);
}
assert_eq!(
yaml_value(&format!("x: {huge}\n")).unwrap()["x"].as_str(),
Some(huge.as_str())
);
let bom = yaml_value("\u{feff}a: [0x1FFFFFFFFFFFFFFFFF, x]\n").unwrap();
assert_eq!(bom["a"], yaml_value("['0x1FFFFFFFFFFFFFFFFF', x]").unwrap());
assert!(Config::parse("routing: {retry: {request-retry: 18446744073709551616}}\n").is_err());
}
#[test]
fn underscore_numbers_read_as_in_go() {
let go: [(&str, Value); 20] = [
("1_000", 1000.into()),
("+_1", 1.into()),
("-1_000", (-1000).into()),
("1__0", 10.into()),
("1_", 1.into()),
("0_x1F", 31.into()),
("-0x1_F", (-31).into()),
("007_1", 57.into()),
("-0b1_0", (-2).into()),
("18_446_744_073_709_551_615", u64::MAX.into()),
("1_0.5", 10.5.into()),
("1_0e1_0", 1e11.into()),
("1._5", 1.5.into()),
(".5_0", 0.5.into()),
("-.5_0", (-0.5).into()),
("1_000_000_000_000_000_000_000", 1e21.into()),
("_1", "_1".into()),
(".5_", ".5_".into()),
("._5", "._5".into()),
("0x1_FFFF_FFFF_FFFF_FFFF_FF", "0x1_FFFF_FFFF_FFFF_FFFF_FF".into()),
];
let leading_zero: [(&str, Value); 10] = [
("007", 7.into()),
("-007", (-7).into()),
("00", 0.into()),
("08", 8.0.into()),
("09.5", 9.5.into()),
("07e1", 70.0.into()),
("01000000000000000000000", 9223372036854775808u64.into()),
("01777777777777777777777", u64::MAX.into()),
("02000000000000000000000", 2e21.into()),
("0111111111111111111111111", 1.1111111111111111e23.into()),
];
let signed: [(&str, Value); 7] = [
("0b_-1", (-1).into()),
("0o_+17", 15.into()),
("0o_-7", (-7).into()),
("0b-1", (-1).into()),
("0o+17", 15.into()),
("+0b-1", "+0b-1".into()),
(
"0b+1111111111111111111111111111111111111111111111111111111111111111",
"0b+1111111111111111111111111111111111111111111111111111111111111111".into(),
),
];
let zeros = "0".repeat(64);
let wide = [
"0o2000000000000000000000".to_owned(),
"+0o2000000000000000000000".to_owned(),
format!("-0b1{zeros}"),
"+0o1000000000000000000000".to_owned(),
"+0b1_000000000000000000000000000000000000000000000000000000000000000".to_owned(),
];
let wide: Vec<(&str, Value)> = wide.iter().map(|t| (t.as_str(), Value::from(t.as_str()))).collect();
let prefixes: [(&str, Value); 16] = [
("0X1F", 31.into()),
("-0X1F", (-31).into()),
("+0X1F", 31.into()),
("0O17", 15.into()),
("0B10", 2.into()),
("-0B10", (-2).into()),
("0X", "0X".into()),
("0O8", "0O8".into()),
("0B2", "0B2".into()),
("0X8000000000000000", (1u64 << 63).into()),
("0XFFFFFFFFFFFFFFFF", u64::MAX.into()),
("0X10000000000000000", "0X10000000000000000".into()),
("+9223372036854775807", i64::MAX.into()),
("+9223372036854775808", 9223372036854775808f64.into()),
("+18446744073709551615", 18446744073709551615f64.into()),
("+0x8000000000000000", "+0x8000000000000000".into()),
];
let go = go
.into_iter()
.chain(leading_zero)
.chain(signed)
.chain(wide)
.chain(prefixes)
.collect::<Vec<_>>();
let list = go.iter().map(|(text, _)| *text).collect::<Vec<_>>().join(", ");
let any = yaml_value(&format!("x: [{list}]\n")).unwrap();
for ((text, want), got) in go.iter().zip(any["x"].as_sequence().unwrap()) {
assert_eq!(got, want, "{text}");
}
assert_eq!(yaml_value("x: 007\n").unwrap()["x"], Value::from(7));
assert_eq!(yaml_value("x: 0X1F\n").unwrap()["x"], Value::from(31));
assert_eq!(
yaml_value("x: +9223372036854775808\n").unwrap()["x"],
Value::from(9223372036854775808f64)
);
assert_eq!(
yaml_value("x: 9223372036854775808\n").unwrap()["x"],
Value::from(1u64 << 63)
);
let cfg = Config::parse("server: {github-token: 0X1F}\nrouting: {retry: {request-retry: 0X1F}}\n").unwrap();
assert_eq!(cfg.document["server"]["github-token"].as_str(), Some("0X1F"));
assert_eq!(cfg.routing.retry.request_retry, 31);
assert_eq!(yaml_value("007").unwrap(), Value::from(7));
let cfg = Config::parse(
"server: {github-token: 1_000}\nrouting: {retry: {request-retry: 1_0}}\n\
oauth-excluded-models: {1_0: [a], 007: [b]}\n",
)
.unwrap();
assert_eq!(cfg.document["server"]["github-token"].as_str(), Some("1_000"));
assert_eq!(cfg.routing.retry.request_retry, 10);
assert!(cfg.document["oauth"]["excluded-models"].get("1_0").is_some());
assert!(cfg.document["oauth"]["excluded-models"].get("007").is_some());
let key = yaml_value(&format!("0o2000000000000000000000: a\n-0b1{zeros}: b\n")).unwrap();
assert_eq!(key["0o2000000000000000000000"], Value::from("a"));
assert_eq!(key[format!("-0b1{zeros}").as_str()], Value::from("b"));
assert_eq!(
body_value("1_000", &["server", "github-token"]).unwrap(),
Value::from("1_000")
);
}
#[test]
fn plain_timestamps_read_as_in_go() {
let go = [
("2001-12-14", Some("2001-12-14T00:00:00Z")),
("2001-1-2", Some("2001-01-02T00:00:00Z")),
("2001-12-14 21:59:43.10", Some("2001-12-14T21:59:43.1Z")),
("2001-12-14T21:59:43.10-05:00", Some("2001-12-14T21:59:43.1-05:00")),
("2001-12-14t21:59:43,5+00:60", Some("2001-12-14T21:59:43.5+01:00")),
(
"2001-12-14T21:59:43.123456789123Z",
Some("2001-12-14T21:59:43.123456789Z"),
),
("2001-12-14T21:59:43-00:00", Some("2001-12-14T21:59:43Z")),
("2004-2-29 1:2:3", Some("2004-02-29T01:02:03Z")),
("0001-01-01", Some("0001-01-01T00:00:00Z")),
("2001-12-14 21:59:43.10 -5", None),
("2001-12-14x", None),
("2001-02-29", None),
("2001-12-14t21:59:43.10z", None),
("2001-12-14 21:59:43.10Z", None),
("2001-12-14T24:00:00Z", None),
("2001-12-14 \t21:59:43", None),
];
let list: String = go.iter().map(|(text, _)| format!(" - {text}\n")).collect();
let any = yaml_value(&format!("x:\n{list} - '2001-12-14'\n")).unwrap();
let json = serde_json::to_value(AsJson(&any)).unwrap();
for (i, (text, want)) in go.iter().enumerate() {
let tagged = matches!(&any["x"][i], Value::Tagged(t) if t.tag == TIMESTAMP_TAG);
assert_eq!(tagged, want.is_some(), "{text}");
assert_eq!(json["x"][i], want.unwrap_or(text), "{text}");
}
assert_eq!(any["x"][go.len()], Value::from("2001-12-14"));
let text = yaml_string(&any).unwrap();
assert!(text.contains("\n- 2001-12-14T00:00:00Z\n"), "{text}");
assert_eq!(yaml_value(&text).unwrap(), any, "{text}");
let cfg =
Config::parse("server: {github-token: 2001-12-14}\noauth-excluded-models: {2001-12-14: [a]}\n").unwrap();
assert_eq!(cfg.document["server"]["github-token"].as_str(), Some("2001-12-14"));
assert!(cfg.document["oauth"]["excluded-models"].get("2001-12-14").is_some());
let hash = "$2a$10$abcdefghijklmnopqrstuuvwxyzabcdefghijklmnopqrstuvwxy";
let saved = with_secret_hash("management: {secret-key: plain}\nx: [2001-12-14]\n", hash).unwrap();
assert!(saved.contains(hash), "{saved}");
let prepared = prepared_for_upload("management: {secret-key: plain}\nx: [2001-12-14]\n").unwrap();
assert!(prepared.contains("$2"), "{prepared}");
for (text, want) in [
(
"x: 2001-12-14\n 21:59:43\n",
serde_json::json!({"x": "2001-12-14T21:59:43Z"}),
),
(
"x: [2001-12-14\n 21:59:43]\n",
serde_json::json!({"x": ["2001-12-14T21:59:43Z"]}),
),
(
"x: &a 2001-12-14\n 21:59:43\ny: *a\n",
serde_json::json!({"x": "2001-12-14T21:59:43Z", "y": "2001-12-14T21:59:43Z"}),
),
(
"x: &a\n 2001-12-14\n 21:59:43\ny: *a\n",
serde_json::json!({"x": "2001-12-14T21:59:43Z", "y": "2001-12-14T21:59:43Z"}),
),
(
"x: &a # c\n # d\n 2001-12-14\n 21:59:43\ny: *a\n",
serde_json::json!({"x": "2001-12-14T21:59:43Z", "y": "2001-12-14T21:59:43Z"}),
),
(
"x: &a\u{2028} 2001-12-14\n 21:59:43\ny: *a\n",
serde_json::json!({"x": "2001-12-14T21:59:43Z", "y": "2001-12-14T21:59:43Z"}),
),
(
"x: &a\n # c\n 2001-12-14\n 21:59:43\ny: *a\n",
serde_json::json!({"x": "2001-12-14T21:59:43Z", "y": "2001-12-14T21:59:43Z"}),
),
(
"x: &a\u{2029} 2001-12-14\n 21:59:43\ny: *a\n",
serde_json::json!({"x": "2001-12-14T21:59:43Z", "y": "2001-12-14T21:59:43Z"}),
),
(
"x: &a\u{85} 2001-12-14\n 21:59:43\ny: *a\n",
serde_json::json!({"x": "2001-12-14T21:59:43Z", "y": "2001-12-14T21:59:43Z"}),
),
(
"x: [&a 2001-12-14\n 21:59:43, *a]\n",
serde_json::json!({"x": ["2001-12-14T21:59:43Z", "2001-12-14T21:59:43Z"]}),
),
(
"%TAG ! tag:example.com,2000:\n---\nx: 2001-12-14\n",
serde_json::json!({"x": "2001-12-14T00:00:00Z"}),
),
(
"x: !y {at: 2001-12-14}\n",
serde_json::json!({"x": {"at": "2001-12-14T00:00:00Z"}}),
),
] {
let json = serde_json::to_value(AsJson(&yaml_value(text).unwrap())).unwrap();
assert_eq!(json, want, "{text}");
}
let directive = yaml_value("%TAG ! tag:example.com,2000:\n---\nx: 2001-12-14\n").unwrap();
assert!(
matches!(&directive["x"], Value::Tagged(t) if t.tag == TIMESTAMP_TAG),
"{directive:?}"
);
let key = yaml_string(&yaml_value("{'2001-12-14': a}").unwrap()).unwrap();
assert_eq!(key, "\"2001-12-14\": a\n");
let wide = "x: 2001-12-14T21:59:43+24:00\n";
let err = yaml_value(wide).unwrap_err();
assert!(format!("{err:#}").contains("24 hours"), "{err:#}");
assert!(config_value(wide).is_err() && parse_yaml(wide).is_ok());
}
#[test]
fn a_leading_bom_is_skipped() {
let cfg = Config::parse(
"\u{feff}server: {github-token: !!binary dG9r}\nrouting: {retry: {request-retry: 3}}\n\
x: [18446744073709551616, 007]\n",
)
.unwrap();
assert_eq!(cfg.document["server"]["github-token"].as_str(), Some("tok"));
assert_eq!(cfg.routing.retry.request_retry, 3);
let x = yaml_value("\u{feff}a: b\nx: [18446744073709551616, 007]\n").unwrap();
assert_eq!(x["x"], yaml_value("[1.8446744073709552e19, 7]").unwrap());
for original in [
"\u{feff}# head\nserver:\n port: 1\n",
"\u{feff}# head\nport: 1\nhost: x\n",
] {
let mut doc = ConfigDocument::parse(original).unwrap();
doc.update(&["server", "port"], Value::from(2), false).unwrap();
let basis = doc.migrated_text(original).unwrap_or_else(|| original.to_owned());
let saved = doc.render_preserving(&basis).unwrap();
assert!(saved.starts_with("# head\n"), "{saved:?}");
assert_eq!(Config::parse(&saved).unwrap().port, 2, "{saved:?}");
}
let hash = "$2a$10$abcdefghijklmnopqrstuuvwxyzabcdefghijklmnopqrstuvwxy";
for text in [
"\u{feff}management:\n secret-key: plain\n",
"\u{feff}b: &b {secret-key: plain}\nmanagement: {<<: *b}\n",
] {
let saved = with_secret_hash(text, hash).unwrap();
assert!(!saved.starts_with('\u{feff}') && saved.contains(hash), "{saved:?}");
}
let prepared = prepared_for_upload("\u{feff}management:\n secret-key: plain\nport: 1\n").unwrap();
assert!(
!prepared.starts_with('\u{feff}') && prepared.contains("$2"),
"{prepared:?}"
);
}
#[test]
fn re_emitted_strings_read_back_as_strings() {
let strings = [
"1_000",
"0_7",
"0_8",
"1_0.5",
"0x_1F",
".5_0",
"007",
"0b-1",
"0o+17",
"0X1F",
"0O17",
"+9223372036854775808",
"18446744073709551616",
"-18446744073709551616",
"2001-12-14",
"2001-12-14 21:59:43.10",
];
let value = Value::Sequence(strings.iter().map(|s| Value::from(*s)).collect());
let text = yaml_string(&value).unwrap();
assert_eq!(parse_yaml(&text).unwrap(), value, "{text}");
let keys = yaml_value("{'1_000': a, '007': b, 7: c}").unwrap();
let text = yaml_string(&keys).unwrap();
assert_eq!(text, "\"1_000\": a\n'007': b\n7: c\n");
assert_eq!(parse_yaml(&text).unwrap(), keys, "{text}");
assert_eq!(
yaml_string(&yaml_value("[7, 1000, 0.5]").unwrap()).unwrap(),
"- 7\n- 1000\n- 0.5\n"
);
let text = "base: &b {secret-key: plain}\nmanagement: {<<: *b}\n\
requests: {payload: {default: [{models: [{name: m}], params: {a: '1_000', b: '007'}}]}}\n";
let saved = with_secret_hash(text, "$2a$10$abcdefghijklmnopqrstuuvwxyzabcdefghijklmnopqrstuvwxy").unwrap();
let params = &parse_yaml(&saved).unwrap()["requests"]["payload"]["default"][0]["params"];
assert_eq!(params["a"], Value::from("1_000"), "{saved}");
assert_eq!(params["b"], Value::from("007"), "{saved}");
}
#[test]
fn scalar_settings_keep_their_yaml_text() {
let go: serde_json::Value =
serde_json::from_str(include_str!("../tests/fixtures/scalar_settings_go.json")).unwrap();
for case in go["cases"].as_array().unwrap() {
let cfg = Config::parse(case["yaml"].as_str().unwrap()).unwrap();
for check in case["checks"].as_array().unwrap() {
let path = check["rust"].as_str().unwrap();
let mut node = &cfg.document;
for part in path.split('.') {
node = match part.parse::<usize>() {
Ok(i) => &node[i],
Err(_) => &node[part],
};
}
assert_eq!(node.as_str(), check["value"].as_str(), "{}: {path}", case["name"]);
}
}
let cfg = Config::parse(go["cases"][0]["yaml"].as_str().unwrap()).unwrap();
let aliases = crate::registry::dynamic::global_aliases(&cfg);
let models: Vec<(String, String)> = credentials::from_config(&cfg)
.iter()
.flat_map(|c| crate::registry::dynamic::models_for(&cfg, &aliases, c, 0))
.map(|m| (m.id, m.display_name))
.collect();
assert!(models.contains(&("0x1F/a".into(), "1.50".into())), "{models:?}");
}
}