Skip to main content

type_bridge_server/
config.rs

1use std::ffi::OsString;
2use std::fmt;
3use std::io::{Read, Seek, SeekFrom};
4use std::path::{Component, Path, PathBuf};
5use std::sync::Arc;
6
7#[cfg(unix)]
8use std::os::unix::fs::OpenOptionsExt as _;
9#[cfg(windows)]
10use std::os::windows::fs::OpenOptionsExt as _;
11
12#[cfg(unix)]
13use cap_fs_ext::OpenOptionsSyncExt as _;
14use cap_fs_ext::{
15    DirExt as _, FollowSymlinks, OpenOptionsFollowExt as _, OpenOptionsMaybeDirExt as _,
16};
17use cap_std::ambient_authority;
18#[cfg(windows)]
19use cap_std::fs::OpenOptionsExt as _;
20use cap_std::fs::{Dir, OpenOptions};
21use serde::Deserialize;
22use type_bridge_core_lib::version as core_version;
23
24const MAX_TLS_MATERIAL_BYTES: u64 = 1024 * 1024;
25const MAX_SERVER_CONFIG_BYTES: u64 = 1024 * 1024;
26#[cfg(feature = "v2-query")]
27const MAX_SCHEMA_AUTHORITY_BYTES: usize = type_bridge_schema::MAX_SCHEMA_AUTHORITY_BYTES;
28
29#[derive(Clone, Copy)]
30enum RuntimeConfigParseErrorKind {
31    Syntax,
32    ValueShape,
33    UnknownSecurityKey,
34}
35
36struct RuntimeConfigParseError {
37    kind: RuntimeConfigParseErrorKind,
38    location: Option<(usize, usize)>,
39}
40
41impl RuntimeConfigParseError {
42    fn from_toml(kind: RuntimeConfigParseErrorKind, content: &str, error: toml::de::Error) -> Self {
43        // Extract only numeric source coordinates. The TOML error owns the
44        // original document and its Display text may reproduce a complete
45        // secret-bearing line, so neither is retained as a source.
46        let location = error
47            .span()
48            .and_then(|span| source_line_column(content, span.start));
49        Self { kind, location }
50    }
51
52    const fn unknown_security_key() -> Self {
53        Self {
54            kind: RuntimeConfigParseErrorKind::UnknownSecurityKey,
55            location: None,
56        }
57    }
58}
59
60impl fmt::Display for RuntimeConfigParseError {
61    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
62        let reason = match self.kind {
63            RuntimeConfigParseErrorKind::Syntax => "TOML syntax",
64            RuntimeConfigParseErrorKind::ValueShape => "value shape",
65            RuntimeConfigParseErrorKind::UnknownSecurityKey => "unknown security-sensitive key",
66        };
67        write!(formatter, "server configuration is invalid ({reason})")?;
68        if let Some((line, column)) = self.location {
69            write!(formatter, " at line {line}, column {column}")?;
70        }
71        Ok(())
72    }
73}
74
75impl fmt::Debug for RuntimeConfigParseError {
76    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
77        fmt::Display::fmt(self, formatter)
78    }
79}
80
81impl std::error::Error for RuntimeConfigParseError {}
82
83fn source_line_column(content: &str, byte_offset: usize) -> Option<(usize, usize)> {
84    if byte_offset > content.len() || !content.is_char_boundary(byte_offset) {
85        return None;
86    }
87    let prefix = &content[..byte_offset];
88    let line = prefix.bytes().filter(|byte| *byte == b'\n').count() + 1;
89    let column = prefix
90        .rsplit_once('\n')
91        .map_or(prefix, |(_, tail)| tail)
92        .chars()
93        .count()
94        + 1;
95    Some((line, column))
96}
97
98#[derive(Debug, Deserialize)]
99/// Released server configuration projection.
100pub struct ServerConfig {
101    /// Listener address configuration.
102    pub server: ServerSection,
103    /// TypeDB connection configuration.
104    pub typedb: TypeDBSection,
105    /// Optional V1 TypeQL schema source.
106    #[serde(default)]
107    pub schema: SchemaSection,
108    /// Interceptors enabled for the request pipeline.
109    #[serde(default)]
110    pub interceptors: InterceptorsSection,
111    /// Process logging configuration.
112    #[serde(default)]
113    pub logging: LoggingSection,
114}
115
116/// Standalone-server configuration with additive secure and V2 settings.
117///
118/// [`ServerConfig`] remains the released plaintext configuration surface so
119/// downstream exhaustive struct literals and patterns keep compiling. The
120/// standalone binary parses this projection instead; its private wire types
121/// accept the same TOML tables while keeping new fields out of the released
122/// structs.
123pub struct RuntimeServerConfig {
124    /// Listener address configuration.
125    pub server: ServerSection,
126    /// Validated TypeDB connection and outbound TLS policy.
127    pub typedb: SecureTypeDBSection,
128    /// Optional V1 TypeQL schema source.
129    pub schema: SchemaSection,
130    /// Interceptors enabled for the request pipeline.
131    pub interceptors: InterceptorsSection,
132    /// Process logging configuration.
133    pub logging: LoggingSection,
134    /// Prepared inbound TLS identity, when HTTPS is enabled.
135    pub inbound_tls: Option<InboundTlsSection>,
136    /// Generated-authority-backed V2 query configuration.
137    pub v2: V2Section,
138}
139
140/// TypeDB connection settings for the standalone server's secure entry point.
141///
142/// The credential-bearing V1 projection is deliberately not publicly
143/// reachable from a loaded runtime config:
144///
145/// ```compile_fail
146/// use type_bridge_server::config::SecureTypeDBSection;
147///
148/// fn accidentally_log_raw_connection(config: &SecureTypeDBSection) {
149///     let _ = format!("{:?}", config.connection);
150/// }
151/// ```
152pub struct SecureTypeDBSection {
153    /// Released connection fields, preserved as one exact V1 projection.
154    pub(crate) connection: TypeDBSection,
155    /// Validated transport mode used by both HTTP discovery and gRPC.
156    pub tls_mode: OutboundTlsMode,
157    // Relative custom roots are captured while the configuration directory
158    // handle is retained. Transport preparation consumes these exact bytes
159    // instead of reopening the diagnostic path below.
160    #[cfg_attr(not(feature = "typedb"), allow(dead_code))]
161    pub(crate) custom_root_ca_snapshot: Option<CapturedConfiguredMaterial>,
162    // Runtime-only storage avoids changing the public V2 configuration
163    // projection while binding the declared schema to this exact load.
164    #[cfg(feature = "v2-query")]
165    pub(crate) v2_schema_authority_snapshot: Option<CapturedConfiguredMaterial>,
166}
167
168impl fmt::Debug for RuntimeServerConfig {
169    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
170        formatter
171            .debug_struct("RuntimeServerConfig")
172            .field("server", &self.server)
173            .field("typedb", &self.typedb)
174            .field("schema", &self.schema)
175            .field("interceptors", &self.interceptors)
176            .field("logging", &self.logging)
177            .field("inbound_tls", &self.inbound_tls)
178            .field("v2", &self.v2)
179            .finish()
180    }
181}
182
183impl fmt::Debug for SecureTypeDBSection {
184    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
185        formatter
186            .debug_struct("SecureTypeDBSection")
187            .field("address", &"[REDACTED]")
188            .field("database", &self.connection.database)
189            .field("username", &"[REDACTED]")
190            .field("password", &"[REDACTED]")
191            .field("http_port", &self.connection.http_port)
192            .field("server_version", &self.connection.server_version)
193            .field("tls_mode", &self.tls_mode)
194            .field("custom_root_ca_snapshot", &self.custom_root_ca_snapshot)
195            .finish()
196    }
197}
198
199impl SecureTypeDBSection {
200    /// Construct secure connection settings from an independently owned TLS
201    /// policy. Custom-root paths are captured during transport preparation.
202    #[must_use]
203    pub fn new(connection: TypeDBSection, tls_mode: OutboundTlsMode) -> Self {
204        Self {
205            connection,
206            tls_mode,
207            custom_root_ca_snapshot: None,
208            #[cfg(feature = "v2-query")]
209            v2_schema_authority_snapshot: None,
210        }
211    }
212
213    /// Return the non-secret database name selected by this runtime config.
214    #[must_use]
215    pub fn database(&self) -> &str {
216        &self.connection.database
217    }
218}
219
220/// Authority mode for the standalone V2 query executor.
221#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)]
222#[serde(rename_all = "snake_case")]
223pub enum V2AuthorityMode {
224    /// Require the complete managed migration-control partition and singleton.
225    #[default]
226    Managed,
227    /// Require no V2 or legacy migration controls and bind to this database.
228    QueryOnly,
229}
230
231/// Optional versioned V2 query surface served beside the V1 routes.
232///
233/// Requires a binary built with `--features v2-query`; enabling it on a
234/// build without the feature aborts startup instead of silently serving
235/// 404s.
236#[derive(Debug, Default, Deserialize)]
237pub struct V2Section {
238    /// Serve `/v2/query` and `/v2/capabilities`.
239    #[serde(default)]
240    pub enabled: bool,
241    /// Path to the source-free authority emitted by `schema generate`.
242    #[serde(default)]
243    pub schema_authority_file: String,
244    /// Exact authority contract; defaults to `managed`.
245    #[serde(default)]
246    pub authority_mode: V2AuthorityMode,
247    /// Query limits this executor advertises and enforces, by stable limit
248    /// name. A limit left out keeps its canonical default.
249    #[serde(default)]
250    pub query_limits: std::collections::BTreeMap<String, u64>,
251    /// Answer ceilings this executor advertises and enforces, by stable
252    /// name: how much one query may return. A dimension left out keeps its
253    /// default.
254    #[serde(default)]
255    pub answer_limits: std::collections::BTreeMap<String, u64>,
256    /// Admit staged `/v3/staged` write transactions without an interceptor
257    /// vouching for the caller. Defaults to `false`: writes need an
258    /// authenticating policy.
259    #[serde(default)]
260    pub allow_unauthenticated_staged_writes: bool,
261}
262
263impl V2Section {
264    /// Resolve the configured answer ceilings, refusing unknown names and
265    /// values past a dimension's supported maximum. An unnamed dimension
266    /// keeps the proxy (wire) default, so an unconfigured server advertises
267    /// no answer limit.
268    #[cfg(feature = "v2-query")]
269    pub fn resolved_answer_limits(
270        &self,
271    ) -> Result<type_bridge_orm::QueryExecutionResourceLimits, String> {
272        type_bridge_orm::QueryExecutionResourceLimits::from_overrides(
273            type_bridge_orm::AnswerTransport::Proxy,
274            self.answer_limits
275                .iter()
276                .map(|(name, value)| (name.as_str(), *value)),
277        )
278        .map_err(|error| format!("v2.answer_limits is rejected: {error}"))
279    }
280
281    /// Resolve the configured query limits, refusing unknown names and
282    /// values the implementation does not support.
283    pub fn resolved_query_limits(
284        &self,
285    ) -> Result<type_bridge_contract::limits::QueryLimits, String> {
286        type_bridge_contract::limits::QueryLimits::from_overrides(
287            self.query_limits
288                .iter()
289                .map(|(name, value)| (name.as_str(), *value)),
290        )
291        .map_err(|error| format!("v2.query_limits is rejected: {error}"))
292    }
293}
294
295#[derive(Debug, Deserialize)]
296/// HTTP listener address for the standalone server.
297pub struct ServerSection {
298    /// Interface or hostname on which the server listens.
299    #[serde(default = "default_host")]
300    pub host: String,
301    /// TCP port on which the server listens.
302    #[serde(default = "default_port")]
303    pub port: u16,
304}
305
306/// Inbound server identity loaded and validated before binding a listener.
307#[derive(Clone, Debug, Deserialize)]
308#[serde(deny_unknown_fields)]
309pub struct InboundTlsSection {
310    /// Path to the PEM-encoded certificate chain.
311    #[serde(rename = "cert-path")]
312    pub cert_path: PathBuf,
313    /// Path to the PEM-encoded private key.
314    #[serde(rename = "key-path")]
315    pub key_path: PathBuf,
316    #[serde(skip)]
317    prepared: Option<PreparedInboundTlsMaterial>,
318}
319
320#[derive(Clone)]
321pub(crate) struct CapturedConfiguredMaterial {
322    pub(crate) path: PathBuf,
323    pub(crate) bytes: Arc<[u8]>,
324}
325
326impl fmt::Debug for CapturedConfiguredMaterial {
327    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
328        formatter
329            .debug_struct("CapturedConfiguredMaterial")
330            .field("path", &self.path)
331            .field("bytes", &self.bytes.len())
332            .finish()
333    }
334}
335
336#[derive(Clone, Default)]
337struct PreparedInboundTlsMaterial {
338    certificate: Option<CapturedConfiguredMaterial>,
339    private_key: Option<CapturedConfiguredMaterial>,
340}
341
342impl fmt::Debug for PreparedInboundTlsMaterial {
343    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
344        formatter
345            .debug_struct("PreparedInboundTlsMaterial")
346            .field(
347                "certificate_bytes",
348                &self
349                    .certificate
350                    .as_ref()
351                    .map(|material| material.bytes.len()),
352            )
353            .field(
354                "private_key_bytes",
355                &self
356                    .private_key
357                    .as_ref()
358                    .map(|material| material.bytes.len()),
359            )
360            .finish()
361    }
362}
363
364impl InboundTlsSection {
365    /// Construct an inbound identity whose absolute or caller-owned paths are
366    /// read when the transport identity is loaded.
367    #[must_use]
368    pub fn from_paths(cert_path: PathBuf, key_path: PathBuf) -> Self {
369        Self {
370            cert_path,
371            key_path,
372            prepared: None,
373        }
374    }
375}
376
377#[cfg(feature = "axum-transport")]
378impl InboundTlsSection {
379    /// Load and cross-check the certificate chain and private key before bind.
380    pub async fn load(
381        &self,
382    ) -> Result<axum_server::tls_rustls::RustlsConfig, Box<dyn std::error::Error>> {
383        fn read_bounded(path: &Path, field: &str) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
384            use std::path::Component;
385
386            use cap_fs_ext::{
387                DirExt as _, FollowSymlinks, OpenOptionsFollowExt as _,
388                OpenOptionsMaybeDirExt as _, OpenOptionsSyncExt as _,
389            };
390
391            if !path.is_absolute() {
392                return Err(format!("{field} must be an absolute resolved path").into());
393            }
394            let anchor = path
395                .ancestors()
396                .last()
397                .ok_or_else(|| format!("{field} has no filesystem anchor"))?;
398            let relative = path
399                .strip_prefix(anchor)
400                .map_err(|_| format!("{field} is not beneath its filesystem anchor"))?;
401            let components = relative
402                .components()
403                .map(|component| match component {
404                    Component::Normal(name) => Ok(name),
405                    _ => Err(format!("{field} contains an invalid path component")),
406                })
407                .collect::<Result<Vec<_>, _>>()?;
408            let (name, parents) = components
409                .split_last()
410                .ok_or_else(|| format!("{field} has no file name"))?;
411            let mut directory =
412                cap_std::fs::Dir::open_ambient_dir(anchor, cap_std::ambient_authority())
413                    .map_err(|error| format!("cannot read {field}: {error}"))?;
414            for parent in parents {
415                directory = directory
416                    .open_dir_nofollow(parent)
417                    .map_err(|error| format!("cannot read {field}: {error}"))?;
418            }
419            let mut options = cap_std::fs::OpenOptions::new();
420            options.read(true).follow(FollowSymlinks::No).nonblock(true);
421            // A directory must open (Windows needs backup semantics for
422            // that) so the regular-file classification below comes from the
423            // opened handle's metadata, exactly as it does on Unix.
424            options.maybe_dir(true);
425            let mut file = directory
426                .open_with(name, &options)
427                .map(cap_std::fs::File::into_std)
428                .map_err(|error| format!("cannot read {field}: {error}"))?;
429            let metadata = file
430                .metadata()
431                .map_err(|error| format!("cannot inspect {field}: {error}"))?;
432            if !metadata.is_file() {
433                return Err(format!("{field} must name a regular file").into());
434            }
435            let mut bytes = Vec::new();
436            (&mut file)
437                .take(MAX_TLS_MATERIAL_BYTES + 1)
438                .read_to_end(&mut bytes)
439                .map_err(|error| format!("cannot read {field}: {error}"))?;
440            if bytes.is_empty()
441                || u64::try_from(bytes.len()).unwrap_or(u64::MAX) > MAX_TLS_MATERIAL_BYTES
442            {
443                return Err(
444                    format!("{field} must be a non-empty file no larger than 1 MiB").into(),
445                );
446            }
447            file.seek(SeekFrom::Start(0))
448                .map_err(|error| format!("cannot reread {field}: {error}"))?;
449            let mut verification_bytes = Vec::new();
450            (&mut file)
451                .take(MAX_TLS_MATERIAL_BYTES + 1)
452                .read_to_end(&mut verification_bytes)
453                .map_err(|error| format!("cannot reread {field}: {error}"))?;
454            let after = file
455                .metadata()
456                .map_err(|error| format!("cannot inspect {field}: {error}"))?;
457            let timestamps_match = match (metadata.modified(), after.modified()) {
458                (Ok(before), Ok(after)) => before == after,
459                (Err(_), Err(_)) => true,
460                _ => false,
461            };
462            if metadata.len() != after.len()
463                || metadata.len() != u64::try_from(bytes.len()).unwrap_or(u64::MAX)
464                || bytes != verification_bytes
465                || !timestamps_match
466            {
467                return Err(format!("{field} changed while it was being read").into());
468            }
469            Ok(bytes)
470        }
471
472        fn captured_bytes(
473            material: Option<&CapturedConfiguredMaterial>,
474            current_path: &Path,
475            field: &str,
476        ) -> Result<Option<Vec<u8>>, Box<dyn std::error::Error>> {
477            let Some(material) = material else {
478                return Ok(None);
479            };
480            if material.path != current_path {
481                return Err(format!(
482                    "{field} changed after its relative material was captured; reload the configuration"
483                )
484                .into());
485            }
486            Ok(Some(material.bytes.to_vec()))
487        }
488
489        let certificate = match captured_bytes(
490            self.prepared
491                .as_ref()
492                .and_then(|prepared| prepared.certificate.as_ref()),
493            &self.cert_path,
494            "server.tls.cert-path",
495        )? {
496            Some(bytes) => bytes,
497            None => read_bounded(&self.cert_path, "server.tls.cert-path")?,
498        };
499        let private_key = match captured_bytes(
500            self.prepared
501                .as_ref()
502                .and_then(|prepared| prepared.private_key.as_ref()),
503            &self.key_path,
504            "server.tls.key-path",
505        )? {
506            Some(bytes) => bytes,
507            None => read_bounded(&self.key_path, "server.tls.key-path")?,
508        };
509        axum_server::tls_rustls::RustlsConfig::from_pem(certificate, private_key)
510            .await
511            .map_err(|error| format!("invalid server.tls identity: {error}").into())
512    }
513}
514
515#[derive(Deserialize)]
516/// Released TypeDB connection settings.
517pub struct TypeDBSection {
518    /// TypeDB gRPC address.
519    pub address: String,
520    /// Default TypeDB database name.
521    pub database: String,
522    /// TypeDB username.
523    #[serde(default = "default_username")]
524    pub username: String,
525    /// TypeDB password.
526    #[serde(default = "default_password")]
527    pub password: String,
528    /// Port of the TypeDB HTTP API on the same host as `address`; the
529    /// connect-time version gate probes `/v1/version` here.
530    #[serde(default = "default_http_port")]
531    pub http_port: u16,
532    /// Exact TypeDB server version to validate when the HTTP API is disabled
533    /// or unreachable. When set, the connect-time gate skips HTTP probing.
534    #[serde(default)]
535    pub server_version: Option<String>,
536}
537
538impl fmt::Debug for TypeDBSection {
539    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
540        formatter
541            .debug_struct("TypeDBSection")
542            .field("address", &"[REDACTED]")
543            .field("database", &self.database)
544            .field("username", &"[REDACTED]")
545            .field("password", &"[REDACTED]")
546            .field("http_port", &self.http_port)
547            .field("server_version", &self.server_version)
548            .finish()
549    }
550}
551
552/// Validated outbound TLS policy independent of any driver implementation.
553#[derive(Clone, Debug, Eq, PartialEq)]
554pub enum OutboundTlsMode {
555    /// Connect without TLS.
556    Disabled,
557    /// Validate the TypeDB identity with native platform roots.
558    NativeRoots,
559    /// Validate the TypeDB identity with the PEM root at this path.
560    CustomRootCa(PathBuf),
561}
562
563#[derive(Debug, Deserialize)]
564struct RuntimeServerConfigWire {
565    server: RuntimeServerSectionWire,
566    typedb: RuntimeTypeDBSectionWire,
567    #[serde(default)]
568    schema: RuntimeSchemaSectionWire,
569    #[serde(default)]
570    interceptors: RuntimeInterceptorsSectionWire,
571    #[serde(default)]
572    logging: RuntimeLoggingSectionWire,
573    #[serde(default)]
574    v2: RuntimeV2SectionWire,
575}
576
577#[derive(Debug, Deserialize)]
578struct RuntimeServerSectionWire {
579    #[serde(default = "default_host")]
580    host: String,
581    #[serde(default = "default_port")]
582    port: u16,
583    #[serde(default)]
584    tls: Option<InboundTlsSection>,
585}
586
587#[derive(Deserialize)]
588struct RuntimeTypeDBSectionWire {
589    address: String,
590    database: String,
591    #[serde(default = "default_username")]
592    username: String,
593    #[serde(default = "default_password")]
594    password: String,
595    #[serde(default = "default_http_port")]
596    http_port: u16,
597    #[serde(default)]
598    server_version: Option<String>,
599    #[serde(default)]
600    tls: Option<bool>,
601    #[serde(default, rename = "tls-root-ca")]
602    tls_root_ca: Option<PathBuf>,
603}
604
605impl fmt::Debug for RuntimeTypeDBSectionWire {
606    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
607        formatter
608            .debug_struct("RuntimeTypeDBSectionWire")
609            .field("address", &"[REDACTED]")
610            .field("database", &self.database)
611            .field("username", &"[REDACTED]")
612            .field("password", &"[REDACTED]")
613            .field("http_port", &self.http_port)
614            .field("server_version", &self.server_version)
615            .field("tls", &self.tls)
616            .field("tls_root_ca", &self.tls_root_ca)
617            .finish()
618    }
619}
620
621#[derive(Debug, Default, Deserialize)]
622struct RuntimeSchemaSectionWire {
623    #[serde(default)]
624    source_file: String,
625}
626
627#[derive(Debug, Default, Deserialize)]
628struct RuntimeInterceptorsSectionWire {
629    #[serde(default)]
630    enabled: Vec<String>,
631    #[serde(default, rename = "audit-log")]
632    audit_log: Option<RuntimeAuditLogConfigWire>,
633}
634
635#[derive(Debug, Clone, Deserialize)]
636struct RuntimeAuditLogConfigWire {
637    #[serde(default = "default_audit_output")]
638    output: String,
639    #[serde(default)]
640    file_path: String,
641}
642
643#[derive(Debug, Deserialize)]
644struct RuntimeLoggingSectionWire {
645    #[serde(default = "default_log_level")]
646    level: String,
647    #[serde(default = "default_log_format")]
648    format: String,
649}
650
651impl Default for RuntimeLoggingSectionWire {
652    fn default() -> Self {
653        Self {
654            level: default_log_level(),
655            format: default_log_format(),
656        }
657    }
658}
659
660#[derive(Debug, Default, Deserialize)]
661#[serde(deny_unknown_fields)]
662struct RuntimeV2SectionWire {
663    #[serde(default)]
664    enabled: bool,
665    #[serde(default)]
666    schema_authority_file: String,
667    #[serde(default)]
668    authority_mode: V2AuthorityMode,
669    #[serde(default)]
670    query_limits: std::collections::BTreeMap<String, u64>,
671    #[serde(default)]
672    answer_limits: std::collections::BTreeMap<String, u64>,
673    #[serde(default)]
674    allow_unauthenticated_staged_writes: bool,
675}
676
677impl From<RuntimeSchemaSectionWire> for SchemaSection {
678    fn from(wire: RuntimeSchemaSectionWire) -> Self {
679        Self {
680            source_file: wire.source_file,
681        }
682    }
683}
684
685impl From<RuntimeInterceptorsSectionWire> for InterceptorsSection {
686    fn from(wire: RuntimeInterceptorsSectionWire) -> Self {
687        Self {
688            enabled: wire.enabled,
689            audit_log: wire.audit_log.map(Into::into),
690        }
691    }
692}
693
694impl From<RuntimeAuditLogConfigWire> for AuditLogConfig {
695    fn from(wire: RuntimeAuditLogConfigWire) -> Self {
696        Self {
697            output: wire.output,
698            file_path: wire.file_path,
699        }
700    }
701}
702
703impl From<RuntimeLoggingSectionWire> for LoggingSection {
704    fn from(wire: RuntimeLoggingSectionWire) -> Self {
705        Self {
706            level: wire.level,
707            format: wire.format,
708        }
709    }
710}
711
712impl From<RuntimeV2SectionWire> for V2Section {
713    fn from(wire: RuntimeV2SectionWire) -> Self {
714        Self {
715            enabled: wire.enabled,
716            schema_authority_file: wire.schema_authority_file,
717            authority_mode: wire.authority_mode,
718            query_limits: wire.query_limits,
719            answer_limits: wire.answer_limits,
720            allow_unauthenticated_staged_writes: wire.allow_unauthenticated_staged_writes,
721        }
722    }
723}
724
725#[derive(Debug, Default, Deserialize)]
726/// Optional V1 TypeQL schema source configuration.
727pub struct SchemaSection {
728    /// Path to a TypeQL schema file, or an empty string when unused.
729    #[serde(default)]
730    pub source_file: String,
731}
732
733#[derive(Debug, Default, Deserialize)]
734/// Query-pipeline interceptor configuration.
735pub struct InterceptorsSection {
736    /// Interceptor names to install, in request order.
737    #[serde(default)]
738    pub enabled: Vec<String>,
739    /// Audit-log settings when the audit interceptor is enabled.
740    #[serde(default, rename = "audit-log")]
741    pub audit_log: Option<AuditLogConfig>,
742}
743
744#[derive(Debug, Clone, Deserialize)]
745/// Audit-log destination configuration.
746pub struct AuditLogConfig {
747    /// Destination kind: `stdout` or `file`.
748    #[serde(default = "default_audit_output")]
749    pub output: String,
750    /// Append-only file path when `output` is `file`.
751    #[serde(default)]
752    pub file_path: String,
753}
754
755#[derive(Debug, Deserialize)]
756/// Process log formatting and verbosity configuration.
757pub struct LoggingSection {
758    /// Tracing filter level such as `info` or `debug`.
759    #[serde(default = "default_log_level")]
760    pub level: String,
761    /// Log encoding format, such as `pretty` or `json`.
762    #[serde(default = "default_log_format")]
763    pub format: String,
764}
765
766impl Default for LoggingSection {
767    fn default() -> Self {
768        Self {
769            level: default_log_level(),
770            format: default_log_format(),
771        }
772    }
773}
774
775fn default_host() -> String {
776    "0.0.0.0".to_string()
777}
778
779fn default_port() -> u16 {
780    8080
781}
782
783fn default_http_port() -> u16 {
784    core_version::DEFAULT_HTTP_PORT
785}
786
787fn default_username() -> String {
788    "admin".to_string()
789}
790
791fn default_password() -> String {
792    "password".to_string()
793}
794
795fn default_log_level() -> String {
796    "info".to_string()
797}
798
799fn default_log_format() -> String {
800    "json".to_string()
801}
802
803fn default_audit_output() -> String {
804    "stdout".to_string()
805}
806
807impl ServerConfig {
808    /// Load the released plaintext server configuration.
809    pub fn from_file(path: &str) -> Result<Self, Box<dyn std::error::Error>> {
810        Self::from_file_with_env(path, |name| std::env::var(name).ok())
811    }
812
813    fn from_file_with_env<F>(path: &str, get_env: F) -> Result<Self, Box<dyn std::error::Error>>
814    where
815        F: FnMut(&str) -> Option<String>,
816    {
817        let content = std::fs::read_to_string(path)?;
818        let mut config: ServerConfig = toml::from_str(&content)?;
819        config.apply_env_overrides_from(get_env)?;
820        Ok(config)
821    }
822
823    fn apply_env_overrides_from<F>(
824        &mut self,
825        mut get_env: F,
826    ) -> Result<(), Box<dyn std::error::Error>>
827    where
828        F: FnMut(&str) -> Option<String>,
829    {
830        if let Some(address) = get_env("TYPEDB_ADDRESS") {
831            self.typedb.address = address;
832        }
833        if let Some(database) = get_env("TYPEDB_DATABASE") {
834            self.typedb.database = database;
835        }
836        if let Some(username) = get_env("TYPEDB_USERNAME") {
837            self.typedb.username = username;
838        }
839        if let Some(password) = get_env("TYPEDB_PASSWORD") {
840            self.typedb.password = password;
841        }
842        if let Some(raw) = get_env("TYPEDB_HTTP_PORT") {
843            self.typedb.http_port = raw.parse::<u16>().map_err(|_| {
844                format!("TYPEDB_HTTP_PORT must be a valid port number (0–65535), got {raw:?}")
845            })?;
846        }
847        if let Some(server_version) = get_env("TYPEDB_SERVER_VERSION") {
848            self.typedb.server_version = Some(server_version);
849        }
850        Ok(())
851    }
852}
853
854impl RuntimeServerConfig {
855    /// Load the standalone runtime projection, including secure and V2 TOML.
856    pub fn from_file(path: &str) -> Result<Self, Box<dyn std::error::Error>> {
857        Self::from_file_with_env(path, |name| std::env::var(name).ok())
858    }
859
860    /// Return the immutable V2 schema-authority bytes captured by [`Self::from_file`].
861    ///
862    /// A caller that mutates the public diagnostic path after loading must
863    /// reload the complete configuration instead of pairing it with stale
864    /// schema authority.
865    #[cfg(feature = "v2-query")]
866    pub fn v2_schema_authority_bytes(&self) -> Result<Option<&[u8]>, &'static str> {
867        let Some(material) = &self.typedb.v2_schema_authority_snapshot else {
868            return Ok(None);
869        };
870        if material.path != Path::new(&self.v2.schema_authority_file) {
871            return Err(
872                "v2.schema_authority_file changed after its bytes were captured; reload the configuration",
873            );
874        }
875        Ok(Some(material.bytes.as_ref()))
876    }
877
878    fn from_file_with_env<F>(path: &str, mut get_env: F) -> Result<Self, Box<dyn std::error::Error>>
879    where
880        F: FnMut(&str) -> Option<String>,
881    {
882        Self::from_file_with_env_after_probes(path, &mut get_env, || {}, || {})
883    }
884
885    #[cfg(test)]
886    fn from_file_with_env_after_probe<F, H>(
887        path: &str,
888        mut get_env: F,
889        after_probe: H,
890    ) -> Result<Self, Box<dyn std::error::Error>>
891    where
892        F: FnMut(&str) -> Option<String>,
893        H: FnOnce(),
894    {
895        Self::from_file_with_env_after_probes(path, &mut get_env, after_probe, || {})
896    }
897
898    fn from_file_with_env_after_probes<F, H, I>(
899        path: &str,
900        mut get_env: F,
901        after_probe: H,
902        after_authorized_read: I,
903    ) -> Result<Self, Box<dyn std::error::Error>>
904    where
905        F: FnMut(&str) -> Option<String>,
906        H: FnOnce(),
907        I: FnOnce(),
908    {
909        let (mut wire, relative_authority) = load_runtime_wire(path, after_probe)?;
910        // Tests use this seam to prove that every relative authority-bearing
911        // runtime file is opened through the already-retained directory even
912        // if its ambient name is replaced after the authoritative read.
913        after_authorized_read();
914        if let Some(address) = get_env("TYPEDB_ADDRESS") {
915            wire.typedb.address = address;
916        }
917        if let Some(database) = get_env("TYPEDB_DATABASE") {
918            wire.typedb.database = database;
919        }
920        if let Some(username) = get_env("TYPEDB_USERNAME") {
921            wire.typedb.username = username;
922        }
923        if let Some(password) = get_env("TYPEDB_PASSWORD") {
924            wire.typedb.password = password;
925        }
926        if let Some(raw) = get_env("TYPEDB_HTTP_PORT") {
927            wire.typedb.http_port = raw.parse::<u16>().map_err(|_| {
928                format!("TYPEDB_HTTP_PORT must be a valid port number (0–65535), got {raw:?}")
929            })?;
930        }
931        if let Some(server_version) = get_env("TYPEDB_SERVER_VERSION") {
932            wire.typedb.server_version = Some(server_version);
933        }
934
935        // Reject contradictions before resolving or opening any configured
936        // trust or identity path.
937        let tls_mode = outbound_tls_mode(wire.typedb.tls, wire.typedb.tls_root_ca.take())?;
938        let mut custom_root_ca_snapshot = None;
939        let tls_mode = match tls_mode {
940            OutboundTlsMode::CustomRootCa(path) => {
941                let resolved = resolve_configured_file(
942                    relative_authority.as_ref(),
943                    &path,
944                    "typedb.tls-root-ca",
945                )?;
946                custom_root_ca_snapshot =
947                    resolved.snapshot.map(|bytes| CapturedConfiguredMaterial {
948                        path: resolved.path.clone(),
949                        bytes,
950                    });
951                OutboundTlsMode::CustomRootCa(resolved.path)
952            }
953            other => other,
954        };
955        if let Some(tls) = &mut wire.server.tls {
956            let certificate = resolve_configured_file(
957                relative_authority.as_ref(),
958                &tls.cert_path,
959                "server.tls.cert-path",
960            )?;
961            let private_key = resolve_configured_file(
962                relative_authority.as_ref(),
963                &tls.key_path,
964                "server.tls.key-path",
965            )?;
966            tls.cert_path = certificate.path;
967            tls.key_path = private_key.path;
968            if certificate.snapshot.is_some() || private_key.snapshot.is_some() {
969                tls.prepared = Some(PreparedInboundTlsMaterial {
970                    certificate: certificate
971                        .snapshot
972                        .map(|bytes| CapturedConfiguredMaterial {
973                            path: tls.cert_path.clone(),
974                            bytes,
975                        }),
976                    private_key: private_key
977                        .snapshot
978                        .map(|bytes| CapturedConfiguredMaterial {
979                            path: tls.key_path.clone(),
980                            bytes,
981                        }),
982                });
983            }
984        }
985
986        #[cfg(feature = "v2-query")]
987        let v2_schema_authority_snapshot = if wire.v2.enabled
988            && !wire.v2.schema_authority_file.is_empty()
989        {
990            let configured_path = Path::new(&wire.v2.schema_authority_file);
991            Some(CapturedConfiguredMaterial {
992                path: configured_path.to_path_buf(),
993                bytes: capture_schema_authority_file(relative_authority.as_ref(), configured_path)?,
994            })
995        } else {
996            None
997        };
998
999        Ok(Self {
1000            server: ServerSection {
1001                host: wire.server.host,
1002                port: wire.server.port,
1003            },
1004            typedb: SecureTypeDBSection {
1005                connection: TypeDBSection {
1006                    address: wire.typedb.address,
1007                    database: wire.typedb.database,
1008                    username: wire.typedb.username,
1009                    password: wire.typedb.password,
1010                    http_port: wire.typedb.http_port,
1011                    server_version: wire.typedb.server_version,
1012                },
1013                tls_mode,
1014                custom_root_ca_snapshot,
1015                #[cfg(feature = "v2-query")]
1016                v2_schema_authority_snapshot,
1017            },
1018            schema: wire.schema.into(),
1019            interceptors: wire.interceptors.into(),
1020            logging: wire.logging.into(),
1021            inbound_tls: wire.server.tls,
1022            v2: wire.v2.into(),
1023        })
1024    }
1025}
1026
1027fn read_runtime_config_path(path: &Path) -> Result<String, Box<dyn std::error::Error>> {
1028    let mut options = std::fs::OpenOptions::new();
1029    options.read(true);
1030    #[cfg(unix)]
1031    options.custom_flags(rustix::fs::OFlags::NONBLOCK.bits() as i32);
1032    #[cfg(windows)]
1033    {
1034        const FILE_SHARE_READ: u32 = 0x0000_0001;
1035        // Backup semantics let a directory path open so the regular-file
1036        // classification comes from the opened handle's metadata, exactly
1037        // as it does on Unix.
1038        const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;
1039        options.share_mode(FILE_SHARE_READ);
1040        options.custom_flags(FILE_FLAG_BACKUP_SEMANTICS);
1041    }
1042    let file = options
1043        .open(path)
1044        .map_err(|error| format!("cannot read server configuration: {error}"))?;
1045    read_runtime_config_handle(file)
1046}
1047
1048fn read_runtime_config_handle(file: std::fs::File) -> Result<String, Box<dyn std::error::Error>> {
1049    read_runtime_config_handle_with_hooks(file, || {}, || {})
1050}
1051
1052#[cfg(test)]
1053fn read_runtime_config_handle_after_inspect<H>(
1054    file: std::fs::File,
1055    after_inspect: H,
1056) -> Result<String, Box<dyn std::error::Error>>
1057where
1058    H: FnOnce(),
1059{
1060    read_runtime_config_handle_with_hooks(file, after_inspect, || {})
1061}
1062
1063fn read_runtime_config_handle_with_hooks<H, I>(
1064    mut file: std::fs::File,
1065    after_inspect: H,
1066    after_first_read: I,
1067) -> Result<String, Box<dyn std::error::Error>>
1068where
1069    H: FnOnce(),
1070    I: FnOnce(),
1071{
1072    let metadata = file
1073        .metadata()
1074        .map_err(|error| format!("cannot inspect server configuration: {error}"))?;
1075    if !metadata.is_file() || metadata.len() > MAX_SERVER_CONFIG_BYTES {
1076        return Err("server configuration must name a regular file no larger than 1 MiB".into());
1077    }
1078    after_inspect();
1079    let mut bytes = Vec::new();
1080    (&mut file)
1081        .take(MAX_SERVER_CONFIG_BYTES + 1)
1082        .read_to_end(&mut bytes)
1083        .map_err(|error| format!("cannot read server configuration: {error}"))?;
1084    if u64::try_from(bytes.len()).unwrap_or(u64::MAX) > MAX_SERVER_CONFIG_BYTES {
1085        return Err("server configuration must be no larger than 1 MiB".into());
1086    }
1087    after_first_read();
1088    file.seek(SeekFrom::Start(0))
1089        .map_err(|error| format!("cannot reread server configuration: {error}"))?;
1090    let mut verification_bytes = Vec::new();
1091    (&mut file)
1092        .take(MAX_SERVER_CONFIG_BYTES + 1)
1093        .read_to_end(&mut verification_bytes)
1094        .map_err(|error| format!("cannot reread server configuration: {error}"))?;
1095    let after = file
1096        .metadata()
1097        .map_err(|error| format!("cannot inspect server configuration: {error}"))?;
1098    let timestamps_match = match (metadata.modified(), after.modified()) {
1099        (Ok(before), Ok(after)) => before == after,
1100        (Err(_), Err(_)) => true,
1101        _ => false,
1102    };
1103    if metadata.len() != after.len()
1104        || metadata.len() != u64::try_from(bytes.len()).unwrap_or(u64::MAX)
1105        || bytes != verification_bytes
1106        || !timestamps_match
1107    {
1108        return Err("server configuration changed while it was being read".into());
1109    }
1110    String::from_utf8(bytes).map_err(|_| "server configuration must be valid UTF-8".into())
1111}
1112
1113fn load_runtime_wire<H>(
1114    path: &str,
1115    after_probe: H,
1116) -> Result<(RuntimeServerConfigWire, Option<RelativeConfigAuthority>), Box<dyn std::error::Error>>
1117where
1118    H: FnOnce(),
1119{
1120    let content = read_runtime_config_path(Path::new(path))?;
1121    let wire = parse_runtime_wire(&content)?;
1122    // Preserve fail-fast contradiction handling: a relative path must not
1123    // cause any additional pathname lookup when the policy itself is invalid.
1124    outbound_tls_mode(wire.typedb.tls, wire.typedb.tls_root_ca.clone())?;
1125    after_probe();
1126
1127    if !wire_uses_relative_runtime_paths(&wire) {
1128        return Ok((wire, None));
1129    }
1130
1131    // The preliminary bytes only determine whether compatibility permits a
1132    // single read. Once relative security material is present, resolve the
1133    // configuration identity first and use bytes read through that resolved
1134    // path. This prevents a configuration symlink swap from pairing one
1135    // target's policy with another target's base directory.
1136    let resolved_config = Path::new(path).canonicalize()?;
1137    let authority = RelativeConfigAuthority::open(&resolved_config)?;
1138    let content = authority.read_config()?;
1139    let wire = parse_runtime_wire(&content)?;
1140    outbound_tls_mode(wire.typedb.tls, wire.typedb.tls_root_ca.clone())?;
1141    let relative_authority = if wire_uses_relative_runtime_paths(&wire) {
1142        Some(authority)
1143    } else {
1144        None
1145    };
1146    Ok((wire, relative_authority))
1147}
1148
1149struct RelativeConfigAuthority {
1150    directory: Dir,
1151    ancestors: Vec<Dir>,
1152    config_name: OsString,
1153    display_base: PathBuf,
1154}
1155
1156impl RelativeConfigAuthority {
1157    fn open(resolved_config: &Path) -> Result<Self, Box<dyn std::error::Error>> {
1158        let display_base = resolved_config
1159            .parent()
1160            .ok_or("server configuration path has no parent directory")?
1161            .to_path_buf();
1162        let config_name = resolved_config
1163            .file_name()
1164            .map(OsString::from)
1165            .ok_or("server configuration path has no file name")?;
1166        // Open every absolute component from a retained root handle. Keeping
1167        // the complete lineage makes `../` relative paths stable too: a later
1168        // rename cannot cause `open_parent_dir` to discover a different
1169        // ambient parent.
1170        let mut components = display_base.components();
1171        let mut anchor = PathBuf::new();
1172        let mut saw_prefix = false;
1173        let mut saw_root = false;
1174        loop {
1175            match components.clone().next() {
1176                Some(Component::Prefix(prefix)) if !saw_prefix && !saw_root => {
1177                    anchor.push(prefix.as_os_str());
1178                    saw_prefix = true;
1179                    let _ = components.next();
1180                }
1181                Some(Component::RootDir) if !saw_root => {
1182                    anchor.push(Component::RootDir.as_os_str());
1183                    saw_root = true;
1184                    let _ = components.next();
1185                }
1186                _ => break,
1187            }
1188        }
1189        if !saw_root {
1190            return Err("resolved server configuration directory is not absolute".into());
1191        }
1192        let mut directory = Dir::open_ambient_dir(&anchor, ambient_authority())?;
1193        let mut ancestors = Vec::new();
1194        for component in components {
1195            match component {
1196                Component::CurDir => {}
1197                Component::Normal(name) => {
1198                    let child = directory.open_dir_nofollow(name)?;
1199                    ancestors.push(directory);
1200                    directory = child;
1201                }
1202                Component::ParentDir | Component::Prefix(_) | Component::RootDir => {
1203                    return Err(
1204                        "resolved server configuration directory has an invalid component".into(),
1205                    );
1206                }
1207            }
1208        }
1209        Ok(Self {
1210            directory,
1211            ancestors,
1212            config_name,
1213            display_base,
1214        })
1215    }
1216
1217    fn read_config(&self) -> Result<String, Box<dyn std::error::Error>> {
1218        let mut options = OpenOptions::new();
1219        options.read(true).follow(FollowSymlinks::No);
1220        // A directory must open (Windows needs backup semantics for that)
1221        // so the regular-file classification comes from the opened handle's
1222        // metadata, exactly as it does on Unix.
1223        options.maybe_dir(true);
1224        #[cfg(unix)]
1225        options.nonblock(true);
1226        #[cfg(windows)]
1227        {
1228            const FILE_SHARE_READ: u32 = 0x0000_0001;
1229            options.share_mode(FILE_SHARE_READ);
1230        }
1231        let file = self
1232            .directory
1233            .open_with(Path::new(&self.config_name), &options)
1234            .map(cap_std::fs::File::into_std)?;
1235        read_runtime_config_handle(file)
1236    }
1237
1238    fn open_relative_file_nofollow(
1239        &self,
1240        path: &Path,
1241        field: &str,
1242    ) -> Result<std::fs::File, Box<dyn std::error::Error>> {
1243        if path.as_os_str().is_empty() || path.is_absolute() {
1244            return Err(format!("{field} must be a non-empty relative path").into());
1245        }
1246        let file_name = path
1247            .file_name()
1248            .map(OsString::from)
1249            .ok_or_else(|| format!("{field} must name a file"))?;
1250        let parent = path.parent().unwrap_or_else(|| Path::new(""));
1251        let mut directory = self
1252            .directory
1253            .try_clone()
1254            .map_err(|error| format!("cannot resolve {field}: {error}"))?;
1255        let mut ancestors = self
1256            .ancestors
1257            .iter()
1258            .map(Dir::try_clone)
1259            .collect::<Result<Vec<_>, _>>()
1260            .map_err(|error| format!("cannot resolve {field}: {error}"))?;
1261        for component in parent.components() {
1262            match component {
1263                Component::CurDir => {}
1264                Component::ParentDir => {
1265                    directory = ancestors.pop().ok_or_else(|| {
1266                        format!("cannot resolve {field}: path escapes the filesystem root")
1267                    })?;
1268                }
1269                Component::Normal(name) => {
1270                    let child = directory
1271                        .open_dir_nofollow(name)
1272                        .map_err(|error| format!("cannot resolve {field}: {error}"))?;
1273                    ancestors.push(directory);
1274                    directory = child;
1275                }
1276                Component::Prefix(_) | Component::RootDir => {
1277                    return Err(format!("{field} contains an invalid path component").into());
1278                }
1279            }
1280        }
1281
1282        let mut options = OpenOptions::new();
1283        options.read(true).follow(FollowSymlinks::No);
1284        // A directory must open (Windows needs backup semantics for that)
1285        // so the regular-file classification comes from the opened handle's
1286        // metadata, exactly as it does on Unix.
1287        options.maybe_dir(true);
1288        #[cfg(unix)]
1289        options.nonblock(true);
1290        #[cfg(windows)]
1291        {
1292            // Permit only concurrent readers while the bounded snapshot is
1293            // captured; replacement and writes remain denied on Windows.
1294            const FILE_SHARE_READ: u32 = 0x0000_0001;
1295            options.share_mode(FILE_SHARE_READ);
1296        }
1297        directory
1298            .open_with(Path::new(&file_name), &options)
1299            .map(cap_std::fs::File::into_std)
1300            .map_err(|error| format!("cannot resolve {field}: {error}").into())
1301    }
1302
1303    fn capture_relative_file(
1304        &self,
1305        path: &Path,
1306        field: &str,
1307    ) -> Result<ResolvedConfiguredFile, Box<dyn std::error::Error>> {
1308        let mut file = self.open_relative_file_nofollow(path, field)?;
1309        let metadata = file
1310            .metadata()
1311            .map_err(|error| format!("cannot inspect {field}: {error}"))?;
1312        if !metadata.is_file() {
1313            return Err(format!("{field} must name a regular file").into());
1314        }
1315        if metadata.len() == 0 || metadata.len() > MAX_TLS_MATERIAL_BYTES {
1316            return Err(format!("{field} must be a non-empty file no larger than 1 MiB").into());
1317        }
1318        let mut bytes = Vec::new();
1319        (&mut file)
1320            .take(MAX_TLS_MATERIAL_BYTES + 1)
1321            .read_to_end(&mut bytes)
1322            .map_err(|error| format!("cannot read {field}: {error}"))?;
1323        if bytes.is_empty()
1324            || u64::try_from(bytes.len()).unwrap_or(u64::MAX) > MAX_TLS_MATERIAL_BYTES
1325        {
1326            return Err(format!("{field} must be a non-empty file no larger than 1 MiB").into());
1327        }
1328        file.seek(SeekFrom::Start(0))
1329            .map_err(|error| format!("cannot reread {field}: {error}"))?;
1330        let mut verification_bytes = Vec::new();
1331        (&mut file)
1332            .take(MAX_TLS_MATERIAL_BYTES + 1)
1333            .read_to_end(&mut verification_bytes)
1334            .map_err(|error| format!("cannot reread {field}: {error}"))?;
1335        let after = file
1336            .metadata()
1337            .map_err(|error| format!("cannot inspect {field}: {error}"))?;
1338        let timestamps_match = match (metadata.modified(), after.modified()) {
1339            (Ok(before), Ok(after)) => before == after,
1340            (Err(_), Err(_)) => true,
1341            _ => false,
1342        };
1343        if metadata.len() != after.len()
1344            || metadata.len() != u64::try_from(bytes.len()).unwrap_or(u64::MAX)
1345            || bytes != verification_bytes
1346            || !timestamps_match
1347        {
1348            return Err(format!("{field} changed while it was being read").into());
1349        }
1350        Ok(ResolvedConfiguredFile {
1351            // This path remains a diagnostic projection only. Consumers use
1352            // `snapshot` for relative files, so an ambient parent replacement
1353            // cannot redirect a later TLS read through this name.
1354            path: self.display_base.join(path),
1355            snapshot: Some(bytes.into()),
1356        })
1357    }
1358
1359    #[cfg(feature = "v2-query")]
1360    fn capture_relative_schema_authority(
1361        &self,
1362        path: &Path,
1363    ) -> Result<Arc<[u8]>, Box<dyn std::error::Error>> {
1364        let file = self.open_relative_file_nofollow(path, "v2.schema_authority_file")?;
1365        capture_schema_authority_handle(file)
1366    }
1367}
1368
1369#[cfg(feature = "v2-query")]
1370fn capture_schema_authority_file(
1371    relative_authority: Option<&RelativeConfigAuthority>,
1372    path: &Path,
1373) -> Result<Arc<[u8]>, Box<dyn std::error::Error>> {
1374    if path.is_absolute() {
1375        return capture_absolute_schema_authority_file(path);
1376    }
1377    relative_authority
1378        .ok_or(
1379            "cannot resolve relative v2.schema_authority_file without the configuration directory",
1380        )?
1381        .capture_relative_schema_authority(path)
1382}
1383
1384#[cfg(feature = "v2-query")]
1385fn capture_absolute_schema_authority_file(
1386    path: &Path,
1387) -> Result<Arc<[u8]>, Box<dyn std::error::Error>> {
1388    let field = "v2.schema_authority_file";
1389    let anchor = path
1390        .ancestors()
1391        .last()
1392        .ok_or_else(|| format!("{field} has no filesystem anchor"))?;
1393    let relative = path
1394        .strip_prefix(anchor)
1395        .map_err(|_| format!("{field} is not beneath its filesystem anchor"))?;
1396    let components = relative
1397        .components()
1398        .map(|component| match component {
1399            Component::Normal(name) => Ok(name),
1400            _ => Err(format!("{field} contains an invalid path component")),
1401        })
1402        .collect::<Result<Vec<_>, _>>()?;
1403    let (name, parents) = components
1404        .split_last()
1405        .ok_or_else(|| format!("{field} has no file name"))?;
1406    let mut directory = Dir::open_ambient_dir(anchor, ambient_authority())
1407        .map_err(|error| format!("cannot resolve {field}: {error}"))?;
1408    for parent in parents {
1409        directory = directory
1410            .open_dir_nofollow(parent)
1411            .map_err(|error| format!("cannot resolve {field}: {error}"))?;
1412    }
1413    let mut options = OpenOptions::new();
1414    options.read(true).follow(FollowSymlinks::No);
1415    // A directory must open (Windows needs backup semantics for that) so
1416    // the regular-file classification comes from the opened handle's
1417    // metadata, exactly as it does on Unix.
1418    options.maybe_dir(true);
1419    #[cfg(unix)]
1420    options.nonblock(true);
1421    #[cfg(windows)]
1422    {
1423        const FILE_SHARE_READ: u32 = 0x0000_0001;
1424        options.share_mode(FILE_SHARE_READ);
1425    }
1426    let file = directory
1427        .open_with(name, &options)
1428        .map(cap_std::fs::File::into_std)
1429        .map_err(|error| format!("cannot resolve {field}: {error}"))?;
1430    capture_schema_authority_handle(file)
1431}
1432
1433#[cfg(feature = "v2-query")]
1434fn capture_schema_authority_handle(
1435    mut file: std::fs::File,
1436) -> Result<Arc<[u8]>, Box<dyn std::error::Error>> {
1437    let field = "v2.schema_authority_file";
1438    let ceiling = u64::try_from(MAX_SCHEMA_AUTHORITY_BYTES)
1439        .map_err(|_| "canonical schema-authority byte ceiling is not representable")?;
1440    let metadata = file
1441        .metadata()
1442        .map_err(|error| format!("cannot inspect {field}: {error}"))?;
1443    if !metadata.is_file() {
1444        return Err(format!("{field} must name a regular file").into());
1445    }
1446    if metadata.len() == 0 || metadata.len() > ceiling {
1447        return Err(format!("{field} must be a non-empty file no larger than 16 MiB").into());
1448    }
1449
1450    let mut bytes = Vec::new();
1451    (&mut file)
1452        .take(ceiling + 1)
1453        .read_to_end(&mut bytes)
1454        .map_err(|error| format!("cannot read {field}: {error}"))?;
1455    if bytes.is_empty() || bytes.len() > MAX_SCHEMA_AUTHORITY_BYTES {
1456        return Err(format!("{field} must be a non-empty file no larger than 16 MiB").into());
1457    }
1458    file.seek(SeekFrom::Start(0))
1459        .map_err(|error| format!("cannot reread {field}: {error}"))?;
1460    let mut verification_bytes = Vec::new();
1461    (&mut file)
1462        .take(ceiling + 1)
1463        .read_to_end(&mut verification_bytes)
1464        .map_err(|error| format!("cannot reread {field}: {error}"))?;
1465    let after = file
1466        .metadata()
1467        .map_err(|error| format!("cannot inspect {field}: {error}"))?;
1468    let timestamps_match = match (metadata.modified(), after.modified()) {
1469        (Ok(before), Ok(after)) => before == after,
1470        (Err(_), Err(_)) => true,
1471        _ => false,
1472    };
1473    if metadata.len() != after.len()
1474        || metadata.len() != u64::try_from(bytes.len()).unwrap_or(u64::MAX)
1475        || bytes != verification_bytes
1476        || !timestamps_match
1477    {
1478        return Err(format!("{field} changed while it was being read").into());
1479    }
1480    Ok(bytes.into())
1481}
1482
1483fn parse_runtime_wire(
1484    content: &str,
1485) -> Result<RuntimeServerConfigWire, Box<dyn std::error::Error>> {
1486    reject_ambiguous_security_keys(content)?;
1487    toml::from_str(content).map_err(|error| {
1488        RuntimeConfigParseError::from_toml(RuntimeConfigParseErrorKind::ValueShape, content, error)
1489            .into()
1490    })
1491}
1492
1493fn wire_uses_relative_runtime_paths(wire: &RuntimeServerConfigWire) -> bool {
1494    let uses_relative_tls_path = wire
1495        .typedb
1496        .tls_root_ca
1497        .as_deref()
1498        .is_some_and(|path| !path.is_absolute())
1499        || wire
1500            .server
1501            .tls
1502            .as_ref()
1503            .is_some_and(|tls| !tls.cert_path.is_absolute() || !tls.key_path.is_absolute());
1504    #[cfg(feature = "v2-query")]
1505    {
1506        uses_relative_tls_path
1507            || (wire.v2.enabled
1508                && !wire.v2.schema_authority_file.is_empty()
1509                && !Path::new(&wire.v2.schema_authority_file).is_absolute())
1510    }
1511    #[cfg(not(feature = "v2-query"))]
1512    {
1513        uses_relative_tls_path
1514    }
1515}
1516
1517/// Preserve the released parser's tolerance for extension keys without
1518/// allowing a misspelled TLS option to be silently ignored as plaintext.
1519fn reject_ambiguous_security_keys(content: &str) -> Result<(), Box<dyn std::error::Error>> {
1520    let document: toml::Value = toml::from_str(content).map_err(|error| {
1521        RuntimeConfigParseError::from_toml(RuntimeConfigParseErrorKind::Syntax, content, error)
1522    })?;
1523    let Some(root) = document.as_table() else {
1524        return Ok(());
1525    };
1526    for key in root.keys() {
1527        let path = [key.clone()];
1528        if security_shaped_key(key) && !documented_security_path(&path) {
1529            return Err(RuntimeConfigParseError::unknown_security_key().into());
1530        }
1531    }
1532    for namespace in ["server", "typedb"] {
1533        let Some(table) = root.get(namespace).and_then(toml::Value::as_table) else {
1534            continue;
1535        };
1536        for key in table.keys() {
1537            let path = [namespace.to_owned(), key.clone()];
1538            if security_shaped_key(key) && !documented_security_path(&path) {
1539                return Err(RuntimeConfigParseError::unknown_security_key().into());
1540            }
1541        }
1542    }
1543    Ok(())
1544}
1545
1546fn documented_security_path(path: &[String]) -> bool {
1547    matches!(
1548        path,
1549        [server, tls]
1550            if server == "server" && tls == "tls"
1551    ) || matches!(
1552        path,
1553        [server, tls, field]
1554            if server == "server"
1555                && tls == "tls"
1556                && matches!(field.as_str(), "cert-path" | "key-path")
1557    ) || matches!(
1558        path,
1559        [typedb, field]
1560            if typedb == "typedb" && matches!(field.as_str(), "tls" | "tls-root-ca")
1561    )
1562}
1563
1564fn security_shaped_key(key: &str) -> bool {
1565    let normalized = key
1566        .chars()
1567        .filter(|character| character.is_ascii_alphanumeric())
1568        .flat_map(char::to_lowercase)
1569        .collect::<String>();
1570    normalized.starts_with("tls")
1571        || normalized.ends_with("tls")
1572        || normalized.starts_with("ssl")
1573        || normalized.ends_with("ssl")
1574        || normalized.starts_with("https")
1575        || normalized.ends_with("https")
1576        || matches!(
1577            normalized.as_str(),
1578            "cafile"
1579                | "capath"
1580                | "rootca"
1581                | "rootcapath"
1582                | "truststore"
1583                | "truststorepath"
1584                | "certfile"
1585                | "certificatepath"
1586                | "certpath"
1587                | "clientcert"
1588                | "clientcertpath"
1589                | "keyfile"
1590                | "keypath"
1591                | "privatekey"
1592                | "privatekeypath"
1593        )
1594}
1595
1596impl OutboundTlsMode {
1597    /// Return whether this policy requires TLS on every outbound transport.
1598    #[must_use]
1599    pub const fn is_enabled(&self) -> bool {
1600        !matches!(self, Self::Disabled)
1601    }
1602}
1603
1604fn outbound_tls_mode(
1605    tls: Option<bool>,
1606    root: Option<PathBuf>,
1607) -> Result<OutboundTlsMode, Box<dyn std::error::Error>> {
1608    match (tls, root) {
1609        (None | Some(false), None) => Ok(OutboundTlsMode::Disabled),
1610        (Some(true), None) => Ok(OutboundTlsMode::NativeRoots),
1611        (Some(true), Some(path)) => Ok(OutboundTlsMode::CustomRootCa(path)),
1612        (Some(false), Some(_)) => Err("typedb.tls-root-ca contradicts typedb.tls = false".into()),
1613        (None, Some(_)) => Err("typedb.tls-root-ca requires explicit typedb.tls = true".into()),
1614    }
1615}
1616
1617struct ResolvedConfiguredFile {
1618    path: PathBuf,
1619    snapshot: Option<Arc<[u8]>>,
1620}
1621
1622fn capture_tls_material_handle(
1623    mut file: std::fs::File,
1624    field: &str,
1625) -> Result<Arc<[u8]>, Box<dyn std::error::Error>> {
1626    let metadata = file
1627        .metadata()
1628        .map_err(|error| format!("cannot inspect {field}: {error}"))?;
1629    if !metadata.is_file() {
1630        return Err(format!("{field} must name a regular file").into());
1631    }
1632    if metadata.len() == 0 || metadata.len() > MAX_TLS_MATERIAL_BYTES {
1633        return Err(format!("{field} must be a non-empty file no larger than 1 MiB").into());
1634    }
1635
1636    let mut bytes = Vec::new();
1637    (&mut file)
1638        .take(MAX_TLS_MATERIAL_BYTES + 1)
1639        .read_to_end(&mut bytes)
1640        .map_err(|error| format!("cannot read {field}: {error}"))?;
1641    if bytes.is_empty() || u64::try_from(bytes.len()).unwrap_or(u64::MAX) > MAX_TLS_MATERIAL_BYTES {
1642        return Err(format!("{field} must be a non-empty file no larger than 1 MiB").into());
1643    }
1644    file.seek(SeekFrom::Start(0))
1645        .map_err(|error| format!("cannot reread {field}: {error}"))?;
1646    let mut verification_bytes = Vec::new();
1647    (&mut file)
1648        .take(MAX_TLS_MATERIAL_BYTES + 1)
1649        .read_to_end(&mut verification_bytes)
1650        .map_err(|error| format!("cannot reread {field}: {error}"))?;
1651    let after = file
1652        .metadata()
1653        .map_err(|error| format!("cannot inspect {field}: {error}"))?;
1654    let timestamps_match = match (metadata.modified(), after.modified()) {
1655        (Ok(before), Ok(after)) => before == after,
1656        (Err(_), Err(_)) => true,
1657        _ => false,
1658    };
1659    if metadata.len() != after.len()
1660        || metadata.len() != u64::try_from(bytes.len()).unwrap_or(u64::MAX)
1661        || bytes != verification_bytes
1662        || !timestamps_match
1663    {
1664        return Err(format!("{field} changed while it was being read").into());
1665    }
1666    Ok(bytes.into())
1667}
1668
1669fn capture_absolute_configured_file(
1670    path: &Path,
1671    field: &str,
1672) -> Result<ResolvedConfiguredFile, Box<dyn std::error::Error>> {
1673    if path.as_os_str().is_empty() || !path.is_absolute() {
1674        return Err(format!("{field} must be a non-empty absolute path").into());
1675    }
1676    let mut options = std::fs::OpenOptions::new();
1677    options.read(true);
1678    #[cfg(unix)]
1679    options.custom_flags(rustix::fs::OFlags::NONBLOCK.bits() as i32);
1680    #[cfg(windows)]
1681    {
1682        const FILE_SHARE_READ: u32 = 0x0000_0001;
1683        // Backup semantics let a directory path open so the regular-file
1684        // classification comes from the opened handle's metadata, exactly
1685        // as it does on Unix.
1686        const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;
1687        options.share_mode(FILE_SHARE_READ);
1688        options.custom_flags(FILE_FLAG_BACKUP_SEMANTICS);
1689    }
1690    let file = options
1691        .open(path)
1692        .map_err(|error| format!("cannot resolve {field}: {error}"))?;
1693    let snapshot = capture_tls_material_handle(file, field)?;
1694    let canonical = path
1695        .canonicalize()
1696        .map_err(|error| format!("cannot resolve {field}: {error}"))?;
1697    Ok(ResolvedConfiguredFile {
1698        path: canonical,
1699        snapshot: Some(snapshot),
1700    })
1701}
1702
1703fn resolve_configured_file(
1704    relative_authority: Option<&RelativeConfigAuthority>,
1705    path: &Path,
1706    field: &str,
1707) -> Result<ResolvedConfiguredFile, Box<dyn std::error::Error>> {
1708    if path.is_absolute() {
1709        return capture_absolute_configured_file(path, field);
1710    }
1711    let authority = relative_authority.ok_or_else(|| {
1712        format!("cannot resolve relative {field} without the configuration directory")
1713    })?;
1714    authority.capture_relative_file(path, field)
1715}
1716
1717#[cfg(test)]
1718#[cfg_attr(coverage_nightly, coverage(off))]
1719mod tests {
1720    use super::*;
1721
1722    const FULL_CONFIG: &str = r#"
1723[server]
1724host = "127.0.0.1"
1725port = 9090
1726
1727[typedb]
1728address = "localhost:1729"
1729database = "mydb"
1730username = "root"
1731password = "secret"
1732server_version = "3.11.5"
1733
1734[schema]
1735source_file = "schema.tql"
1736
1737[interceptors]
1738enabled = ["audit-log"]
1739
1740[interceptors.audit-log]
1741output = "file"
1742file_path = "/tmp/audit.log"
1743
1744[logging]
1745level = "debug"
1746format = "text"
1747"#;
1748
1749    const MINIMAL_CONFIG: &str = r#"
1750[server]
1751
1752[typedb]
1753address = "localhost:1729"
1754database = "mydb"
1755"#;
1756
1757    // --- from_file tests ---
1758
1759    #[test]
1760    fn from_file_valid_full_config() {
1761        let dir = tempfile::tempdir().unwrap();
1762        let path = dir.path().join("server.toml");
1763        std::fs::write(&path, FULL_CONFIG).unwrap();
1764
1765        let config = ServerConfig::from_file_with_env(path.to_str().unwrap(), |_| None).unwrap();
1766        assert_eq!(config.server.host, "127.0.0.1");
1767        assert_eq!(config.server.port, 9090);
1768        assert_eq!(config.typedb.address, "localhost:1729");
1769        assert_eq!(config.typedb.database, "mydb");
1770        assert_eq!(config.typedb.username, "root");
1771        assert_eq!(config.typedb.password, "secret");
1772        assert_eq!(config.typedb.server_version.as_deref(), Some("3.11.5"));
1773        assert_eq!(config.schema.source_file, "schema.tql");
1774        assert_eq!(config.interceptors.enabled, vec!["audit-log"]);
1775        let audit = config.interceptors.audit_log.unwrap();
1776        assert_eq!(audit.output, "file");
1777        assert_eq!(audit.file_path, "/tmp/audit.log");
1778        assert_eq!(config.logging.level, "debug");
1779        assert_eq!(config.logging.format, "text");
1780    }
1781
1782    #[test]
1783    fn v2_section_defaults_to_disabled() {
1784        let dir = tempfile::tempdir().unwrap();
1785        let path = dir.path().join("server.toml");
1786        std::fs::write(&path, MINIMAL_CONFIG).unwrap();
1787
1788        let config =
1789            RuntimeServerConfig::from_file_with_env(path.to_str().unwrap(), |_| None).unwrap();
1790        assert!(!config.v2.enabled);
1791        assert!(config.v2.schema_authority_file.is_empty());
1792        assert_eq!(config.v2.authority_mode, V2AuthorityMode::Managed);
1793        assert_eq!(config.typedb.tls_mode, OutboundTlsMode::Disabled);
1794        assert!(config.inbound_tls.is_none());
1795    }
1796
1797    #[test]
1798    fn v2_section_parses_when_configured() {
1799        let config_text = format!(
1800            "{MINIMAL_CONFIG}\n[v2]\nenabled = true\n\
1801             schema_authority_file = \"schema-authority.json\"\n\
1802             authority_mode = \"query_only\"\n"
1803        );
1804        let dir = tempfile::tempdir().unwrap();
1805        let path = dir.path().join("server.toml");
1806        std::fs::write(&path, config_text).unwrap();
1807        #[cfg(feature = "v2-query")]
1808        std::fs::write(
1809            dir.path().join("schema-authority.json"),
1810            "captured authority",
1811        )
1812        .unwrap();
1813
1814        let config =
1815            RuntimeServerConfig::from_file_with_env(path.to_str().unwrap(), |_| None).unwrap();
1816        assert!(config.v2.enabled);
1817        assert_eq!(config.v2.schema_authority_file, "schema-authority.json");
1818        assert_eq!(config.v2.authority_mode, V2AuthorityMode::QueryOnly);
1819    }
1820
1821    #[test]
1822    fn v2_section_rejects_removed_duplicate_authority_fields() {
1823        for removed in [
1824            "declared_schema_file = \"declared-schema.json\"",
1825            "scope = \"prod\"",
1826            "profile = \"typedb-3.12.1/v1\"",
1827        ] {
1828            let dir = tempfile::tempdir().unwrap();
1829            let path = dir.path().join("server.toml");
1830            std::fs::write(
1831                &path,
1832                format!("{MINIMAL_CONFIG}\n[v2]\nenabled = false\n{removed}\n"),
1833            )
1834            .unwrap();
1835
1836            RuntimeServerConfig::from_file_with_env(path.to_str().unwrap(), |_| None)
1837                .expect_err("removed V2 authority fields must fail closed");
1838        }
1839    }
1840
1841    #[cfg(feature = "v2-query")]
1842    #[test]
1843    fn relative_v2_schema_authority_is_config_relative_and_snapshot_stable() {
1844        let dir = tempfile::tempdir().unwrap();
1845        let schemas = dir.path().join("schemas");
1846        std::fs::create_dir(&schemas).unwrap();
1847        let authority_path = schemas.join("schema-authority.json");
1848        let original = b"captured schema authority";
1849        std::fs::write(&authority_path, original).unwrap();
1850        let config_path = dir.path().join("server.toml");
1851        std::fs::write(
1852            &config_path,
1853            format!(
1854                "{MINIMAL_CONFIG}\n[schema]\nsource_file = \"released-schema.tql\"\n\
1855                 [v2]\nenabled = true\nschema_authority_file = \"schemas/schema-authority.json\"\n"
1856            ),
1857        )
1858        .unwrap();
1859
1860        let mut config =
1861            RuntimeServerConfig::from_file_with_env(config_path.to_str().unwrap(), |_| None)
1862                .unwrap();
1863        assert_eq!(
1864            config.v2.schema_authority_file,
1865            "schemas/schema-authority.json"
1866        );
1867        assert_eq!(config.schema.source_file, "released-schema.tql");
1868        assert_eq!(
1869            config.v2_schema_authority_bytes().unwrap(),
1870            Some(original.as_slice())
1871        );
1872
1873        std::fs::write(&authority_path, "ambient replacement").unwrap();
1874        assert_eq!(
1875            config.v2_schema_authority_bytes().unwrap(),
1876            Some(original.as_slice()),
1877            "post-load replacement must not change V2 schema authority"
1878        );
1879
1880        config.v2.schema_authority_file = "other.json".to_owned();
1881        let error = config
1882            .v2_schema_authority_bytes()
1883            .expect_err("a mutated public path must not detach the captured bytes");
1884        assert!(error.contains("changed after"), "{error}");
1885    }
1886
1887    #[cfg(all(feature = "v2-query", unix))]
1888    #[test]
1889    fn relative_v2_schema_authority_uses_retained_base_after_ambient_parent_swap() {
1890        let dir = tempfile::tempdir().unwrap();
1891        let active = dir.path().join("active");
1892        let retained = dir.path().join("retained");
1893        std::fs::create_dir_all(active.join("schemas")).unwrap();
1894        let original = b"original schema authority";
1895        std::fs::write(active.join("schemas/schema-authority.json"), original).unwrap();
1896        let config_text = format!(
1897            "{MINIMAL_CONFIG}\n[v2]\nenabled = true\n\
1898             schema_authority_file = \"schemas/schema-authority.json\"\n"
1899        );
1900        let config_path = active.join("server.toml");
1901        std::fs::write(&config_path, &config_text).unwrap();
1902        let active_for_swap = active.clone();
1903        let retained_for_swap = retained.clone();
1904
1905        let config = RuntimeServerConfig::from_file_with_env_after_probes(
1906            config_path.to_str().unwrap(),
1907            |_| None,
1908            || {},
1909            move || {
1910                std::fs::rename(&active_for_swap, &retained_for_swap).unwrap();
1911                std::fs::create_dir_all(active_for_swap.join("schemas")).unwrap();
1912                std::fs::write(
1913                    active_for_swap.join("schemas/schema-authority.json"),
1914                    "replacement schema authority",
1915                )
1916                .unwrap();
1917                std::fs::write(active_for_swap.join("server.toml"), config_text).unwrap();
1918            },
1919        )
1920        .unwrap();
1921
1922        assert_eq!(
1923            config.v2_schema_authority_bytes().unwrap(),
1924            Some(original.as_slice()),
1925            "ambient parent replacement must not redirect the retained config authority"
1926        );
1927        assert_eq!(
1928            std::fs::read(active.join("schemas/schema-authority.json")).unwrap(),
1929            b"replacement schema authority"
1930        );
1931    }
1932
1933    #[cfg(all(feature = "v2-query", unix))]
1934    #[test]
1935    fn absolute_v2_schema_authority_symlink_is_rejected() {
1936        use std::os::unix::fs::symlink;
1937
1938        let dir = tempfile::tempdir().unwrap();
1939        let target = dir.path().join("target.json");
1940        let authority_path = dir.path().join("schema-authority.json");
1941        std::fs::write(&target, "target schema").unwrap();
1942        symlink(&target, &authority_path).unwrap();
1943        let config_path = dir.path().join("server.toml");
1944        std::fs::write(
1945            &config_path,
1946            format!(
1947                "{MINIMAL_CONFIG}\n[v2]\nenabled = true\nschema_authority_file = {:?}\n",
1948                authority_path.to_str().unwrap()
1949            ),
1950        )
1951        .unwrap();
1952
1953        let error =
1954            RuntimeServerConfig::from_file_with_env(config_path.to_str().unwrap(), |_| None)
1955                .expect_err("the final V2 schema component must not follow symlinks");
1956        assert!(
1957            error.to_string().contains("v2.schema_authority_file"),
1958            "{error}"
1959        );
1960    }
1961
1962    #[cfg(feature = "v2-query")]
1963    #[test]
1964    fn non_regular_v2_schema_authority_is_rejected() {
1965        let dir = tempfile::tempdir().unwrap();
1966        std::fs::create_dir(dir.path().join("schema-authority.json")).unwrap();
1967        let config_path = dir.path().join("server.toml");
1968        std::fs::write(
1969            &config_path,
1970            format!(
1971                "{MINIMAL_CONFIG}\n[v2]\nenabled = true\n\
1972                 schema_authority_file = \"schema-authority.json\"\n"
1973            ),
1974        )
1975        .unwrap();
1976
1977        let error =
1978            RuntimeServerConfig::from_file_with_env(config_path.to_str().unwrap(), |_| None)
1979                .expect_err("a V2 schema directory must fail during config loading");
1980        assert!(error.to_string().contains("regular file"), "{error}");
1981    }
1982
1983    #[cfg(feature = "v2-query")]
1984    #[test]
1985    fn oversized_v2_schema_authority_is_rejected_at_the_canonical_ceiling() {
1986        let dir = tempfile::tempdir().unwrap();
1987        let authority_path = dir.path().join("schema-authority.json");
1988        let file = std::fs::File::create(&authority_path).unwrap();
1989        file.set_len(u64::try_from(MAX_SCHEMA_AUTHORITY_BYTES).unwrap() + 1)
1990            .unwrap();
1991        // Close the writable fixture handle before loading: the capture
1992        // opens the file denying concurrent writers, so a live writer
1993        // handle on Windows is a sharing violation, not a size failure.
1994        drop(file);
1995        let config_path = dir.path().join("server.toml");
1996        std::fs::write(
1997            &config_path,
1998            format!(
1999                "{MINIMAL_CONFIG}\n[v2]\nenabled = true\n\
2000                 schema_authority_file = \"schema-authority.json\"\n"
2001            ),
2002        )
2003        .unwrap();
2004
2005        let error =
2006            RuntimeServerConfig::from_file_with_env(config_path.to_str().unwrap(), |_| None)
2007                .expect_err("an oversized V2 schema must fail during config loading");
2008        assert!(
2009            error.to_string().contains("no larger than 16 MiB"),
2010            "{error}"
2011        );
2012    }
2013
2014    #[test]
2015    fn runtime_wire_preserves_released_unknown_field_tolerance() {
2016        let cases = [
2017            (
2018                "root",
2019                r#"unexpected = true
2020[server]
2021[typedb]
2022address = "localhost:1729"
2023database = "db"
2024"#,
2025            ),
2026            (
2027                "server",
2028                r#"[server]
2029vendor_extension = true
2030[typedb]
2031address = "localhost:1729"
2032database = "db"
2033"#,
2034            ),
2035            (
2036                "typedb",
2037                r#"[server]
2038[typedb]
2039address = "localhost:1729"
2040database = "db"
2041vendor_extension = true
2042"#,
2043            ),
2044            (
2045                "schema",
2046                r#"[server]
2047[typedb]
2048address = "localhost:1729"
2049database = "db"
2050[schema]
2051source-file = "schema.tql"
2052"#,
2053            ),
2054            (
2055                "interceptors",
2056                r#"[server]
2057[typedb]
2058address = "localhost:1729"
2059database = "db"
2060[interceptors]
2061enable = ["audit-log"]
2062"#,
2063            ),
2064            (
2065                "audit-log",
2066                r#"[server]
2067[typedb]
2068address = "localhost:1729"
2069database = "db"
2070[interceptors]
2071enabled = ["audit-log"]
2072[interceptors.audit-log]
2073file-path = "audit.jsonl"
2074"#,
2075            ),
2076            (
2077                "logging",
2078                r#"[server]
2079[typedb]
2080address = "localhost:1729"
2081database = "db"
2082[logging]
2083log-level = "debug"
2084"#,
2085            ),
2086        ];
2087
2088        for (level, source) in cases {
2089            toml::from_str::<RuntimeServerConfigWire>(source).unwrap_or_else(|error| {
2090                panic!("released {level} extension key regressed: {error}")
2091            });
2092        }
2093    }
2094
2095    #[test]
2096    fn new_security_sections_remain_closed_to_unknown_keys() {
2097        let cases = [
2098            r#"[server]
2099[typedb]
2100address = "localhost:1729"
2101database = "db"
2102[v2]
2103enable = true
2104"#,
2105            r#"[server]
2106[server.tls]
2107cert-path = "server.pem"
2108key-path = "server.key"
2109certificate-path = "ignored.pem"
2110[typedb]
2111address = "localhost:1729"
2112database = "db"
2113"#,
2114        ];
2115        for source in cases {
2116            let error = toml::from_str::<RuntimeServerConfigWire>(source)
2117                .expect_err("new security-sensitive sections must fail closed");
2118            assert!(error.to_string().contains("unknown field"), "{error}");
2119        }
2120    }
2121
2122    #[test]
2123    fn ambiguous_tls_aliases_cannot_silently_select_plaintext() {
2124        let cases = [
2125            (
2126                "server tls alias",
2127                r#"[server]
2128tls-enabled = true
2129[typedb]
2130address = "localhost:1729"
2131database = "db"
2132"#,
2133            ),
2134            (
2135                "typedb tls alias",
2136                r#"[server]
2137[typedb]
2138address = "localhost:1729"
2139database = "db"
2140tls_enabled = true
2141"#,
2142            ),
2143            (
2144                "root CA alias",
2145                r#"[server]
2146[typedb]
2147address = "localhost:1729"
2148database = "db"
2149ca-file = "root.pem"
2150"#,
2151            ),
2152            (
2153                "hyphenated top-level table",
2154                r#"[server-tls]
2155enabled = true
2156[server]
2157[typedb]
2158address = "localhost:1729"
2159database = "db"
2160"#,
2161            ),
2162            (
2163                "underscored top-level table",
2164                r#"[server_tls]
2165enabled = true
2166[server]
2167[typedb]
2168address = "localhost:1729"
2169database = "db"
2170"#,
2171            ),
2172            (
2173                "top-level TLS table",
2174                r#"[tls]
2175enabled = true
2176[server]
2177[typedb]
2178address = "localhost:1729"
2179database = "db"
2180"#,
2181            ),
2182            (
2183                "nested SSL table",
2184                r#"[server]
2185[typedb]
2186address = "localhost:1729"
2187database = "db"
2188[typedb.ssl]
2189enabled = true
2190"#,
2191            ),
2192            (
2193                "top-level SSL flag",
2194                r#"ssl = true
2195[server]
2196[typedb]
2197address = "localhost:1729"
2198database = "db"
2199"#,
2200            ),
2201        ];
2202
2203        let dir = tempfile::tempdir().unwrap();
2204        for (index, (name, source)) in cases.into_iter().enumerate() {
2205            let path = dir.path().join(format!("ambiguous-{index}.toml"));
2206            std::fs::write(&path, source).unwrap();
2207            let error = RuntimeServerConfig::from_file_with_env(path.to_str().unwrap(), |_| None)
2208                .unwrap_err();
2209            assert!(
2210                error.to_string().contains("security-sensitive"),
2211                "{name} was not rejected by the downgrade guard: {error}"
2212            );
2213        }
2214    }
2215
2216    #[test]
2217    fn runtime_toml_errors_and_debug_never_retain_secret_source_values() {
2218        const SENTINEL: &str = "TB_SECRET_SENTINEL_7b4f";
2219
2220        let syntax = format!(
2221            "[server]\n[typedb]\naddress = \"localhost:1729\"\ndatabase = \"db\"\npassword = \"{SENTINEL}\n"
2222        );
2223        let wrong_password = format!(
2224            "[server]\n[typedb]\naddress = \"localhost:1729\"\ndatabase = \"db\"\npassword = [\"{SENTINEL}\"]\n"
2225        );
2226        let wrong_username = format!(
2227            "[server]\n[typedb]\naddress = \"localhost:1729\"\ndatabase = \"db\"\nusername = {{ secret = \"{SENTINEL}\" }}\n"
2228        );
2229        let unknown_security_key = format!(
2230            "[server]\n[typedb]\naddress = \"localhost:1729\"\ndatabase = \"db\"\ntls-{SENTINEL} = true\n"
2231        );
2232
2233        for (name, source) in [
2234            ("syntax", syntax),
2235            ("wrong password type", wrong_password),
2236            ("wrong username type", wrong_username),
2237            ("unknown security key", unknown_security_key),
2238        ] {
2239            let error = parse_runtime_wire(&source).expect_err(name);
2240            let rendered = format!("{error}\n{error:?}");
2241            assert!(!rendered.contains(SENTINEL), "{name}: {rendered}");
2242            assert!(
2243                error.source().is_none(),
2244                "{name} retained a source error that could expose TOML bytes"
2245            );
2246            assert!(
2247                rendered.contains("server configuration is invalid"),
2248                "{name}: {rendered}"
2249            );
2250        }
2251
2252        let dir = tempfile::tempdir().unwrap();
2253        let path = dir.path().join("server.toml");
2254        std::fs::write(
2255            &path,
2256            format!(
2257                "[server]\n[typedb]\naddress = \"admin:{SENTINEL}@localhost:1729\"\ndatabase = \"db\"\nusername = \"{SENTINEL}\"\npassword = \"{SENTINEL}\"\n"
2258            ),
2259        )
2260        .unwrap();
2261        let config = RuntimeServerConfig::from_file_with_env(path.to_str().unwrap(), |_| None)
2262            .expect("valid runtime config");
2263        let rendered = format!("{config:?}");
2264        assert!(!rendered.contains(SENTINEL), "{rendered}");
2265        assert!(rendered.contains("[REDACTED]"));
2266        let typedb_rendered = format!("{:?}", config.typedb);
2267        assert!(!typedb_rendered.contains(SENTINEL), "{typedb_rendered}");
2268        assert!(typedb_rendered.contains("[REDACTED]"));
2269
2270        let wire = parse_runtime_wire(&std::fs::read_to_string(path).unwrap()).unwrap();
2271        assert!(!format!("{wire:?}").contains(SENTINEL));
2272    }
2273
2274    #[test]
2275    fn unrelated_legacy_extension_keys_remain_tolerated() {
2276        let source = r#"[server]
2277vendor_extension = true
2278[typedb]
2279address = "localhost:1729"
2280database = "db"
2281[legacy]
2282keyboard_layout = "dvorak"
2283hassle = false
2284monkey = "capuchin"
2285uncertainty = 0.1
2286[legacy.transport]
2287key = "request-id"
2288cert = "third-party.pem"
2289private-key = "third-party.key"
2290trust-store = "third-party.pem"
2291[logging.labels]
2292key = "request-id"
2293cert = "classification"
2294api-key = "redacted"
2295cache-key = "server-v1"
2296"#;
2297        reject_ambiguous_security_keys(source).unwrap();
2298    }
2299
2300    #[test]
2301    fn released_top_level_and_known_namespace_extension_keys_remain_tolerated() {
2302        let source = r#"api-key = "redacted"
2303[server]
2304cache-key = "server-v1"
2305key = "request-id"
2306cert = "classification"
2307[typedb]
2308address = "localhost:1729"
2309database = "db"
2310api-key = "redacted"
2311certificate = "extension-metadata"
2312"#;
2313        reject_ambiguous_security_keys(source).unwrap();
2314    }
2315
2316    #[test]
2317    fn common_tls_typos_and_aliases_remain_downgrade_guarded() {
2318        for key in [
2319            "tls_enable",
2320            "enable_tls",
2321            "tls-root",
2322            "ssl-ca",
2323            "tls-cert-file",
2324            "key-path",
2325            "trust-store",
2326        ] {
2327            let source = format!(
2328                "[server]\n[typedb]\naddress = \"localhost:1729\"\ndatabase = \"db\"\n{key} = \"ignored\"\n"
2329            );
2330            let error = reject_ambiguous_security_keys(&source)
2331                .expect_err("TLS-shaped direct keys must not be ignored");
2332            assert!(
2333                error.to_string().contains("security-sensitive"),
2334                "{key}: {error}"
2335            );
2336        }
2337    }
2338
2339    #[test]
2340    fn env_overrides_typedb_section() {
2341        let mut config: ServerConfig = toml::from_str(FULL_CONFIG).unwrap();
2342        config
2343            .apply_env_overrides_from(|name| match name {
2344                "TYPEDB_ADDRESS" => Some("typedb:1729".to_string()),
2345                "TYPEDB_DATABASE" => Some("docker_db".to_string()),
2346                "TYPEDB_USERNAME" => Some("docker_user".to_string()),
2347                "TYPEDB_PASSWORD" => Some("docker_pass".to_string()),
2348                _ => None,
2349            })
2350            .unwrap();
2351
2352        assert_eq!(config.typedb.address, "typedb:1729");
2353        assert_eq!(config.typedb.database, "docker_db");
2354        assert_eq!(config.typedb.username, "docker_user");
2355        assert_eq!(config.typedb.password, "docker_pass");
2356    }
2357
2358    #[test]
2359    fn from_file_valid_minimal_config() {
2360        let dir = tempfile::tempdir().unwrap();
2361        let path = dir.path().join("server.toml");
2362        std::fs::write(&path, MINIMAL_CONFIG).unwrap();
2363
2364        let config = ServerConfig::from_file_with_env(path.to_str().unwrap(), |_| None).unwrap();
2365        // Defaults should kick in
2366        assert_eq!(config.server.host, "0.0.0.0");
2367        assert_eq!(config.server.port, 8080);
2368        assert_eq!(config.typedb.username, "admin");
2369        assert_eq!(config.typedb.password, "password");
2370        assert_eq!(config.typedb.server_version, None);
2371        assert_eq!(config.schema.source_file, "");
2372        assert!(config.interceptors.enabled.is_empty());
2373        assert!(config.interceptors.audit_log.is_none());
2374        assert_eq!(config.logging.level, "info");
2375        assert_eq!(config.logging.format, "json");
2376    }
2377
2378    #[test]
2379    fn outbound_tls_truth_table_rejects_implicit_enablement() {
2380        let parse =
2381            |tls: Option<bool>, root: Option<&str>| outbound_tls_mode(tls, root.map(PathBuf::from));
2382        assert_eq!(parse(None, None).unwrap(), OutboundTlsMode::Disabled);
2383        assert_eq!(parse(Some(false), None).unwrap(), OutboundTlsMode::Disabled,);
2384        assert_eq!(
2385            parse(Some(true), None).unwrap(),
2386            OutboundTlsMode::NativeRoots,
2387        );
2388        assert!(parse(None, Some("root.pem")).is_err());
2389        assert!(parse(Some(false), Some("root.pem")).is_err());
2390        assert!(matches!(
2391            parse(Some(true), Some("root.pem")).unwrap(),
2392            OutboundTlsMode::CustomRootCa(path) if path == Path::new("root.pem")
2393        ));
2394    }
2395
2396    #[test]
2397    fn tls_paths_resolve_against_the_config_file() {
2398        let dir = tempfile::tempdir().unwrap();
2399        std::fs::create_dir(dir.path().join("certs")).unwrap();
2400        for name in ["ca.pem", "server.pem", "server.key"] {
2401            std::fs::write(dir.path().join("certs").join(name), "test-only material").unwrap();
2402        }
2403        let path = dir.path().join("server.toml");
2404        std::fs::write(
2405            &path,
2406            r#"[server]
2407[server.tls]
2408cert-path = "certs/server.pem"
2409key-path = "certs/server.key"
2410[typedb]
2411address = "localhost:1729"
2412database = "db"
2413tls = true
2414tls-root-ca = "certs/ca.pem"
2415"#,
2416        )
2417        .unwrap();
2418
2419        let config =
2420            RuntimeServerConfig::from_file_with_env(path.to_str().unwrap(), |_| None).unwrap();
2421        assert!(matches!(
2422            config.typedb.tls_mode,
2423            OutboundTlsMode::CustomRootCa(ref path) if path.is_absolute()
2424        ));
2425        let inbound = config.inbound_tls.unwrap();
2426        assert!(inbound.cert_path.is_absolute());
2427        assert!(inbound.key_path.is_absolute());
2428    }
2429
2430    #[cfg(unix)]
2431    #[test]
2432    fn relative_tls_config_symlink_swap_cannot_mix_policy_and_base() {
2433        use std::os::unix::fs::symlink;
2434
2435        let dir = tempfile::tempdir().unwrap();
2436        let first = dir.path().join("first");
2437        let second = dir.path().join("second");
2438        std::fs::create_dir(&first).unwrap();
2439        std::fs::create_dir(&second).unwrap();
2440        for (root, database) in [(&first, "first-db"), (&second, "second-db")] {
2441            std::fs::write(root.join("root.pem"), database).unwrap();
2442            std::fs::write(
2443                root.join("server.toml"),
2444                format!(
2445                    r#"[server]
2446[typedb]
2447address = "localhost:1729"
2448database = "{database}"
2449tls = true
2450tls-root-ca = "root.pem"
2451"#
2452                ),
2453            )
2454            .unwrap();
2455        }
2456        let config_link = dir.path().join("server.toml");
2457        symlink(first.join("server.toml"), &config_link).unwrap();
2458        let replacement = second.join("server.toml");
2459        let link_for_swap = config_link.clone();
2460
2461        let config = RuntimeServerConfig::from_file_with_env_after_probe(
2462            config_link.to_str().unwrap(),
2463            |_| None,
2464            move || {
2465                std::fs::remove_file(&link_for_swap).unwrap();
2466                symlink(&replacement, &link_for_swap).unwrap();
2467            },
2468        )
2469        .unwrap();
2470
2471        assert_eq!(config.typedb.connection.database, "second-db");
2472        assert_eq!(
2473            config.typedb.tls_mode,
2474            OutboundTlsMode::CustomRootCa(second.join("root.pem").canonicalize().unwrap())
2475        );
2476        assert_eq!(
2477            config
2478                .typedb
2479                .custom_root_ca_snapshot
2480                .as_ref()
2481                .map(|material| material.bytes.as_ref()),
2482            Some(b"second-db".as_slice())
2483        );
2484    }
2485
2486    #[cfg(unix)]
2487    #[test]
2488    fn relative_tls_parent_swap_after_authorized_read_uses_one_directory_identity() {
2489        let dir = tempfile::tempdir().unwrap();
2490        let active = dir.path().join("active");
2491        let retained = dir.path().join("retained");
2492        std::fs::create_dir(&active).unwrap();
2493        std::fs::write(active.join("root.pem"), "original root").unwrap();
2494        std::fs::write(active.join("server.pem"), "original certificate").unwrap();
2495        std::fs::write(active.join("server.key"), "original private key").unwrap();
2496        let config_path = active.join("server.toml");
2497        std::fs::write(
2498            &config_path,
2499            r#"[server]
2500[server.tls]
2501cert-path = "server.pem"
2502key-path = "server.key"
2503[typedb]
2504address = "localhost:1729"
2505database = "original-db"
2506tls = true
2507tls-root-ca = "root.pem"
2508"#,
2509        )
2510        .unwrap();
2511        let active_for_swap = active.clone();
2512        let retained_for_swap = retained.clone();
2513
2514        let config = RuntimeServerConfig::from_file_with_env_after_probes(
2515            config_path.to_str().unwrap(),
2516            |_| None,
2517            || {},
2518            move || {
2519                std::fs::rename(&active_for_swap, &retained_for_swap).unwrap();
2520                std::fs::create_dir(&active_for_swap).unwrap();
2521                std::fs::write(active_for_swap.join("root.pem"), "replacement root").unwrap();
2522                std::fs::write(
2523                    active_for_swap.join("server.pem"),
2524                    "replacement certificate",
2525                )
2526                .unwrap();
2527                std::fs::write(
2528                    active_for_swap.join("server.key"),
2529                    "replacement private key",
2530                )
2531                .unwrap();
2532            },
2533        )
2534        .unwrap();
2535
2536        assert_eq!(config.typedb.connection.database, "original-db");
2537        assert_eq!(
2538            config
2539                .typedb
2540                .custom_root_ca_snapshot
2541                .as_ref()
2542                .map(|material| material.bytes.as_ref()),
2543            Some(b"original root".as_slice())
2544        );
2545        let inbound = config.inbound_tls.unwrap();
2546        let prepared = inbound.prepared.unwrap();
2547        assert_eq!(
2548            prepared
2549                .certificate
2550                .as_ref()
2551                .map(|material| material.bytes.as_ref()),
2552            Some(b"original certificate".as_slice())
2553        );
2554        assert_eq!(
2555            prepared
2556                .private_key
2557                .as_ref()
2558                .map(|material| material.bytes.as_ref()),
2559            Some(b"original private key".as_slice())
2560        );
2561    }
2562
2563    #[cfg(unix)]
2564    #[test]
2565    fn parent_relative_tls_uses_the_retained_ancestor_after_parent_swap() {
2566        let dir = tempfile::tempdir().unwrap();
2567        let active_parent = dir.path().join("active-parent");
2568        let config_dir = active_parent.join("config");
2569        let retained_parent = dir.path().join("retained-parent");
2570        std::fs::create_dir_all(&config_dir).unwrap();
2571        std::fs::write(active_parent.join("root.pem"), "original ancestor root").unwrap();
2572        let config_path = config_dir.join("server.toml");
2573        std::fs::write(
2574            &config_path,
2575            r#"[server]
2576[typedb]
2577address = "localhost:1729"
2578database = "original-db"
2579tls = true
2580tls-root-ca = "../root.pem"
2581"#,
2582        )
2583        .unwrap();
2584        let active_for_swap = active_parent.clone();
2585        let retained_for_swap = retained_parent.clone();
2586
2587        let config = RuntimeServerConfig::from_file_with_env_after_probes(
2588            config_path.to_str().unwrap(),
2589            |_| None,
2590            || {},
2591            move || {
2592                std::fs::rename(&active_for_swap, &retained_for_swap).unwrap();
2593                std::fs::create_dir(&active_for_swap).unwrap();
2594                std::fs::write(
2595                    active_for_swap.join("root.pem"),
2596                    "replacement ancestor root",
2597                )
2598                .unwrap();
2599            },
2600        )
2601        .unwrap();
2602
2603        assert_eq!(config.typedb.connection.database, "original-db");
2604        assert_eq!(
2605            config
2606                .typedb
2607                .custom_root_ca_snapshot
2608                .as_ref()
2609                .map(|material| material.bytes.as_ref()),
2610            Some(b"original ancestor root".as_slice())
2611        );
2612    }
2613
2614    #[test]
2615    fn plaintext_config_does_not_require_a_post_read_path_lookup() {
2616        let dir = tempfile::tempdir().unwrap();
2617        let path = dir.path().join("server.toml");
2618        std::fs::write(&path, MINIMAL_CONFIG).unwrap();
2619        let remove_after_read = path.clone();
2620
2621        let config = RuntimeServerConfig::from_file_with_env_after_probe(
2622            path.to_str().unwrap(),
2623            |_| None,
2624            move || std::fs::remove_file(remove_after_read).unwrap(),
2625        )
2626        .unwrap();
2627
2628        assert_eq!(config.typedb.connection.database, "mydb");
2629        assert_eq!(config.typedb.tls_mode, OutboundTlsMode::Disabled);
2630    }
2631
2632    #[test]
2633    fn absolute_tls_paths_do_not_require_a_post_read_config_lookup() {
2634        let dir = tempfile::tempdir().unwrap();
2635        let root = dir.path().join("root.pem");
2636        std::fs::write(&root, "root material").unwrap();
2637        let path = dir.path().join("server.toml");
2638        std::fs::write(
2639            &path,
2640            format!(
2641                r#"[server]
2642[typedb]
2643address = "localhost:1729"
2644database = "db"
2645tls = true
2646tls-root-ca = {root:?}
2647"#,
2648                root = root.to_str().unwrap()
2649            ),
2650        )
2651        .unwrap();
2652        let remove_after_read = path.clone();
2653
2654        let config = RuntimeServerConfig::from_file_with_env_after_probe(
2655            path.to_str().unwrap(),
2656            |_| None,
2657            move || std::fs::remove_file(remove_after_read).unwrap(),
2658        )
2659        .unwrap();
2660
2661        assert_eq!(
2662            config.typedb.tls_mode,
2663            OutboundTlsMode::CustomRootCa(root.canonicalize().unwrap())
2664        );
2665        assert_eq!(
2666            config
2667                .typedb
2668                .custom_root_ca_snapshot
2669                .as_ref()
2670                .map(|material| material.bytes.as_ref()),
2671            Some(b"root material".as_slice())
2672        );
2673    }
2674
2675    #[test]
2676    fn absolute_tls_material_survives_parent_replacement_after_config_load() {
2677        let dir = tempfile::tempdir().unwrap();
2678        let active = dir.path().join("active");
2679        let retained = dir.path().join("retained");
2680        std::fs::create_dir(&active).unwrap();
2681        let root = active.join("root.pem");
2682        let certificate = active.join("server.pem");
2683        let private_key = active.join("server.key");
2684        std::fs::write(&root, "original root").unwrap();
2685        std::fs::write(&certificate, "original certificate").unwrap();
2686        std::fs::write(&private_key, "original private key").unwrap();
2687        let config_path = dir.path().join("server.toml");
2688        std::fs::write(
2689            &config_path,
2690            format!(
2691                r#"[server]
2692[server.tls]
2693cert-path = {certificate:?}
2694key-path = {private_key:?}
2695[typedb]
2696address = "localhost:1729"
2697database = "db"
2698tls = true
2699tls-root-ca = {root:?}
2700"#,
2701            ),
2702        )
2703        .unwrap();
2704
2705        let config =
2706            RuntimeServerConfig::from_file_with_env(config_path.to_str().unwrap(), |_| None)
2707                .unwrap();
2708        std::fs::rename(&active, &retained).unwrap();
2709        std::fs::create_dir(&active).unwrap();
2710        std::fs::write(active.join("root.pem"), "replacement root").unwrap();
2711        std::fs::write(active.join("server.pem"), "replacement certificate").unwrap();
2712        std::fs::write(active.join("server.key"), "replacement private key").unwrap();
2713
2714        assert_eq!(
2715            config
2716                .typedb
2717                .custom_root_ca_snapshot
2718                .as_ref()
2719                .map(|material| material.bytes.as_ref()),
2720            Some(b"original root".as_slice())
2721        );
2722        let prepared = config.inbound_tls.unwrap().prepared.unwrap();
2723        assert_eq!(
2724            prepared
2725                .certificate
2726                .as_ref()
2727                .map(|material| material.bytes.as_ref()),
2728            Some(b"original certificate".as_slice())
2729        );
2730        assert_eq!(
2731            prepared
2732                .private_key
2733                .as_ref()
2734                .map(|material| material.bytes.as_ref()),
2735            Some(b"original private key".as_slice())
2736        );
2737    }
2738
2739    #[test]
2740    fn outbound_root_contradiction_fails_before_file_access() {
2741        let dir = tempfile::tempdir().unwrap();
2742        let path = dir.path().join("server.toml");
2743        std::fs::write(
2744            &path,
2745            r#"[server]
2746[typedb]
2747address = "localhost:1729"
2748database = "db"
2749tls = false
2750tls-root-ca = "missing.pem"
2751"#,
2752        )
2753        .unwrap();
2754        let error = RuntimeServerConfig::from_file_with_env(path.to_str().unwrap(), |_| None)
2755            .expect_err("contradictory policy must fail before reading the path");
2756        assert!(error.to_string().contains("contradicts"));
2757    }
2758
2759    #[test]
2760    fn oversized_tls_material_fails_before_identity_or_provider_construction() {
2761        let dir = tempfile::tempdir().unwrap();
2762        let root = dir.path().join("root.pem");
2763        let file = std::fs::File::create(&root).unwrap();
2764        file.set_len(MAX_TLS_MATERIAL_BYTES + 1).unwrap();
2765        // Close the writable fixture handle before loading: the capture
2766        // opens the file denying concurrent writers, so a live writer
2767        // handle on Windows is a sharing violation, not a size failure.
2768        drop(file);
2769        let path = dir.path().join("server.toml");
2770        std::fs::write(
2771            &path,
2772            r#"[server]
2773[typedb]
2774address = "localhost:1729"
2775database = "db"
2776tls = true
2777tls-root-ca = "root.pem"
2778"#,
2779        )
2780        .unwrap();
2781        let error = RuntimeServerConfig::from_file_with_env(path.to_str().unwrap(), |_| None)
2782            .expect_err("oversized trust material must fail during config loading");
2783        assert!(error.to_string().contains("no larger than 1 MiB"));
2784    }
2785
2786    #[tokio::test]
2787    async fn malformed_inbound_identity_fails_before_bind() {
2788        let dir = tempfile::tempdir().unwrap();
2789        let cert = dir.path().join("server.pem");
2790        let key = dir.path().join("server.key");
2791        std::fs::write(&cert, "not a certificate").unwrap();
2792        std::fs::write(&key, "not a key").unwrap();
2793        let tls = InboundTlsSection::from_paths(cert, key);
2794        assert!(tls.load().await.is_err());
2795    }
2796
2797    #[tokio::test]
2798    async fn inbound_identity_load_rechecks_the_open_handle_byte_limit() {
2799        let dir = tempfile::tempdir().unwrap();
2800        // load() walks parent components without following symlinks; the
2801        // ambient temp directory may sit behind symlinked components
2802        // (macOS /var), which would fail before the byte-limit check.
2803        let root = dir.path().canonicalize().unwrap();
2804        let cert = root.join("server.pem");
2805        let key = root.join("server.key");
2806        let file = std::fs::File::create(&cert).unwrap();
2807        file.set_len(MAX_TLS_MATERIAL_BYTES + 1).unwrap();
2808        std::fs::write(&key, "not a key").unwrap();
2809        let tls = InboundTlsSection::from_paths(cert, key);
2810        let error = tls
2811            .load()
2812            .await
2813            .expect_err("oversized identity must fail bounded");
2814        assert!(error.to_string().contains("no larger than 1 MiB"));
2815    }
2816
2817    #[cfg(unix)]
2818    #[tokio::test]
2819    async fn relative_inbound_identity_ignores_a_post_capture_symlink_swap() {
2820        use std::os::unix::fs::symlink;
2821
2822        let identity = rcgen::generate_simple_self_signed(vec!["localhost".to_owned()]).unwrap();
2823        let dir = tempfile::tempdir().unwrap();
2824        let cert = dir.path().join("server.pem");
2825        let replacement = dir.path().join("replacement.pem");
2826        let key = dir.path().join("server.key");
2827        std::fs::write(&cert, identity.cert.pem()).unwrap();
2828        std::fs::write(&replacement, "attacker-controlled replacement").unwrap();
2829        std::fs::write(&key, identity.key_pair.serialize_pem()).unwrap();
2830        let config_path = dir.path().join("server.toml");
2831        std::fs::write(
2832            &config_path,
2833            r#"[server]
2834[server.tls]
2835cert-path = "server.pem"
2836key-path = "server.key"
2837[typedb]
2838address = "localhost:1729"
2839database = "db"
2840"#,
2841        )
2842        .unwrap();
2843        let config =
2844            RuntimeServerConfig::from_file_with_env(config_path.to_str().unwrap(), |_| None)
2845                .unwrap();
2846        let tls = config.inbound_tls.unwrap();
2847
2848        std::fs::remove_file(&cert).unwrap();
2849        symlink(&replacement, &cert).unwrap();
2850        tls.load()
2851            .await
2852            .expect("relative identity loading must consume the captured certificate bytes");
2853    }
2854
2855    #[cfg(unix)]
2856    #[tokio::test]
2857    async fn relative_inbound_identity_ignores_a_post_capture_parent_swap() {
2858        use std::os::unix::fs::symlink;
2859
2860        let identity = rcgen::generate_simple_self_signed(vec!["localhost".to_owned()]).unwrap();
2861        let dir = tempfile::tempdir().unwrap();
2862        let identity_dir = dir.path().join("identity");
2863        let replacement_dir = dir.path().join("replacement");
2864        std::fs::create_dir(&identity_dir).unwrap();
2865        std::fs::create_dir(&replacement_dir).unwrap();
2866        std::fs::write(identity_dir.join("server.pem"), identity.cert.pem()).unwrap();
2867        std::fs::write(
2868            identity_dir.join("server.key"),
2869            identity.key_pair.serialize_pem(),
2870        )
2871        .unwrap();
2872        std::fs::write(
2873            replacement_dir.join("server.pem"),
2874            "attacker-controlled certificate",
2875        )
2876        .unwrap();
2877        std::fs::write(
2878            replacement_dir.join("server.key"),
2879            "attacker-controlled private key",
2880        )
2881        .unwrap();
2882        let config_path = dir.path().join("server.toml");
2883        std::fs::write(
2884            &config_path,
2885            r#"[server]
2886[server.tls]
2887cert-path = "identity/server.pem"
2888key-path = "identity/server.key"
2889[typedb]
2890address = "localhost:1729"
2891database = "db"
2892"#,
2893        )
2894        .unwrap();
2895        let config =
2896            RuntimeServerConfig::from_file_with_env(config_path.to_str().unwrap(), |_| None)
2897                .unwrap();
2898        let tls = config.inbound_tls.unwrap();
2899
2900        std::fs::rename(&identity_dir, dir.path().join("identity-original")).unwrap();
2901        symlink(&replacement_dir, &identity_dir).unwrap();
2902        tls.load()
2903            .await
2904            .expect("relative identity loading must consume the captured identity bytes");
2905    }
2906
2907    #[tokio::test]
2908    async fn relative_inbound_identity_rejects_a_mutated_diagnostic_path() {
2909        let dir = tempfile::tempdir().unwrap();
2910        std::fs::write(dir.path().join("server.pem"), "captured certificate").unwrap();
2911        std::fs::write(dir.path().join("server.key"), "captured private key").unwrap();
2912        let config_path = dir.path().join("server.toml");
2913        std::fs::write(
2914            &config_path,
2915            r#"[server]
2916[server.tls]
2917cert-path = "server.pem"
2918key-path = "server.key"
2919[typedb]
2920address = "localhost:1729"
2921database = "db"
2922"#,
2923        )
2924        .unwrap();
2925        let config =
2926            RuntimeServerConfig::from_file_with_env(config_path.to_str().unwrap(), |_| None)
2927                .unwrap();
2928        let mut tls = config.inbound_tls.unwrap();
2929        tls.cert_path = dir.path().join("mutated.pem");
2930
2931        let error = tls
2932            .load()
2933            .await
2934            .expect_err("captured certificate bytes must remain bound to their exact path");
2935        assert!(
2936            error
2937                .to_string()
2938                .contains("server.tls.cert-path changed after"),
2939            "{error}"
2940        );
2941    }
2942
2943    #[cfg(unix)]
2944    #[test]
2945    fn inbound_identity_fifo_rejects_without_blocking() {
2946        use std::sync::mpsc;
2947        use std::time::Duration;
2948
2949        let dir = tempfile::tempdir().unwrap();
2950        // load() walks parent components without following symlinks; the
2951        // ambient temp directory may sit behind symlinked components
2952        // (macOS /var), which would fail before the regular-file check.
2953        let root = dir.path().canonicalize().unwrap();
2954        let fifo = root.join("server.pem");
2955        let status = std::process::Command::new("mkfifo")
2956            .arg(&fifo)
2957            .status()
2958            .expect("POSIX mkfifo is available");
2959        assert!(status.success(), "mkfifo failed: {status}");
2960        let key = root.join("server.key");
2961        std::fs::write(&key, "not reached").unwrap();
2962        let tls = InboundTlsSection::from_paths(fifo, key);
2963        let (sender, receiver) = mpsc::sync_channel(1);
2964        std::thread::spawn(move || {
2965            let runtime = tokio::runtime::Builder::new_current_thread()
2966                .enable_all()
2967                .build()
2968                .unwrap();
2969            sender
2970                .send(
2971                    runtime
2972                        .block_on(tls.load())
2973                        .map(|_| ())
2974                        .map_err(|error| error.to_string()),
2975                )
2976                .ok();
2977        });
2978        let result = receiver
2979            .recv_timeout(Duration::from_secs(2))
2980            .expect("opening a FIFO must never block the process");
2981        let error = result.expect_err("a FIFO is not valid identity material");
2982        assert!(error.to_string().contains("must name a regular file"));
2983    }
2984
2985    #[tokio::test]
2986    async fn mismatched_inbound_identity_fails_before_bind() {
2987        let first = rcgen::generate_simple_self_signed(vec!["localhost".to_owned()]).unwrap();
2988        let second = rcgen::generate_simple_self_signed(vec!["localhost".to_owned()]).unwrap();
2989        let dir = tempfile::tempdir().unwrap();
2990        let cert = dir.path().join("server.pem");
2991        let key = dir.path().join("server.key");
2992        std::fs::write(&cert, first.cert.pem()).unwrap();
2993        std::fs::write(&key, second.key_pair.serialize_pem()).unwrap();
2994        let tls = InboundTlsSection::from_paths(cert, key);
2995        assert!(tls.load().await.is_err());
2996    }
2997
2998    #[cfg(unix)]
2999    #[test]
3000    fn runtime_config_fifo_rejects_without_blocking() {
3001        use std::sync::mpsc;
3002        use std::time::Duration;
3003
3004        let dir = tempfile::tempdir().unwrap();
3005        let fifo = dir.path().join("server.toml");
3006        let status = std::process::Command::new("mkfifo")
3007            .arg(&fifo)
3008            .status()
3009            .expect("POSIX mkfifo is available");
3010        assert!(status.success(), "mkfifo failed: {status}");
3011        let (sender, receiver) = mpsc::sync_channel(1);
3012        std::thread::spawn(move || {
3013            sender
3014                .send(read_runtime_config_path(&fifo).map_err(|error| error.to_string()))
3015                .ok();
3016        });
3017        let result = receiver
3018            .recv_timeout(Duration::from_secs(2))
3019            .expect("opening a configuration FIFO must never block the process");
3020        let error = result.expect_err("a FIFO is not a valid server configuration");
3021        assert!(error.contains("regular file"), "{error}");
3022    }
3023
3024    #[test]
3025    fn oversized_runtime_config_is_rejected_from_same_handle_metadata() {
3026        let dir = tempfile::tempdir().unwrap();
3027        let path = dir.path().join("server.toml");
3028        let file = std::fs::File::create(&path).unwrap();
3029        file.set_len(MAX_SERVER_CONFIG_BYTES + 1).unwrap();
3030        // Close the writable fixture handle before loading: the reader
3031        // opens the file denying concurrent writers, so a live writer
3032        // handle on Windows is a sharing violation, not a size failure.
3033        drop(file);
3034
3035        let error = read_runtime_config_path(&path).unwrap_err();
3036        assert!(error.to_string().contains("no larger than 1 MiB"));
3037    }
3038
3039    #[test]
3040    fn non_regular_runtime_config_path_is_rejected() {
3041        let dir = tempfile::tempdir().unwrap();
3042        let error = read_runtime_config_path(dir.path()).unwrap_err();
3043        assert!(error.to_string().contains("regular file"), "{error}");
3044    }
3045
3046    #[test]
3047    fn non_regular_absolute_configured_file_is_rejected() {
3048        let dir = tempfile::tempdir().unwrap();
3049        let error = match capture_absolute_configured_file(dir.path(), "typedb.tls-root-ca") {
3050            Ok(_) => panic!("a directory must not resolve as configured TLS material"),
3051            Err(error) => error,
3052        };
3053        assert!(error.to_string().contains("regular file"), "{error}");
3054    }
3055
3056    #[cfg(feature = "v2-query")]
3057    #[test]
3058    fn non_regular_absolute_schema_authority_is_rejected() {
3059        let dir = tempfile::tempdir().unwrap();
3060        // The capture walks parent components without following symlinks;
3061        // the ambient temp directory may sit behind symlinked components
3062        // (macOS /var), so hand it an already-physical path.
3063        let root = dir.path().canonicalize().unwrap();
3064        let error = capture_absolute_schema_authority_file(&root)
3065            .expect_err("a directory must not resolve as schema authority");
3066        assert!(error.to_string().contains("regular file"), "{error}");
3067    }
3068
3069    #[test]
3070    fn runtime_config_growth_after_metadata_is_rejected_by_bounded_read() {
3071        let dir = tempfile::tempdir().unwrap();
3072        let path = dir.path().join("server.toml");
3073        std::fs::write(&path, MINIMAL_CONFIG).unwrap();
3074        let file = std::fs::OpenOptions::new()
3075            .read(true)
3076            .write(true)
3077            .open(&path)
3078            .unwrap();
3079        let grow = file.try_clone().unwrap();
3080
3081        let error = read_runtime_config_handle_after_inspect(file, move || {
3082            grow.set_len(MAX_SERVER_CONFIG_BYTES + 1).unwrap();
3083        })
3084        .unwrap_err();
3085        assert!(error.to_string().contains("no larger than 1 MiB"));
3086    }
3087
3088    #[test]
3089    fn same_size_runtime_config_rewrite_between_reads_is_rejected() {
3090        use std::io::{Seek as _, Write as _};
3091
3092        let dir = tempfile::tempdir().unwrap();
3093        let path = dir.path().join("server.toml");
3094        let original = MINIMAL_CONFIG.replace("mydb", "aaaa");
3095        let replacement = MINIMAL_CONFIG.replace("mydb", "bbbb");
3096        assert_eq!(original.len(), replacement.len());
3097        std::fs::write(&path, original).unwrap();
3098        let reader = std::fs::File::open(&path).unwrap();
3099        let mut writer = std::fs::OpenOptions::new().write(true).open(&path).unwrap();
3100
3101        let error = read_runtime_config_handle_with_hooks(
3102            reader,
3103            || {},
3104            move || {
3105                writer.seek(SeekFrom::Start(0)).unwrap();
3106                writer.write_all(replacement.as_bytes()).unwrap();
3107                writer.flush().unwrap();
3108            },
3109        )
3110        .unwrap_err();
3111        assert!(error.to_string().contains("changed while"), "{error}");
3112    }
3113
3114    #[test]
3115    fn from_file_missing_file() {
3116        let result = ServerConfig::from_file("/nonexistent/path/server.toml");
3117        assert!(result.is_err());
3118    }
3119
3120    #[test]
3121    fn from_file_invalid_toml() {
3122        let dir = tempfile::tempdir().unwrap();
3123        let path = dir.path().join("bad.toml");
3124        std::fs::write(&path, "this is not valid toml {{{}}}").unwrap();
3125
3126        let result = ServerConfig::from_file(path.to_str().unwrap());
3127        assert!(result.is_err());
3128    }
3129
3130    #[test]
3131    fn from_file_missing_required_typedb_section() {
3132        let dir = tempfile::tempdir().unwrap();
3133        let path = dir.path().join("incomplete.toml");
3134        std::fs::write(&path, "[server]\n").unwrap();
3135
3136        let result = ServerConfig::from_file(path.to_str().unwrap());
3137        assert!(result.is_err());
3138    }
3139
3140    #[test]
3141    fn from_file_missing_required_typedb_fields() {
3142        let dir = tempfile::tempdir().unwrap();
3143        let path = dir.path().join("incomplete.toml");
3144        std::fs::write(&path, "[server]\n[typedb]\n").unwrap();
3145
3146        let result = ServerConfig::from_file(path.to_str().unwrap());
3147        assert!(result.is_err()); // address and database are required
3148    }
3149
3150    // --- Default function tests ---
3151
3152    #[test]
3153    fn default_host_value() {
3154        assert_eq!(default_host(), "0.0.0.0");
3155    }
3156
3157    #[test]
3158    fn default_port_value() {
3159        assert_eq!(default_port(), 8080);
3160    }
3161
3162    #[test]
3163    fn default_username_value() {
3164        assert_eq!(default_username(), "admin");
3165    }
3166
3167    #[test]
3168    fn default_password_value() {
3169        assert_eq!(default_password(), "password");
3170    }
3171
3172    #[test]
3173    fn default_log_level_value() {
3174        assert_eq!(default_log_level(), "info");
3175    }
3176
3177    #[test]
3178    fn default_log_format_value() {
3179        assert_eq!(default_log_format(), "json");
3180    }
3181
3182    #[test]
3183    fn default_audit_output_value() {
3184        assert_eq!(default_audit_output(), "stdout");
3185    }
3186
3187    // --- LoggingSection default ---
3188
3189    #[test]
3190    fn logging_section_default() {
3191        let logging = LoggingSection::default();
3192        assert_eq!(logging.level, "info");
3193        assert_eq!(logging.format, "json");
3194    }
3195
3196    // --- Serde deserialization edge cases ---
3197
3198    #[test]
3199    fn server_section_custom_host_default_port() {
3200        let toml = r#"
3201[server]
3202host = "192.168.1.1"
3203
3204[typedb]
3205address = "localhost:1729"
3206database = "db"
3207"#;
3208        let config: ServerConfig = toml::from_str(toml).unwrap();
3209        assert_eq!(config.server.host, "192.168.1.1");
3210        assert_eq!(config.server.port, 8080); // default
3211    }
3212
3213    #[test]
3214    fn server_section_custom_port_default_host() {
3215        let toml = r#"
3216[server]
3217port = 3000
3218
3219[typedb]
3220address = "localhost:1729"
3221database = "db"
3222"#;
3223        let config: ServerConfig = toml::from_str(toml).unwrap();
3224        assert_eq!(config.server.host, "0.0.0.0"); // default
3225        assert_eq!(config.server.port, 3000);
3226    }
3227
3228    #[test]
3229    fn typedb_section_custom_credentials() {
3230        let toml = r#"
3231[server]
3232
3233[typedb]
3234address = "remote:1729"
3235database = "prod"
3236username = "superuser"
3237password = "hunter2"
3238"#;
3239        let config: ServerConfig = toml::from_str(toml).unwrap();
3240        assert_eq!(config.typedb.username, "superuser");
3241        assert_eq!(config.typedb.password, "hunter2");
3242    }
3243
3244    #[test]
3245    fn schema_section_default_when_missing() {
3246        let config: ServerConfig = toml::from_str(MINIMAL_CONFIG).unwrap();
3247        assert_eq!(config.schema.source_file, "");
3248    }
3249
3250    #[test]
3251    fn schema_section_with_file() {
3252        let toml = r#"
3253[server]
3254[typedb]
3255address = "localhost:1729"
3256database = "db"
3257[schema]
3258source_file = "my_schema.tql"
3259"#;
3260        let config: ServerConfig = toml::from_str(toml).unwrap();
3261        assert_eq!(config.schema.source_file, "my_schema.tql");
3262    }
3263
3264    #[test]
3265    fn interceptors_enabled_empty_by_default() {
3266        let config: ServerConfig = toml::from_str(MINIMAL_CONFIG).unwrap();
3267        assert!(config.interceptors.enabled.is_empty());
3268        assert!(config.interceptors.audit_log.is_none());
3269    }
3270
3271    #[test]
3272    fn interceptors_enabled_without_audit_config() {
3273        let toml = r#"
3274[server]
3275[typedb]
3276address = "localhost:1729"
3277database = "db"
3278[interceptors]
3279enabled = ["audit-log"]
3280"#;
3281        let config: ServerConfig = toml::from_str(toml).unwrap();
3282        assert_eq!(config.interceptors.enabled, vec!["audit-log"]);
3283        assert!(config.interceptors.audit_log.is_none());
3284    }
3285
3286    #[test]
3287    fn interceptors_with_audit_config() {
3288        let toml = r#"
3289[server]
3290[typedb]
3291address = "localhost:1729"
3292database = "db"
3293[interceptors]
3294enabled = ["audit-log"]
3295[interceptors.audit-log]
3296output = "file"
3297file_path = "/var/log/audit.jsonl"
3298"#;
3299        let config: ServerConfig = toml::from_str(toml).unwrap();
3300        let audit = config.interceptors.audit_log.unwrap();
3301        assert_eq!(audit.output, "file");
3302        assert_eq!(audit.file_path, "/var/log/audit.jsonl");
3303    }
3304
3305    #[test]
3306    fn audit_log_config_defaults() {
3307        let toml = r#"
3308[server]
3309[typedb]
3310address = "localhost:1729"
3311database = "db"
3312[interceptors]
3313enabled = ["audit-log"]
3314[interceptors.audit-log]
3315"#;
3316        let config: ServerConfig = toml::from_str(toml).unwrap();
3317        let audit = config.interceptors.audit_log.unwrap();
3318        assert_eq!(audit.output, "stdout"); // default
3319        assert_eq!(audit.file_path, ""); // default
3320    }
3321
3322    #[test]
3323    fn extra_fields_ignored() {
3324        let toml = r#"
3325[server]
3326host = "0.0.0.0"
3327unknown_field = "ignored"
3328
3329[typedb]
3330address = "localhost:1729"
3331database = "db"
3332"#;
3333        // toml crate with serde ignores unknown fields by default
3334        let result: Result<ServerConfig, _> = toml::from_str(toml);
3335        assert!(result.is_ok());
3336    }
3337
3338    #[test]
3339    fn multiple_interceptors_enabled() {
3340        let toml = r#"
3341[server]
3342[typedb]
3343address = "localhost:1729"
3344database = "db"
3345[interceptors]
3346enabled = ["audit-log", "rate-limiter", "custom"]
3347"#;
3348        let config: ServerConfig = toml::from_str(toml).unwrap();
3349        assert_eq!(config.interceptors.enabled.len(), 3);
3350    }
3351
3352    // --- TYPEDB_HTTP_PORT env override ---
3353
3354    #[test]
3355    fn env_overrides_http_port() {
3356        let dir = tempfile::tempdir().unwrap();
3357        let path = dir.path().join("server.toml");
3358        std::fs::write(&path, MINIMAL_CONFIG).unwrap();
3359
3360        let config = ServerConfig::from_file_with_env(path.to_str().unwrap(), |name| {
3361            if name == "TYPEDB_HTTP_PORT" {
3362                Some("9123".to_string())
3363            } else {
3364                None
3365            }
3366        })
3367        .unwrap();
3368
3369        assert_eq!(config.typedb.http_port, 9123);
3370    }
3371
3372    #[test]
3373    fn env_overrides_server_version() {
3374        let dir = tempfile::tempdir().unwrap();
3375        let path = dir.path().join("server.toml");
3376        std::fs::write(&path, MINIMAL_CONFIG).unwrap();
3377
3378        let config = ServerConfig::from_file_with_env(path.to_str().unwrap(), |name| {
3379            if name == "TYPEDB_SERVER_VERSION" {
3380                Some("3.10.4".to_string())
3381            } else {
3382                None
3383            }
3384        })
3385        .unwrap();
3386
3387        assert_eq!(config.typedb.server_version.as_deref(), Some("3.10.4"));
3388    }
3389
3390    #[test]
3391    fn env_invalid_http_port_errors() {
3392        let dir = tempfile::tempdir().unwrap();
3393        let path = dir.path().join("server.toml");
3394        std::fs::write(&path, MINIMAL_CONFIG).unwrap();
3395
3396        let result = ServerConfig::from_file_with_env(path.to_str().unwrap(), |name| {
3397            if name == "TYPEDB_HTTP_PORT" {
3398                Some("not-a-port".to_string())
3399            } else {
3400                None
3401            }
3402        });
3403
3404        assert!(
3405            result.is_err(),
3406            "invalid TYPEDB_HTTP_PORT must return an error"
3407        );
3408        let msg = result.unwrap_err().to_string();
3409        assert!(
3410            msg.contains("TYPEDB_HTTP_PORT"),
3411            "error message must mention TYPEDB_HTTP_PORT: {msg}"
3412        );
3413    }
3414
3415    #[test]
3416    fn default_http_port_equals_ssot() {
3417        // Pins the server default against the core SSOT constant so any
3418        // divergence between the two fails at test time.
3419        use super::core_version;
3420        assert_eq!(
3421            default_http_port(),
3422            core_version::DEFAULT_HTTP_PORT,
3423            "server default_http_port() must equal core DEFAULT_HTTP_PORT"
3424        );
3425    }
3426    #[test]
3427    fn v2_query_limits_resolve_by_name_and_refuse_unknown_or_unsupported_values() {
3428        use type_bridge_contract::limits::QueryLimits;
3429
3430        let section = |entries: &[(&str, u64)]| V2Section {
3431            query_limits: entries
3432                .iter()
3433                .map(|(name, value)| ((*name).to_owned(), *value))
3434                .collect(),
3435            ..V2Section::default()
3436        };
3437        assert_eq!(
3438            section(&[]).resolved_query_limits().expect("defaults"),
3439            QueryLimits::CANONICAL
3440        );
3441        let raised = section(&[
3442            ("canonical_bytes", 64 << 20),
3443            ("remote_request_bytes", 128 << 20),
3444        ])
3445        .resolved_query_limits()
3446        .expect("raised limits");
3447        assert_eq!(raised.codec.max_bytes, 64 << 20);
3448        assert_eq!(raised.remote_request_bytes, 128 << 20);
3449        assert_eq!(raised.structural, QueryLimits::CANONICAL.structural);
3450
3451        assert!(
3452            section(&[("made_up", 1)])
3453                .resolved_query_limits()
3454                .unwrap_err()
3455                .contains("not a known query limit")
3456        );
3457        assert!(
3458            section(&[("canonical_depth", 1_000)])
3459                .resolved_query_limits()
3460                .unwrap_err()
3461                .contains("canonical_depth")
3462        );
3463    }
3464
3465    #[cfg(feature = "v2-query")]
3466    #[test]
3467    fn v2_answer_limits_resolve_by_name_and_refuse_unknown_or_unsupported_values() {
3468        use type_bridge_orm::{AnswerTransport, QueryExecutionResourceLimits};
3469
3470        let section = |entries: &[(&str, u64)]| V2Section {
3471            answer_limits: entries
3472                .iter()
3473                .map(|(name, value)| ((*name).to_owned(), *value))
3474                .collect(),
3475            ..V2Section::default()
3476        };
3477        let proxy = QueryExecutionResourceLimits::default_for(AnswerTransport::Proxy);
3478        let defaults = section(&[]).resolved_answer_limits().expect("defaults");
3479        assert_eq!(defaults, proxy);
3480        assert!(
3481            defaults.overrides().is_empty(),
3482            "a default-configured server advertises an empty answer_limits map"
3483        );
3484        assert!(
3485            V2Section::default()
3486                .resolved_answer_limits()
3487                .expect("defaults")
3488                .overrides()
3489                .is_empty()
3490        );
3491        let raised = section(&[("items", 1_000_000), ("bytes", 1 << 30)])
3492            .resolved_answer_limits()
3493            .expect("raised ceilings");
3494        assert_eq!((raised.items, raised.bytes), (1_000_000, 1 << 30));
3495        assert_eq!(raised.graph_nodes, proxy.graph_nodes);
3496        assert_eq!(
3497            raised.overrides(),
3498            std::collections::BTreeMap::from([
3499                ("bytes".to_owned(), 1 << 30),
3500                ("items".to_owned(), 1_000_000),
3501            ])
3502        );
3503
3504        assert!(
3505            section(&[("made_up", 1)])
3506                .resolved_answer_limits()
3507                .unwrap_err()
3508                .contains("not a known answer limit")
3509        );
3510        assert!(
3511            section(&[("statements", 4)])
3512                .resolved_answer_limits()
3513                .unwrap_err()
3514                .contains("statements")
3515        );
3516    }
3517}