Skip to main content

modelexpress_server/
config.rs

1// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4use clap::Parser;
5use config::ConfigError;
6use modelexpress_common::config::{LogFormat, LogLevel, load_layered_config};
7use serde::{Deserialize, Serialize};
8use std::net::SocketAddr;
9use std::num::NonZeroU16;
10use std::path::PathBuf;
11use tracing::Level;
12
13use crate::cache::CacheEvictionConfig;
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum, Default)]
16#[serde(rename_all = "lowercase")]
17pub enum AuthMode {
18    #[default]
19    Off,
20    Enforce,
21}
22
23/// A `<namespace>:<serviceaccount>` pair, parsed from `ns:sa`.
24#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
25pub struct ServiceAccountRef {
26    pub namespace: String,
27    pub service_account: String,
28}
29
30impl std::fmt::Display for ServiceAccountRef {
31    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32        write!(f, "{}:{}", self.namespace, self.service_account)
33    }
34}
35
36impl std::str::FromStr for ServiceAccountRef {
37    type Err = String;
38
39    fn from_str(s: &str) -> Result<Self, Self::Err> {
40        let (namespace, service_account) = s
41            .split_once(':')
42            .ok_or_else(|| format!("expected '<namespace>:<serviceaccount>', got '{s}'"))?;
43        let namespace = namespace.trim();
44        let service_account = service_account.trim();
45        if namespace.is_empty() || service_account.is_empty() {
46            return Err(format!(
47                "namespace and service account must both be non-empty in '{s}'"
48            ));
49        }
50        Ok(Self {
51            namespace: namespace.to_string(),
52            service_account: service_account.to_string(),
53        })
54    }
55}
56
57/// Comma-separated CLI/env list of `T`, ignoring blank entries.
58#[derive(Debug, Clone)]
59pub struct CommaList<T>(Vec<T>);
60
61impl<T> CommaList<T> {
62    #[must_use]
63    pub fn into_inner(self) -> Vec<T> {
64        self.0
65    }
66}
67
68impl<T: std::str::FromStr> std::str::FromStr for CommaList<T> {
69    type Err = T::Err;
70
71    fn from_str(s: &str) -> Result<Self, Self::Err> {
72        let items = s
73            .split(',')
74            .map(str::trim)
75            .filter(|part| !part.is_empty())
76            .map(T::from_str)
77            .collect::<Result<Vec<_>, _>>()?;
78        Ok(Self(items))
79    }
80}
81
82#[derive(Debug, Clone, Serialize, Deserialize)]
83#[serde(default)]
84pub struct SecurityConfig {
85    pub mode: Option<AuthMode>,
86    pub token_audiences: Vec<String>,
87    pub allowed_service_accounts: Vec<ServiceAccountRef>,
88    pub cache_ttl_secs: u64,
89}
90
91impl Default for SecurityConfig {
92    fn default() -> Self {
93        Self {
94            mode: None,
95            token_audiences: Vec::new(),
96            allowed_service_accounts: Vec::new(),
97            cache_ttl_secs: 60,
98        }
99    }
100}
101
102impl SecurityConfig {
103    #[must_use]
104    pub fn resolve_mode(&self) -> AuthMode {
105        self.mode.unwrap_or(AuthMode::Off)
106    }
107
108    pub fn validate_resolved(&self, mode: AuthMode) -> Result<(), String> {
109        if mode == AuthMode::Enforce {
110            if self.token_audiences.is_empty() {
111                return Err(
112                    "security mode 'enforce' requires at least one token audience \
113                    (security.token_audiences)"
114                        .to_string(),
115                );
116            }
117            if self.allowed_service_accounts.is_empty() {
118                return Err(
119                    "security mode 'enforce' requires a non-empty service account \
120                    allowlist (security.allowed_service_accounts)"
121                        .to_string(),
122                );
123            }
124        }
125        Ok(())
126    }
127}
128
129#[derive(clap::Args, Debug, Default)]
130pub struct SecurityArgs {
131    /// ServiceAccount auth mode (off, enforce). Off by default.
132    #[arg(
133        long = "security-mode",
134        env = modelexpress_common::envs::MODEL_EXPRESS_SECURITY_MODE,
135        value_enum
136    )]
137    pub mode: Option<AuthMode>,
138
139    /// Comma-separated SA token audiences the caller's token must carry.
140    #[arg(
141        long = "security-token-audiences",
142        env = modelexpress_common::envs::MODEL_EXPRESS_SECURITY_TOKEN_AUDIENCES
143    )]
144    pub token_audiences: Option<CommaList<String>>,
145
146    /// Comma-separated allowed callers as `<namespace>:<serviceaccount>`.
147    #[arg(
148        long = "security-allowed-service-accounts",
149        env = modelexpress_common::envs::MODEL_EXPRESS_SECURITY_ALLOWED_SERVICE_ACCOUNTS
150    )]
151    pub allowed_service_accounts: Option<CommaList<ServiceAccountRef>>,
152
153    /// TTL for the verified-token and rejection caches, in seconds.
154    #[arg(
155        long = "security-cache-ttl-secs",
156        env = modelexpress_common::envs::MODEL_EXPRESS_SECURITY_CACHE_TTL_SECS
157    )]
158    pub cache_ttl_secs: Option<u64>,
159}
160
161/// Command line arguments for the server
162#[derive(Parser, Debug)]
163#[command(author, version, about, long_about = None)]
164pub struct ServerArgs {
165    /// Configuration file path
166    #[arg(short, long, value_name = "FILE")]
167    pub config: Option<PathBuf>,
168
169    /// Server port
170    #[arg(short, long, env = modelexpress_common::envs::MODEL_EXPRESS_SERVER_PORT)]
171    pub port: Option<NonZeroU16>,
172
173    /// Server host address
174    #[arg(long, env = modelexpress_common::envs::MODEL_EXPRESS_SERVER_HOST)]
175    pub host: Option<String>,
176
177    // This clap override is the ONLY path that reaches
178    // `ServerSettings::metrics_port`. The layered config loader builds its
179    // environment source as
180    // `Environment::with_prefix("MODEL_EXPRESS").separator("_")`, so
181    // `MODEL_EXPRESS_SERVER_METRICS_PORT` resolves to the key path
182    // `server.metrics.port`, matches no field, and is dropped by serde without a
183    // warning. Do not "simplify" this by deleting the override. Kept as a plain
184    // comment rather than a doc comment so it stays out of `--help`.
185    /// Prometheus `/metrics` port. `0` disables the metrics listener.
186    #[arg(long, env = modelexpress_common::envs::MODEL_EXPRESS_SERVER_METRICS_PORT)]
187    pub metrics_port: Option<u16>,
188
189    /// Log level
190    #[arg(short, long, env = modelexpress_common::envs::MODEL_EXPRESS_LOG_LEVEL, value_enum)]
191    pub log_level: Option<LogLevel>,
192
193    /// Log format
194    #[arg(long, env = modelexpress_common::envs::MODEL_EXPRESS_LOG_FORMAT, value_enum)]
195    pub log_format: Option<LogFormat>,
196
197    /// Cache directory path
198    #[arg(long, env = modelexpress_common::envs::MODEL_EXPRESS_CACHE_DIRECTORY)]
199    pub cache_directory: Option<PathBuf>,
200
201    /// Enable cache eviction
202    #[arg(long, env = modelexpress_common::envs::MODEL_EXPRESS_CACHE_EVICTION_ENABLED)]
203    pub cache_eviction_enabled: Option<bool>,
204
205    #[command(flatten)]
206    pub security: SecurityArgs,
207
208    /// Validate configuration and exit
209    #[arg(long)]
210    pub validate_config: bool,
211}
212
213/// Complete server configuration
214#[derive(Debug, Clone, Serialize, Deserialize, Default)]
215pub struct ServerConfig {
216    /// Server settings
217    pub server: ServerSettings,
218    /// Cache configuration
219    pub cache: CacheConfig,
220    /// Logging configuration
221    pub logging: LoggingConfig,
222    #[serde(default)]
223    pub security: SecurityConfig,
224}
225
226/// Server-specific settings
227#[derive(Debug, Clone, Serialize, Deserialize)]
228pub struct ServerSettings {
229    /// Server host address
230    pub host: String,
231    /// Server port
232    pub port: NonZeroU16,
233    /// Prometheus `/metrics` port. `0` disables the listener.
234    ///
235    /// Two properties here are load-bearing, and both exist because
236    /// `load_layered_config` swallows any deserialization error and silently
237    /// returns `T::default()` — so anything this field rejects is not "the
238    /// field is ignored" but "the entire config file is ignored", with no log
239    /// line at any level. The gRPC port, cache directory, eviction policy and
240    /// **auth settings** would all revert to defaults because of a typo here.
241    ///
242    /// 1. `#[serde(default)]` covers the missing-key case. `ServerSettings` has
243    ///    no struct-level default, so without it every existing
244    ///    `model-express.yaml` — none of which mention this field — would fail
245    ///    to parse.
246    /// 2. The type is `u16`, not `NonZeroU16`. `0` is the documented disable
247    ///    value, and `NonZeroU16` rejects it during deserialization, which is
248    ///    exactly the silent-total-fallback case above. Normalization to
249    ///    "disabled" happens in [`ServerConfig::metrics_socket_addr`].
250    #[serde(default = "default_metrics_port")]
251    pub metrics_port: u16,
252}
253
254/// Serde default for [`ServerSettings::metrics_port`]. Server metrics are on by
255/// default; the client's stay opt-in.
256fn default_metrics_port() -> u16 {
257    modelexpress_common::constants::DEFAULT_METRICS_PORT.get()
258}
259
260/// Cache configuration wrapper
261#[derive(Debug, Clone, Serialize, Deserialize)]
262pub struct CacheConfig {
263    /// Cache eviction settings
264    pub eviction: CacheEvictionConfig,
265    /// Cache directory path
266    pub directory: PathBuf,
267    /// Maximum cache size in bytes
268    pub max_size_bytes: Option<u64>,
269}
270
271/// Logging configuration
272#[derive(Debug, Clone, Serialize, Deserialize, Default)]
273pub struct LoggingConfig {
274    /// Log level
275    #[serde(default)]
276    pub level: LogLevel,
277    /// Log format (json, pretty, compact)
278    #[serde(default)]
279    pub format: LogFormat,
280    /// Log to file
281    pub file: Option<PathBuf>,
282    /// Enable structured logging
283    pub structured: bool,
284}
285
286impl Default for ServerSettings {
287    fn default() -> Self {
288        Self {
289            host: "0.0.0.0".to_string(),
290            port: modelexpress_common::constants::DEFAULT_GRPC_PORT,
291            metrics_port: default_metrics_port(),
292        }
293    }
294}
295
296impl Default for CacheConfig {
297    fn default() -> Self {
298        Self {
299            eviction: CacheEvictionConfig::default(),
300            directory: PathBuf::from("./cache"),
301            max_size_bytes: None,
302        }
303    }
304}
305
306impl ServerConfig {
307    /// Load configuration from multiple sources in order of precedence:
308    /// 1. Command line arguments (highest priority)
309    /// 2. Environment variables
310    /// 3. Configuration file
311    /// 4. Default values (lowest priority)
312    pub fn load(args: ServerArgs) -> Result<Self, ConfigError> {
313        Self::load_internal(args, false)
314    }
315
316    /// Load and validate configuration file strictly without fallbacks.
317    /// This method should be used when validating configuration files.
318    /// It will return an error if the file has invalid syntax or values.
319    pub fn load_and_validate_strict(args: ServerArgs) -> Result<Self, ConfigError> {
320        Self::load_internal(args, true)
321    }
322
323    /// Internal method to load configuration with optional strict mode
324    fn load_internal(args: ServerArgs, strict_mode: bool) -> Result<Self, ConfigError> {
325        let mut config = if strict_mode {
326            // Use strict loading - fail on any configuration errors
327            if let Some(ref config_file) = args.config {
328                // Load file strictly without fallbacks
329                modelexpress_common::config::validate_config_file(config_file)?
330            } else {
331                // No config file specified, use defaults
332                Self::default()
333            }
334        } else {
335            // Use layered config loading with fallbacks to defaults
336            load_layered_config(
337                args.config.clone(),
338                modelexpress_common::envs::MODEL_EXPRESS_PREFIX,
339                Self::default(),
340            )?
341        };
342
343        // Apply command line overrides (same for both modes)
344        if let Some(port) = args.port {
345            config.server.port = port;
346        }
347
348        if let Some(host) = args.host {
349            config.server.host = host;
350        }
351
352        // `0` is the documented "off" value. Env-only deployments (Helm) have no
353        // other way to turn the listener off.
354        if let Some(metrics_port) = args.metrics_port {
355            config.server.metrics_port = metrics_port;
356        }
357
358        if let Some(log_level) = args.log_level {
359            config.logging.level = log_level;
360        }
361
362        if let Some(log_format) = args.log_format {
363            config.logging.format = log_format;
364        }
365
366        // Apply cache overrides
367        if let Some(cache_directory) = args.cache_directory {
368            config.cache.directory = cache_directory;
369        }
370
371        if let Some(cache_eviction_enabled) = args.cache_eviction_enabled {
372            config.cache.eviction.enabled = cache_eviction_enabled;
373        }
374
375        // Apply security overrides
376        if let Some(mode) = args.security.mode {
377            config.security.mode = Some(mode);
378        }
379        if let Some(token_audiences) = args.security.token_audiences {
380            config.security.token_audiences = token_audiences.into_inner();
381        }
382        if let Some(allowed) = args.security.allowed_service_accounts {
383            config.security.allowed_service_accounts = allowed.into_inner();
384        }
385        if let Some(cache_ttl_secs) = args.security.cache_ttl_secs {
386            config.security.cache_ttl_secs = cache_ttl_secs;
387        }
388
389        // Validate the final configuration
390        config.validate()?;
391
392        Ok(config)
393    }
394
395    /// Validate the configuration
396    pub fn validate(&self) -> Result<(), ConfigError> {
397        // Validate cache directory
398        if let Some(parent) = self.cache.directory.parent()
399            && !parent.exists()
400        {
401            return Err(ConfigError::Message(format!(
402                "Cache directory parent does not exist: {}",
403                parent.display()
404            )));
405        }
406
407        let mode = self.security.resolve_mode();
408        self.security
409            .validate_resolved(mode)
410            .map_err(ConfigError::Message)?;
411
412        Ok(())
413    }
414
415    /// Get the server socket address
416    pub fn socket_addr(&self) -> Result<SocketAddr, ConfigError> {
417        let addr = format!("{}:{}", self.server.host, self.server.port);
418        addr.parse()
419            .map_err(|e| ConfigError::Message(format!("Invalid server address {addr}: {e}")))
420    }
421
422    /// Socket address for the Prometheus `/metrics` listener, or `None` when
423    /// metrics are disabled.
424    ///
425    /// # Errors
426    /// Returns an error when host and metrics port do not form a valid address.
427    pub fn metrics_socket_addr(&self) -> Result<Option<SocketAddr>, ConfigError> {
428        // `0` is the disable sentinel. Normalizing here rather than in the field
429        // type keeps `0` deserializable from a config file; see
430        // `ServerSettings::metrics_port`.
431        let Some(metrics_port) = NonZeroU16::new(self.server.metrics_port) else {
432            return Ok(None);
433        };
434        let addr = format!("{}:{}", self.server.host, metrics_port);
435        addr.parse()
436            .map(Some)
437            .map_err(|e| ConfigError::Message(format!("Invalid metrics address {addr}: {e}")))
438    }
439
440    /// Get the logging level as a tracing Level
441    pub fn log_level(&self) -> Level {
442        self.logging.level.into()
443    }
444
445    /// Print the configuration for debugging
446    pub fn print_config(&self) {
447        use tracing::info;
448
449        info!("Server Configuration:");
450        info!("  Host: {}", self.server.host);
451        info!("  Port: {}", self.server.port);
452        match NonZeroU16::new(self.server.metrics_port) {
453            Some(port) => info!("  Metrics Port: {port} (/metrics)"),
454            None => info!("  Metrics Port: disabled"),
455        }
456
457        info!("Cache Configuration:");
458        info!("  Directory: {}", self.cache.directory.display());
459        info!("  Max Size: {:?}", self.cache.max_size_bytes);
460        info!("  Eviction Enabled: {}", self.cache.eviction.enabled);
461        info!(
462            "  Eviction Check Interval: {}s",
463            self.cache.eviction.check_interval.num_seconds()
464        );
465
466        info!("Logging Configuration:");
467        info!("  Level: {}", self.logging.level);
468        info!("  Format: {}", self.logging.format);
469        info!("  File: {:?}", self.logging.file);
470        info!("  Structured: {}", self.logging.structured);
471
472        info!("Security Configuration:");
473        info!("  Mode: {:?}", self.security.resolve_mode());
474        info!("  Token audiences: {:?}", self.security.token_audiences);
475        info!(
476            "  Allowed service accounts: {}",
477            self.security
478                .allowed_service_accounts
479                .iter()
480                .map(ToString::to_string)
481                .collect::<Vec<_>>()
482                .join(", ")
483        );
484        info!("  Cache TTL: {}s", self.security.cache_ttl_secs);
485    }
486}
487
488#[cfg(test)]
489mod tests {
490    use super::*;
491    use chrono::Duration;
492    use clap::Parser;
493    use modelexpress_common::config::{DurationConfig, parse_duration_string};
494    use std::fs;
495    use tempfile::tempdir;
496
497    #[test]
498    fn test_log_level_enum_parsing() {
499        // Test valid log levels
500        let valid_levels = [
501            ("trace", LogLevel::Trace),
502            ("debug", LogLevel::Debug),
503            ("info", LogLevel::Info),
504            ("warn", LogLevel::Warn),
505            ("error", LogLevel::Error),
506        ];
507
508        for (level_str, expected_level) in &valid_levels {
509            let args = vec!["test", "--log-level", level_str];
510            if let Ok(parsed_args) = ServerArgs::try_parse_from(args) {
511                assert_eq!(parsed_args.log_level, Some(*expected_level));
512
513                // Test conversion to string
514                assert_eq!(expected_level.to_string(), *level_str);
515
516                // Test conversion to tracing::Level
517                let tracing_level: Level = (*expected_level).into();
518                // Just verify the conversion works - the exact debug format may vary
519                match expected_level {
520                    LogLevel::Trace => assert_eq!(tracing_level, Level::TRACE),
521                    LogLevel::Debug => assert_eq!(tracing_level, Level::DEBUG),
522                    LogLevel::Info => assert_eq!(tracing_level, Level::INFO),
523                    LogLevel::Warn => assert_eq!(tracing_level, Level::WARN),
524                    LogLevel::Error => assert_eq!(tracing_level, Level::ERROR),
525                }
526            } else {
527                panic!("Failed to parse valid log level: {level_str}");
528            }
529        }
530    }
531
532    #[test]
533    fn test_log_level_enum_invalid() {
534        // Test invalid log level
535        let args = vec!["test", "--log-level", "invalid"];
536        let result = ServerArgs::try_parse_from(args);
537        assert!(result.is_err());
538    }
539
540    #[test]
541    fn test_log_level_display() {
542        assert_eq!(LogLevel::Trace.to_string(), "trace");
543        assert_eq!(LogLevel::Debug.to_string(), "debug");
544        assert_eq!(LogLevel::Info.to_string(), "info");
545        assert_eq!(LogLevel::Warn.to_string(), "warn");
546        assert_eq!(LogLevel::Error.to_string(), "error");
547    }
548
549    #[test]
550    #[allow(clippy::expect_used)]
551    fn test_log_level_from_str() {
552        assert_eq!(
553            "trace"
554                .parse::<LogLevel>()
555                .expect("Failed to parse 'trace'"),
556            LogLevel::Trace
557        );
558        assert_eq!(
559            "debug"
560                .parse::<LogLevel>()
561                .expect("Failed to parse 'debug'"),
562            LogLevel::Debug
563        );
564        assert_eq!(
565            "info".parse::<LogLevel>().expect("Failed to parse 'info'"),
566            LogLevel::Info
567        );
568        assert_eq!(
569            "warn".parse::<LogLevel>().expect("Failed to parse 'warn'"),
570            LogLevel::Warn
571        );
572        assert_eq!(
573            "error"
574                .parse::<LogLevel>()
575                .expect("Failed to parse 'error'"),
576            LogLevel::Error
577        );
578
579        // Test case insensitive
580        assert_eq!(
581            "TRACE"
582                .parse::<LogLevel>()
583                .expect("Failed to parse 'TRACE'"),
584            LogLevel::Trace
585        );
586        assert_eq!(
587            "Info".parse::<LogLevel>().expect("Failed to parse 'Info'"),
588            LogLevel::Info
589        );
590
591        // Test invalid
592        assert!("invalid".parse::<LogLevel>().is_err());
593    }
594
595    #[test]
596    fn test_log_format_display() {
597        assert_eq!(LogFormat::Json.to_string(), "json");
598        assert_eq!(LogFormat::Pretty.to_string(), "pretty");
599        assert_eq!(LogFormat::Compact.to_string(), "compact");
600    }
601
602    #[test]
603    #[allow(clippy::expect_used)]
604    fn test_log_format_from_str() {
605        assert_eq!(
606            "json".parse::<LogFormat>().expect("Failed to parse 'json'"),
607            LogFormat::Json
608        );
609        assert_eq!(
610            "pretty"
611                .parse::<LogFormat>()
612                .expect("Failed to parse 'pretty'"),
613            LogFormat::Pretty
614        );
615        assert_eq!(
616            "compact"
617                .parse::<LogFormat>()
618                .expect("Failed to parse 'compact'"),
619            LogFormat::Compact
620        );
621
622        // Test case insensitive
623        assert_eq!(
624            "JSON".parse::<LogFormat>().expect("Failed to parse 'JSON'"),
625            LogFormat::Json
626        );
627        assert_eq!(
628            "Pretty"
629                .parse::<LogFormat>()
630                .expect("Failed to parse 'Pretty'"),
631            LogFormat::Pretty
632        );
633
634        // Test invalid
635        assert!("invalid".parse::<LogFormat>().is_err());
636    }
637
638    #[test]
639    #[allow(clippy::expect_used)]
640    fn test_parse_duration_string() {
641        // Test various duration formats
642        assert_eq!(
643            parse_duration_string("30m")
644                .expect("Failed to parse 30m")
645                .num_seconds(),
646            30 * 60
647        );
648        assert_eq!(
649            parse_duration_string("45s")
650                .expect("Failed to parse 45s")
651                .num_seconds(),
652            45
653        );
654        assert_eq!(
655            parse_duration_string("1d")
656                .expect("Failed to parse 1d")
657                .num_seconds(),
658            24 * 3600
659        );
660        assert_eq!(
661            parse_duration_string("2h")
662                .expect("Failed to parse 2h")
663                .num_seconds(),
664            2 * 3600
665        );
666        assert_eq!(
667            parse_duration_string("2h30m")
668                .expect("Failed to parse 2h30m")
669                .num_seconds(),
670            2 * 3600 + 30 * 60
671        );
672
673        // Test invalid format
674        assert!(parse_duration_string("invalid").is_err());
675    }
676
677    #[test]
678    fn test_duration_config() {
679        // Test creation
680        let duration_config = DurationConfig::new(Duration::hours(2));
681        assert_eq!(duration_config.num_seconds(), 2 * 3600);
682        assert_eq!(duration_config.as_chrono_duration(), Duration::hours(2));
683
684        // Test hours constructor
685        let duration_config = DurationConfig::hours(3);
686        assert_eq!(duration_config.num_seconds(), 3 * 3600);
687
688        // Test display
689        assert_eq!(duration_config.to_string(), "10800s");
690    }
691
692    #[test]
693    #[allow(clippy::expect_used)]
694    fn test_duration_config_serde() {
695        // Test deserializing from string
696        let json = r#""2h""#;
697        let duration_config: DurationConfig = serde_json::from_str(json).expect("Failed to parse");
698        assert_eq!(duration_config.num_seconds(), 2 * 3600);
699
700        // Test deserializing from number (seconds)
701        let json = r#"3600"#;
702        let duration_config: DurationConfig = serde_json::from_str(json).expect("Failed to parse");
703        assert_eq!(duration_config.num_seconds(), 3600);
704
705        // Test serializing (it should serialize as just the number)
706        let duration_config = DurationConfig::hours(1);
707        let serialized = serde_json::to_string(&duration_config).expect("Failed to serialize");
708        assert_eq!(serialized, r#"3600"#);
709    }
710
711    #[test]
712    #[allow(clippy::expect_used)]
713    fn test_server_config_load_and_validate_strict_valid_config() {
714        let temp_dir = tempdir().expect("Failed to create temp dir");
715        let config_file = temp_dir.path().join("valid_server_config.yaml");
716
717        let valid_config = r#"
718            server:
719              host: "127.0.0.1"
720              port: 8002
721            cache:
722              eviction:
723                enabled: false
724                policy:
725                  type: lru
726                  unused_threshold: "3d"
727                  max_models: 10
728                  min_free_space_bytes: 1000000
729                check_interval: "30m"
730              directory: "./test_cache"
731              max_size_bytes: 5000000
732            logging:
733              level: Debug
734              format: Json
735              file: null
736              structured: true
737        "#;
738
739        fs::write(&config_file, valid_config).expect("Failed to write config file");
740
741        let args = ServerArgs {
742            config: Some(config_file),
743            port: None,
744            host: None,
745            metrics_port: None,
746            log_level: None,
747            log_format: None,
748            cache_directory: None,
749            cache_eviction_enabled: None,
750            security: SecurityArgs::default(),
751            validate_config: false,
752        };
753
754        let result = ServerConfig::load_and_validate_strict(args);
755        assert!(result.is_ok());
756
757        let config = result.expect("Expected successful config parsing");
758        assert_eq!(config.server.host, "127.0.0.1");
759        assert_eq!(config.server.port.get(), 8002);
760        assert!(!config.cache.eviction.enabled);
761        assert_eq!(config.logging.level, LogLevel::Debug);
762        assert_eq!(config.logging.format, LogFormat::Json);
763    }
764
765    #[test]
766    #[allow(clippy::expect_used)]
767    fn test_server_config_load_and_validate_strict_invalid_config() {
768        let temp_dir = tempdir().expect("Failed to create temp dir");
769        let config_file = temp_dir.path().join("invalid_server_config.yaml");
770
771        let invalid_config = r#"
772            server:
773              host: "127.0.0.1"
774              port: 8002
775            cache:
776              eviction:
777                enabled: "not_a_boolean"  # Invalid type
778        "#;
779
780        fs::write(&config_file, invalid_config).expect("Failed to write config file");
781
782        let args = ServerArgs {
783            config: Some(config_file),
784            port: None,
785            host: None,
786            metrics_port: None,
787            log_level: None,
788            log_format: None,
789            cache_directory: None,
790            cache_eviction_enabled: None,
791            security: SecurityArgs::default(),
792            validate_config: false,
793        };
794
795        let result = ServerConfig::load_and_validate_strict(args);
796        assert!(result.is_err());
797    }
798
799    #[test]
800    #[allow(clippy::expect_used)]
801    fn test_server_config_load_and_validate_strict_with_cli_overrides() {
802        let temp_dir = tempdir().expect("Failed to create temp dir");
803        let config_file = temp_dir.path().join("override_test_config.yaml");
804
805        let base_config = r#"
806            server:
807              host: "127.0.0.1"
808              port: 8002
809            cache:
810              eviction:
811                enabled: true
812                policy:
813                  type: lru
814                  unused_threshold: "1d"
815                  max_models: null
816                  min_free_space_bytes: null
817                check_interval: "1h"
818              directory: "./cache"
819              max_size_bytes: null
820            logging:
821              level: Info
822              format: Pretty
823              file: null
824              structured: false
825        "#;
826
827        fs::write(&config_file, base_config).expect("Failed to write config file");
828
829        let args = ServerArgs {
830            config: Some(config_file),
831            port: Some(NonZeroU16::new(9000).expect("9000 is non-zero")),
832            host: Some("0.0.0.0".to_string()),
833            metrics_port: None,
834            log_level: Some(LogLevel::Error),
835            log_format: Some(LogFormat::Json),
836            cache_directory: Some(PathBuf::from("/tmp/override_cache")),
837            cache_eviction_enabled: Some(false),
838            security: SecurityArgs::default(),
839            validate_config: false,
840        };
841
842        let result = ServerConfig::load_and_validate_strict(args);
843        assert!(result.is_ok());
844
845        let config = result.expect("Expected successful config parsing");
846        // CLI overrides should be applied
847        assert_eq!(config.server.host, "0.0.0.0");
848        assert_eq!(config.server.port.get(), 9000);
849        assert_eq!(config.logging.level, LogLevel::Error);
850        assert_eq!(config.logging.format, LogFormat::Json);
851        assert_eq!(config.cache.directory, PathBuf::from("/tmp/override_cache"));
852        assert!(!config.cache.eviction.enabled);
853    }
854
855    #[test]
856    #[allow(clippy::expect_used)]
857    fn test_server_config_load_and_validate_strict_no_config_file() {
858        let args = ServerArgs {
859            config: None,
860            port: Some(NonZeroU16::new(9001).expect("9001 is non-zero")),
861            host: Some("localhost".to_string()),
862            metrics_port: None,
863            log_level: Some(LogLevel::Warn),
864            log_format: None,
865            cache_directory: None,
866            cache_eviction_enabled: None,
867            security: SecurityArgs::default(),
868            validate_config: false,
869        };
870
871        // When no config file is specified, it should fall back to normal loading
872        let result = ServerConfig::load_and_validate_strict(args);
873        assert!(result.is_ok());
874
875        let config = result.expect("Expected successful config parsing");
876        assert_eq!(config.server.host, "localhost");
877        assert_eq!(config.server.port.get(), 9001);
878        assert_eq!(config.logging.level, LogLevel::Warn);
879    }
880
881    #[test]
882    fn security_defaults_to_off() {
883        let security = SecurityConfig::default();
884        assert_eq!(security.resolve_mode(), AuthMode::Off);
885        assert!(security.token_audiences.is_empty());
886        assert!(security.allowed_service_accounts.is_empty());
887    }
888
889    #[test]
890    #[allow(clippy::expect_used)]
891    fn service_account_ref_parses_namespace_and_sa() {
892        let parsed: ServiceAccountRef = "vllm:worker".parse().expect("valid ns:sa");
893        assert_eq!(parsed.namespace, "vllm");
894        assert_eq!(parsed.service_account, "worker");
895        assert_eq!(parsed.to_string(), "vllm:worker");
896        let trimmed: ServiceAccountRef = "  ns : sa ".parse().expect("trims");
897        assert_eq!(trimmed, "ns:sa".parse().expect("valid"));
898    }
899
900    #[test]
901    fn service_account_ref_rejects_malformed() {
902        assert!("noseparator".parse::<ServiceAccountRef>().is_err());
903        assert!(":sa".parse::<ServiceAccountRef>().is_err());
904        assert!("ns:".parse::<ServiceAccountRef>().is_err());
905    }
906
907    #[test]
908    #[allow(clippy::expect_used)]
909    fn comma_list_parses_and_skips_blanks() {
910        let list: CommaList<ServiceAccountRef> =
911            "a:one, b:two ,, c:three".parse().expect("valid list");
912        let items = list.into_inner();
913        assert_eq!(items.len(), 3);
914        assert_eq!(items[1].namespace, "b");
915        assert_eq!(items[2].service_account, "three");
916
917        let empty: CommaList<String> = "  ".parse().expect("empty");
918        assert!(empty.into_inner().is_empty());
919    }
920
921    #[test]
922    fn enforce_requires_audience_and_allowlist() {
923        let mut security = SecurityConfig {
924            mode: Some(AuthMode::Enforce),
925            ..SecurityConfig::default()
926        };
927        assert!(security.validate_resolved(AuthMode::Enforce).is_err());
928
929        security.token_audiences = vec!["modelexpress".to_string()];
930        assert!(security.validate_resolved(AuthMode::Enforce).is_err());
931
932        security.allowed_service_accounts = vec![ServiceAccountRef {
933            namespace: "vllm".to_string(),
934            service_account: "worker".to_string(),
935        }];
936        assert!(security.validate_resolved(AuthMode::Enforce).is_ok());
937    }
938
939    /// A config file must survive both spellings of the metrics port.
940    ///
941    /// `load_layered_config` swallows every deserialization error and returns
942    /// `T::default()` with no log line, so any value this field rejects costs the
943    /// operator the gRPC port, the cache directory, the eviction policy and the
944    /// auth settings -- silently. That is why `metrics_port` is a `u16` and not a
945    /// `NonZeroU16` (`0` has to deserialize, and is normalized afterwards), and
946    /// why it carries `#[serde(default)]` (no existing model-express.yaml mentions
947    /// it). Both cases assert the *rest* of the file survived, because that is how
948    /// the failure would present.
949    #[test]
950    #[allow(clippy::expect_used)]
951    fn metrics_port_never_costs_the_rest_of_the_config_file() {
952        // (metrics_port line, expected port, expected metrics address)
953        let cases = [
954            ("metrics_port: 0", 0_u16, None),
955            ("", default_metrics_port(), Some(default_metrics_port())),
956        ];
957
958        for (metrics_line, expected_metrics_port, expects_addr) in cases {
959            let temp_dir = tempdir().expect("Failed to create temp dir");
960            let config_file = temp_dir.path().join("metrics_port.yaml");
961            fs::write(
962                &config_file,
963                format!(
964                    r#"
965            server:
966              host: "127.0.0.1"
967              port: 18012
968              {metrics_line}
969            cache:
970              eviction:
971                enabled: false
972                policy:
973                  type: lru
974                  unused_threshold: "3d"
975                  max_models: 10
976                  min_free_space_bytes: 1000000
977                check_interval: "30m"
978              directory: "./cache"
979              max_size_bytes: 5000000
980            logging:
981              level: Debug
982              format: Json
983              file: null
984              structured: true
985        "#
986                ),
987            )
988            .expect("Failed to write config file");
989
990            let args = ServerArgs {
991                config: Some(config_file),
992                port: None,
993                host: None,
994                metrics_port: None,
995                log_level: None,
996                log_format: None,
997                cache_directory: None,
998                cache_eviction_enabled: None,
999                security: SecurityArgs::default(),
1000                validate_config: false,
1001            };
1002            let config = ServerConfig::load(args).expect("config should load");
1003
1004            assert_eq!(config.server.metrics_port, expected_metrics_port);
1005            assert_eq!(
1006                config
1007                    .metrics_socket_addr()
1008                    .expect("metrics address should resolve")
1009                    .map(|addr| addr.port()),
1010                expects_addr,
1011                "0 must mean disabled and nothing else"
1012            );
1013            // The rest of the file survived. If this regresses these fail
1014            // together, because the whole file was dropped.
1015            assert_eq!(config.server.port.get(), 18012, "the file was dropped");
1016            assert_eq!(config.server.host, "127.0.0.1");
1017            assert!(!config.cache.eviction.enabled);
1018            assert_eq!(config.logging.level, LogLevel::Debug);
1019        }
1020    }
1021
1022    /// The env var must stay wired through clap.
1023    ///
1024    /// `load_layered_config` reads env as
1025    /// `Environment::with_prefix("MODEL_EXPRESS").separator("_")`, so
1026    /// `MODEL_EXPRESS_SERVER_METRICS_PORT` resolves to the key path
1027    /// `server.metrics.port`, matches no field, and serde drops it without a
1028    /// warning. The clap `#[arg(env = ...)]` override is the only path that
1029    /// reaches the field, and `--metrics-port` is what the Helm chart drives.
1030    #[test]
1031    fn metrics_port_is_reachable_from_the_command_line() {
1032        use clap::Parser as _;
1033
1034        let args = ServerArgs::parse_from(["modelexpress-server", "--metrics-port", "9999"]);
1035        assert_eq!(args.metrics_port, Some(9999));
1036
1037        let off = ServerArgs::parse_from(["modelexpress-server", "--metrics-port", "0"]);
1038        assert_eq!(
1039            off.metrics_port,
1040            Some(0),
1041            "0 is the documented disable value"
1042        );
1043    }
1044}