Skip to main content

fraiseql_server/server_config/
methods.rs

1use super::ServerConfig;
2
3impl ServerConfig {
4    /// Load server configuration from a TOML file.
5    ///
6    /// # Errors
7    ///
8    /// Returns an error string if the file cannot be read or the TOML cannot be parsed.
9    pub fn from_file(path: impl AsRef<std::path::Path>) -> Result<Self, String> {
10        let content = std::fs::read_to_string(path.as_ref())
11            .map_err(|e| format!("Cannot read config file: {e}"))?;
12        toml::from_str(&content).map_err(|e| format!("Invalid TOML config: {e}"))
13    }
14
15    /// Check if running in production mode.
16    ///
17    /// Production mode is detected via `FRAISEQL_ENV` environment variable.
18    /// - `production` or `prod` (or any value other than `development`/`dev`) → production mode
19    /// - `development` or `dev` → development mode
20    #[must_use]
21    pub fn is_production_mode() -> bool {
22        let env = std::env::var("FRAISEQL_ENV")
23            .unwrap_or_else(|_| "production".to_string())
24            .to_lowercase();
25        env != "development" && env != "dev"
26    }
27
28    /// Validate configuration.
29    ///
30    /// # Errors
31    ///
32    /// Returns error if:
33    /// - `metrics_enabled` is true but `metrics_token` is not set
34    /// - `metrics_token` is set but too short (< 16 characters)
35    /// - `auth` config is set but invalid (e.g., empty issuer)
36    /// - `tls` is enabled but cert or key path is missing
37    /// - TLS minimum version is invalid
38    /// - In production mode: `playground_enabled` is true
39    /// - In production mode: `cors_enabled` is true but `cors_origins` is empty
40    pub fn validate(&self) -> Result<(), String> {
41        if self.metrics_enabled {
42            match &self.metrics_token {
43                None => {
44                    return Err("metrics_enabled is true but metrics_token is not set. \
45                         Set FRAISEQL_METRICS_TOKEN or metrics_token in config."
46                        .to_string());
47                },
48                Some(token) if token.len() < 16 => {
49                    return Err(
50                        "metrics_token must be at least 16 characters for security.".to_string()
51                    );
52                },
53                Some(_) => {},
54            }
55        }
56
57        // Admin API validation
58        if self.admin_api_enabled {
59            match &self.admin_token {
60                None => {
61                    return Err("admin_api_enabled is true but admin_token is not set. \
62                         Set FRAISEQL_ADMIN_TOKEN or admin_token in config."
63                        .to_string());
64                },
65                Some(token) if token.len() < 32 => {
66                    return Err(
67                        "admin_token must be at least 32 characters for security.".to_string()
68                    );
69                },
70                Some(_) => {},
71            }
72
73            // Validate the optional read-only token when provided.
74            if let Some(ref ro_token) = self.admin_readonly_token {
75                if ro_token.len() < 32 {
76                    return Err(
77                        "admin_readonly_token must be at least 32 characters for security."
78                            .to_string(),
79                    );
80                }
81                if Some(ro_token) == self.admin_token.as_ref() {
82                    return Err("admin_readonly_token must differ from admin_token.".to_string());
83                }
84            }
85        }
86
87        // Validate OIDC config if present
88        if let Some(ref auth) = self.auth {
89            auth.validate().map_err(|e| e.to_string())?;
90        }
91
92        // OIDC and HS256 are mutually exclusive.
93        if self.auth.is_some() && self.auth_hs256.is_some() {
94            return Err("Both [auth] (OIDC) and [auth_hs256] are configured. Pick one — \
95                 HS256 is intended for integration testing and internal services; \
96                 OIDC is intended for public-facing production."
97                .to_string());
98        }
99
100        // Validate HS256 config if present: the secret env var must be set.
101        if let Some(ref hs) = self.auth_hs256 {
102            if hs.secret_env.trim().is_empty() {
103                return Err("auth_hs256.secret_env must not be empty".to_string());
104            }
105            hs.load_secret()?;
106        }
107
108        // Validate TLS config if present and enabled
109        if let Some(ref tls) = self.tls {
110            if tls.enabled {
111                if !tls.cert_path.exists() {
112                    return Err(format!(
113                        "TLS enabled but certificate file not found: {}",
114                        tls.cert_path.display()
115                    ));
116                }
117                if !tls.key_path.exists() {
118                    return Err(format!(
119                        "TLS enabled but key file not found: {}",
120                        tls.key_path.display()
121                    ));
122                }
123
124                // Validate TLS version
125                if !["1.2", "1.3"].contains(&tls.min_version.as_str()) {
126                    return Err("TLS min_version must be '1.2' or '1.3'".to_string());
127                }
128
129                // Validate mTLS config if required
130                if tls.require_client_cert {
131                    if let Some(ref ca_path) = tls.client_ca_path {
132                        if !ca_path.exists() {
133                            return Err(format!("Client CA file not found: {}", ca_path.display()));
134                        }
135                    } else {
136                        return Err(
137                            "require_client_cert is true but client_ca_path is not set".to_string()
138                        );
139                    }
140                }
141            }
142        }
143
144        // Pool invariants
145        if self.pool_max_size == 0 {
146            return Err("pool_max_size must be at least 1".to_string());
147        }
148        if self.pool_min_size > self.pool_max_size {
149            return Err(format!(
150                "pool_min_size ({}) must not exceed pool_max_size ({})",
151                self.pool_min_size, self.pool_max_size
152            ));
153        }
154        if self.pool_timeout_secs == 0 {
155            return Err("pool_timeout_secs must be > 0. A zero-second timeout would cause every \
156                 connection acquisition to fail immediately. Use a positive value (e.g. 30) \
157                 or remove the field to use the default (30s)."
158                .to_string());
159        }
160
161        // Validate database TLS config if present
162        if let Some(ref db_tls) = self.database_tls {
163            // Validate PostgreSQL SSL mode
164            if ![
165                "disable",
166                "allow",
167                "prefer",
168                "require",
169                "verify-ca",
170                "verify-full",
171            ]
172            .contains(&db_tls.postgres_ssl_mode.as_str())
173            {
174                return Err("Invalid postgres_ssl_mode. Must be one of: \
175                     disable, allow, prefer, require, verify-ca, verify-full"
176                    .to_string());
177            }
178
179            // Validate CA bundle path if provided
180            if let Some(ref ca_path) = db_tls.ca_bundle_path {
181                if !ca_path.exists() {
182                    return Err(format!("CA bundle file not found: {}", ca_path.display()));
183                }
184            }
185        }
186
187        // Rate limiting sanity check
188        if let Some(ref rl) = self.rate_limiting {
189            if rl.rps_per_ip > 0 && rl.rps_per_user > 0 && rl.rps_per_ip > rl.rps_per_user {
190                tracing::warn!(
191                    rps_per_ip = rl.rps_per_ip,
192                    rps_per_user = rl.rps_per_user,
193                    "rps_per_ip exceeds rps_per_user — authenticated users are more \
194                     restricted than anonymous IPs"
195                );
196            }
197        }
198
199        // Production safety validation
200        if Self::is_production_mode() {
201            // Playground should be disabled in production
202            if self.playground_enabled {
203                return Err("playground_enabled is true in production mode. \
204                     Disable the playground or set FRAISEQL_ENV=development. \
205                     The playground exposes sensitive schema information."
206                    .to_string());
207            }
208
209            // CORS origins must be explicitly configured in production
210            if self.cors_enabled && self.cors_origins.is_empty() {
211                return Err("cors_enabled is true but cors_origins is empty in production mode. \
212                     This allows requests from ANY origin, which is a security risk. \
213                     Explicitly configure cors_origins with your allowed domains, \
214                     or disable CORS and set FRAISEQL_ENV=development to bypass this check."
215                    .to_string());
216            }
217        }
218
219        Ok(())
220    }
221
222    /// Check if authentication is enabled.
223    #[must_use]
224    pub const fn auth_enabled(&self) -> bool {
225        self.auth.is_some()
226    }
227}