1mod store;
4mod validation;
5mod workspace;
6
7use std::collections::{BTreeMap, BTreeSet};
8use std::env;
9use std::fs;
10use std::io::{Read as _, Write as _};
11use std::net::SocketAddr;
12#[cfg(unix)]
13use std::os::unix::fs::{OpenOptionsExt as _, PermissionsExt as _};
14use std::path::{Component, Path, PathBuf};
15use std::sync::Mutex;
16use std::time::{SystemTime, UNIX_EPOCH};
17
18use mobius::agent::DEFAULT_MAX_MODEL_STEPS;
19use mobius::backend::model::provider::{
20 ProviderAuth, ProviderDefinition, default_provider, provider,
21};
22use mobius::protocol::TokenUsage;
23use serde::{Deserialize, Serialize};
24use serde_json::Value;
25use sha2::Digest as _;
26
27use crate::wire::{
28 AgentComposition, DailyUsage, ProfileSnapshot, ProviderConfig, ProviderEndpointAuth,
29 ProviderTint, VersionedAgentConfig, WorkspaceInfo,
30};
31use crate::{Error, Result};
32
33use self::store::*;
34pub use self::store::{ConfigStore, CredentialStore, load_cloudflare_token, state_dir};
35pub use self::validation::validate_agent_composition;
36use self::validation::*;
37pub(crate) use self::validation::{effective_reasoning_effort, model_route_id};
38use self::workspace::*;
39pub(crate) use self::workspace::{
40 create_workspace_directory, local_user_name, prepare_background_workspace,
41};
42
43const CONFIG_VERSION: u32 = 23;
44const CHAT_SPEC_VERSION: u32 = 14;
45pub(crate) const CHAT_SPEC_METADATA_KEY: &str = "mobius_gateway.chat";
46const CONFIG_FILE: &str = "gateway.toml";
47const CLOUDFLARE_TOKEN_FILE: &str = "cloudflare-token";
48const MAX_CONFIG_BYTES: u64 = 1024 * 1024;
49const MAX_CREDENTIAL_STATE_BYTES: usize = 256 * 1024;
50const MAX_SYSTEM_PROMPT_BYTES: usize = 64 * 1024;
51pub(crate) const MAX_API_KEY_BYTES: usize = 16 * 1024;
52const MAX_PROVIDER_CATALOG_ENTRIES: usize = 64;
53const MAX_PROVIDER_CATALOG_ENTRY_BYTES: usize = 1024;
54const MAX_PROVIDER_CATALOG_BYTES: usize = 16 * 1024;
55const MAX_CUSTOM_MODEL_ROUTES: usize = 64;
56const MAX_CLOUDFLARE_TOKEN_BYTES: usize = 16 * 1024;
57const MAX_WORKSPACE_DIRECTORY_NAME_BYTES: usize = 255;
58const SECONDS_PER_DAY: u64 = 86_400;
59const USAGE_HISTORY_DAYS: u64 = 52 * 7;
60
61mod defaults {
62 include!(concat!(env!("OUT_DIR"), "/defaults.rs"));
63}
64
65pub const DEFAULT_LISTEN: SocketAddr =
67 SocketAddr::new(std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST), 8741);
68
69pub const DEFAULT_SYSTEM_PROMPT: &str = defaults::DEFAULT_SYSTEM_PROMPT;
71
72pub const DEFAULT_CONTEXT_WINDOW: i64 = defaults::DEFAULT_CONTEXT_WINDOW;
74
75#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
77#[serde(deny_unknown_fields)]
78pub struct TlsConfig {
79 pub certificate: PathBuf,
80 pub private_key: PathBuf,
81}
82
83#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
85#[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)]
86pub enum CloudflareConfig {
87 Quick,
89 Named { hostname: String },
91}
92
93#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
95#[serde(deny_unknown_fields)]
96pub struct GatewayConfig {
97 version: u32,
98 pub listen: SocketAddr,
99 pub tls: Option<TlsConfig>,
100 pub cloudflare: Option<CloudflareConfig>,
101 pub bot_defaults: Option<VersionedAgentConfig>,
102 pub(crate) configured_providers: BTreeMap<String, ConfiguredProvider>,
103 pub(crate) installed_extensions: BTreeMap<String, crate::extensions::InstalledExtension>,
104 usage: UsageHistory,
105}
106
107#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
109#[serde(deny_unknown_fields)]
110pub(crate) struct ConfiguredProvider {
111 pub(crate) selection: ProviderConfig,
112 pub(crate) label: String,
113 pub(crate) tint: ProviderTint,
114 pub(crate) model_ids: Vec<String>,
115 pub(crate) reasoning_efforts: Vec<String>,
116}
117
118#[derive(Debug, Clone, PartialEq, Eq)]
120pub(crate) struct ChatSpec {
121 version: u32,
122 pub(crate) workspace: PathBuf,
123 pub(crate) bot_id: String,
124 pub(crate) bot_description: String,
125 pub(crate) agent: VersionedAgentConfig,
126 pub(crate) catalog_visible: bool,
127}
128
129#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
130#[serde(deny_unknown_fields)]
131struct StoredChatSpec {
132 version: u32,
133 workspace: PathBuf,
134 bot_id: String,
135}
136
137impl Default for AgentComposition {
138 fn default() -> Self {
139 let provider = default_provider();
140 let model = provider
141 .default_model()
142 .and_then(|id| provider.model(id))
143 .expect("default model manifest");
144 Self {
145 provider: ProviderConfig {
146 instance: provider.id().into(),
147 provider: provider.id().into(),
148 model: model.id.into(),
149 base_url: provider.default_base_url().map(str::to_string),
150 endpoint_auth: ProviderEndpointAuth::ProviderDefault,
151 reasoning_effort: model.default_reasoning.map(str::to_string),
152 web_search: *provider
153 .web_search()
154 .first()
155 .expect("default provider web-search manifest"),
156 },
157 middleware: crate::middleware_manifest::default_config(),
158 extensions: BTreeSet::new(),
159 system_prompt: DEFAULT_SYSTEM_PROMPT.into(),
160 max_model_steps: DEFAULT_MAX_MODEL_STEPS as u64,
161 }
162 }
163}
164
165impl GatewayConfig {
166 pub fn new(listen: SocketAddr, tls: Option<TlsConfig>) -> Result<Self> {
168 let config = Self {
169 version: CONFIG_VERSION,
170 listen,
171 tls,
172 cloudflare: None,
173 bot_defaults: None,
174 configured_providers: BTreeMap::new(),
175 installed_extensions: BTreeMap::new(),
176 usage: UsageHistory::default(),
177 };
178 config.validate()?;
179 Ok(config)
180 }
181
182 pub fn new_cloudflare(listen: SocketAddr, cloudflare: CloudflareConfig) -> Result<Self> {
184 let mut config = Self::new(listen, None)?;
185 config.cloudflare = Some(cloudflare);
186 config.validate()?;
187 Ok(config)
188 }
189
190 pub(crate) fn registering_provider(
192 &self,
193 selection: ProviderConfig,
194 label: String,
195 tint: ProviderTint,
196 model_ids: Vec<String>,
197 reasoning_efforts: Vec<String>,
198 ) -> Result<Self> {
199 if let Some(configured) = self.configured_providers.get(&selection.instance)
200 && configured.selection.provider != selection.provider
201 {
202 return Err(Error::Config(format!(
203 "provider instance `{}` already belongs to `{}`",
204 selection.instance, configured.selection.provider
205 )));
206 }
207 let configured = ConfiguredProvider {
208 selection: selection.clone(),
209 label,
210 tint,
211 model_ids,
212 reasoning_efforts,
213 };
214 let mut next = self.clone();
215 next.configured_providers
216 .insert(selection.instance.clone(), configured);
217 if self.bot_defaults.is_none() {
218 let config = AgentComposition {
219 provider: selection,
220 ..AgentComposition::default()
221 };
222 next.bot_defaults = Some(VersionedAgentConfig {
223 revision: 1,
224 config,
225 });
226 }
227 next.validate()?;
228 Ok(next)
229 }
230
231 pub(crate) fn removing_provider(&self, instance: &str) -> Result<Self> {
233 if !self.configured_providers.contains_key(instance) {
234 return Err(Error::Config(format!(
235 "provider instance `{instance}` is not configured"
236 )));
237 }
238 if self
239 .bot_defaults
240 .as_ref()
241 .is_some_and(|default| default.config.provider.instance == instance)
242 {
243 return Err(Error::Config(
244 "choose another provider for Bot defaults before removing this provider".into(),
245 ));
246 }
247 let mut next = self.clone();
248 next.configured_providers.remove(instance);
249 let mut bot_defaults = next
250 .bot_defaults
251 .as_ref()
252 .expect("a removable provider cannot be the only configured provider")
253 .config
254 .clone();
255 if clear_missing_model_routes(&mut bot_defaults, &next)? {
256 let default = next
257 .bot_defaults
258 .as_mut()
259 .expect("a removable provider cannot be the only configured provider");
260 default.config = bot_defaults;
261 default.revision = default
262 .revision
263 .checked_add(1)
264 .ok_or_else(|| Error::Config("configuration revision overflow".into()))?;
265 }
266 next.validate()?;
267 Ok(next)
268 }
269
270 pub(crate) fn replacing_bot_defaults(
272 &self,
273 expected_revision: u64,
274 composition: AgentComposition,
275 ) -> Result<Self> {
276 let current = self
277 .bot_defaults
278 .as_ref()
279 .ok_or_else(|| Error::Config("configure a provider before saving defaults".into()))?;
280 if current.revision != expected_revision {
281 return Err(Error::Config(format!(
282 "configuration revision changed from {expected_revision} to {}",
283 current.revision
284 )));
285 }
286 let mut next = self.clone();
287 next.bot_defaults = Some(VersionedAgentConfig {
288 revision: current
289 .revision
290 .checked_add(1)
291 .ok_or_else(|| Error::Config("configuration revision overflow".into()))?,
292 config: composition,
293 });
294 next.validate()?;
295 Ok(next)
296 }
297
298 pub(crate) fn validate_provider_selection(&self, selection: &ProviderConfig) -> Result<()> {
299 validate_provider_config(selection)?;
300 let configured = self
301 .configured_providers
302 .get(&selection.instance)
303 .ok_or_else(|| {
304 Error::Config("provider selection must use a configured provider entry".into())
305 })?;
306 validate_configured_provider_selection(configured, selection)
307 }
308
309 pub fn observe_usage(&mut self, provider: &str, usage: &TokenUsage) -> Result<bool> {
311 self.usage.observe(provider, usage, SystemTime::now())
312 }
313
314 #[must_use]
316 pub fn profile(&self) -> ProfileSnapshot {
317 ProfileSnapshot {
318 user_name: local_user_name(),
319 daily_usage: self
320 .usage
321 .days
322 .iter()
323 .flat_map(|(unix_day, providers)| {
324 providers.iter().map(|(provider, usage)| DailyUsage {
325 unix_day: *unix_day,
326 provider: provider.clone(),
327 usage: usage.clone(),
328 })
329 })
330 .collect(),
331 run_stats: crate::wire::RunStats::default(),
332 recent_run_groups: Vec::new(),
333 }
334 }
335
336 pub fn validate(&self) -> Result<()> {
338 if self.version != CONFIG_VERSION {
339 return Err(Error::Config(format!(
340 "unsupported gateway config version {}",
341 self.version
342 )));
343 }
344 if self.listen.port() == 0 {
345 return Err(Error::Config(
346 "gateway listen port must be greater than zero".into(),
347 ));
348 }
349 match (&self.tls, self.listen.ip().is_loopback()) {
350 (None, false) => {
351 return Err(Error::Config(
352 "non-loopback gateway listeners require a TLS certificate and private key"
353 .into(),
354 ));
355 }
356 (Some(tls), _) => tls.validate()?,
357 (None, true) => {}
358 }
359 if self.cloudflare.is_some() && (!self.listen.ip().is_loopback() || self.tls.is_some()) {
360 return Err(Error::Config(
361 "Cloudflare gateways require a plaintext loopback listener".into(),
362 ));
363 }
364 if let Some(cloudflare) = &self.cloudflare {
365 cloudflare.validate()?;
366 }
367 if self.configured_providers.is_empty() != self.bot_defaults.is_none() {
368 return Err(Error::Config(
369 "Bot defaults must exist exactly when a provider is configured".into(),
370 ));
371 }
372 for (instance, configured) in &self.configured_providers {
373 if instance != &configured.selection.instance {
374 return Err(Error::Config(format!(
375 "configured provider key `{instance}` does not match `{}`",
376 configured.selection.instance
377 )));
378 }
379 validate_configured_provider(configured)?;
380 }
381 crate::extensions::validate_installed(&self.installed_extensions)?;
382 validate_custom_model_route_count(&self.configured_providers)?;
383 if let Some(default) = &self.bot_defaults {
384 if default.revision == 0 {
385 return Err(Error::Config(
386 "configuration revision must be positive".into(),
387 ));
388 }
389 validate_agent_composition(&default.config)?;
390 self.validate_provider_selection(&default.config.provider)?;
391 for (middleware, setting, route) in
392 crate::middleware_manifest::configured_model_routes(&default.config.middleware)
393 {
394 if !crate::provider_catalog::configured_route_exists(self, route)? {
395 return Err(Error::Config(format!(
396 "Bot default middleware setting `{middleware}.{setting}` is not a configured model route"
397 )));
398 }
399 }
400 }
401 for providers in self.usage.days.values() {
402 for (provider, usage) in providers {
403 validate_usage_provider(provider)?;
404 validate_usage(usage)?;
405 }
406 }
407 Ok(())
408 }
409}
410
411impl ChatSpec {
412 pub(crate) fn for_bot(
413 workspace: &Path,
414 bot: &crate::wire::BotRecord,
415 state_dir: &Path,
416 tls: Option<&TlsConfig>,
417 ) -> Result<Self> {
418 let spec = Self {
419 version: CHAT_SPEC_VERSION,
420 workspace: validate_chat_workspace(workspace, state_dir, tls)?,
421 bot_id: bot.id.clone(),
422 bot_description: bot.description.clone(),
423 agent: bot.config.clone(),
424 catalog_visible: true,
425 };
426 spec.validate(state_dir, tls)?;
427 Ok(spec)
428 }
429
430 pub(crate) fn from_metadata(
431 metadata: &BTreeMap<String, Value>,
432 bots: &crate::bots::BotStore,
433 state_dir: &Path,
434 tls: Option<&TlsConfig>,
435 ) -> Result<Self> {
436 Self::from_metadata_if_present(metadata, bots, state_dir, tls)?.ok_or_else(|| {
437 Error::Config("chat checkpoint has no gateway runtime configuration".into())
438 })
439 }
440
441 pub(crate) fn from_metadata_if_present(
442 metadata: &BTreeMap<String, Value>,
443 bots: &crate::bots::BotStore,
444 state_dir: &Path,
445 tls: Option<&TlsConfig>,
446 ) -> Result<Option<Self>> {
447 let Some(value) = metadata.get(CHAT_SPEC_METADATA_KEY) else {
448 return Ok(None);
449 };
450 let stored: StoredChatSpec = serde_json::from_value(value.clone())?;
451 let bot = bots.bot(&stored.bot_id)?;
452 let spec = Self {
453 version: stored.version,
454 workspace: stored.workspace,
455 bot_id: bot.id,
456 bot_description: bot.description,
457 agent: bot.config,
458 catalog_visible: true,
459 };
460 spec.validate(state_dir, tls)?;
461 Ok(Some(spec))
462 }
463
464 pub(crate) fn metadata(&self) -> Result<BTreeMap<String, Value>> {
465 Ok(BTreeMap::from([(
466 CHAT_SPEC_METADATA_KEY.into(),
467 serde_json::to_value(StoredChatSpec {
468 version: self.version,
469 workspace: self.workspace.clone(),
470 bot_id: self.bot_id.clone(),
471 })?,
472 )]))
473 }
474
475 #[must_use]
476 pub(crate) fn workspace_info(&self) -> WorkspaceInfo {
477 WorkspaceInfo {
478 id: workspace_id(&self.workspace),
479 path: self.workspace.clone(),
480 }
481 }
482
483 fn validate(&self, state_dir: &Path, tls: Option<&TlsConfig>) -> Result<()> {
484 if self.version != CHAT_SPEC_VERSION {
485 return Err(Error::Config(format!(
486 "unsupported chat configuration version {}",
487 self.version
488 )));
489 }
490 if self.agent.revision == 0 {
491 return Err(Error::Config(
492 "chat configuration revision must be positive".into(),
493 ));
494 }
495 if self.bot_id.is_empty() || self.bot_description.trim().is_empty() {
496 return Err(Error::Config("chat Bot ownership is invalid".into()));
497 }
498 let workspace = validate_chat_workspace(&self.workspace, state_dir, tls)?;
499 if workspace != self.workspace {
500 return Err(Error::Config(
501 "chat workspace must use its canonical path".into(),
502 ));
503 }
504 validate_agent_composition(&self.agent.config)
505 }
506}
507
508fn clear_missing_model_routes(
509 composition: &mut AgentComposition,
510 gateway: &GatewayConfig,
511) -> Result<bool> {
512 let routes = crate::middleware_manifest::configured_model_routes(&composition.middleware)
513 .into_iter()
514 .map(|(middleware, setting, route)| {
515 (middleware.to_owned(), setting.to_owned(), route.to_owned())
516 })
517 .collect::<Vec<_>>();
518 let mut changed = false;
519 for (middleware, setting, route) in routes {
520 if !crate::provider_catalog::configured_route_exists(gateway, &route)? {
521 composition
522 .middleware
523 .set_setting(middleware, setting, None);
524 changed = true;
525 }
526 }
527 Ok(changed)
528}
529
530impl TlsConfig {
531 fn validate(&self) -> Result<()> {
532 for (name, path) in [
533 ("TLS certificate", &self.certificate),
534 ("TLS private key", &self.private_key),
535 ] {
536 if !path.is_absolute() || !path.is_file() {
537 return Err(Error::Config(format!(
538 "{name} must be an existing absolute file"
539 )));
540 }
541 }
542 Ok(())
543 }
544}
545
546impl CloudflareConfig {
547 pub fn named(hostname: &str) -> Result<Self> {
549 let hostname = hostname.trim().to_ascii_lowercase();
550 let config = Self::Named { hostname };
551 config.validate()?;
552 Ok(config)
553 }
554
555 #[must_use]
557 pub fn endpoint(&self) -> Option<String> {
558 self.hostname().map(|hostname| format!("wss://{hostname}"))
559 }
560
561 #[must_use]
563 pub fn hostname(&self) -> Option<&str> {
564 match self {
565 Self::Quick => None,
566 Self::Named { hostname } => Some(hostname),
567 }
568 }
569
570 pub fn validate_token(token: &str) -> Result<()> {
572 validate_cloudflare_token(token).map(|_| ())
573 }
574
575 fn validate(&self) -> Result<()> {
576 if let Self::Named { hostname } = self
577 && (hostname.len() > 253
578 || !hostname.is_ascii()
579 || hostname != &hostname.to_ascii_lowercase()
580 || !hostname.contains('.')
581 || !hostname.split('.').all(valid_hostname_label))
582 {
583 return Err(invalid_cloudflare_hostname());
584 }
585 Ok(())
586 }
587}
588
589#[cfg(test)]
590mod tests;