Skip to main content

fraiseql_server/server_config/
mod.rs

1//! Server configuration (`*Config` types).
2//!
3//! These are developer-facing configuration types loaded from `fraiseql.toml`,
4//! environment variables, or CLI flags. They are mutable between deployments.
5//!
6//! For the distinction between `*Config` (developer-facing, mutable) and
7//! `*Settings` (compiled into `schema.compiled.json`, immutable at runtime),
8//! see `docs/architecture/config-vs-settings.md`.
9
10pub(crate) mod defaults;
11pub mod hs256;
12mod methods;
13pub mod observers;
14pub mod storage;
15pub mod tls;
16
17#[cfg(test)]
18mod tests;
19
20use std::{collections::HashMap, net::SocketAddr, path::PathBuf};
21
22use defaults::{
23    default_bind_addr, default_database_url, default_graphql_path, default_health_path,
24    default_introspection_path, default_max_header_bytes, default_max_header_count,
25    default_max_request_body_bytes, default_metrics_json_path, default_metrics_path,
26    default_playground_path, default_pool_max_size, default_pool_min_size, default_pool_timeout,
27    default_readiness_path, default_schema_path, default_shutdown_timeout_secs,
28    default_subscription_path,
29};
30use fraiseql_core::security::OidcConfig;
31pub use hs256::Hs256Config;
32pub use observers::AdmissionConfig;
33#[cfg(feature = "observers")]
34pub use observers::{ObserverConfig, ObserverPoolConfig, ObserverRuntimeSettings};
35use serde::{Deserialize, Serialize};
36pub use storage::{ResolvedStorage, build_storage_state, resolve_storage_section};
37pub use tls::{DatabaseTlsConfig, PlaygroundTool, TlsServerConfig};
38
39use crate::middleware::RateLimitConfig;
40
41/// Server configuration.
42#[derive(Debug, Clone, Serialize, Deserialize)]
43pub struct ServerConfig {
44    /// Path to compiled schema JSON file.
45    #[serde(default = "defaults::default_schema_path")]
46    pub schema_path: PathBuf,
47
48    /// Fail boot if any declared `sql_source` (query view / mutation function) is
49    /// not backed by the database (#487).
50    ///
51    /// Default `false` — the boot path is unchanged. Postgres-only. The
52    /// `--validate-sql-sources` CLI flag and the `FRAISEQL_VALIDATE_SQL_SOURCES`
53    /// environment variable both override this (env/flag win over the config key).
54    #[serde(default)]
55    pub validate_sql_sources: bool,
56
57    /// Database connection URL (PostgreSQL, MySQL, SQLite, SQL Server).
58    #[serde(default = "defaults::default_database_url")]
59    pub database_url: String,
60
61    /// Server bind address.
62    #[serde(default = "defaults::default_bind_addr")]
63    pub bind_addr: SocketAddr,
64
65    /// Arrow Flight gRPC bind address (requires `arrow` feature).
66    ///
67    /// Defaults to `0.0.0.0:50051`. Override with `FRAISEQL_FLIGHT_BIND_ADDR`
68    /// environment variable or this field in the config file.
69    #[cfg(feature = "arrow")]
70    #[serde(default = "defaults::default_flight_bind_addr")]
71    pub flight_bind_addr: SocketAddr,
72
73    /// Enable CORS.
74    #[serde(default = "defaults::default_true")]
75    pub cors_enabled: bool,
76
77    /// CORS allowed origins (if empty, allows all).
78    #[serde(default)]
79    pub cors_origins: Vec<String>,
80
81    /// Enable framework-level response compression.
82    ///
83    /// Defaults to `false`. In production FraiseQL is typically deployed
84    /// behind a reverse proxy (Nginx, Caddy, cloud load balancer) that
85    /// handles compression more efficiently (brotli, shared across upstreams,
86    /// cacheable). Enable this only for single-binary / no-proxy deployments.
87    #[serde(default = "defaults::default_false")]
88    pub compression_enabled: bool,
89
90    /// Enable request tracing.
91    #[serde(default = "defaults::default_true")]
92    pub tracing_enabled: bool,
93
94    /// OTLP exporter endpoint for distributed tracing.
95    ///
96    /// When set (e.g. `"http://otel-collector:4317"`), the server initializes an
97    /// `OpenTelemetry` OTLP exporter. When `None`, the `OTEL_EXPORTER_OTLP_ENDPOINT`
98    /// environment variable is checked as a fallback. If neither is set, no OTLP
99    /// export occurs (zero overhead).
100    #[serde(default)]
101    pub otlp_endpoint: Option<String>,
102
103    /// OTLP exporter timeout in seconds (default: 10).
104    #[serde(default = "defaults::default_otlp_timeout_secs")]
105    pub otlp_export_timeout_secs: u64,
106
107    /// Service name for distributed tracing (default: `"fraiseql"`).
108    #[serde(default = "defaults::default_service_name")]
109    pub tracing_service_name: String,
110
111    /// Enable APQ (Automatic Persisted Queries).
112    #[serde(default = "defaults::default_true")]
113    pub apq_enabled: bool,
114
115    /// Enable query caching.
116    #[serde(default = "defaults::default_true")]
117    pub cache_enabled: bool,
118
119    /// GraphQL endpoint path.
120    #[serde(default = "defaults::default_graphql_path")]
121    pub graphql_path: String,
122
123    /// Health check endpoint path (liveness probe).
124    ///
125    /// Returns 200 as long as the process is alive, 503 if the database is down.
126    #[serde(default = "defaults::default_health_path")]
127    pub health_path: String,
128
129    /// Readiness probe endpoint path.
130    ///
131    /// Returns 200 when the server is ready to serve traffic (database reachable),
132    /// 503 otherwise. Kubernetes `readinessProbe` should point here.
133    #[serde(default = "defaults::default_readiness_path")]
134    pub readiness_path: String,
135
136    /// Introspection endpoint path.
137    #[serde(default = "defaults::default_introspection_path")]
138    pub introspection_path: String,
139
140    /// Metrics endpoint path (Prometheus format).
141    #[serde(default = "defaults::default_metrics_path")]
142    pub metrics_path: String,
143
144    /// Metrics JSON endpoint path.
145    #[serde(default = "defaults::default_metrics_json_path")]
146    pub metrics_json_path: String,
147
148    /// Playground (GraphQL IDE) endpoint path.
149    #[serde(default = "defaults::default_playground_path")]
150    pub playground_path: String,
151
152    /// Enable GraphQL playground/IDE (default: false for production safety).
153    ///
154    /// When enabled, serves a GraphQL IDE (`GraphiQL` or Apollo Sandbox)
155    /// at the configured `playground_path`.
156    ///
157    /// **Security**: Disabled by default for production safety. Set to true for development
158    /// environments only. The playground exposes schema information and can be a
159    /// reconnaissance vector for attackers.
160    #[serde(default)]
161    pub playground_enabled: bool,
162
163    /// Which GraphQL IDE to use.
164    ///
165    /// - `graphiql`: The classic GraphQL IDE (default)
166    /// - `apollo-sandbox`: Apollo's embeddable sandbox
167    #[serde(default)]
168    pub playground_tool: PlaygroundTool,
169
170    /// `WebSocket` endpoint path for GraphQL subscriptions.
171    #[serde(default = "defaults::default_subscription_path")]
172    pub subscription_path: String,
173
174    /// Enable GraphQL subscriptions over `WebSocket`.
175    ///
176    /// When enabled, provides graphql-ws (graphql-transport-ws) protocol
177    /// support for real-time subscription events.
178    #[serde(default = "defaults::default_true")]
179    pub subscriptions_enabled: bool,
180
181    /// Enable metrics endpoints.
182    ///
183    /// **Security**: Disabled by default for production safety.
184    /// When enabled, requires `metrics_token` to be set for authentication.
185    #[serde(default)]
186    pub metrics_enabled: bool,
187
188    /// Bearer token for metrics endpoint authentication.
189    ///
190    /// Required when `metrics_enabled` is true. Requests must include:
191    /// `Authorization: Bearer <token>`
192    ///
193    /// **Security**: Use a strong, random token (e.g., 32+ characters).
194    #[serde(default)]
195    pub metrics_token: Option<String>,
196
197    /// Enable admin API endpoints (default: false for production safety).
198    ///
199    /// **Security**: Disabled by default. When enabled, requires `admin_token` to be set.
200    /// Admin endpoints allow schema reloading, cache management, and config inspection.
201    #[serde(default)]
202    pub admin_api_enabled: bool,
203
204    /// Bearer token for admin API authentication.
205    ///
206    /// Required when `admin_api_enabled` is true. Requests must include:
207    /// `Authorization: Bearer <token>`
208    ///
209    /// **Security**: Use a strong, random token (minimum 32 characters).
210    /// This token grants access to **destructive** admin operations:
211    /// `reload-schema`, `cache/clear`.
212    ///
213    /// If `admin_readonly_token` is set, this token is restricted to write
214    /// operations only. If `admin_readonly_token` is not set, this token
215    /// also grants access to read-only endpoints (backwards-compatible).
216    #[serde(default)]
217    pub admin_token: Option<String>,
218
219    /// Optional separate bearer token for read-only admin operations.
220    ///
221    /// When set, restricts `admin_token` to destructive operations only
222    /// (`reload-schema`, `cache/clear`) and uses this token for read-only
223    /// endpoints (`config`, `cache/stats`, `explain`, `grafana-dashboard`).
224    ///
225    /// Operators and monitoring tools can use this token without gaining
226    /// the ability to modify server state or reload the schema.
227    ///
228    /// **Security**: Must be different from `admin_token` and at least 32
229    /// characters. Requires `admin_api_enabled = true` and `admin_token` set.
230    #[serde(default)]
231    pub admin_readonly_token: Option<String>,
232
233    /// Enable introspection endpoint (default: false for production safety).
234    ///
235    /// **Security**: Disabled by default. When enabled, the introspection endpoint
236    /// exposes the complete GraphQL schema structure. Combined with `introspection_require_auth`,
237    /// you can optionally protect it with OIDC authentication.
238    #[serde(default)]
239    pub introspection_enabled: bool,
240
241    /// Require authentication for introspection endpoint (default: true).
242    ///
243    /// When true and OIDC is configured, introspection requires same auth as GraphQL endpoint.
244    /// When false, introspection is publicly accessible (use only in development).
245    #[serde(default = "defaults::default_true")]
246    pub introspection_require_auth: bool,
247
248    /// Require authentication for the schema metadata endpoint (default: None).
249    ///
250    /// When `Some(true)`, the `/api/v1/schema/metadata` endpoint requires OIDC auth
251    /// independently of introspection. When `Some(false)`, metadata is publicly
252    /// accessible regardless of introspection auth. When `None` (default), falls
253    /// back to `introspection_require_auth` for backwards compatibility.
254    #[serde(default, skip_serializing_if = "Option::is_none")]
255    pub metadata_require_auth: Option<bool>,
256
257    /// Require authentication for schema export endpoints (default: None).
258    ///
259    /// Controls `/api/v1/schema.graphql` and `/api/v1/schema.json` independently of
260    /// introspection auth. When `Some(true)`, schema export requires OIDC auth. When
261    /// `Some(false)`, schema export is publicly accessible. When `None` (default),
262    /// falls back to `introspection_require_auth` for backwards compatibility.
263    #[serde(default, skip_serializing_if = "Option::is_none")]
264    pub schema_export_require_auth: Option<bool>,
265
266    /// Require authentication for the GraphQL Playground endpoint (default: None).
267    ///
268    /// Controls the playground independently of introspection auth. When `Some(true)`,
269    /// the playground requires OIDC auth. When `Some(false)`, the playground is publicly
270    /// accessible. When `None` (default), falls back to `introspection_require_auth`
271    /// for backwards compatibility.
272    #[serde(default, skip_serializing_if = "Option::is_none")]
273    pub playground_require_auth: Option<bool>,
274
275    /// Require authentication for the `WebSocket` subscription endpoint (default: None).
276    ///
277    /// Controls the `/subscriptions` endpoint independently of introspection auth.
278    /// When `Some(true)`, the subscription endpoint requires OIDC auth. When `Some(false)`,
279    /// subscriptions are publicly accessible. When `None` (default), falls back to
280    /// `introspection_require_auth` for backwards compatibility.
281    #[serde(default, skip_serializing_if = "Option::is_none")]
282    pub subscription_require_auth: Option<bool>,
283
284    /// Require authentication for design audit API endpoints (default: true).
285    ///
286    /// Design audit endpoints expose system architecture and optimization opportunities.
287    /// When true and OIDC is configured, design endpoints require same auth as GraphQL endpoint.
288    /// When false, design endpoints are publicly accessible (use only in development).
289    #[serde(default = "defaults::default_true")]
290    pub design_api_require_auth: bool,
291
292    /// Database connection pool minimum size.
293    #[serde(default = "defaults::default_pool_min_size")]
294    pub pool_min_size: usize,
295
296    /// Database connection pool maximum size.
297    #[serde(default = "defaults::default_pool_max_size")]
298    pub pool_max_size: usize,
299
300    /// Database connection pool timeout in seconds.
301    #[serde(default = "defaults::default_pool_timeout")]
302    pub pool_timeout_secs: u64,
303
304    /// OIDC authentication configuration (optional).
305    ///
306    /// When set, enables JWT authentication using OIDC discovery.
307    /// Supports Auth0, Keycloak, Okta, Cognito, Azure AD, and any
308    /// OIDC-compliant provider.
309    ///
310    /// # Example (TOML)
311    ///
312    /// ```toml
313    /// [auth]
314    /// issuer = "https://your-tenant.auth0.com/"
315    /// audience = "your-api-identifier"
316    /// ```
317    #[serde(default)]
318    pub auth: Option<OidcConfig>,
319
320    /// HS256 symmetric-key authentication (optional).
321    ///
322    /// Alternative to `auth` (OIDC) for integration testing and internal
323    /// service-to-service scenarios. Mutually exclusive with `auth`.
324    ///
325    /// Validation is fully local — no discovery endpoint, no JWKS fetch.
326    /// Not recommended for public-facing production.
327    ///
328    /// # Example (TOML)
329    ///
330    /// ```toml
331    /// [auth_hs256]
332    /// secret_env = "FRAISEQL_HS256_SECRET"
333    /// issuer = "my-test-suite"
334    /// audience = "my-api"
335    /// ```
336    #[serde(default)]
337    pub auth_hs256: Option<Hs256Config>,
338
339    /// Name of the environment variable holding the server HMAC secret.
340    ///
341    /// When set, the per-dispatch idempotency token surfaced to functions is
342    /// HMAC-signed with a subkey derived from this secret, making it unforgeable —
343    /// required before it is exposed externally as a VERP delivery-tracking
344    /// Return-Path. Unset → the token is an unsigned digest (the zero-config
345    /// default). The secret must be **stable across restarts and shared across
346    /// instances** (a per-process random value would break resume + multi-instance
347    /// idempotency); resolved from the environment at startup, never the config file.
348    ///
349    /// ```toml
350    /// hmac_secret_env = "FRAISEQL_HMAC_SECRET"
351    /// ```
352    #[serde(default)]
353    pub hmac_secret_env: Option<String>,
354
355    /// TLS/SSL configuration for HTTPS and encrypted connections.
356    ///
357    /// When set, enables TLS enforcement for HTTP/gRPC endpoints and
358    /// optionally requires mutual TLS (mTLS) for client certificates.
359    ///
360    /// # Example (TOML)
361    ///
362    /// ```toml
363    /// [tls]
364    /// enabled = true
365    /// cert_path = "/etc/fraiseql/cert.pem"
366    /// key_path = "/etc/fraiseql/key.pem"
367    /// require_client_cert = false
368    /// min_version = "1.2"  # "1.2" or "1.3"
369    /// ```
370    #[serde(default)]
371    pub tls: Option<TlsServerConfig>,
372
373    /// Database TLS configuration.
374    ///
375    /// Enables TLS for database connections and configures
376    /// per-database TLS settings (PostgreSQL, Redis, `ClickHouse`, etc.).
377    ///
378    /// # Example (TOML)
379    ///
380    /// ```toml
381    /// [database_tls]
382    /// postgres_ssl_mode = "require"  # disable, allow, prefer, require, verify-ca, verify-full
383    /// redis_ssl = true               # Use rediss:// protocol
384    /// clickhouse_https = true         # Use HTTPS
385    /// elasticsearch_https = true      # Use HTTPS
386    /// verify_certificates = true      # Verify server certificates
387    /// ```
388    #[serde(default)]
389    pub database_tls: Option<DatabaseTlsConfig>,
390
391    /// Require `Content-Type: application/json` on POST requests (default: true).
392    ///
393    /// CSRF protection: rejects POST requests with non-JSON Content-Type
394    /// (e.g. `text/plain`, `application/x-www-form-urlencoded`) with 415.
395    #[serde(default = "defaults::default_true")]
396    pub require_json_content_type: bool,
397
398    /// Maximum request body size in bytes (default: 1 MB).
399    ///
400    /// Requests exceeding this limit receive 413 Payload Too Large.
401    /// Set to 0 to use axum's default (no limit).
402    #[serde(default = "defaults::default_max_request_body_bytes")]
403    pub max_request_body_bytes: usize,
404
405    /// Maximum number of HTTP headers per request (default: 100).
406    ///
407    /// Requests with more headers than this limit receive 431 Request Header Fields Too Large.
408    /// Prevents header-flooding `DoS` attacks that exhaust memory.
409    #[serde(default = "defaults::default_max_header_count")]
410    pub max_header_count: usize,
411
412    /// Maximum total size of all HTTP headers in bytes (default: 32 `KiB`).
413    ///
414    /// Requests whose combined header name+value bytes exceed this limit receive
415    /// 431 Request Header Fields Too Large. Prevents memory exhaustion from
416    /// oversized header values.
417    #[serde(default = "defaults::default_max_header_bytes")]
418    pub max_header_bytes: usize,
419
420    /// Per-request processing timeout in seconds (default: `None` — no timeout).
421    ///
422    /// When set, each HTTP request must complete within this many seconds or
423    /// the server returns **408 Request Timeout**.  This is a defence-in-depth
424    /// measure against slow or runaway database queries.
425    ///
426    /// **Recommendation**: set to `60` for production deployments.
427    ///
428    /// # Example (TOML)
429    ///
430    /// ```toml
431    /// request_timeout_secs = 60
432    /// ```
433    #[serde(default)]
434    pub request_timeout_secs: Option<u64>,
435
436    /// Maximum byte length for a query string delivered via HTTP GET.
437    ///
438    /// GET queries are URL-encoded and passed as a query parameter. Very long
439    /// strings are either a `DoS` attempt or a sign that the caller should use
440    /// POST instead. Default: `100_000` (100 `KiB`).
441    ///
442    /// # Example (TOML)
443    ///
444    /// ```toml
445    /// max_get_query_bytes = 50000
446    /// ```
447    #[serde(default = "defaults::default_max_get_query_bytes")]
448    pub max_get_query_bytes: usize,
449
450    /// Rate limiting configuration for GraphQL requests.
451    ///
452    /// When configured, enables per-IP and per-user rate limiting with token bucket algorithm.
453    /// Defaults to enabled with sensible per-IP limits for security-by-default.
454    ///
455    /// # Example (TOML)
456    ///
457    /// ```toml
458    /// [rate_limiting]
459    /// enabled = true
460    /// rps_per_ip = 100      # 100 requests/second per IP
461    /// rps_per_user = 1000   # 1000 requests/second per authenticated user
462    /// burst_size = 500      # Allow bursts up to 500 requests
463    /// ```
464    #[serde(default)]
465    pub rate_limiting: Option<RateLimitConfig>,
466
467    /// Observer runtime configuration (optional, requires `observers` feature).
468    #[cfg(feature = "observers")]
469    #[serde(default)]
470    pub observers: Option<ObserverConfig>,
471
472    /// Connection pool pressure monitoring configuration.
473    ///
474    /// When `enabled = true`, the server spawns a background task that monitors
475    /// pool metrics and emits scaling recommendations via Prometheus metrics and
476    /// log lines. **The pool is not resized at runtime** — act on
477    /// `fraiseql_pool_tuning_*` events by adjusting `max_connections` and restarting.
478    ///
479    /// # Example (TOML)
480    ///
481    /// ```toml
482    /// [pool_tuning]
483    /// enabled = true
484    /// min_pool_size = 5
485    /// max_pool_size = 50
486    /// tuning_interval_ms = 30000
487    /// ```
488    #[serde(default)]
489    pub pool_tuning: Option<crate::config::pool_tuning::PoolPressureMonitorConfig>,
490
491    /// Admission control configuration.
492    ///
493    /// When set, enforces a maximum number of concurrent in-flight requests and
494    /// a maximum queue depth.  Requests that exceed either limit receive
495    /// `503 Service Unavailable` immediately instead of stalling under load.
496    ///
497    /// # Example (TOML)
498    ///
499    /// ```toml
500    /// [admission_control]
501    /// max_concurrent = 500
502    /// max_queue_depth = 1000
503    /// ```
504    #[serde(default)]
505    pub admission_control: Option<AdmissionConfig>,
506
507    /// Security contact email for `/.well-known/security.txt` (RFC 9116).
508    ///
509    /// When set, the server exposes a `/.well-known/security.txt` endpoint
510    /// with this email address as the security contact. This helps security
511    /// researchers report vulnerabilities responsibly.
512    ///
513    /// # Example (TOML)
514    ///
515    /// ```toml
516    /// security_contact = "security@example.com"
517    /// ```
518    #[serde(default)]
519    pub security_contact: Option<String>,
520
521    /// Query validation overrides (depth and complexity limits).
522    ///
523    /// When present, these values take precedence over the limits baked into
524    /// the compiled schema, allowing operators to tune validation without
525    /// recompiling.
526    ///
527    /// # Example (TOML)
528    ///
529    /// ```toml
530    /// [validation]
531    /// max_query_depth = 15
532    /// max_query_complexity = 200
533    /// ```
534    #[serde(default)]
535    pub validation: Option<fraiseql_core::schema::ValidationConfig>,
536
537    /// Maximum failed admin bearer auth attempts per IP within a 60-second
538    /// window before the IP is blocked with 429 Too Many Requests (default: 10).
539    ///
540    /// Set to `0` to disable brute-force protection entirely (not recommended).
541    ///
542    /// # Example (TOML)
543    ///
544    /// ```toml
545    /// admin_auth_max_failures = 5
546    /// ```
547    #[serde(default = "defaults::default_admin_auth_max_failures")]
548    pub admin_auth_max_failures: u32,
549
550    /// Bearer token protecting the storage REST API (`/storage/v1/`).
551    ///
552    /// When set, all requests to storage endpoints must include an
553    /// `Authorization: Bearer <token>` header that matches this value.  Requests
554    /// without a valid token receive **401 Unauthorized**.
555    ///
556    /// **Security**: This token protects *all* storage operations (upload, download,
557    /// delete, presigned URL).  Use a strong random string (minimum 32 characters).
558    /// Omit the field (or set `None`) to leave storage endpoints open — appropriate
559    /// only in development or when the storage API is behind a trusted network boundary.
560    ///
561    /// # Example (TOML)
562    ///
563    /// ```toml
564    /// storage_token = "your-strong-random-token-here"
565    /// ```
566    #[serde(default)]
567    pub storage_token: Option<String>,
568
569    /// Graceful shutdown drain timeout in seconds (default: 30).
570    ///
571    /// After a SIGTERM or Ctrl+C signal, the server stops accepting new connections and
572    /// waits for in-flight requests and background runtimes (observers) to finish.
573    /// If the drain takes longer than this value, the process logs a warning and exits
574    /// immediately instead of hanging indefinitely.
575    ///
576    /// Set this to match `terminationGracePeriodSeconds` in your Kubernetes pod spec
577    /// minus a small buffer (e.g., 25s when `terminationGracePeriodSeconds = 30`).
578    ///
579    /// Override with `FRAISEQL_SHUTDOWN_TIMEOUT_SECS`.
580    #[serde(default = "defaults::default_shutdown_timeout_secs")]
581    pub shutdown_timeout_secs: u64,
582
583    /// Usage counter persistence configuration (optional).
584    ///
585    /// When set, mutation usage counters are periodically flushed to PostgreSQL
586    /// and restored on server startup.  Requires a PostgreSQL database URL.
587    ///
588    /// ```toml
589    /// [usage]
590    /// flush_interval_secs = 60
591    /// ```
592    ///
593    /// When absent (default), counters are in-memory only and reset on restart.
594    #[serde(default)]
595    pub usage: Option<crate::config::UsagePersistenceConfig>,
596
597    /// Named object-storage backend configurations, keyed by storage name.
598    ///
599    /// Each `[storage.<name>]` section is wired into a mounted `/storage/v1/*`
600    /// route group on startup (PostgreSQL only — the object-metadata repository
601    /// requires a `sqlx::PgPool`). The section name is the logical bucket name in
602    /// the URL path (`/storage/v1/object/<name>/<key>`). See
603    /// [`StorageSectionConfig`].
604    ///
605    /// **v1 supports a single section.** Configuring more than one
606    /// `[storage.<name>]` is a startup error (multiplexing several physical
607    /// backends behind one route group is a planned follow-up).
608    ///
609    /// # Example (TOML)
610    ///
611    /// ```toml
612    /// [storage.uploads]
613    /// backend = "local"
614    /// path = "/var/lib/fraiseql/uploads"
615    /// access = "public_read"
616    /// ```
617    #[serde(default)]
618    pub storage: HashMap<String, StorageSectionConfig>,
619
620    /// Named file-upload route configurations, keyed by route name.
621    ///
622    /// **Not yet wired into the binary** (tracked as a `[storage]` follow-up).
623    /// The section is parsed only so the server can warn at startup rather than
624    /// silently dropping it. See [`FileSectionConfig`].
625    #[serde(default)]
626    pub files: HashMap<String, FileSectionConfig>,
627
628    /// Inbound webhook receiver routes (`[webhooks.<name>]`), keyed by route name.
629    ///
630    /// Each entry mounts `POST /webhooks/<name>`: the delivery is signature-verified
631    /// (per `provider`, secret from `secret_env`), normalized to an `InboundMessage`,
632    /// and persisted onto the durable spine. Requires the `inbound` feature and a
633    /// PostgreSQL pool; empty by default.
634    #[cfg(feature = "inbound")]
635    #[serde(default)]
636    pub webhooks: HashMap<String, crate::config::WebhookRouteConfig>,
637
638    /// Connected mailbox accounts (`[mailbox.<name>]`), keyed by account name.
639    ///
640    /// Each account carries an optional poll-IMAP receive half
641    /// (`[mailbox.<name>.imap]`) — a background poll worker that fetches new
642    /// messages by UID watermark, normalizes their MIME to an `InboundMessage` on
643    /// the durable spine, and fires `after:ingest:email` functions — and (via the
644    /// hardening `send_email` transport) an SMTP send half. Requires the
645    /// `inbound-email` feature and a PostgreSQL pool; empty by default.
646    #[cfg(feature = "inbound-email")]
647    #[serde(default)]
648    pub mailbox: HashMap<String, crate::inbound::email::MailboxConfig>,
649
650    /// Delivery-feedback send policy (`[send]`).
651    ///
652    /// Governs how the correlation step reacts to inbound bounces / challenges /
653    /// replies — currently the challenge-suppression threshold
654    /// (`challenge_suppress_after`, default 2). Requires the `inbound-email`
655    /// feature; defaults apply when the section is absent.
656    #[cfg(feature = "inbound-email")]
657    #[serde(default)]
658    pub send: crate::inbound::email::SendSettings,
659
660    /// Multi-tenant executor runtime configuration.
661    ///
662    /// Off by default. Enable with `[tenancy.runtime] enabled = true` to mount the
663    /// multi-tenant runtime in the off-the-shelf binary: the per-tenant executor
664    /// registry, `X-Tenant-ID` / JWT `tenant_id` / Host dispatch, and the
665    /// `/api/v1/admin/tenants/*` lifecycle API. Runtime tenant provisioning
666    /// (registering a tenant with its own connection) is PostgreSQL-only.
667    ///
668    /// ```toml
669    /// [tenancy.runtime]
670    /// enabled = true
671    /// ```
672    #[serde(default)]
673    pub tenancy: TenancyServerConfig,
674
675    /// Enriched-identity resolution (#539): `[identity.enrichment]` /
676    /// `[identity.sender]`. Top-level (not under `[auth]`) so it applies under
677    /// any auth mode — HS256/OIDC parity by construction. Gated on `auth`
678    /// because enrichment requires an authenticated subject and the auth DB pool.
679    #[cfg(feature = "auth")]
680    #[serde(default)]
681    pub identity: Option<crate::identity::IdentityConfig>,
682}
683
684/// A single `[storage.<name>]` configuration section.
685///
686/// Combines the storage *backend* connection settings (mapped to
687/// [`fraiseql_storage::config::StorageConfig`] and passed to
688/// `fraiseql_storage::create_backend`) with the optional *logical-bucket* access
689/// policy (mapped to `fraiseql_storage::config::BucketConfig`). The section name
690/// becomes the logical bucket name in the URL path.
691///
692/// The connection fields mirror [`fraiseql_storage::config::StorageConfig`]; the
693/// policy fields (`access`, `max_object_bytes`, `allowed_mime_types`,
694/// `serve_inline`) are optional and default to a private, force-download bucket.
695#[derive(Debug, Clone, Serialize, Deserialize)]
696pub struct StorageSectionConfig {
697    /// Backend type: `"local"`, `"s3"` (and S3-compatible providers `"hetzner"`,
698    /// `"scaleway"`, `"ovh"`, `"exoscale"`, `"backblaze"`, `"r2"`), `"gcs"`,
699    /// `"azure"`. Non-local backends require the matching Cargo feature
700    /// (`aws-s3`, `gcs`, `azure-blob`) to be compiled in.
701    pub backend: String,
702
703    /// Filesystem path for the `local` backend.
704    #[serde(default)]
705    pub path: Option<String>,
706
707    /// Physical bucket name for S3/GCS/Azure backends.
708    #[serde(default)]
709    pub bucket: Option<String>,
710
711    /// Region for S3-compatible backends.
712    #[serde(default)]
713    pub region: Option<String>,
714
715    /// Custom endpoint URL for S3-compatible services and cloud emulators.
716    #[serde(default)]
717    pub endpoint: Option<String>,
718
719    /// GCP project ID for the GCS backend.
720    #[serde(default)]
721    pub project_id: Option<String>,
722
723    /// Azure storage account name.
724    #[serde(default)]
725    pub account_name: Option<String>,
726
727    /// Access policy for the logical bucket: `"private"` (default) or
728    /// `"public_read"`. An unrecognised value is a startup error.
729    #[serde(default)]
730    pub access: Option<String>,
731
732    /// Maximum object size in bytes for the logical bucket (None = unlimited,
733    /// subject to the route-wide body limit).
734    #[serde(default)]
735    pub max_object_bytes: Option<u64>,
736
737    /// Allowed MIME types for uploads (None = any). Supports `image/*`-style
738    /// wildcards.
739    #[serde(default)]
740    pub allowed_mime_types: Option<Vec<String>>,
741
742    /// Serve downloads with `Content-Disposition: inline` instead of the default
743    /// `attachment`. Active-content types (`text/html`, `image/svg+xml`, …) are
744    /// always served as `attachment` regardless of this flag.
745    #[serde(default)]
746    pub serve_inline: Option<bool>,
747}
748
749/// A single `[files.<name>]` configuration section.
750///
751/// File-upload routes are **not yet wired** into the binary; this type exists so
752/// the server can warn rather than silently ignore the section. All fields are
753/// optional to keep parsing tolerant.
754#[derive(Debug, Clone, Default, Serialize, Deserialize)]
755pub struct FileSectionConfig {
756    /// Named storage backend this upload route writes to.
757    #[serde(default)]
758    pub storage: Option<String>,
759
760    /// Maximum upload size (e.g. `"50MB"`).
761    #[serde(default)]
762    pub max_size: Option<String>,
763
764    /// URL path prefix override.
765    #[serde(default)]
766    pub path: Option<String>,
767}
768
769/// Multi-tenant runtime configuration (`[tenancy]`).
770#[derive(Debug, Clone, Default, Serialize, Deserialize)]
771pub struct TenancyServerConfig {
772    /// Per-tenant executor runtime settings (`[tenancy.runtime]`).
773    #[serde(default)]
774    pub runtime: TenancyRuntimeConfig,
775}
776
777/// Per-tenant executor runtime settings (`[tenancy.runtime]`).
778#[derive(Debug, Clone, Default, Serialize, Deserialize)]
779pub struct TenancyRuntimeConfig {
780    /// Mount the multi-tenant executor runtime (registry + admin tenant API +
781    /// `X-Tenant-ID` / JWT / Host dispatch). Defaults to `false`.
782    #[serde(default)]
783    pub enabled: bool,
784}
785
786impl Default for ServerConfig {
787    fn default() -> Self {
788        Self {
789            schema_path: default_schema_path(),
790            validate_sql_sources: false,
791            database_url: default_database_url(),
792            bind_addr: default_bind_addr(),
793            #[cfg(feature = "arrow")]
794            flight_bind_addr: defaults::default_flight_bind_addr(),
795            cors_enabled: true,
796            cors_origins: Vec::new(),
797            compression_enabled: false,
798            tracing_enabled: true,
799            otlp_endpoint: None,
800            otlp_export_timeout_secs: defaults::default_otlp_timeout_secs(),
801            tracing_service_name: defaults::default_service_name(),
802            apq_enabled: true,
803            cache_enabled: true,
804            graphql_path: default_graphql_path(),
805            health_path: default_health_path(),
806            readiness_path: default_readiness_path(),
807            introspection_path: default_introspection_path(),
808            metrics_path: default_metrics_path(),
809            metrics_json_path: default_metrics_json_path(),
810            playground_path: default_playground_path(),
811            playground_enabled: false, // Disabled by default for security
812            playground_tool: PlaygroundTool::default(),
813            subscription_path: default_subscription_path(),
814            subscriptions_enabled: true,
815            metrics_enabled: false, // Disabled by default for security
816            metrics_token: None,
817            admin_api_enabled: false, // Disabled by default for security
818            admin_token: None,
819            admin_readonly_token: None,
820            introspection_enabled: false, // Disabled by default for security
821            introspection_require_auth: true, // Require auth when enabled
822            metadata_require_auth: None,  // Falls back to introspection_require_auth
823            schema_export_require_auth: None, // Falls back to introspection_require_auth
824            playground_require_auth: None, // Falls back to introspection_require_auth
825            subscription_require_auth: None, // Falls back to introspection_require_auth
826            design_api_require_auth: true, // Require auth for design endpoints
827            pool_min_size: default_pool_min_size(),
828            pool_max_size: default_pool_max_size(),
829            pool_timeout_secs: default_pool_timeout(),
830            auth: None,            // No auth by default
831            auth_hs256: None,      // No HS256 auth by default
832            hmac_secret_env: None, // No HMAC secret → unsigned idempotency token
833            tls: None,             // TLS disabled by default
834            database_tls: None,    /* Database TLS disabled
835                                    * by default */
836            require_json_content_type: true, // CSRF protection
837            max_request_body_bytes: default_max_request_body_bytes(), // 1 MB
838            max_header_count: default_max_header_count(), // 100 headers
839            max_header_bytes: default_max_header_bytes(), // 32 KiB
840            rate_limiting: None,             // Rate limiting uses defaults
841            #[cfg(feature = "observers")]
842            observers: None, // Observers disabled by default
843            pool_tuning: None,               // Pool pressure monitoring disabled by default
844            admission_control: None,         // Admission control disabled by default
845            security_contact: None,          // No security.txt by default
846            validation: None,                // Use compiled schema defaults
847            shutdown_timeout_secs: default_shutdown_timeout_secs(),
848            request_timeout_secs: None,
849            max_get_query_bytes: defaults::default_max_get_query_bytes(),
850            admin_auth_max_failures: defaults::default_admin_auth_max_failures(),
851            storage_token: None,
852            usage: None,             // Usage persistence disabled by default
853            storage: HashMap::new(), // No storage backends wired by default
854            files: HashMap::new(),   // No file-upload routes by default
855            #[cfg(feature = "inbound")]
856            webhooks: HashMap::new(), // No inbound webhook routes by default
857            #[cfg(feature = "inbound-email")]
858            mailbox: HashMap::new(), // No connected mailboxes by default
859            #[cfg(feature = "inbound-email")]
860            send: crate::inbound::email::SendSettings::default(),
861            tenancy: TenancyServerConfig::default(), // Multi-tenant runtime off by default
862            #[cfg(feature = "auth")]
863            identity: None, // Enriched-identity resolution off by default
864        }
865    }
866}