Skip to main content

fraiseql_cli/config/
mod.rs

1//! Configuration loading and management
2//!
3//! This module handles loading configuration from fraiseql.toml files,
4//! including security settings, project metadata, and compilation options.
5
6pub mod discovery;
7pub mod inject_defaults;
8pub mod runtime;
9pub mod security;
10pub mod toml_schema;
11
12use std::path::Path;
13
14use anyhow::{Context, Result};
15pub use discovery::ConfigSource;
16use fraiseql_core::schema::NamingConvention;
17pub use runtime::{DatabaseRuntimeConfig, ServerRuntimeConfig};
18pub use security::SecurityConfig;
19use serde::{Deserialize, Serialize};
20pub use toml_schema::TomlSchema;
21use tracing::info;
22
23/// Project configuration from fraiseql.toml
24#[derive(Debug, Clone, Default, Deserialize, Serialize)]
25#[serde(default, deny_unknown_fields)]
26pub struct TomlProjectConfig {
27    /// Project metadata (name, version, description)
28    #[serde(rename = "project")]
29    pub project: ProjectConfig,
30
31    /// FraiseQL-specific settings
32    #[serde(rename = "fraiseql")]
33    pub fraiseql: FraiseQLSettings,
34
35    /// HTTP server runtime configuration (optional — all fields have defaults).
36    #[serde(default)]
37    pub server: ServerRuntimeConfig,
38
39    /// Database connection pool configuration (optional — all fields have defaults).
40    #[serde(default)]
41    pub database: DatabaseRuntimeConfig,
42
43    /// Project-wide default injected parameters (`[inject_defaults]`, #1384) — the
44    /// section the SDK config loaders read from this same file.
45    #[serde(default, skip_serializing_if = "Option::is_none")]
46    pub inject_defaults: Option<inject_defaults::InjectDefaultsToml>,
47}
48
49/// Project metadata
50#[derive(Debug, Clone, Deserialize, Serialize)]
51#[serde(default, deny_unknown_fields)]
52pub struct ProjectConfig {
53    /// Project name
54    pub name:            String,
55    /// Project version
56    pub version:         String,
57    /// Optional project description
58    pub description:     Option<String>,
59    /// Target database backend. Only `"postgresql"` is accepted: MySQL, SQLite and SQL
60    /// Server were removed in v2.15.0 (#374), and [`TomlProjectConfig::validate`] refuses
61    /// them (see `config::validate_database_target`).
62    pub database_target: Option<String>,
63}
64
65impl Default for ProjectConfig {
66    fn default() -> Self {
67        Self {
68            name:            "my-fraiseql-app".to_string(),
69            version:         "1.0.0".to_string(),
70            description:     None,
71            database_target: None,
72        }
73    }
74}
75
76/// FraiseQL-specific settings
77#[derive(Debug, Clone, Deserialize, Serialize)]
78#[serde(default, deny_unknown_fields)]
79pub struct FraiseQLSettings {
80    /// Path to the GraphQL schema file
81    pub schema_file:       String,
82    /// Path to the output compiled schema file
83    pub output_file:       String,
84    /// Security configuration
85    #[serde(rename = "security")]
86    pub security:          SecurityConfig,
87    /// Tenancy isolation configuration
88    #[serde(default)]
89    pub tenancy:           security::TenancyTomlConfig,
90    /// Mutation compilation options (`[fraiseql.mutations]`)
91    #[serde(default)]
92    pub mutations:         MutationsConfig,
93    /// Naming/casing options (`[fraiseql.naming]`)
94    #[serde(default)]
95    pub naming:            NamingTomlConfig,
96    /// Per-operation `@cost` weight overrides (`[fraiseql.cost_weights]`, #379):
97    /// root query/mutation name → manual cost weight, consulted by the runtime
98    /// per-tenant cost-budget check. Empty by default.
99    #[serde(default)]
100    pub cost_weights:      std::collections::HashMap<String, usize>,
101    /// Per-request PostgreSQL session variables (`[fraiseql.session_variables]`).
102    ///
103    /// Applied with `set_config(name, value, true)` before every query and
104    /// mutation, so RLS policies can read them with `current_setting(…)`. This is
105    /// the mechanism database-layer tenant isolation is built on (#628).
106    ///
107    /// Deliberately the same type the runtime consumes — a mirror struct here is
108    /// exactly the producer↔consumer seam that keeps dropping declarations.
109    #[serde(default)]
110    pub session_variables: fraiseql_core::schema::SessionVariablesConfig,
111}
112
113impl Default for FraiseQLSettings {
114    fn default() -> Self {
115        Self {
116            schema_file:       "schema.json".to_string(),
117            output_file:       "schema.compiled.json".to_string(),
118            security:          SecurityConfig::default(),
119            tenancy:           security::TenancyTomlConfig::default(),
120            mutations:         MutationsConfig::default(),
121            naming:            NamingTomlConfig::default(),
122            cost_weights:      std::collections::HashMap::new(),
123            session_variables: fraiseql_core::schema::SessionVariablesConfig::default(),
124        }
125    }
126}
127
128/// Naming/casing options from `[fraiseql.naming]`.
129#[derive(Debug, Clone, Deserialize, Serialize)]
130#[serde(default, deny_unknown_fields)]
131pub struct NamingTomlConfig {
132    /// GraphQL surface naming convention for the JSON-schema compile workflow
133    /// (`fraiseql-cli compile schema.json`). Defaults to `camelCase`:
134    /// `snake_case` columns/functions in the database, `camelCase` operation and
135    /// field names exposed to clients, with incoming mutation input keys recased
136    /// `camelCase` → `snake_case` before they reach the SQL functions. Set
137    /// `convention = "preserve"` to keep names exactly as authored (`snake_case`
138    /// on the wire, no recasing). This knob does not apply to the author-in-TOML
139    /// workflow, which carries its own `naming_convention`.
140    pub convention: NamingConvention,
141    /// Acronyms whose internal digit stays attached when a GraphQL field name is
142    /// mapped back to its `snake_case` JSONB key (e.g. `s3`, `ipv4`, `oauth2`),
143    /// added on top of the engine's built-in defaults. Author the atomic form
144    /// (`s3`, not `s_3`). Example: `acronyms = ["s3", "ipv4"]`.
145    pub acronyms:   Vec<String>,
146}
147
148impl Default for NamingTomlConfig {
149    fn default() -> Self {
150        Self {
151            // Workflow-B compiles to a camelCase GraphQL surface by default; see
152            // the `convention` field docs. Override with `convention = "preserve"`.
153            convention: NamingConvention::CamelCase,
154            acronyms:   Vec::new(),
155        }
156    }
157}
158
159/// Mutation compilation options from `[fraiseql.mutations]`.
160#[derive(Debug, Clone, Default, Deserialize, Serialize)]
161#[serde(default, deny_unknown_fields)]
162pub struct MutationsConfig {
163    /// Opt-in: auto-synthesize a shared `MutationError` type and a per-mutation
164    /// result union (`<Mutation>Result = Entity | MutationError`) for every
165    /// object-returning mutation, rewriting its return type to that union so the
166    /// server's success/error discrimination has a union to resolve against.
167    /// Off by default; mutations that already return a union are left untouched.
168    pub auto_error_union: bool,
169}
170
171impl TomlProjectConfig {
172    /// Load configuration from fraiseql.toml file.
173    ///
174    /// Supports `${VAR}` environment variable interpolation throughout the file.
175    ///
176    /// # Errors
177    ///
178    /// Returns an error if the file does not exist, cannot be read, or cannot be
179    /// parsed as valid TOML matching the `TomlProjectConfig` structure.
180    pub fn from_file(path: &str) -> Result<Self> {
181        info!("Loading configuration from {path}");
182
183        let path = Path::new(path);
184        if !path.exists() {
185            anyhow::bail!("Configuration file not found: {}", path.display());
186        }
187
188        let raw = std::fs::read_to_string(path).context("Failed to read fraiseql.toml")?;
189        let toml_content = expand_env_vars(&raw)?;
190
191        let config: TomlProjectConfig = toml::from_str(&toml_content)
192            .map_err(|e| anyhow::anyhow!("Failed to parse fraiseql.toml: {e}"))?;
193
194        Ok(config)
195    }
196
197    /// Validate configuration.
198    ///
199    /// # Errors
200    ///
201    /// Returns an error if `[project] database_target` names anything but PostgreSQL, or
202    /// if any security, server, or database configuration value is invalid (e.g.
203    /// unsupported algorithm, zero window, or bad port range).
204    pub fn validate(&self) -> Result<()> {
205        info!("Validating configuration");
206        if let Some(target) = &self.project.database_target {
207            validate_database_target("[project]", target)?;
208        }
209        self.fraiseql.security.validate()?;
210        self.fraiseql.tenancy.validate()?;
211        self.server.validate()?;
212        self.database.validate()?;
213        Ok(())
214    }
215}
216
217/// Refuse a `database_target` other than `postgresql` (compared case-insensitively).
218///
219/// The one rule for both keys that carry a target: `[project] database_target`, which
220/// `fraiseql init` writes into every new `fraiseql.toml`, and `[schema] database_target`
221/// in a TOML schema. `section` names the key in the message.
222///
223/// # Errors
224///
225/// Returns an error naming the removed backends and `docs/database-compatibility.md`.
226pub(crate) fn validate_database_target(section: &str, target: &str) -> Result<()> {
227    let target = target.trim();
228    if target.eq_ignore_ascii_case("postgresql") {
229        return Ok(());
230    }
231    anyhow::bail!(
232        "{section} database_target = {target:?} is not supported: FraiseQL targets \
233         PostgreSQL only. The `mysql`, `sqlite` and `sqlserver` backends were removed in \
234         v2.15.0 (#374), so a schema declaring one would compile PostgreSQL SQL. Set \
235         `database_target = \"postgresql\"` or remove the key. See \
236         docs/database-compatibility.md."
237    )
238}
239
240/// Expand `${VAR}` environment variable placeholders in a string.
241///
242/// Unknown variables are left as-is (no panic, silent passthrough).
243#[allow(clippy::expect_used)] // Reason: regex pattern is a compile-time constant guaranteed to be valid
244pub(crate) fn expand_env_vars(content: &str) -> Result<String> {
245    use std::sync::LazyLock;
246
247    static ENV_VAR_REGEX: LazyLock<regex::Regex> = LazyLock::new(|| {
248        regex::Regex::new(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}").expect("env var regex is valid")
249    });
250
251    let mut result = String::with_capacity(content.len());
252    let mut last_end = 0;
253
254    for cap in ENV_VAR_REGEX.captures_iter(content) {
255        // INVARIANT: Regex captures iterator yields Captures where group 0 (the full match) is
256        // always present
257        let m = cap.get(0).expect("INVARIANT: Regex captures group 0 is always present");
258        result.push_str(&content[last_end..m.start()]);
259        let var_name = &cap[1];
260        match std::env::var(var_name) {
261            Ok(val) => {
262                validate_env_var_value(var_name, &val)?;
263                result.push_str(&val);
264            },
265            Err(_) => {
266                result.push_str(&format!("${{{}}}", var_name));
267            },
268        }
269        last_end = m.end();
270    }
271    result.push_str(&content[last_end..]);
272    Ok(result)
273}
274
275fn validate_env_var_value(var_name: &str, value: &str) -> Result<()> {
276    if value.contains('\n') {
277        anyhow::bail!("Environment variable {} contains newline character", var_name);
278    }
279    if value.contains('\r') {
280        anyhow::bail!("Environment variable {} contains carriage return character", var_name);
281    }
282    if value.contains('\0') {
283        anyhow::bail!("Environment variable {} contains null character", var_name);
284    }
285    // Check for unescaped TOML metacharacters: ", ', \, ], [, {, }
286    if value.contains('"')
287        || value.contains('\'')
288        || value.contains('\\')
289        || value.contains(']')
290        || value.contains('[')
291        || value.contains('{')
292        || value.contains('}')
293    {
294        anyhow::bail!(
295            "Environment variable {} contains TOML metacharacter that could break TOML parsing",
296            var_name
297        );
298    }
299    Ok(())
300}
301
302#[cfg(test)]
303mod tests;