Skip to main content

respan_gateway/
config.rs

1//! The configuration: where it comes from (a TOML file, the environment or
2//! `proxy`) and what it says. [`App::new`](crate::App::new) checks and
3//! composes it.
4
5use std::net::SocketAddr;
6use std::path::{Path, PathBuf};
7use std::time::Duration;
8
9use indexmap::IndexMap;
10pub use respan_gateway_plugin_routing::Pick;
11use serde::{Deserialize, Deserializer};
12
13use crate::Error;
14use crate::logging::LogFormat;
15use crate::mcp::McpConfig;
16use crate::network::{NetworkConfig, Proxy};
17use crate::vendors;
18pub use respan_gateway_sdk::{Model, Price};
19
20/// A client key in the config: the key alone, or with the name its requests
21/// are logged under and what it may do.
22#[derive(Clone, PartialEq, Eq)]
23pub enum ClientKey {
24    Key(String),
25    Named(NamedKey),
26}
27
28#[derive(Clone, PartialEq, Eq, Deserialize)]
29#[serde(deny_unknown_fields)]
30pub struct NamedKey {
31    pub name: String,
32    pub key: String,
33    /// Whether the key reaches the admin API. When no key sets it, every
34    /// key does; once one sets `true`, only those do.
35    #[serde(default)]
36    pub admin: Option<bool>,
37    /// The tool loop and aggregate tools (`server__tool` globs) the key's
38    /// requests may use, within the global `allow` and `deny`; all if unset,
39    /// none if empty. A key that sets it reaches MCP servers at `/mcp`
40    /// alone, not each at `/mcp/{name}`, which offers all of a server's.
41    #[serde(default)]
42    pub tools: Option<Vec<String>>,
43}
44
45// A key is a secret: a debug print shows its name alone.
46impl std::fmt::Debug for ClientKey {
47    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48        match self {
49            Self::Key(_) => f.write_str("ClientKey(..)"),
50            Self::Named(named) => write!(f, "ClientKey({})", named.name),
51        }
52    }
53}
54
55impl std::fmt::Debug for NamedKey {
56    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57        f.debug_struct("NamedKey")
58            .field("name", &self.name)
59            .field("admin", &self.admin)
60            .field("tools", &self.tools)
61            .finish_non_exhaustive()
62    }
63}
64
65impl<'de> Deserialize<'de> for ClientKey {
66    fn deserialize<D: Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
67        use serde::de::Error;
68        let value = serde_json::Value::deserialize(de)?;
69        match value {
70            serde_json::Value::String(key) => Ok(Self::Key(key)),
71            serde_json::Value::Object(_) => serde_json::from_value(value)
72                .map(Self::Named)
73                .map_err(|e| D::Error::custom(format!("a client key entry: {e}"))),
74            _ => Err(D::Error::custom(
75                "a client key is a string, or `{ name, key, admin?, tools? }`",
76            )),
77        }
78    }
79}
80
81impl ClientKey {
82    pub fn key(&self) -> &str {
83        match self {
84            Self::Key(key) => key,
85            Self::Named(named) => &named.key,
86        }
87    }
88
89    pub fn name(&self) -> Option<&str> {
90        match self {
91            Self::Key(_) => None,
92            Self::Named(named) => Some(&named.name),
93        }
94    }
95
96    /// What the entry says of admin access, if it does.
97    pub fn admin(&self) -> Option<bool> {
98        match self {
99            Self::Key(_) => None,
100            Self::Named(named) => named.admin,
101        }
102    }
103
104    pub fn tools(&self) -> Option<&[String]> {
105        match self {
106            Self::Key(_) => None,
107            Self::Named(named) => named.tools.as_deref(),
108        }
109    }
110}
111
112impl From<&str> for ClientKey {
113    fn from(key: &str) -> Self {
114        Self::Key(key.to_owned())
115    }
116}
117
118/// A provider's formats: by name, each at its vendor's base URL or the
119/// provider's `base_url`; or each at a base URL of its own.
120#[derive(Clone, Debug, PartialEq, Deserialize)]
121#[serde(untagged)]
122pub enum Formats {
123    /// One format, by name.
124    One(String),
125    /// Several, by name.
126    Many(Vec<String>),
127    /// Each format's base URL, by the format's name.
128    At(IndexMap<String, String>),
129}
130
131impl Formats {
132    /// Its formats' names, in order.
133    pub fn names(&self) -> Vec<&str> {
134        match self {
135            Formats::One(name) => vec![name.as_str()],
136            Formats::Many(names) => names.iter().map(String::as_str).collect(),
137            Formats::At(urls) => urls.keys().map(String::as_str).collect(),
138        }
139    }
140
141    /// The base URL it gives format `name`, if it gives one.
142    pub fn url_of(&self, name: &str) -> Option<&str> {
143        match self {
144            Formats::At(urls) => urls.get(name).map(String::as_str),
145            _ => None,
146        }
147    }
148
149    /// It, with what a URL may hold of a secret redacted.
150    fn redacted(&self) -> Formats {
151        match self {
152            Formats::At(urls) => Formats::At(
153                urls.iter()
154                    .map(|(format, url)| (format.clone(), crate::redact::url(url)))
155                    .collect(),
156            ),
157            other => other.clone(),
158        }
159    }
160}
161
162// Secrets stay out of a debug print: a key, `env:NAME` or not, is not shown.
163impl std::fmt::Debug for ProviderConfig {
164    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
165        f.debug_struct("ProviderConfig")
166            .field("vendor", &self.vendor)
167            .field("formats", &self.formats.as_ref().map(Formats::redacted))
168            .field(
169                "base_url",
170                &self.base_url.as_deref().map(crate::redact::url),
171            )
172            .finish_non_exhaustive()
173    }
174}
175
176impl std::fmt::Debug for Auth {
177    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
178        match self {
179            Self::Bearer { .. } => f.write_str("Auth::Bearer(..)"),
180            Self::Header { name, .. } => write!(f, "Auth::Header({name}: ..)"),
181        }
182    }
183}
184
185/// A gateway's configuration, as `gateway.toml` writes it.
186#[derive(Debug, Clone, Deserialize)]
187#[serde(deny_unknown_fields)]
188pub struct Config {
189    /// Where to listen, as `host:port` (a name is resolved), `:port` or a
190    /// bare port (on 127.0.0.1); `127.0.0.1:8080` if unset.
191    #[serde(default, deserialize_with = "listen_address")]
192    pub listen: Option<SocketAddr>,
193    /// The most bytes of a client's request, and of a provider's answer
194    /// held at once, past which the request fails 413 or the answer 502; a
195    /// number of bytes or a size such as `32MiB`; 32 MiB if unset.
196    #[serde(default, deserialize_with = "size")]
197    pub body_limit: Option<usize>,
198    /// The largest WebSocket message of a session, from the client or the
199    /// provider, past which the session ends (close 1009); a number of
200    /// bytes or a size such as `16MiB`; 16 MiB if unset.
201    #[serde(default, deserialize_with = "size")]
202    pub ws_message_limit: Option<usize>,
203    /// Models declared by `provider/model`, each a card (`pricing`,
204    /// `display_name`, `context_window`, `capabilities`, ...) laid over what
205    /// the provider's list says of it, or the whole of what is known of a
206    /// model it does not list. A call's cost is its model's `pricing`.
207    #[serde(default, deserialize_with = "models")]
208    pub models: IndexMap<String, Model>,
209    /// Retired: `models`, each with its `pricing`. Refused with how.
210    #[serde(default)]
211    pub prices: Option<serde::de::IgnoredAny>,
212    /// How long open responses and end hooks get, together, after a stop
213    /// signal, before they are cut: seconds, or a duration such as `30s`,
214    /// `2m` or `500ms`; 30 s if unset.
215    #[serde(default, deserialize_with = "span")]
216    pub shutdown_grace: Option<Duration>,
217    /// Client keys, literal or `env:NAME`, each alone or as
218    /// `{ name, key }`. When set, every request needs one; it is consumed
219    /// by the gateway and never sent to a provider. A request is logged
220    /// under its key's name (`key-1`, `key-2`... for a key without one).
221    #[serde(default)]
222    pub client_keys: Vec<ClientKey>,
223    /// How each finished request is printed to stderr: `text`, `json` or
224    /// `off`.
225    #[serde(default)]
226    pub log: LogFormat,
227    /// Whether the web UI and its admin API are served under `/ui/`.
228    #[serde(default = "enabled")]
229    pub ui: bool,
230    /// Providers by name, in order: the first serving a kind is that
231    /// kind's default.
232    #[serde(default)]
233    pub providers: IndexMap<String, ProviderConfig>,
234    /// The formats served to clients, by name, tried in order. Unset:
235    /// `openai-chat`, `anthropic-messages`, and every format of another
236    /// kind some provider speaks, except `passthrough`. Serve
237    /// `passthrough` last to relay every other request unread to the
238    /// provider of format `passthrough`, whose `base_url` is then the
239    /// vendor's origin. Clients of a format no other translates,
240    /// `passthrough` or a session's, go to the one provider of that format.
241    pub formats: Option<Vec<String>>,
242    /// Model routes by the model name clients ask for, or a glob of names
243    /// such as `llama-*`: where each goes, and how its candidates are
244    /// picked, retried and raced. An exact name is tried first, then a
245    /// `provider/model` name, then the globs in order, then each vendor's
246    /// own model names, then the kind's default.
247    #[serde(default)]
248    pub routes: IndexMap<String, RouteConfig>,
249    /// Tool servers by name, each served to clients over MCP at
250    /// `/mcp/{name}`: an MCP server at a streamable-HTTP `url` or run as a
251    /// `command`, or a tool `vendor`'s HTTP API. Name `mcp` in `formats` if
252    /// that lists formats.
253    #[serde(default)]
254    pub tools: IndexMap<String, McpConfig>,
255    /// Retired: `tools`. Refused with how.
256    #[serde(default)]
257    pub mcp: Option<serde::de::IgnoredAny>,
258    /// Which web pages may call the gateway from a browser; none if unset.
259    pub cors: Option<CorsConfig>,
260    /// How the gateway reaches providers and tool servers: through which
261    /// proxy, trusting which certificates besides the system's.
262    #[serde(default)]
263    pub network: NetworkConfig,
264    /// The compiled-in plugins, each configured under its name. The gateway
265    /// runs them in an order of its own, whatever the order here.
266    #[serde(default)]
267    pub plugins: PluginsConfig,
268    #[serde(skip)]
269    pub(crate) source: Source,
270    /// Relay each request to one vendor, with the client's own credentials
271    /// (`proxy`).
272    #[serde(skip)]
273    pub(crate) relay: bool,
274}
275
276fn enabled() -> bool {
277    true
278}
279
280impl Default for Config {
281    fn default() -> Self {
282        Self {
283            listen: None,
284            body_limit: None,
285            ws_message_limit: None,
286            models: IndexMap::new(),
287            prices: None,
288            shutdown_grace: None,
289            client_keys: Vec::new(),
290            log: LogFormat::Text,
291            ui: true,
292            providers: IndexMap::new(),
293            formats: None,
294            routes: IndexMap::new(),
295            tools: IndexMap::new(),
296            mcp: None,
297            plugins: PluginsConfig::default(),
298            cors: None,
299            network: NetworkConfig::default(),
300            source: Source::Inline,
301            relay: false,
302        }
303    }
304}
305
306/// One provider: a vendor, explicit formats, or a vendor with some
307/// of its settings replaced.
308#[derive(Clone, Default, Deserialize)]
309#[serde(deny_unknown_fields)]
310pub struct ProviderConfig {
311    /// A vendor: `openai`, `anthropic`, `gemini`, `groq`, ...
312    pub vendor: Option<String>,
313    /// Its format, or several: by name, or a table of each format's base
314    /// URL by its name, which a vendor whose formats sit at different URLs
315    /// (Gemini) needs to be moved; a vendor's are every format it speaks
316    /// compiled in, each at its own URL.
317    #[serde(default)]
318    pub formats: Option<Formats>,
319    /// The base URL its formats share, its API's, in place of a table's
320    /// or its vendor's; a format of whole paths, such as `passthrough`,
321    /// takes its origin.
322    pub base_url: Option<String>,
323    /// Its key, literal or `env:NAME`, sent as its formats expect; a
324    /// vendor's is `env:<VENDOR>_API_KEY`.
325    pub key: Option<String>,
326    /// Its credentials as one header, in place of `key`. A provider with
327    /// neither, and no vendor key, passes on the client's.
328    pub auth: Option<Auth>,
329    /// Its proxy, in place of `network`'s: a URL, literal or `env:NAME`, or
330    /// `false` for none.
331    pub proxy: Option<Proxy>,
332}
333
334#[derive(Clone, Deserialize)]
335#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
336pub enum Auth {
337    /// `Authorization: Bearer <key>`
338    Bearer { key: String },
339    /// `<name>: <key>`
340    Header { name: String, key: String },
341}
342
343/// The compiled-in plugins. Each is configured under its own name, and the
344/// gateway registers them in a fixed order: the request log, routing, the
345/// MCP aggregate, video jobs, the tool loop, then the dispatch of routes. Video
346/// jobs are always on; a vendor's quirks are in the formats it speaks, not
347/// plugins.
348#[derive(Debug, Clone, Default, Deserialize)]
349#[serde(deny_unknown_fields)]
350pub struct PluginsConfig {
351    /// Which provider each request goes to; always on. Its routes are
352    /// the top-level `routes`.
353    #[serde(default)]
354    pub routing: RoutingConfig,
355    /// Retired: a route's `to`, `fallback` and `tries`. Refused with how.
356    #[serde(default)]
357    pub fallback: Option<serde::de::IgnoredAny>,
358    /// Retired: a route's `hedge`. Refused with how.
359    #[serde(default)]
360    pub hedge: Option<serde::de::IgnoredAny>,
361    /// Run tools of tool servers inside chat requests; off if unset.
362    pub tool_loop: Option<ToolLoopConfig>,
363    /// Keep the conversation state a client or provider cannot: Responses
364    /// translated to another provider's format, so a client's
365    /// `previous_response_id` works with it, and a Chat client's reasoning
366    /// between tool calls with OpenAI's Responses. On unless
367    /// `enabled = false`.
368    #[serde(default)]
369    pub responses: ResponsesConfig,
370    /// Send each request to Respan as a trace; off if unset.
371    pub respan: Option<RespanConfig>,
372    /// The request history the web UI and admin API read; always on.
373    #[serde(default)]
374    pub request_log: RequestLogConfig,
375}
376
377/// Respan observability: each request a trace, sent to Respan.
378#[derive(Clone, Deserialize)]
379#[serde(deny_unknown_fields)]
380pub struct RespanConfig {
381    /// The Respan API key, literal or `env:NAME`.
382    pub key: String,
383    /// The OTLP trace endpoint; Respan's if unset.
384    pub url: Option<String>,
385    /// Whether a model's messages and reply are sent; true if unset.
386    pub content: Option<bool>,
387    /// The service the traces are of; `respan-gateway` if unset.
388    pub service: Option<String>,
389}
390
391// Its key is a secret: not printed.
392impl std::fmt::Debug for RespanConfig {
393    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
394        f.debug_struct("RespanConfig")
395            .field("content", &self.content)
396            .finish_non_exhaustive()
397    }
398}
399
400/// The conversation state the gateway keeps
401/// (`respan_gateway_plugin_responses`), in its memory: not across a
402/// restart, nor shared between gateways, so a client whose requests reach
403/// several gateways needs them to reach the one that kept its conversation.
404#[derive(Debug, Clone, Deserialize)]
405#[serde(deny_unknown_fields)]
406pub struct ResponsesConfig {
407    /// Whether it is kept; it is unless `false`.
408    #[serde(default = "enabled")]
409    pub enabled: bool,
410    /// How long what is kept is kept after it was last read; an hour if
411    /// unset.
412    #[serde(default, deserialize_with = "span")]
413    pub keep: Option<Duration>,
414}
415
416impl Default for ResponsesConfig {
417    fn default() -> Self {
418        Self {
419            enabled: true,
420            keep: None,
421        }
422    }
423}
424
425/// Routing: which provider each request goes to.
426#[derive(Debug, Clone, Default, Deserialize)]
427#[serde(deny_unknown_fields)]
428pub struct RoutingConfig {
429    /// Retired: the top-level `routes`. Refused with how.
430    #[serde(default)]
431    pub models: Option<serde::de::IgnoredAny>,
432    /// The provider of each kind it serves for requests nothing else
433    /// routes; the first provider serving the kind if unset.
434    pub default: Option<String>,
435    /// Whether each provider's model list is read at start and every ten
436    /// minutes, so a model one lists goes to it, and routes can pick by
437    /// price and capability; true if unset.
438    pub listings: Option<bool>,
439}
440
441/// One route: the candidates a model name goes to, and how they are
442/// picked, retried and raced.
443#[derive(Debug, Clone, Deserialize)]
444#[serde(deny_unknown_fields)]
445pub struct RouteConfig {
446    /// Where it goes: `provider`, `provider/model` or `provider/{model}`
447    /// (`{model}` the name asked for), or a list of them, each alone or
448    /// as `{ target = "..", weight = 3 }`.
449    #[serde(deserialize_with = "route_targets")]
450    pub to: Vec<RouteTarget>,
451    /// How the candidates are ordered: `first` (as listed), `cheapest`
452    /// (by each model's `pricing`: input plus three times output), `fastest` (by the gateway's own record of each one's time
453    /// to a response), `weighted` or `random`. `first` if unset.
454    #[serde(default)]
455    pub pick: Pick,
456    /// What a candidate's model must be able to do, as its provider's
457    /// listing says, such as `tools` or `vision`; one the listing says
458    /// nothing of is kept.
459    #[serde(default)]
460    pub needs: Vec<String>,
461    /// Which requests it applies to; every request if unset.
462    #[serde(default)]
463    pub when: RouteWhen,
464    /// Whether a failed candidate falls back to the next; true if unset.
465    pub fallback: Option<bool>,
466    /// Races the candidates instead, each started this long after the one
467    /// before, such as `200ms`; off if unset.
468    #[serde(default, deserialize_with = "span")]
469    pub hedge: Option<Duration>,
470    /// Tries per candidate, retries included; 1 if unset.
471    pub tries: Option<u32>,
472    /// The first wait before a retry, doubled after each; 250 ms if unset.
473    #[serde(default, deserialize_with = "span")]
474    pub backoff: Option<Duration>,
475    /// The longest wait before a retry; a `Retry-After` longer than it means
476    /// no retry. 10 s if unset.
477    #[serde(default, deserialize_with = "span")]
478    pub max_backoff: Option<Duration>,
479    /// How far an answer is read before it counts as a success.
480    #[serde(default)]
481    pub until: Commit,
482}
483
484/// A route's candidate, alone or weighted.
485#[derive(Debug, Clone, PartialEq, Eq)]
486pub struct RouteTarget {
487    /// `provider`, `provider/model` or `provider/{model}`.
488    pub target: String,
489    /// Its share of requests for `pick = "weighted"`; 1 if unset.
490    pub weight: u32,
491}
492
493fn route_targets<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<RouteTarget>, D::Error> {
494    #[derive(Deserialize)]
495    #[serde(deny_unknown_fields)]
496    struct Weighted {
497        target: String,
498        weight: Option<u32>,
499    }
500    #[derive(Deserialize)]
501    #[serde(untagged)]
502    enum One {
503        Plain(String),
504        Weighted(Weighted),
505    }
506    #[derive(Deserialize)]
507    #[serde(untagged)]
508    enum Targets {
509        One(One),
510        Many(Vec<One>),
511    }
512    let shape = "routes: to: a target such as \"openai/gpt-4o\", \
513                 `{ target = \"..\", weight = 3 }`, or a list of them";
514    let targets = Targets::deserialize(d).map_err(|_| serde::de::Error::custom(shape))?;
515    let list = match targets {
516        Targets::One(one) => vec![one],
517        Targets::Many(many) => many,
518    };
519    Ok(list
520        .into_iter()
521        .map(|one| match one {
522            One::Plain(target) => RouteTarget { target, weight: 1 },
523            One::Weighted(w) => RouteTarget {
524                target: w.target,
525                weight: w.weight.unwrap_or(1),
526            },
527        })
528        .collect())
529}
530
531/// Which requests a route applies to.
532#[derive(Debug, Clone, Default, Deserialize)]
533#[serde(deny_unknown_fields)]
534pub struct RouteWhen {
535    /// The client keys, by name; any if empty.
536    #[serde(default)]
537    pub clients: Vec<String>,
538    /// The kinds, such as `chat` or `embedding`; any if empty.
539    #[serde(default)]
540    pub kinds: Vec<String>,
541}
542
543/// How far an attempt's answer is read before it counts as a success, and
544/// nothing is retried after.
545#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
546#[serde(rename_all = "snake_case")]
547pub enum Commit {
548    /// Its head: a success status. The default.
549    #[default]
550    Head,
551    /// Its whole answer, held until it ends cleanly.
552    End,
553}
554
555/// The request log: the history of finished requests.
556#[derive(Debug, Clone, Default, Deserialize)]
557#[serde(deny_unknown_fields)]
558pub struct RequestLogConfig {
559    /// How many finished requests the in-memory history (the web UI's)
560    /// keeps; 1000 if unset.
561    #[serde(default, deserialize_with = "request_log_history")]
562    pub history: Option<usize>,
563}
564
565/// Browser access: the origins whose pages may call the gateway.
566#[derive(Debug, Clone, Deserialize)]
567#[serde(deny_unknown_fields)]
568pub struct CorsConfig {
569    /// Origins such as `https://app.example.com` (scheme, host and port
570    /// alone), or `*` for any, which needs `client_keys`. Their preflight
571    /// requests are answered without a key; their other requests need the
572    /// gateway's usual one.
573    pub origins: Vec<String>,
574}
575
576/// The tool loop: the gateway offers the tools of tool servers to the
577/// model and runs the ones it calls, so a client that knows nothing of MCP
578/// gets answers that used them.
579#[derive(Debug, Clone, Deserialize)]
580#[serde(deny_unknown_fields)]
581pub struct ToolLoopConfig {
582    /// The tool servers whose tools the gateway offers and runs, as
583    /// `<server>__<tool>`; every one that takes no client's credentials
584    /// if unset, as `/mcp` fronts them.
585    pub servers: Option<Vec<String>>,
586    /// Which of their tools are offered, as the model names them
587    /// (`<server>__<tool>`), `*` standing for any characters, such as
588    /// `github__search_*`; all of them if unset or empty.
589    #[serde(default)]
590    pub allow: Vec<String>,
591    /// Tools never offered, named as `allow` does; it wins over `allow`.
592    #[serde(default)]
593    pub deny: Vec<String>,
594    /// Model name prefixes the loop applies to, as the provider is sent
595    /// them; every chat model if unset.
596    #[serde(default)]
597    pub models: Vec<String>,
598    /// The most calls to the model for one request; 8 if unset.
599    pub max_steps: Option<u32>,
600    /// The wall-clock limit of one request's loop; 5 minutes if unset.
601    #[serde(default, deserialize_with = "span")]
602    pub timeout: Option<Duration>,
603    /// The limit of one tool call; 60 s if unset.
604    #[serde(default, deserialize_with = "span")]
605    pub tool_timeout: Option<Duration>,
606    /// How long a server's tool list is kept; 5 minutes if unset.
607    #[serde(default, deserialize_with = "span")]
608    pub tool_list_ttl: Option<Duration>,
609    /// The most tool calls of one step that run at once; 4 if unset.
610    pub parallel: Option<usize>,
611    /// The most bytes of one tool's answer the model sees; 64 KiB if unset.
612    /// A tool's output is untrusted input to the model.
613    #[serde(default, deserialize_with = "size")]
614    pub max_result: Option<usize>,
615    /// The most bytes of tool answers the model sees in one request, over
616    /// all its steps; 256 KiB if unset.
617    #[serde(default, deserialize_with = "size")]
618    pub max_results: Option<usize>,
619}
620
621/// Where a configuration came from.
622#[derive(Debug, Clone, Default, PartialEq, Eq)]
623pub enum Source {
624    File(PathBuf),
625    Environment,
626    Proxy,
627    #[default]
628    Inline,
629}
630
631impl std::fmt::Display for Source {
632    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
633        match self {
634            Source::File(path) => write!(f, "{}", path.display()),
635            Source::Environment => f.write_str("environment"),
636            Source::Proxy => f.write_str("proxy"),
637            Source::Inline => f.write_str("inline"),
638        }
639    }
640}
641
642/// The vendor `proxy` relays to.
643#[derive(Debug, Clone, Copy, PartialEq, Eq)]
644pub enum ProxyVendor {
645    Anthropic,
646    OpenAi,
647}
648
649/// The file read when none is named.
650pub const DEFAULT_FILE: &str = "gateway.toml";
651
652impl Config {
653    /// A configuration from TOML text. Errors omit source excerpts, which may
654    /// contain credentials, while retaining the line and column.
655    pub fn parse(text: &str) -> Result<Config, Error> {
656        let read = serde_path_to_error::deserialize(toml::Deserializer::new(text));
657        read.map_err(|e| {
658            let path = e.path().to_string();
659            let said = toml_error(text, e.inner());
660            // A message that names its key already, as most of this
661            // module's do, is not named twice.
662            let top = path.split(['.', '[']).next().unwrap_or_default();
663            match path.as_str() {
664                "." => Error::new(said),
665                _ if said.starts_with(top) => Error::new(said),
666                _ => Error::new(format!("{path}: {said}")),
667            }
668        })
669    }
670
671    /// Structured configuration for language bindings, with secret-safe errors.
672    pub fn from_value(value: serde_json::Value) -> Result<Config, Error> {
673        serde_json::from_value(value).map_err(|e| Error::new(redacted(&e.to_string())))
674    }
675
676    /// The configuration in the file at `path`.
677    pub fn load(path: impl AsRef<Path>) -> Result<Config, Error> {
678        let path = path.as_ref();
679        let in_file = |e: String| Error::new(format!("{}: {e}", path.display()));
680        let text = std::fs::read_to_string(path).map_err(|e| in_file(e.to_string()))?;
681        let mut config = Config::parse(&text).map_err(|e| in_file(e.to_string()))?;
682        config.source = Source::File(path.to_owned());
683        Ok(config)
684    }
685
686    /// A configuration with no file: a provider for every vendor whose key
687    /// is in the environment (`OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, ...;
688    /// Ollama if `OLLAMA_HOST` is set). `RESPAN_<VENDOR>_BASE_URL` moves a
689    /// vendor's base URL. `Err` if there is none. Each tool vendor whose
690    /// key is there (`LINKUP_API_KEY`, ...) is a tool server of its name,
691    /// and `/mcp` fronts them; the tool loop stays off.
692    pub fn from_env() -> Result<Config, Error> {
693        let detected = vendors::detected();
694        if detected.is_empty() {
695            return Err(Error::new(no_keys_message()));
696        }
697        let providers = detected
698            .into_iter()
699            .map(|(vendor, key, base_url)| {
700                let provider = ProviderConfig {
701                    vendor: Some(vendor.id.to_owned()),
702                    key,
703                    base_url,
704                    ..ProviderConfig::default()
705                };
706                (vendor.id.to_owned(), provider)
707            })
708            .collect::<IndexMap<String, ProviderConfig>>();
709        // Each tool vendor with its key in the environment, a tool server
710        // of its name, unless a provider has the name.
711        let tools: IndexMap<String, McpConfig> = (respan_gateway_tool_vendors::ALL.iter())
712            .filter(|v| v.key_from_env().is_some() && !providers.contains_key(v.id))
713            .map(|v| (v.id.to_owned(), McpConfig::tool_vendor(v.id)))
714            .collect();
715        Ok(Config {
716            providers,
717            tools,
718            source: Source::Environment,
719            ..Config::default()
720        })
721    }
722
723    /// `path` if given, else `./gateway.toml`, else
724    /// [`from_env`](Self::from_env).
725    pub fn discover(path: Option<&Path>) -> Result<Config, Error> {
726        match path {
727            Some(path) => Config::load(path),
728            None if Path::new(DEFAULT_FILE).exists() => Config::load(DEFAULT_FILE),
729            None => Config::from_env(),
730        }
731    }
732
733    /// The configuration of `proxy`: one vendor at `url` (its public API if
734    /// `None`), no keys of its own, its chat format and every other request
735    /// relayed, with each client's credentials: the chat format writes the
736    /// client's request in its own spec, and passthrough relays the rest
737    /// byte for byte.
738    pub fn proxy(vendor: ProxyVendor, url: Option<&str>) -> Config {
739        let (name, format, default) = match vendor {
740            ProxyVendor::Anthropic => (
741                "anthropic",
742                "anthropic-messages",
743                "https://api.anthropic.com",
744            ),
745            ProxyVendor::OpenAi => ("openai", "openai-chat", "https://api.openai.com/v1"),
746        };
747        let url = url.unwrap_or(default).trim_end_matches('/');
748        // The chat format writes its own path after the vendor's API base;
749        // passthrough relays the client's path at the vendor's origin.
750        let provider = ProviderConfig {
751            formats: Some(Formats::Many(vec![
752                format.to_owned(),
753                "passthrough".to_owned(),
754            ])),
755            base_url: Some(url.to_owned()),
756            ..ProviderConfig::default()
757        };
758        Config {
759            providers: IndexMap::from([(name.to_owned(), provider)]),
760            formats: Some(vec![format.to_owned(), "passthrough".to_owned()]),
761            source: Source::Proxy,
762            relay: true,
763            ..Config::default()
764        }
765    }
766
767    /// Where it came from.
768    pub fn source(&self) -> &Source {
769        &self.source
770    }
771}
772
773pub(crate) fn toml_error(text: &str, error: &toml::de::Error) -> String {
774    let message = redacted(error.message());
775    match error.span() {
776        Some(span) => {
777            let prefix = &text[..span.start.min(text.len())];
778            let line = prefix.bytes().filter(|b| *b == b'\n').count() + 1;
779            let column = prefix
780                .rsplit('\n')
781                .next()
782                .unwrap_or_default()
783                .chars()
784                .count()
785                + 1;
786            format!("{message} at line {line} column {column}")
787        }
788        None => message,
789    }
790}
791
792/// `message` with the values serde echoes in it left out: a string
793/// (`invalid type: string "..."`), and a variant name (`unknown variant
794/// `...``), which a misplaced secret would be.
795fn redacted(message: &str) -> String {
796    let mut out = message.to_owned();
797    for (start, end) in [
798        ("string \"", "\", expected"),
799        ("unknown variant `", "`, expected"),
800    ] {
801        let mut from = 0;
802        while let Some(at) = out[from..].find(start) {
803            let value = from + at + start.len();
804            let Some(len) = out[value..].rfind(end) else {
805                break;
806            };
807            out.replace_range(value..value + len, "...");
808            from = value + 3;
809        }
810    }
811    out
812}
813
814/// What to do when there is no config file and no key in the environment.
815pub fn no_keys_message() -> String {
816    format!(
817        "no configuration found.\n\n\
818         Create a config:\n  respan-gateway init\n\n\
819         Or start with a provider key:\n  export OPENAI_API_KEY=sk-...\n  respan-gateway\n\n\
820         Config file: {DEFAULT_FILE}\n\
821         More options: respan-gateway --help"
822    )
823}
824
825/// Where `text` says to listen: `host:port`, a name resolved, preferring
826/// IPv4; `:port` or a bare port, on 127.0.0.1.
827pub fn parse_listen(text: &str) -> Result<SocketAddr, String> {
828    use std::net::{IpAddr, Ipv4Addr, ToSocketAddrs};
829    let text = text.trim();
830    let port = text.strip_prefix(':').unwrap_or(text);
831    if let Ok(port) = port.parse::<u16>() {
832        return Ok(SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port));
833    }
834    if let Ok(addr) = text.parse() {
835        return Ok(addr);
836    }
837    let usage = || format!("'{text}' is not host:port, :port or a port");
838    if !text.contains(':') {
839        return Err(usage());
840    }
841    let addrs: Vec<SocketAddr> = text
842        .to_socket_addrs()
843        .map_err(|e| format!("{}: {e}", usage()))?
844        .collect();
845    let v4 = addrs.iter().find(|a| a.is_ipv4());
846    v4.or(addrs.first())
847        .copied()
848        .ok_or_else(|| format!("'{text}' resolves to no address"))
849}
850
851fn listen_address<'de, D: Deserializer<'de>>(d: D) -> Result<Option<SocketAddr>, D::Error> {
852    #[derive(Deserialize)]
853    #[serde(untagged)]
854    enum Address {
855        Text(String),
856        Port(u16),
857    }
858    let text = match Option::<Address>::deserialize(d)? {
859        None => return Ok(None),
860        Some(Address::Text(text)) => text,
861        Some(Address::Port(port)) => port.to_string(),
862    };
863    parse_listen(&text)
864        .map(Some)
865        .map_err(|e| serde::de::Error::custom(format!("listen: {e}")))
866}
867
868/// A number of bytes, or a size such as `32MiB`, `512 KB` or `1GiB`
869/// ([`bytesize`]); at least one byte.
870fn size<'de, D: Deserializer<'de>>(d: D) -> Result<Option<usize>, D::Error> {
871    let Some(text) = Option::<Number>::deserialize(d)? else {
872        return Ok(None);
873    };
874    let bytes = match text {
875        Number::Count(bytes) => bytes,
876        Number::Text(text) => text
877            .trim()
878            .parse::<bytesize::ByteSize>()
879            .map(|size| size.as_u64())
880            .map_err(|_| {
881                serde::de::Error::custom(format!("'{text}' is not a size such as 32MiB"))
882            })?,
883    };
884    match usize::try_from(bytes) {
885        Ok(0) => Err(serde::de::Error::custom("a size must be above 0")),
886        Ok(bytes) => Ok(Some(bytes)),
887        Err(_) => Err(serde::de::Error::custom("a size this large cannot be held")),
888    }
889}
890
891/// A count, or text that says one with a unit.
892#[derive(Deserialize)]
893#[serde(untagged)]
894enum Number {
895    Count(u64),
896    Text(String),
897}
898
899/// Each declared model, its id and provider those its key names.
900fn models<'de, D: Deserializer<'de>>(d: D) -> Result<IndexMap<String, Model>, D::Error> {
901    let models = IndexMap::<String, Model>::deserialize(d)?;
902    let bad = |key: &str, why: &str| serde::de::Error::custom(format!("models: {key}: {why}"));
903    let mut declared = IndexMap::new();
904    for (key, mut model) in models {
905        let Some((provider, id)) = key
906            .split_once('/')
907            .filter(|(p, m)| !p.is_empty() && !m.is_empty())
908        else {
909            return Err(bad(&key, "name it as `provider/model`"));
910        };
911        if let Some(p) = &model.price {
912            let rates = [
913                Some(p.input),
914                Some(p.output),
915                p.cached_input,
916                p.cache_write,
917                p.per_second,
918            ];
919            if rates.iter().flatten().any(|r| !r.is_finite() || *r < 0.0) {
920                return Err(bad(&key, "a price must be a number of dollars, 0 or more"));
921            }
922        }
923        (model.id, model.provider) = (id.to_owned(), provider.to_owned());
924        declared.insert(key, model);
925    }
926    Ok(declared)
927}
928
929fn request_log_history<'de, D: Deserializer<'de>>(d: D) -> Result<Option<usize>, D::Error> {
930    match Option::<usize>::deserialize(d)
931        .map_err(|e| serde::de::Error::custom(format!("plugins.request_log.history: {e}")))?
932    {
933        Some(0) => Err(serde::de::Error::custom(
934            "plugins: request_log: history: must be above 0",
935        )),
936        kept => Ok(kept),
937    }
938}
939
940/// A number of seconds, or a duration such as `30s`, `2m`, `1h` or `500ms`
941/// ([`humantime`]).
942fn span<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
943    Ok(match Option::<Number>::deserialize(d)? {
944        None => None,
945        Some(Number::Count(seconds)) => Some(Duration::from_secs(seconds)),
946        Some(Number::Text(text)) => Some(parse_duration(&text).map_err(serde::de::Error::custom)?),
947    })
948}
949
950/// The time `text` says, as [`humantime`] reads it (`30s`, `2m`, `1h 30m`),
951/// or a number of seconds.
952pub fn parse_duration(text: &str) -> Result<Duration, String> {
953    let text = text.trim();
954    match text.parse::<u64>() {
955        Ok(seconds) => Ok(Duration::from_secs(seconds)),
956        Err(_) => humantime::parse_duration(text)
957            .map_err(|_| format!("'{text}' is not a duration such as 30s or 2m")),
958    }
959}
960
961#[cfg(test)]
962mod tests {
963    use super::*;
964
965    #[test]
966    fn toml_preserves_provider_order_and_reads_readable_values() {
967        let config = Config::parse(
968            r#"
969listen = 8080
970body_limit = "2MiB"
971shutdown_grace = "500ms"
972client_keys = [{ name = "ops", key = "env:OPS_KEY", admin = true }]
973[providers.z]
974vendor = "openai"
975[providers.a]
976vendor = "anthropic"
977"#,
978        )
979        .expect("TOML config");
980        assert_eq!(
981            config
982                .providers
983                .keys()
984                .map(String::as_str)
985                .collect::<Vec<_>>(),
986            ["z", "a"]
987        );
988        assert_eq!(config.listen.expect("listen").port(), 8080);
989        assert_eq!(config.body_limit, Some(2 << 20));
990        assert_eq!(config.shutdown_grace, Some(Duration::from_millis(500)));
991        assert_eq!(config.client_keys[0].name(), Some("ops"));
992    }
993
994    #[test]
995    fn toml_diagnostics_have_locations_without_source_secrets() {
996        for text in [
997            "log = 'sk-secret-1'",
998            "client_keys = 'sk-secret-1'",
999            "[providers.p]\nkey = 'sk-secret-1'\nbogus = true",
1000            "[providers.p]\nkey = \"sk-secret-1",
1001        ] {
1002            let error = Config::parse(text).expect_err("invalid").to_string();
1003            assert!(error.contains("line"), "{error}");
1004            assert!(!error.contains("sk-secret-1"), "{error}");
1005        }
1006    }
1007
1008    #[test]
1009    fn toml_example_and_generated_starter_parse() {
1010        Config::parse(include_str!("../../../gateway.example.toml")).expect("example");
1011        let picks = [crate::init::Chosen::parse("openai=key\"with\ncontrols").expect("vendor")];
1012        let text = crate::init::starter(&picks, Some("client-secret"));
1013        let config = Config::parse(&text).expect("starter");
1014        assert_eq!(
1015            config.providers["openai"].key.as_deref(),
1016            Some("key\"with\ncontrols")
1017        );
1018        assert_eq!(config.client_keys[0].key(), "client-secret");
1019    }
1020
1021    #[test]
1022    fn debug_shows_no_secret() {
1023        let config = Config::parse(
1024            "client_keys = [\"bare-secret\", { name = \"ops\", key = \"named-secret\", admin = true }]\nproviders = { a = { vendor = \"openai\", key = \"prov-secret\", base_url = \"https://user:url-secret@h.test/v1?k=q-secret\" }, b = { formats = \"openai-chat\", base_url = \"http://b.test\", auth = { type = \"bearer\", key = \"auth-secret\" } } }\ntools = { m = { command = \"npx\", args = [\"--token\", \"arg-secret\"], env = { T = \"env-secret\" } }, h = { url = \"https://h.test/mcp/tok-in-path\", headers = { x-k = \"mcp-secret\" }, auth = { oauth = { token_url = \"https://o.test/t\", client_id = \"cid\", client_secret = \"oauth-secret\" } } }, b = { url = \"https://b.test/mcp\", auth = { bearer = \"bearer-secret\" } } }\n",
1025        )
1026        .unwrap_or_else(|e| panic!("{e}"));
1027        let shown = format!("{config:?}");
1028        for secret in [
1029            "bare-secret",
1030            "named-secret",
1031            "prov-secret",
1032            "url-secret",
1033            "q-secret",
1034            "auth-secret",
1035            "arg-secret",
1036            "env-secret",
1037            "mcp-secret",
1038            "bearer-secret",
1039            "oauth-secret",
1040            "tok-in-path",
1041        ] {
1042            assert!(!shown.contains(secret), "{secret} in {shown}");
1043        }
1044    }
1045
1046    #[test]
1047    fn a_client_key_entry_with_a_typo_is_named() {
1048        let said = |text: &str| Config::parse(text).err().map(|e| e.to_string());
1049        let bad = said("client_keys = [{ name = \"ci\", ky = \"x\" }]\n").unwrap_or_default();
1050        assert!(bad.contains("ky") && bad.contains("client key"), "{bad}");
1051        assert!(
1052            said(
1053                "client_keys = [{ name = \"ci\", key = \"x\", admin = true, tools = [\"a__*\"] }]\n"
1054            )
1055            .is_none()
1056        );
1057        assert!(said("client_keys = [3]\n").is_some());
1058    }
1059
1060    #[test]
1061    fn a_listen_address_is_a_socket_address() {
1062        let bad = Config::parse("listen = \"127.0.0.1\"\n").err();
1063        assert!(bad.is_some_and(|e| e.to_string().contains("listen")));
1064        let good = Config::parse("listen = \"127.0.0.1:8080\"\n");
1065        assert!(good.is_ok_and(|c| c.listen.is_some_and(|a| a.port() == 8080)));
1066        let named = Config::parse("listen = \"localhost:8081\"\n");
1067        assert!(named.is_ok_and(|c| c.listen.is_some_and(|a| a.port() == 8081)));
1068    }
1069
1070    #[test]
1071    fn a_listen_address_may_be_a_name_a_port_or_colon_port() {
1072        let local = |port| Ok(SocketAddr::from(([127, 0, 0, 1], port)));
1073        assert_eq!(parse_listen("8080"), local(8080));
1074        assert_eq!(parse_listen(":8080"), local(8080));
1075        assert_eq!(parse_listen("localhost:8080").map(|a| a.port()), Ok(8080));
1076        assert!(parse_listen("localhost:8080").is_ok_and(|a| a.ip().is_loopback()));
1077        assert_eq!(
1078            parse_listen("[::1]:9"),
1079            Ok(SocketAddr::from((std::net::Ipv6Addr::LOCALHOST, 9)))
1080        );
1081        assert!(parse_listen("0.0.0.0:80").is_ok_and(|a| a.ip().is_unspecified()));
1082        assert!(parse_listen("localhost").is_err());
1083        assert!(parse_listen("99999").is_err());
1084    }
1085
1086    #[test]
1087    fn vendors_lists_keys_and_switches_parse() {
1088        let text = "client_keys = [\"env:GATEWAY_KEY\", \"sk-local\"]\nlog = \"off\"\nui = false\nproviders = { openai = { vendor = \"openai\" }, claude = { vendor = \"anthropic\", key = \"env:MY_KEY\", base_url = \"http://x.test\" }, both = { formats = [\"openai-chat\", \"anthropic-messages\"], base_url = \"http://y.test\" }, one = { formats = \"openai-chat\", base_url = \"http://z.test\" } }\n";
1089        let config = Config::parse(text).unwrap_or_else(|e| panic!("{e}"));
1090        assert_eq!(
1091            config.client_keys,
1092            [
1093                ClientKey::from("env:GATEWAY_KEY"),
1094                ClientKey::from("sk-local")
1095            ]
1096        );
1097        assert!(config.log == LogFormat::Off && !config.ui);
1098        assert!(config.formats.is_none());
1099        let names: Vec<&str> = config.providers.keys().map(String::as_str).collect();
1100        assert_eq!(
1101            names,
1102            ["openai", "claude", "both", "one"],
1103            "in config order"
1104        );
1105        let both = &config.providers["both"];
1106        assert_eq!(
1107            both.formats.as_ref().map(Formats::names),
1108            Some(vec!["openai-chat", "anthropic-messages"])
1109        );
1110        assert_eq!(
1111            config.providers["one"].formats.as_ref().map(Formats::names),
1112            Some(vec!["openai-chat"])
1113        );
1114        assert_eq!(
1115            config.providers["claude"].key.as_deref(),
1116            Some("env:MY_KEY")
1117        );
1118        assert_eq!(config.providers["openai"].vendor.as_deref(), Some("openai"));
1119    }
1120
1121    #[test]
1122    fn a_body_limit_is_bytes_or_a_size() {
1123        let limit = |text: &str| Config::parse(text).map(|c| c.body_limit);
1124        assert_eq!(limit("body_limit = 1000\n"), Ok(Some(1000)));
1125        assert_eq!(limit("body_limit = \"32MiB\"\n"), Ok(Some(32 << 20)));
1126        assert_eq!(limit("body_limit = \"2 kb\"\n"), Ok(Some(2000)));
1127        let bad = limit("body_limit = \"lots\"\n")
1128            .err()
1129            .map(|e| e.to_string());
1130        assert!(bad.is_some_and(|e| e.contains("body_limit")));
1131    }
1132
1133    #[test]
1134    fn limits_are_sizes_counts_and_durations() {
1135        let config = Config::parse(
1136            "ws_message_limit = \"1MiB\"\nplugins = { request_log = { history = 50 } }\nshutdown_grace = \"2m\"\n",
1137        )
1138        .unwrap_or_else(|e| panic!("{e}"));
1139        assert_eq!(config.ws_message_limit, Some(1 << 20));
1140        assert_eq!(config.plugins.request_log.history, Some(50));
1141        assert_eq!(config.shutdown_grace, Some(Duration::from_secs(120)));
1142        let grace = |text: &str| Config::parse(text).map(|c| c.shutdown_grace);
1143        assert_eq!(
1144            grace("shutdown_grace = \"30s\"\n"),
1145            Ok(Some(Duration::from_secs(30)))
1146        );
1147        assert_eq!(
1148            grace("shutdown_grace = 45\n"),
1149            Ok(Some(Duration::from_secs(45)))
1150        );
1151        assert_eq!(
1152            grace("shutdown_grace = \"500ms\"\n"),
1153            Ok(Some(Duration::from_millis(500)))
1154        );
1155        let defaults = Config::parse("").unwrap_or_else(|e| panic!("{e}"));
1156        assert!(
1157            defaults.plugins.request_log.history.is_none() && defaults.shutdown_grace.is_none()
1158        );
1159        for (text, key) in [
1160            ("shutdown_grace = \"soon\"\n", "shutdown_grace"),
1161            ("shutdown_grace = \"5 parsecs\"\n", "shutdown_grace"),
1162            ("plugins = { request_log = { history = 0 } }\n", "history"),
1163            (
1164                "plugins = { request_log = { history = \"many\" } }\n",
1165                "history",
1166            ),
1167            (
1168                "[routes.x]\nto = \"p\"\nbackoff = \"soon\"\n",
1169                "routes.x.backoff",
1170            ),
1171            ("ws_message_limit = 0\n", "ws_message_limit"),
1172            ("ws_message_limit = \"big\"\n", "ws_message_limit"),
1173            ("body_limit = 0\n", "body_limit"),
1174        ] {
1175            let said = Config::parse(text).err().map(|e| e.to_string());
1176            assert!(said.is_some_and(|e| e.contains(key)), "{text}");
1177        }
1178    }
1179
1180    #[test]
1181    fn old_names_are_refused() {
1182        let old = [
1183            "serve = []\n",
1184            "target = \"p\"\n",
1185            "keys = []\n",
1186            "providers = { p = { format = \"x\" } }\n",
1187            "request_history = 10\n",
1188            "tool_loop = { servers = [\"m\"] }\n",
1189            "mcp_aggregate = {  }\n",
1190            "default = \"p\"\n",
1191            "plugins = [{ models = [] }]\n",
1192            "plugins = { quirks = false }\n",
1193            "plugins = { video_jobs = false }\n",
1194        ];
1195        for text in old {
1196            assert!(Config::parse(text).is_err(), "{text}");
1197        }
1198    }
1199
1200    #[test]
1201    fn defaults_serve_the_ui_and_log() {
1202        let config = Config::parse("").unwrap_or_else(|e| panic!("{e}"));
1203        assert!(config.log == LogFormat::Text && config.ui && config.client_keys.is_empty());
1204        assert_eq!(config.source(), &Source::Inline);
1205    }
1206
1207    #[test]
1208    fn an_error_does_not_echo_a_value_that_may_be_a_secret() {
1209        for text in [
1210            "client_keys = \"sk-secret-1\"\n",
1211            "providers = { p = { vendor = \"openai\", key = [\"sk-secret-1\"] } }\n",
1212            "providers = { p = { vendor = \"openai\", auth = \"sk-secret-1\" } }\n",
1213            "tools = { m = { command = \"x\", env = \"sk-secret-1\" } }\n",
1214            "tools = { m = { command = \"x\", args = \"sk-secret-1\" } }\n",
1215            "tools = { m = { url = \"http://h.test\", headers = \"sk-secret-1\" } }\n",
1216            "tools = { m = { url = \"http://h.test\", auth = \"sk-secret-1\" } }\n",
1217            "tools = { m = { url = \"http://h.test\", auth = { bearer = [\"sk-secret-1\"] } } }\n",
1218            "log = \"sk-secret-1\"\n",
1219            "providers = { p = { vendor = \"openai\", auth = { type = \"sk-secret-1\", key = \"k\" } } }\n",
1220        ] {
1221            let said = Config::parse(text)
1222                .err()
1223                .map(|e| e.to_string())
1224                .unwrap_or_default();
1225            assert!(!said.is_empty(), "{text}");
1226            assert!(!said.contains("sk-secret-1"), "{text}: {said}");
1227        }
1228        let said = Config::parse("client_keys = \"sk-secret-1\"\n")
1229            .err()
1230            .map(|e| e.to_string())
1231            .unwrap_or_default();
1232        assert!(said.contains("string \"...\""), "{said}");
1233    }
1234
1235    #[test]
1236    fn tool_loop_and_cors_keys_parse() {
1237        let text = "plugins = { tool_loop = { servers = [\"github\"], allow = [\"github__*\"], deny = [\"github__delete_*\"], tool_list_ttl = \"1m\", parallel = 2, max_result = \"8KiB\", max_results = \"64KiB\" } }\ncors = { origins = [\"https://app.example.com\"] }\n";
1238        let config = Config::parse(text).unwrap_or_else(|e| panic!("{e}"));
1239        let tool_loop = config
1240            .plugins
1241            .tool_loop
1242            .unwrap_or_else(|| panic!("tool_loop"));
1243        assert_eq!(tool_loop.servers, Some(vec!["github".to_owned()]));
1244        assert_eq!(tool_loop.allow, ["github__*"]);
1245        assert_eq!(tool_loop.deny, ["github__delete_*"]);
1246        assert_eq!(tool_loop.tool_list_ttl, Some(Duration::from_secs(60)));
1247        assert_eq!(tool_loop.parallel, Some(2));
1248        assert_eq!(tool_loop.max_results, Some(64 << 10));
1249        assert!(config.cors.is_some_and(|c| c.origins.len() == 1));
1250    }
1251
1252    #[test]
1253    fn routes_parse_by_model_name() {
1254        let text = "plugins = { routing = { default = \"openai\" } }\n\
1255                    [routes.smart]\n\
1256                    to = [\"anthropic/claude\", { target = \"openai/gpt-5\", weight = 3 }]\n\
1257                    pick = \"weighted\"\n\
1258                    needs = [\"tools\"]\n\
1259                    when = { clients = [\"ops\"], kinds = [\"chat\"] }\n\
1260                    tries = 2\n\
1261                    backoff = \"100ms\"\n\
1262                    until = \"end\"\n\
1263                    [routes.\"llama-*\"]\n\
1264                    to = \"groq\"\n\
1265                    hedge = \"300ms\"\n";
1266        let config = Config::parse(text).unwrap_or_else(|e| panic!("{e}"));
1267        assert_eq!(config.plugins.routing.default.as_deref(), Some("openai"));
1268        let smart = &config.routes["smart"];
1269        assert_eq!(
1270            smart.to,
1271            [
1272                RouteTarget {
1273                    target: "anthropic/claude".into(),
1274                    weight: 1
1275                },
1276                RouteTarget {
1277                    target: "openai/gpt-5".into(),
1278                    weight: 3
1279                },
1280            ]
1281        );
1282        assert_eq!(smart.pick, Pick::Weighted);
1283        assert_eq!(smart.needs, ["tools"]);
1284        assert_eq!(smart.when.clients, ["ops"]);
1285        assert_eq!(smart.tries, Some(2));
1286        assert_eq!(smart.backoff, Some(Duration::from_millis(100)));
1287        assert_eq!(smart.until, Commit::End);
1288        let llama = &config.routes["llama-*"];
1289        assert_eq!(llama.to[0].target, "groq");
1290        assert_eq!(llama.hedge, Some(Duration::from_millis(300)));
1291        assert_eq!(llama.pick, Pick::First);
1292        let said = Config::parse("[routes.x]\nto = 3\n")
1293            .err()
1294            .map(|e| e.to_string())
1295            .unwrap_or_default();
1296        assert!(said.contains("routes: to:"), "{said}");
1297    }
1298
1299    #[test]
1300    fn unknown_fields_are_refused() {
1301        let said = Config::parse("providers = { p = { vendor = \"openai\", bogus = 1 } }\n")
1302            .err()
1303            .map(|e| e.to_string())
1304            .unwrap_or_default();
1305        assert!(said.contains("bogus"), "{said}");
1306    }
1307
1308    #[test]
1309    fn a_provider_s_formats_are_names_or_each_at_its_url() {
1310        let config = Config::parse(
1311            "providers = { g = { vendor = \"gemini\", formats = { gemini-generate = \"http://g.test/v1beta\", openai-chat = \"http://g.test/v1beta/openai\" } } }\n",
1312        )
1313        .unwrap_or_else(|e| panic!("{e}"));
1314        let formats = config.providers["g"].formats.as_ref();
1315        assert_eq!(
1316            formats.map(Formats::names),
1317            Some(vec!["gemini-generate", "openai-chat"])
1318        );
1319        let url = formats.and_then(|f| f.url_of("openai-chat"));
1320        assert_eq!(url, Some("http://g.test/v1beta/openai"));
1321    }
1322
1323    #[test]
1324    fn proxy_is_one_provider_of_the_chat_format_and_passthrough_at_its_api_base() {
1325        let config = Config::proxy(ProxyVendor::OpenAi, Some("http://h.test/v1/"));
1326        let provider = &config.providers["openai"];
1327        assert_eq!(provider.base_url.as_deref(), Some("http://h.test/v1"));
1328        assert_eq!(
1329            provider.formats.as_ref().map(Formats::names),
1330            Some(vec!["openai-chat", "passthrough"])
1331        );
1332        assert!(config.relay);
1333        assert_eq!(config.source().to_string(), "proxy");
1334    }
1335}