Skip to main content

hyprstream_core/config/
server.rs

1//! Server configuration with builder pattern
2//!
3//! This module provides a unified server configuration that combines:
4//! - Network settings (host, port)
5//! - Runtime settings (caching, preloading, logging, metrics)
6//! - CORS configuration
7//! - TLS settings
8//! - Process management (working directory, PID file)
9
10use crate::cli::commands::KVQuantArg;
11use serde::{Deserialize, Serialize};
12use std::path::PathBuf;
13
14/// CORS configuration
15#[derive(Debug, Clone, Serialize, Deserialize)]
16pub struct CorsConfig {
17    /// Enable CORS middleware
18    #[serde(default = "default_cors_enabled")]
19    pub enabled: bool,
20
21    /// Allowed origins.
22    ///
23    /// The default is `["*"]` because these HTTP resource faces carry authority
24    /// explicitly in Bearer/DPoP headers, never in ambient browser credentials.
25    /// Operators may still configure an exact origin list; pairing that list
26    /// with `allow_credentials = true` preserves the legacy deployment posture.
27    #[serde(
28        default = "default_cors_origins",
29        deserialize_with = "deserialize_cors_origins"
30    )]
31    pub allowed_origins: Vec<String>,
32
33    /// Allow ambient browser credentials (cookies or HTTP authentication).
34    ///
35    /// Disabled by default. Bearer and DPoP request headers do not require this
36    /// flag and remain subject to the normal authentication, tenant, and MAC
37    /// enforcement path.
38    #[serde(default = "default_cors_credentials")]
39    pub allow_credentials: bool,
40
41    /// Max age for preflight cache (in seconds)
42    #[serde(default = "default_cors_max_age")]
43    pub max_age: u64,
44
45    /// Allow all headers in CORS preflights (`Access-Control-Allow-Headers: *`).
46    ///
47    /// This deliberately widens the preflight surface and must stay confined to
48    /// fully-public, secret-free GET endpoints whose contents carry no
49    /// authorization — currently only the DID-document routes (see
50    /// [`CorsConfig::did_document`]), where W3C DID Core requires the documents to
51    /// be fetchable cross-origin with arbitrary request headers. It is left
52    /// `false` for the broad public router (`CorsConfig::public`) and every other
53    /// surface so they keep their explicit header allowlist.
54    #[serde(default)]
55    pub permissive_headers: bool,
56}
57
58fn default_cors_enabled() -> bool {
59    true
60}
61fn default_cors_origins() -> Vec<String> {
62    vec!["*".to_owned()]
63}
64
65fn deserialize_cors_origins<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
66where
67    D: serde::Deserializer<'de>,
68{
69    // Environment list parsing preserves separator whitespace. Normalize only
70    // origin entries so the middleware can still perform exact membership
71    // checks, and drop entries that are empty after trimming — matching the
72    // legacy `HYPRSTREAM_CORS_ORIGINS` parser. An empty, whitespace-only, or
73    // separators-only value then yields an empty vector, restoring the
74    // middleware's existing fallback instead of admitting nothing.
75    Vec::<String>::deserialize(deserializer).map(|origins| {
76        origins
77            .into_iter()
78            .map(|origin| origin.trim().to_owned())
79            .filter(|origin| !origin.is_empty())
80            .collect()
81    })
82}
83fn default_cors_credentials() -> bool {
84    false
85}
86fn default_cors_max_age() -> u64 {
87    3600
88}
89
90impl Default for CorsConfig {
91    fn default() -> Self {
92        Self {
93            enabled: default_cors_enabled(),
94            allowed_origins: default_cors_origins(),
95            allow_credentials: default_cors_credentials(),
96            max_age: default_cors_max_age(),
97            permissive_headers: false,
98        }
99    }
100}
101
102impl CorsConfig {
103    /// CORS config for public endpoints (OAuth metadata, token, registration).
104    ///
105    /// Allows any origin but disables credentials (per CORS spec, wildcard +
106    /// credentials is invalid). `permissive_headers` stays `false`: this broad
107    /// router fronts secret-bearing endpoints (`/oauth/token`, `/oauth/register`,
108    /// `/oauth/par`, `/oauth/revoke`, SCIM discovery, …), so it keeps the explicit
109    /// request-header allowlist. The arbitrary-header relaxation needed by public
110    /// DID documents is scoped separately via [`CorsConfig::did_document`].
111    pub fn public() -> Self {
112        Self {
113            enabled: true,
114            allowed_origins: vec!["*".to_owned()],
115            allow_credentials: false,
116            max_age: 3600,
117            permissive_headers: false,
118        }
119    }
120
121    /// CORS config for the public DID-document routes only.
122    ///
123    /// Per W3C DID Core, a DID document is a public identity anchor that carries
124    /// no authorization and must be fetchable cross-origin with arbitrary request
125    /// headers (e.g. extension/SDK-injected headers, `ngrok-skip-browser-warning`
126    /// for dev tunnels) without preflight rejection. These are secret-free GET
127    /// endpoints, so `permissive_headers` is enabled here and nowhere else.
128    ///
129    /// Applied as a route-group layer on the DID routes (`/.well-known/did.json`,
130    /// `/.well-known/atproto-did`, `/users/:username/did.json`,
131    /// `/clients/:client_id/did.json`) so the relaxation never reaches the broad
132    /// public router (closes #472).
133    pub fn did_document() -> Self {
134        Self {
135            enabled: true,
136            allowed_origins: vec!["*".to_owned()],
137            allow_credentials: false,
138            max_age: 3600,
139            permissive_headers: true,
140        }
141    }
142}
143
144/// Default sampling parameters for generation
145#[derive(Debug, Clone, Serialize, Deserialize)]
146pub struct SamplingParamDefaults {
147    #[serde(default = "default_max_tokens")]
148    pub max_tokens: usize,
149
150    #[serde(default = "default_temperature")]
151    pub temperature: f32,
152
153    #[serde(default = "default_top_p")]
154    pub top_p: f32,
155
156    #[serde(default = "default_repeat_penalty")]
157    pub repeat_penalty: f32,
158}
159
160fn default_max_tokens() -> usize {
161    2048
162}
163fn default_temperature() -> f32 {
164    1.0
165}
166fn default_top_p() -> f32 {
167    1.0
168}
169fn default_repeat_penalty() -> f32 {
170    1.1
171}
172
173impl Default for SamplingParamDefaults {
174    fn default() -> Self {
175        Self {
176            max_tokens: default_max_tokens(),
177            temperature: default_temperature(),
178            top_p: default_top_p(),
179            repeat_penalty: default_repeat_penalty(),
180        }
181    }
182}
183
184/// Operator-selected canonical repository for the optional holder-scoped 9P
185/// read export. This names an existing Registry repository and worktree; it
186/// creates neither and grants no access by itself.
187#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
188#[serde(deny_unknown_fields)]
189pub struct NinepCanonicalReadConfig {
190    pub repo_name: String,
191    pub repo_id: String,
192    pub worktree: String,
193}
194
195impl NinepCanonicalReadConfig {
196    pub fn validate(&self) -> anyhow::Result<()> {
197        anyhow::ensure!(
198            !self.repo_name.is_empty()
199                && self.repo_name.len() <= 128
200                && self
201                    .repo_name
202                    .bytes()
203                    .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
204                && self.repo_name != "."
205                && self.repo_name != "..",
206            "invalid 9P repository name"
207        );
208        anyhow::ensure!(
209            uuid::Uuid::parse_str(&self.repo_id).is_ok_and(|id| id.to_string() == self.repo_id),
210            "invalid 9P repository UUID"
211        );
212        anyhow::ensure!(
213            !self.worktree.is_empty()
214                && self.worktree.len() <= 128
215                && self
216                    .worktree
217                    .bytes()
218                    .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
219                && self.worktree != "."
220                && self.worktree != "..",
221            "invalid 9P worktree"
222        );
223        Ok(())
224    }
225}
226
227/// Unified server configuration combining network, runtime, and TLS settings
228#[derive(Debug, Clone, Serialize, Deserialize)]
229pub struct ServerConfig {
230    /// Explicit, single-repository read-only 9P export. Missing means the
231    /// existing synthetic root remains authoritative.
232    #[serde(default)]
233    pub ninep_canonical_read: Option<NinepCanonicalReadConfig>,
234    // Network settings
235    #[serde(default = "default_host")]
236    pub host: String,
237
238    #[serde(default = "default_port")]
239    pub port: u16,
240
241    // Runtime settings
242    #[serde(default = "default_max_cached_models")]
243    pub max_cached_models: usize,
244
245    #[serde(default)]
246    pub preload_models: Vec<String>,
247
248    #[serde(default = "default_true")]
249    pub enable_logging: bool,
250
251    #[serde(default = "default_true")]
252    pub enable_metrics: bool,
253
254    #[serde(default = "default_max_tokens_limit")]
255    pub max_tokens_limit: usize,
256
257    #[serde(default = "default_request_timeout_secs")]
258    pub request_timeout_secs: u64,
259
260    // Concurrency settings
261    #[serde(default = "default_max_concurrent_requests")]
262    pub max_concurrent_requests: usize,
263
264    #[serde(default = "default_cancellation_check_interval")]
265    pub cancellation_check_interval: u64,
266
267    /// Max concurrent server-side streaming responses **per service** — how many
268    /// streaming RPCs one service may actively push data for at once. Bounds the
269    /// streaming-response tasks spawned by the RPC dispatch core (#186).
270    #[serde(default = "default_max_concurrent_streams_per_service")]
271    pub max_concurrent_streams_per_service: usize,
272
273    /// Maximum context length for KV cache allocation.
274    /// Overrides model's max_position_embeddings to reduce GPU memory.
275    /// None = use model's default, Some(n) = cap at n tokens
276    #[serde(default)]
277    pub max_context: Option<usize>,
278
279    /// KV cache quantization type for reduced GPU memory usage.
280    /// Reduces GPU memory by 50-75% at slight quality cost.
281    #[serde(default)]
282    pub kv_quant: KVQuantArg,
283
284    // CORS configuration
285    #[serde(default)]
286    pub cors: CorsConfig,
287
288    // Default sampling parameters
289    #[serde(default)]
290    pub sampling_defaults: SamplingParamDefaults,
291
292    // TLS settings
293    #[serde(default)]
294    pub tls_cert: Option<PathBuf>,
295
296    #[serde(default)]
297    pub tls_key: Option<PathBuf>,
298
299    // Process management
300    #[serde(default)]
301    pub working_dir: Option<PathBuf>,
302
303    #[serde(default)]
304    pub pid_file: Option<PathBuf>,
305}
306
307// Default value functions for serde
308fn default_host() -> String {
309    "0.0.0.0".to_owned()
310}
311fn default_port() -> u16 {
312    50051
313}
314fn default_max_cached_models() -> usize {
315    5
316}
317fn default_true() -> bool {
318    true
319}
320fn default_max_tokens_limit() -> usize {
321    4096
322}
323fn default_request_timeout_secs() -> u64 {
324    300
325}
326fn default_max_concurrent_requests() -> usize {
327    100
328}
329fn default_cancellation_check_interval() -> u64 {
330    100
331}
332fn default_max_concurrent_streams_per_service() -> usize {
333    hyprstream_rpc::streaming::DEFAULT_MAX_CONCURRENT_STREAMS_PER_SERVICE
334}
335
336impl Default for ServerConfig {
337    fn default() -> Self {
338        Self {
339            ninep_canonical_read: None,
340            host: default_host(),
341            port: default_port(),
342            max_cached_models: default_max_cached_models(),
343            preload_models: Vec::new(),
344            enable_logging: true,
345            enable_metrics: true,
346            max_tokens_limit: default_max_tokens_limit(),
347            request_timeout_secs: default_request_timeout_secs(),
348            max_concurrent_requests: default_max_concurrent_requests(),
349            cancellation_check_interval: default_cancellation_check_interval(),
350            max_concurrent_streams_per_service: default_max_concurrent_streams_per_service(),
351            max_context: None, // Use model's default max_position_embeddings
352            kv_quant: KVQuantArg::None,
353            cors: CorsConfig::default(),
354            sampling_defaults: SamplingParamDefaults::default(),
355            tls_cert: None,
356            tls_key: None,
357            working_dir: None,
358            pid_file: None,
359        }
360    }
361}
362
363/// Builder for ServerConfig with chainable methods
364#[derive(Debug, Default)]
365pub struct ServerConfigBuilder {
366    config: ServerConfig,
367}
368
369impl ServerConfigBuilder {
370    /// Create a new builder with default values
371    pub fn new() -> Self {
372        Self {
373            config: ServerConfig::default(),
374        }
375    }
376
377    /// Start from an existing config
378    pub fn from_config(config: ServerConfig) -> Self {
379        Self { config }
380    }
381
382    // Network settings
383    pub fn host(mut self, host: impl Into<String>) -> Self {
384        self.config.host = host.into();
385        self
386    }
387
388    pub fn port(mut self, port: u16) -> Self {
389        self.config.port = port;
390        self
391    }
392
393    // Runtime settings
394    pub fn max_cached_models(mut self, max: usize) -> Self {
395        self.config.max_cached_models = max;
396        self
397    }
398
399    pub fn preload_models(mut self, models: Vec<String>) -> Self {
400        self.config.preload_models = models;
401        self
402    }
403
404    pub fn add_preload_model(mut self, model: impl Into<String>) -> Self {
405        self.config.preload_models.push(model.into());
406        self
407    }
408
409    pub fn enable_logging(mut self, enabled: bool) -> Self {
410        self.config.enable_logging = enabled;
411        self
412    }
413
414    pub fn enable_metrics(mut self, enabled: bool) -> Self {
415        self.config.enable_metrics = enabled;
416        self
417    }
418
419    pub fn max_tokens_limit(mut self, limit: usize) -> Self {
420        self.config.max_tokens_limit = limit;
421        self
422    }
423
424    pub fn request_timeout_secs(mut self, timeout: u64) -> Self {
425        self.config.request_timeout_secs = timeout;
426        self
427    }
428
429    // Concurrency settings
430    pub fn max_concurrent_requests(mut self, max: usize) -> Self {
431        self.config.max_concurrent_requests = max;
432        self
433    }
434
435    pub fn cancellation_check_interval(mut self, interval: u64) -> Self {
436        self.config.cancellation_check_interval = interval;
437        self
438    }
439
440    pub fn cancellation_check_interval_duration(mut self, interval: std::time::Duration) -> Self {
441        self.config.cancellation_check_interval = interval.as_millis() as u64;
442        self
443    }
444
445    /// Set maximum context length for KV cache allocation
446    pub fn max_context(mut self, max_context: Option<usize>) -> Self {
447        self.config.max_context = max_context;
448        self
449    }
450
451    /// Set KV cache quantization type
452    pub fn kv_quant(mut self, kv_quant: KVQuantArg) -> Self {
453        self.config.kv_quant = kv_quant;
454        self
455    }
456
457    // CORS settings
458    pub fn cors(mut self, cors: CorsConfig) -> Self {
459        self.config.cors = cors;
460        self
461    }
462
463    pub fn cors_enabled(mut self, enabled: bool) -> Self {
464        self.config.cors.enabled = enabled;
465        self
466    }
467
468    pub fn cors_origins(mut self, origins: Vec<String>) -> Self {
469        self.config.cors.allowed_origins = origins;
470        self
471    }
472
473    pub fn cors_allow_credentials(mut self, allow: bool) -> Self {
474        self.config.cors.allow_credentials = allow;
475        self
476    }
477
478    pub fn cors_permissive_headers(mut self, permissive: bool) -> Self {
479        self.config.cors.permissive_headers = permissive;
480        self
481    }
482
483    // Sampling defaults
484    pub fn sampling_defaults(mut self, defaults: SamplingParamDefaults) -> Self {
485        self.config.sampling_defaults = defaults;
486        self
487    }
488
489    // TLS settings
490    pub fn tls_cert(mut self, cert: PathBuf) -> Self {
491        self.config.tls_cert = Some(cert);
492        self
493    }
494
495    pub fn tls_key(mut self, key: PathBuf) -> Self {
496        self.config.tls_key = Some(key);
497        self
498    }
499
500    // Process management
501    pub fn working_dir(mut self, dir: PathBuf) -> Self {
502        self.config.working_dir = Some(dir);
503        self
504    }
505
506    pub fn pid_file(mut self, file: PathBuf) -> Self {
507        self.config.pid_file = Some(file);
508        self
509    }
510
511    /// Load values from environment variables (merges with current config)
512    pub fn from_env(mut self) -> Self {
513        // Network
514        if let Ok(host) = std::env::var("HYPRSTREAM_SERVER_HOST") {
515            self.config.host = host;
516        }
517        if let Ok(port) = std::env::var("HYPRSTREAM_SERVER_PORT") {
518            if let Ok(p) = port.parse() {
519                self.config.port = p;
520            }
521        }
522
523        // Concurrency settings
524        if let Ok(max_concurrent) = std::env::var("HYPRSTREAM_MAX_CONCURRENT_REQUESTS") {
525            if let Ok(n) = max_concurrent.parse() {
526                self.config.max_concurrent_requests = n;
527            }
528        }
529
530        if let Ok(interval) = std::env::var("HYPRSTREAM_CANCELLATION_CHECK_INTERVAL") {
531            if let Ok(i) = interval.parse() {
532                self.config.cancellation_check_interval = i;
533            }
534        }
535
536        // Runtime settings
537        if let Ok(max_cached) = std::env::var("HYPRSTREAM_MAX_CACHED_MODELS") {
538            if let Ok(n) = max_cached.parse() {
539                self.config.max_cached_models = n;
540            }
541        }
542
543        if let Ok(models) = std::env::var("HYPRSTREAM_PRELOAD_MODELS") {
544            self.config.preload_models = models
545                .split(',')
546                .map(|s| s.trim().to_owned())
547                .filter(|s| !s.is_empty())
548                .collect();
549        }
550
551        // CORS
552        if let Ok(cors_enabled) = std::env::var("HYPRSTREAM_CORS_ENABLED") {
553            self.config.cors.enabled = cors_enabled.to_lowercase() != "false";
554        }
555
556        if let Ok(cors_origins) = std::env::var("HYPRSTREAM_CORS_ORIGINS") {
557            self.config.cors.allowed_origins = cors_origins
558                .split(',')
559                .map(|s| s.trim().to_owned())
560                .filter(|s| !s.is_empty())
561                .collect();
562
563            if self.config.cors.allowed_origins.contains(&"*".to_owned()) {
564                self.config.cors.allow_credentials = false;
565            }
566        }
567
568        if let Ok(cors_credentials) = std::env::var("HYPRSTREAM_CORS_CREDENTIALS") {
569            if self.config.cors.allowed_origins.contains(&"*".to_owned()) {
570                if cors_credentials.eq_ignore_ascii_case("true") {
571                    tracing::warn!(
572                        "HYPRSTREAM_CORS_CREDENTIALS=true ignored: wildcard CORS origins require \
573                         credentials to remain disabled; set HYPRSTREAM_CORS_ORIGINS to an exact \
574                         origin list before enabling credentials"
575                    );
576                }
577            } else {
578                self.config.cors.allow_credentials = cors_credentials.to_lowercase() == "true";
579            }
580        }
581
582        if let Ok(permissive) = std::env::var("HYPRSTREAM_CORS_PERMISSIVE_HEADERS") {
583            self.config.cors.permissive_headers = permissive.to_lowercase() == "true";
584        }
585
586        // TLS
587        if let Ok(cert) = std::env::var("HYPRSTREAM_TLS_CERT") {
588            self.config.tls_cert = Some(PathBuf::from(cert));
589        }
590        if let Ok(key) = std::env::var("HYPRSTREAM_TLS_KEY") {
591            self.config.tls_key = Some(PathBuf::from(key));
592        }
593
594        // Process management
595        if let Ok(dir) = std::env::var("HYPRSTREAM_WORKING_DIR") {
596            self.config.working_dir = Some(PathBuf::from(dir));
597        }
598        if let Ok(file) = std::env::var("HYPRSTREAM_PID_FILE") {
599            self.config.pid_file = Some(PathBuf::from(file));
600        }
601
602        self
603    }
604
605    /// Build the final configuration
606    pub fn build(self) -> ServerConfig {
607        self.config
608    }
609}
610
611impl ServerConfig {
612    /// Create a builder for this config
613    pub fn builder() -> ServerConfigBuilder {
614        ServerConfigBuilder::new()
615    }
616
617    /// Create a builder from existing config
618    pub fn to_builder(self) -> ServerConfigBuilder {
619        ServerConfigBuilder::from_config(self)
620    }
621}
622
623#[cfg(test)]
624mod tests {
625    //! Regression guards for #1152 (W6): these fields/helpers advertised
626    //! security capabilities (mTLS, TLS-hardening knobs, port-derived CORS)
627    //! that the server never wired up. Config that promises a capability we
628    //! lack is worse than absent config, because reviewers credit it. These
629    //! tests fail if any of the dead surface is reintroduced.
630
631    use std::path::PathBuf;
632
633    /// Read a source file from this crate's `src/` tree.
634    fn read_src(rel: &str) -> String {
635        let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
636        p.push("src");
637        for seg in rel.split('/') {
638            p.push(seg);
639        }
640        std::fs::read_to_string(&p).unwrap_or_else(|e| panic!("could not read src/{rel}: {e}"))
641    }
642
643    /// The four TLS knobs + mTLS CA + the two CORS helpers must not reappear in
644    /// `config/server.rs`. Tokens are assembled by concatenation so this test's
645    /// own source does not contain the forbidden identifiers and therefore
646    /// cannot match itself.
647    #[test]
648    fn dead_security_config_stays_deleted() {
649        let src = read_src("config/server.rs");
650        // Field-name fragments (kept split so the test source scans clean).
651        let forbidden_field_defs = [
652            concat!("pub tls_client", "_ca"),
653            concat!("pub tls_min", "_version"),
654            concat!("pub tls_cipher", "_list"),
655            concat!("pub tls_prefer", "_server_ciphers"),
656        ];
657        for needle in forbidden_field_defs {
658            assert!(
659                !src.contains(needle),
660                "config/server.rs re-introduced dead TLS field `{needle}` (see #1152 W6): \
661                 this advertises a security capability the server does not wire up",
662            );
663        }
664        // Builder setters + env reads + default fns for the same quartet.
665        for needle in [
666            concat!("fn tls_client", "_ca"),
667            concat!("fn tls_min", "_version"),
668            concat!("fn tls_cipher", "_list"),
669            concat!("fn tls_prefer", "_server_ciphers"),
670            concat!("default_tls", "_min_version"),
671            concat!("HYPRSTREAM_TLS_CLIENT", "_CA"),
672            concat!("HYPRSTREAM_TLS_MIN", "_VERSION"),
673        ] {
674            assert!(
675                !src.contains(needle),
676                "config/server.rs re-introduced dead TLS surface `{needle}` (see #1152 W6)",
677            );
678        }
679        // `finalize_cors` had no callers; `CorsConfig::with_port` was called
680        // only from inside `finalize_cors`. Both must stay gone together.
681        for needle in [concat!("fn finalize", "_cors"), concat!("fn with", "_port")] {
682            assert!(
683                !src.contains(needle),
684                "config/server.rs re-introduced dead CORS helper `{needle}` (see #1152 W6): \
685                 it has no callers",
686            );
687        }
688    }
689
690    /// `server/tls.rs` must not install a client-certificate verifier: mTLS is
691    /// not implemented, so advertising it (via config knobs that flow into a
692    /// verifier) would be a phantom security control. This catches a future
693    /// change that wires `tls_client_ca`-style config into a real verifier
694    /// without first deciding the mTLS authz model.
695    #[test]
696    fn mtls_client_verifier_is_not_wired() {
697        let src = read_src("server/tls.rs");
698        assert_no_mtls_verifier(&src);
699    }
700
701    fn assert_no_mtls_verifier(src: &str) {
702        // rustls requires an explicit choice here. Disabling client auth is
703        // not an mTLS implementation; allow only that exact identifier.
704        let src = src
705            .split(|c: char| !c.is_alphanumeric() && c != '_')
706            .filter(|identifier| *identifier != "with_no_client_auth")
707            .collect::<Vec<_>>()
708            .join(" ");
709        for needle in ["client_auth", "client_cert", "ClientCert", "client_ca"] {
710            assert!(
711                !src.contains(needle),
712                "server/tls.rs now references `{needle}`: mTLS client-cert verification is being \
713                 wired. mTLS is deliberately not implemented (#1152 W6); either land the full \
714                 authz model or remove the reference.",
715            );
716        }
717    }
718
719    #[test]
720    fn mtls_guard_allows_explicit_no_client_auth() {
721        assert_no_mtls_verifier("builder.with_no_client_auth().with_cert_resolver(resolver)");
722    }
723
724    #[test]
725    #[should_panic(expected = "mTLS client-cert verification")]
726    fn mtls_guard_rejects_client_verifier() {
727        assert_no_mtls_verifier("builder.with_client_cert_verifier(verifier)");
728    }
729
730    #[test]
731    #[should_panic(expected = "mTLS client-cert verification")]
732    fn mtls_guard_rejects_client_auth_even_alongside_no_auth() {
733        assert_no_mtls_verifier(
734            "builder.with_no_client_auth(); builder.with_client_auth_cert(cert)",
735        );
736    }
737}