1use 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#[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 #[serde(default)]
36 pub admin: Option<bool>,
37 #[serde(default)]
42 pub tools: Option<Vec<String>>,
43}
44
45impl 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 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#[derive(Clone, Debug, PartialEq, Deserialize)]
121#[serde(untagged)]
122pub enum Formats {
123 One(String),
125 Many(Vec<String>),
127 At(IndexMap<String, String>),
129}
130
131impl Formats {
132 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 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 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
162impl 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#[derive(Debug, Clone, Deserialize)]
187#[serde(deny_unknown_fields)]
188pub struct Config {
189 #[serde(default, deserialize_with = "listen_address")]
192 pub listen: Option<SocketAddr>,
193 #[serde(default, deserialize_with = "size")]
197 pub body_limit: Option<usize>,
198 #[serde(default, deserialize_with = "size")]
202 pub ws_message_limit: Option<usize>,
203 #[serde(default, deserialize_with = "models")]
208 pub models: IndexMap<String, Model>,
209 #[serde(default)]
211 pub prices: Option<serde::de::IgnoredAny>,
212 #[serde(default, deserialize_with = "span")]
216 pub shutdown_grace: Option<Duration>,
217 #[serde(default)]
222 pub client_keys: Vec<ClientKey>,
223 #[serde(default)]
226 pub log: LogFormat,
227 #[serde(default = "enabled")]
229 pub ui: bool,
230 #[serde(default)]
233 pub providers: IndexMap<String, ProviderConfig>,
234 pub formats: Option<Vec<String>>,
242 #[serde(default)]
248 pub routes: IndexMap<String, RouteConfig>,
249 #[serde(default)]
254 pub tools: IndexMap<String, McpConfig>,
255 #[serde(default)]
257 pub mcp: Option<serde::de::IgnoredAny>,
258 pub cors: Option<CorsConfig>,
260 #[serde(default)]
263 pub network: NetworkConfig,
264 #[serde(default)]
267 pub plugins: PluginsConfig,
268 #[serde(skip)]
269 pub(crate) source: Source,
270 #[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#[derive(Clone, Default, Deserialize)]
309#[serde(deny_unknown_fields)]
310pub struct ProviderConfig {
311 pub vendor: Option<String>,
313 #[serde(default)]
318 pub formats: Option<Formats>,
319 pub base_url: Option<String>,
323 pub key: Option<String>,
326 pub auth: Option<Auth>,
329 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 Bearer { key: String },
339 Header { name: String, key: String },
341}
342
343#[derive(Debug, Clone, Default, Deserialize)]
349#[serde(deny_unknown_fields)]
350pub struct PluginsConfig {
351 #[serde(default)]
354 pub routing: RoutingConfig,
355 #[serde(default)]
357 pub fallback: Option<serde::de::IgnoredAny>,
358 #[serde(default)]
360 pub hedge: Option<serde::de::IgnoredAny>,
361 pub tool_loop: Option<ToolLoopConfig>,
363 #[serde(default)]
369 pub responses: ResponsesConfig,
370 pub respan: Option<RespanConfig>,
372 #[serde(default)]
374 pub request_log: RequestLogConfig,
375}
376
377#[derive(Clone, Deserialize)]
379#[serde(deny_unknown_fields)]
380pub struct RespanConfig {
381 pub key: String,
383 pub url: Option<String>,
385 pub content: Option<bool>,
387 pub service: Option<String>,
389}
390
391impl 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#[derive(Debug, Clone, Deserialize)]
405#[serde(deny_unknown_fields)]
406pub struct ResponsesConfig {
407 #[serde(default = "enabled")]
409 pub enabled: bool,
410 #[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#[derive(Debug, Clone, Default, Deserialize)]
427#[serde(deny_unknown_fields)]
428pub struct RoutingConfig {
429 #[serde(default)]
431 pub models: Option<serde::de::IgnoredAny>,
432 pub default: Option<String>,
435 pub listings: Option<bool>,
439}
440
441#[derive(Debug, Clone, Deserialize)]
444#[serde(deny_unknown_fields)]
445pub struct RouteConfig {
446 #[serde(deserialize_with = "route_targets")]
450 pub to: Vec<RouteTarget>,
451 #[serde(default)]
455 pub pick: Pick,
456 #[serde(default)]
460 pub needs: Vec<String>,
461 #[serde(default)]
463 pub when: RouteWhen,
464 pub fallback: Option<bool>,
466 #[serde(default, deserialize_with = "span")]
469 pub hedge: Option<Duration>,
470 pub tries: Option<u32>,
472 #[serde(default, deserialize_with = "span")]
474 pub backoff: Option<Duration>,
475 #[serde(default, deserialize_with = "span")]
478 pub max_backoff: Option<Duration>,
479 #[serde(default)]
481 pub until: Commit,
482}
483
484#[derive(Debug, Clone, PartialEq, Eq)]
486pub struct RouteTarget {
487 pub target: String,
489 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#[derive(Debug, Clone, Default, Deserialize)]
533#[serde(deny_unknown_fields)]
534pub struct RouteWhen {
535 #[serde(default)]
537 pub clients: Vec<String>,
538 #[serde(default)]
540 pub kinds: Vec<String>,
541}
542
543#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
546#[serde(rename_all = "snake_case")]
547pub enum Commit {
548 #[default]
550 Head,
551 End,
553}
554
555#[derive(Debug, Clone, Default, Deserialize)]
557#[serde(deny_unknown_fields)]
558pub struct RequestLogConfig {
559 #[serde(default, deserialize_with = "request_log_history")]
562 pub history: Option<usize>,
563}
564
565#[derive(Debug, Clone, Deserialize)]
567#[serde(deny_unknown_fields)]
568pub struct CorsConfig {
569 pub origins: Vec<String>,
574}
575
576#[derive(Debug, Clone, Deserialize)]
580#[serde(deny_unknown_fields)]
581pub struct ToolLoopConfig {
582 pub servers: Option<Vec<String>>,
586 #[serde(default)]
590 pub allow: Vec<String>,
591 #[serde(default)]
593 pub deny: Vec<String>,
594 #[serde(default)]
597 pub models: Vec<String>,
598 pub max_steps: Option<u32>,
600 #[serde(default, deserialize_with = "span")]
602 pub timeout: Option<Duration>,
603 #[serde(default, deserialize_with = "span")]
605 pub tool_timeout: Option<Duration>,
606 #[serde(default, deserialize_with = "span")]
608 pub tool_list_ttl: Option<Duration>,
609 pub parallel: Option<usize>,
611 #[serde(default, deserialize_with = "size")]
614 pub max_result: Option<usize>,
615 #[serde(default, deserialize_with = "size")]
618 pub max_results: Option<usize>,
619}
620
621#[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
644pub enum ProxyVendor {
645 Anthropic,
646 OpenAi,
647}
648
649pub const DEFAULT_FILE: &str = "gateway.toml";
651
652impl Config {
653 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 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 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 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 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 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 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 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 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 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
792fn 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
814pub 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
825pub 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
868fn 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#[derive(Deserialize)]
893#[serde(untagged)]
894enum Number {
895 Count(u64),
896 Text(String),
897}
898
899fn 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
940fn 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
950pub 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}