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 /// TLS/SSL configuration for HTTPS and encrypted connections.
340 ///
341 /// When set, enables TLS enforcement for HTTP/gRPC endpoints and
342 /// optionally requires mutual TLS (mTLS) for client certificates.
343 ///
344 /// # Example (TOML)
345 ///
346 /// ```toml
347 /// [tls]
348 /// enabled = true
349 /// cert_path = "/etc/fraiseql/cert.pem"
350 /// key_path = "/etc/fraiseql/key.pem"
351 /// require_client_cert = false
352 /// min_version = "1.2" # "1.2" or "1.3"
353 /// ```
354 #[serde(default)]
355 pub tls: Option<TlsServerConfig>,
356
357 /// Database TLS configuration.
358 ///
359 /// Enables TLS for database connections and configures
360 /// per-database TLS settings (PostgreSQL, Redis, `ClickHouse`, etc.).
361 ///
362 /// # Example (TOML)
363 ///
364 /// ```toml
365 /// [database_tls]
366 /// postgres_ssl_mode = "require" # disable, allow, prefer, require, verify-ca, verify-full
367 /// redis_ssl = true # Use rediss:// protocol
368 /// clickhouse_https = true # Use HTTPS
369 /// elasticsearch_https = true # Use HTTPS
370 /// verify_certificates = true # Verify server certificates
371 /// ```
372 #[serde(default)]
373 pub database_tls: Option<DatabaseTlsConfig>,
374
375 /// Require `Content-Type: application/json` on POST requests (default: true).
376 ///
377 /// CSRF protection: rejects POST requests with non-JSON Content-Type
378 /// (e.g. `text/plain`, `application/x-www-form-urlencoded`) with 415.
379 #[serde(default = "defaults::default_true")]
380 pub require_json_content_type: bool,
381
382 /// Maximum request body size in bytes (default: 1 MB).
383 ///
384 /// Requests exceeding this limit receive 413 Payload Too Large.
385 /// Set to 0 to use axum's default (no limit).
386 #[serde(default = "defaults::default_max_request_body_bytes")]
387 pub max_request_body_bytes: usize,
388
389 /// Maximum number of HTTP headers per request (default: 100).
390 ///
391 /// Requests with more headers than this limit receive 431 Request Header Fields Too Large.
392 /// Prevents header-flooding `DoS` attacks that exhaust memory.
393 #[serde(default = "defaults::default_max_header_count")]
394 pub max_header_count: usize,
395
396 /// Maximum total size of all HTTP headers in bytes (default: 32 `KiB`).
397 ///
398 /// Requests whose combined header name+value bytes exceed this limit receive
399 /// 431 Request Header Fields Too Large. Prevents memory exhaustion from
400 /// oversized header values.
401 #[serde(default = "defaults::default_max_header_bytes")]
402 pub max_header_bytes: usize,
403
404 /// Per-request processing timeout in seconds (default: `None` — no timeout).
405 ///
406 /// When set, each HTTP request must complete within this many seconds or
407 /// the server returns **408 Request Timeout**. This is a defence-in-depth
408 /// measure against slow or runaway database queries.
409 ///
410 /// **Recommendation**: set to `60` for production deployments.
411 ///
412 /// # Example (TOML)
413 ///
414 /// ```toml
415 /// request_timeout_secs = 60
416 /// ```
417 #[serde(default)]
418 pub request_timeout_secs: Option<u64>,
419
420 /// Maximum byte length for a query string delivered via HTTP GET.
421 ///
422 /// GET queries are URL-encoded and passed as a query parameter. Very long
423 /// strings are either a `DoS` attempt or a sign that the caller should use
424 /// POST instead. Default: `100_000` (100 `KiB`).
425 ///
426 /// # Example (TOML)
427 ///
428 /// ```toml
429 /// max_get_query_bytes = 50000
430 /// ```
431 #[serde(default = "defaults::default_max_get_query_bytes")]
432 pub max_get_query_bytes: usize,
433
434 /// Rate limiting configuration for GraphQL requests.
435 ///
436 /// When configured, enables per-IP and per-user rate limiting with token bucket algorithm.
437 /// Defaults to enabled with sensible per-IP limits for security-by-default.
438 ///
439 /// # Example (TOML)
440 ///
441 /// ```toml
442 /// [rate_limiting]
443 /// enabled = true
444 /// rps_per_ip = 100 # 100 requests/second per IP
445 /// rps_per_user = 1000 # 1000 requests/second per authenticated user
446 /// burst_size = 500 # Allow bursts up to 500 requests
447 /// ```
448 #[serde(default)]
449 pub rate_limiting: Option<RateLimitConfig>,
450
451 /// Observer runtime configuration (optional, requires `observers` feature).
452 #[cfg(feature = "observers")]
453 #[serde(default)]
454 pub observers: Option<ObserverConfig>,
455
456 /// Connection pool pressure monitoring configuration.
457 ///
458 /// When `enabled = true`, the server spawns a background task that monitors
459 /// pool metrics and emits scaling recommendations via Prometheus metrics and
460 /// log lines. **The pool is not resized at runtime** — act on
461 /// `fraiseql_pool_tuning_*` events by adjusting `max_connections` and restarting.
462 ///
463 /// # Example (TOML)
464 ///
465 /// ```toml
466 /// [pool_tuning]
467 /// enabled = true
468 /// min_pool_size = 5
469 /// max_pool_size = 50
470 /// tuning_interval_ms = 30000
471 /// ```
472 #[serde(default)]
473 pub pool_tuning: Option<crate::config::pool_tuning::PoolPressureMonitorConfig>,
474
475 /// Admission control configuration.
476 ///
477 /// When set, enforces a maximum number of concurrent in-flight requests and
478 /// a maximum queue depth. Requests that exceed either limit receive
479 /// `503 Service Unavailable` immediately instead of stalling under load.
480 ///
481 /// # Example (TOML)
482 ///
483 /// ```toml
484 /// [admission_control]
485 /// max_concurrent = 500
486 /// max_queue_depth = 1000
487 /// ```
488 #[serde(default)]
489 pub admission_control: Option<AdmissionConfig>,
490
491 /// Security contact email for `/.well-known/security.txt` (RFC 9116).
492 ///
493 /// When set, the server exposes a `/.well-known/security.txt` endpoint
494 /// with this email address as the security contact. This helps security
495 /// researchers report vulnerabilities responsibly.
496 ///
497 /// # Example (TOML)
498 ///
499 /// ```toml
500 /// security_contact = "security@example.com"
501 /// ```
502 #[serde(default)]
503 pub security_contact: Option<String>,
504
505 /// Query validation overrides (depth and complexity limits).
506 ///
507 /// When present, these values take precedence over the limits baked into
508 /// the compiled schema, allowing operators to tune validation without
509 /// recompiling.
510 ///
511 /// # Example (TOML)
512 ///
513 /// ```toml
514 /// [validation]
515 /// max_query_depth = 15
516 /// max_query_complexity = 200
517 /// ```
518 #[serde(default)]
519 pub validation: Option<fraiseql_core::schema::ValidationConfig>,
520
521 /// Maximum failed admin bearer auth attempts per IP within a 60-second
522 /// window before the IP is blocked with 429 Too Many Requests (default: 10).
523 ///
524 /// Set to `0` to disable brute-force protection entirely (not recommended).
525 ///
526 /// # Example (TOML)
527 ///
528 /// ```toml
529 /// admin_auth_max_failures = 5
530 /// ```
531 #[serde(default = "defaults::default_admin_auth_max_failures")]
532 pub admin_auth_max_failures: u32,
533
534 /// Bearer token protecting the storage REST API (`/storage/v1/`).
535 ///
536 /// When set, all requests to storage endpoints must include an
537 /// `Authorization: Bearer <token>` header that matches this value. Requests
538 /// without a valid token receive **401 Unauthorized**.
539 ///
540 /// **Security**: This token protects *all* storage operations (upload, download,
541 /// delete, presigned URL). Use a strong random string (minimum 32 characters).
542 /// Omit the field (or set `None`) to leave storage endpoints open — appropriate
543 /// only in development or when the storage API is behind a trusted network boundary.
544 ///
545 /// # Example (TOML)
546 ///
547 /// ```toml
548 /// storage_token = "your-strong-random-token-here"
549 /// ```
550 #[serde(default)]
551 pub storage_token: Option<String>,
552
553 /// Graceful shutdown drain timeout in seconds (default: 30).
554 ///
555 /// After a SIGTERM or Ctrl+C signal, the server stops accepting new connections and
556 /// waits for in-flight requests and background runtimes (observers) to finish.
557 /// If the drain takes longer than this value, the process logs a warning and exits
558 /// immediately instead of hanging indefinitely.
559 ///
560 /// Set this to match `terminationGracePeriodSeconds` in your Kubernetes pod spec
561 /// minus a small buffer (e.g., 25s when `terminationGracePeriodSeconds = 30`).
562 ///
563 /// Override with `FRAISEQL_SHUTDOWN_TIMEOUT_SECS`.
564 #[serde(default = "defaults::default_shutdown_timeout_secs")]
565 pub shutdown_timeout_secs: u64,
566
567 /// Usage counter persistence configuration (optional).
568 ///
569 /// When set, mutation usage counters are periodically flushed to PostgreSQL
570 /// and restored on server startup. Requires a PostgreSQL database URL.
571 ///
572 /// ```toml
573 /// [usage]
574 /// flush_interval_secs = 60
575 /// ```
576 ///
577 /// When absent (default), counters are in-memory only and reset on restart.
578 #[serde(default)]
579 pub usage: Option<crate::config::UsagePersistenceConfig>,
580
581 /// Named object-storage backend configurations, keyed by storage name.
582 ///
583 /// Each `[storage.<name>]` section is wired into a mounted `/storage/v1/*`
584 /// route group on startup (PostgreSQL only — the object-metadata repository
585 /// requires a `sqlx::PgPool`). The section name is the logical bucket name in
586 /// the URL path (`/storage/v1/object/<name>/<key>`). See
587 /// [`StorageSectionConfig`].
588 ///
589 /// **v1 supports a single section.** Configuring more than one
590 /// `[storage.<name>]` is a startup error (multiplexing several physical
591 /// backends behind one route group is a planned follow-up).
592 ///
593 /// # Example (TOML)
594 ///
595 /// ```toml
596 /// [storage.uploads]
597 /// backend = "local"
598 /// path = "/var/lib/fraiseql/uploads"
599 /// access = "public_read"
600 /// ```
601 #[serde(default)]
602 pub storage: HashMap<String, StorageSectionConfig>,
603
604 /// Named file-upload route configurations, keyed by route name.
605 ///
606 /// **Not yet wired into the binary** (tracked as a `[storage]` follow-up).
607 /// The section is parsed only so the server can warn at startup rather than
608 /// silently dropping it. See [`FileSectionConfig`].
609 #[serde(default)]
610 pub files: HashMap<String, FileSectionConfig>,
611
612 /// Multi-tenant executor runtime configuration.
613 ///
614 /// Off by default. Enable with `[tenancy.runtime] enabled = true` to mount the
615 /// multi-tenant runtime in the off-the-shelf binary: the per-tenant executor
616 /// registry, `X-Tenant-ID` / JWT `tenant_id` / Host dispatch, and the
617 /// `/api/v1/admin/tenants/*` lifecycle API. Runtime tenant provisioning
618 /// (registering a tenant with its own connection) is PostgreSQL-only.
619 ///
620 /// ```toml
621 /// [tenancy.runtime]
622 /// enabled = true
623 /// ```
624 #[serde(default)]
625 pub tenancy: TenancyServerConfig,
626}
627
628/// A single `[storage.<name>]` configuration section.
629///
630/// Combines the storage *backend* connection settings (mapped to
631/// [`fraiseql_storage::config::StorageConfig`] and passed to
632/// `fraiseql_storage::create_backend`) with the optional *logical-bucket* access
633/// policy (mapped to `fraiseql_storage::config::BucketConfig`). The section name
634/// becomes the logical bucket name in the URL path.
635///
636/// The connection fields mirror [`fraiseql_storage::config::StorageConfig`]; the
637/// policy fields (`access`, `max_object_bytes`, `allowed_mime_types`,
638/// `serve_inline`) are optional and default to a private, force-download bucket.
639#[derive(Debug, Clone, Serialize, Deserialize)]
640pub struct StorageSectionConfig {
641 /// Backend type: `"local"`, `"s3"` (and S3-compatible providers `"hetzner"`,
642 /// `"scaleway"`, `"ovh"`, `"exoscale"`, `"backblaze"`, `"r2"`), `"gcs"`,
643 /// `"azure"`. Non-local backends require the matching Cargo feature
644 /// (`aws-s3`, `gcs`, `azure-blob`) to be compiled in.
645 pub backend: String,
646
647 /// Filesystem path for the `local` backend.
648 #[serde(default)]
649 pub path: Option<String>,
650
651 /// Physical bucket name for S3/GCS/Azure backends.
652 #[serde(default)]
653 pub bucket: Option<String>,
654
655 /// Region for S3-compatible backends.
656 #[serde(default)]
657 pub region: Option<String>,
658
659 /// Custom endpoint URL for S3-compatible services and cloud emulators.
660 #[serde(default)]
661 pub endpoint: Option<String>,
662
663 /// GCP project ID for the GCS backend.
664 #[serde(default)]
665 pub project_id: Option<String>,
666
667 /// Azure storage account name.
668 #[serde(default)]
669 pub account_name: Option<String>,
670
671 /// Access policy for the logical bucket: `"private"` (default) or
672 /// `"public_read"`. An unrecognised value is a startup error.
673 #[serde(default)]
674 pub access: Option<String>,
675
676 /// Maximum object size in bytes for the logical bucket (None = unlimited,
677 /// subject to the route-wide body limit).
678 #[serde(default)]
679 pub max_object_bytes: Option<u64>,
680
681 /// Allowed MIME types for uploads (None = any). Supports `image/*`-style
682 /// wildcards.
683 #[serde(default)]
684 pub allowed_mime_types: Option<Vec<String>>,
685
686 /// Serve downloads with `Content-Disposition: inline` instead of the default
687 /// `attachment`. Active-content types (`text/html`, `image/svg+xml`, …) are
688 /// always served as `attachment` regardless of this flag.
689 #[serde(default)]
690 pub serve_inline: Option<bool>,
691}
692
693/// A single `[files.<name>]` configuration section.
694///
695/// File-upload routes are **not yet wired** into the binary; this type exists so
696/// the server can warn rather than silently ignore the section. All fields are
697/// optional to keep parsing tolerant.
698#[derive(Debug, Clone, Default, Serialize, Deserialize)]
699pub struct FileSectionConfig {
700 /// Named storage backend this upload route writes to.
701 #[serde(default)]
702 pub storage: Option<String>,
703
704 /// Maximum upload size (e.g. `"50MB"`).
705 #[serde(default)]
706 pub max_size: Option<String>,
707
708 /// URL path prefix override.
709 #[serde(default)]
710 pub path: Option<String>,
711}
712
713/// Multi-tenant runtime configuration (`[tenancy]`).
714#[derive(Debug, Clone, Default, Serialize, Deserialize)]
715pub struct TenancyServerConfig {
716 /// Per-tenant executor runtime settings (`[tenancy.runtime]`).
717 #[serde(default)]
718 pub runtime: TenancyRuntimeConfig,
719}
720
721/// Per-tenant executor runtime settings (`[tenancy.runtime]`).
722#[derive(Debug, Clone, Default, Serialize, Deserialize)]
723pub struct TenancyRuntimeConfig {
724 /// Mount the multi-tenant executor runtime (registry + admin tenant API +
725 /// `X-Tenant-ID` / JWT / Host dispatch). Defaults to `false`.
726 #[serde(default)]
727 pub enabled: bool,
728}
729
730impl Default for ServerConfig {
731 fn default() -> Self {
732 Self {
733 schema_path: default_schema_path(),
734 validate_sql_sources: false,
735 database_url: default_database_url(),
736 bind_addr: default_bind_addr(),
737 #[cfg(feature = "arrow")]
738 flight_bind_addr: defaults::default_flight_bind_addr(),
739 cors_enabled: true,
740 cors_origins: Vec::new(),
741 compression_enabled: false,
742 tracing_enabled: true,
743 otlp_endpoint: None,
744 otlp_export_timeout_secs: defaults::default_otlp_timeout_secs(),
745 tracing_service_name: defaults::default_service_name(),
746 apq_enabled: true,
747 cache_enabled: true,
748 graphql_path: default_graphql_path(),
749 health_path: default_health_path(),
750 readiness_path: default_readiness_path(),
751 introspection_path: default_introspection_path(),
752 metrics_path: default_metrics_path(),
753 metrics_json_path: default_metrics_json_path(),
754 playground_path: default_playground_path(),
755 playground_enabled: false, // Disabled by default for security
756 playground_tool: PlaygroundTool::default(),
757 subscription_path: default_subscription_path(),
758 subscriptions_enabled: true,
759 metrics_enabled: false, // Disabled by default for security
760 metrics_token: None,
761 admin_api_enabled: false, // Disabled by default for security
762 admin_token: None,
763 admin_readonly_token: None,
764 introspection_enabled: false, // Disabled by default for security
765 introspection_require_auth: true, // Require auth when enabled
766 metadata_require_auth: None, // Falls back to introspection_require_auth
767 schema_export_require_auth: None, // Falls back to introspection_require_auth
768 playground_require_auth: None, // Falls back to introspection_require_auth
769 subscription_require_auth: None, // Falls back to introspection_require_auth
770 design_api_require_auth: true, // Require auth for design endpoints
771 pool_min_size: default_pool_min_size(),
772 pool_max_size: default_pool_max_size(),
773 pool_timeout_secs: default_pool_timeout(),
774 auth: None, // No auth by default
775 auth_hs256: None, // No HS256 auth by default
776 tls: None, // TLS disabled by default
777 database_tls: None, /* Database TLS disabled
778 * by default */
779 require_json_content_type: true, // CSRF protection
780 max_request_body_bytes: default_max_request_body_bytes(), // 1 MB
781 max_header_count: default_max_header_count(), // 100 headers
782 max_header_bytes: default_max_header_bytes(), // 32 KiB
783 rate_limiting: None, // Rate limiting uses defaults
784 #[cfg(feature = "observers")]
785 observers: None, // Observers disabled by default
786 pool_tuning: None, // Pool pressure monitoring disabled by default
787 admission_control: None, // Admission control disabled by default
788 security_contact: None, // No security.txt by default
789 validation: None, // Use compiled schema defaults
790 shutdown_timeout_secs: default_shutdown_timeout_secs(),
791 request_timeout_secs: None,
792 max_get_query_bytes: defaults::default_max_get_query_bytes(),
793 admin_auth_max_failures: defaults::default_admin_auth_max_failures(),
794 storage_token: None,
795 usage: None, // Usage persistence disabled by default
796 storage: HashMap::new(), // No storage backends wired by default
797 files: HashMap::new(), // No file-upload routes by default
798 tenancy: TenancyServerConfig::default(), // Multi-tenant runtime off by default
799 }
800 }
801}