1use std::sync::Arc;
4
5#[cfg(feature = "arrow")]
6use fraiseql_arrow::FraiseQLFlightService;
7use fraiseql_core::{
8 cache::{CacheConfig, CachedDatabaseAdapter, QueryResultCache},
9 db::traits::DatabaseAdapter,
10 runtime::{Executor, RuntimeConfig, SubscriptionManager},
11 schema::CompiledSchema,
12 security::{AuthConfig, AuthMiddleware, OidcValidator},
13};
14use tracing::{info, warn};
15
16use super::{RateLimiter, Result, Server, ServerConfig, ServerError};
17
18pub(super) fn build_hs256_auth(config: &ServerConfig) -> Result<Option<Arc<AuthMiddleware>>> {
20 let Some(ref hs) = config.auth_hs256 else {
21 return Ok(None);
22 };
23 hs.validate()
28 .map_err(|e| ServerError::ConfigError(format!("Failed to initialize HS256 auth: {e}")))?;
29 let secret = hs
30 .load_secret()
31 .map_err(|e| ServerError::ConfigError(format!("Failed to initialize HS256 auth: {e}")))?;
32 let mut auth_config = AuthConfig::with_hs256(&secret);
33 if let Some(ref iss) = hs.issuer {
34 auth_config = auth_config.with_issuer(iss);
35 }
36 if let Some(ref aud) = hs.audience {
37 auth_config = auth_config.with_audience(aud);
38 }
39 info!(
40 secret_env = %hs.secret_env,
41 issuer = ?hs.issuer,
42 audience = ?hs.audience,
43 "Initializing HS256 authentication (local validation, no network)"
44 );
45 Ok(Some(Arc::new(AuthMiddleware::from_config(auth_config))))
46}
47
48impl<A: DatabaseAdapter + Clone + Send + Sync + 'static> Server<CachedDatabaseAdapter<A>> {
49 #[allow(clippy::cognitive_complexity)] pub async fn new(
87 config: ServerConfig,
88 schema: CompiledSchema,
89 adapter: Arc<A>,
90 db_pool: Option<sqlx::PgPool>,
91 ) -> Result<Self> {
92 if schema.schema_format_version.is_none() {
95 warn!(
96 "Loaded schema has no schema_format_version (pre-v2.1 format). \
97 Re-compile with the current fraiseql-cli for version compatibility checking."
98 );
99 }
100 schema.validate_format_version().map_err(|msg| {
101 ServerError::ConfigError(format!("Incompatible compiled schema: {msg}"))
102 })?;
103
104 #[cfg(feature = "federation")]
106 let circuit_breaker = schema.federation.as_ref().and_then(
107 crate::federation::circuit_breaker::FederationCircuitBreakerManager::from_config,
108 );
109 #[cfg(not(feature = "federation"))]
110 let circuit_breaker: Option<()> = None;
111 #[cfg(not(feature = "federation"))]
112 let _ = &schema.federation;
113 let error_sanitizer = Self::error_sanitizer_from_schema(&schema);
114 #[cfg(feature = "auth")]
115 let state_encryption = Self::state_encryption_from_schema(&schema)?;
116 #[cfg(not(feature = "auth"))]
117 let state_encryption: Option<
118 std::sync::Arc<crate::auth::state_encryption::StateEncryptionService>,
119 > = None;
120 #[cfg(feature = "auth")]
121 let pkce_store = Self::pkce_store_from_schema(&schema, state_encryption.as_ref()).await?;
122 #[cfg(not(feature = "auth"))]
123 let pkce_store: Option<std::sync::Arc<crate::auth::PkceStateStore>> = None;
124 #[cfg(feature = "auth")]
125 let oidc_server_client = Self::oidc_server_client_from_schema(&schema);
126 #[cfg(not(feature = "auth"))]
127 let oidc_server_client: Option<std::sync::Arc<crate::auth::OidcServerClient>> = None;
128 let schema_rate_limiter = Self::rate_limiter_from_schema(&schema).await?;
129 let api_key_authenticator = crate::api_key::api_key_authenticator_from_schema(&schema);
130 if api_key_authenticator.is_some() {
131 info!("API key authentication enabled");
132 }
133 let revocation_manager = crate::token_revocation::revocation_manager_from_schema(&schema)?;
134 if revocation_manager.is_some() {
135 info!("Token revocation enabled");
136 }
137 let mut tasks: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
140 let trusted_docs = Self::trusted_docs_from_schema(&schema, &mut tasks);
141
142 if config.cache_enabled && !schema.has_rls_configured() {
147 if schema.is_multi_tenant() {
148 return Err(ServerError::ConfigError(
150 "Cache is enabled in a multi-tenant schema but no Row-Level Security \
151 policies are declared. This would allow cross-tenant cache hits and \
152 data leakage. In fraiseql.toml, either disable caching with \
153 [cache] enabled = false, declare [security.rls] policies, or set \
154 [security] multi_tenant = false to acknowledge single-tenant mode."
155 .to_string(),
156 ));
157 }
158 warn!(
160 "Query-result caching is enabled but no Row-Level Security policies are \
161 declared in the compiled schema. This is safe for single-tenant deployments. \
162 For multi-tenant deployments, declare RLS policies and set \
163 `security.multi_tenant = true` in your schema."
164 );
165 }
166
167 let cache_config = CacheConfig::from(config.cache_enabled);
169 let cache = QueryResultCache::new(cache_config);
170
171 if cache_config.enabled {
173 tracing::info!(
174 max_entries = cache_config.max_entries,
175 ttl_seconds = cache_config.ttl_seconds,
176 rls_enforcement = ?cache_config.rls_enforcement,
177 "Query result cache: active"
178 );
179 } else {
180 tracing::info!("Query result cache: disabled");
181 }
182
183 let subscriptions_config = schema.subscriptions_config.clone();
185
186 let inner = Arc::into_inner(adapter)
188 .expect("CachedDatabaseAdapter wrapping requires exclusive Arc ownership at startup");
189 let cached = CachedDatabaseAdapter::new(inner, cache, schema.content_hash())
190 .with_ttl_overrides_from_schema(&schema)
191 .with_rls(schema.has_rls_configured());
192
193 let audit_mutations = schema
196 .security
197 .as_ref()
198 .and_then(|s| s.additional.get("enterprise"))
199 .and_then(|e| e.get("audit_logging_enabled"))
200 .and_then(|v| v.as_bool())
201 .unwrap_or(false);
202 if audit_mutations {
203 info!("Mutation audit logging enabled (target: fraiseql::mutation_audit)");
204 }
205 let max_page_size = page_size_precedence(
208 std::env::var("FRAISEQL_MAX_PAGE_SIZE").ok().as_deref(),
209 schema.validation_config.as_ref().and_then(|v| v.max_page_size),
210 );
211 let executor_config = RuntimeConfig {
212 audit_mutations,
213 max_page_size,
214 ..RuntimeConfig::default()
215 };
216 let executor =
217 Arc::new(Executor::with_config(schema.clone(), Arc::new(cached), executor_config));
218 let subscription_manager = Arc::new(SubscriptionManager::new(Arc::new(schema)));
219
220 let mut server = Self::from_executor(
221 config,
222 executor,
223 subscription_manager,
224 circuit_breaker,
225 error_sanitizer,
226 state_encryption,
227 pkce_store,
228 oidc_server_client,
229 schema_rate_limiter,
230 api_key_authenticator,
231 revocation_manager,
232 trusted_docs,
233 db_pool,
234 tasks,
235 )
236 .await?;
237
238 server.adapter_cache_enabled = cache_config.enabled;
239
240 if let Some(pt) = server.config.pool_tuning.clone() {
242 if pt.enabled {
243 server = server
244 .with_pool_tuning(pt)
245 .map_err(|e| ServerError::ConfigError(format!("pool_tuning: {e}")))?;
246 }
247 }
248
249 #[cfg(feature = "mcp")]
251 if let Some(ref cfg) = server.executor.schema().mcp_config {
252 if cfg.enabled {
253 let tool_count =
254 crate::mcp::tools::schema_to_tools(server.executor.schema(), cfg).len();
255 info!(
256 path = %cfg.path,
257 transport = %cfg.transport,
258 tools = tool_count,
259 "MCP server configured"
260 );
261 server.mcp_config = Some(cfg.clone());
262 }
263 }
264
265 if server.config.apq_enabled {
267 let apq_store: fraiseql_core::apq::ArcApqStorage =
268 Arc::new(fraiseql_core::apq::InMemoryApqStorage::default());
269 server.apq_store = Some(apq_store);
270 info!("APQ (Automatic Persisted Queries) enabled — in-memory backend");
271 }
272
273 if let Some(ref subs) = subscriptions_config {
275 if let Some(max) = subs.max_subscriptions_per_connection {
276 server.max_subscriptions_per_connection = Some(max);
277 }
278 if let Some(lifecycle) = crate::subscriptions::WebhookLifecycle::from_config(subs) {
279 server.subscription_lifecycle = Arc::new(lifecycle);
280 }
281 }
282
283 Ok(server)
284 }
285}
286
287impl<A: DatabaseAdapter + Clone + Send + Sync + 'static> Server<A> {
288 #[allow(clippy::too_many_arguments)]
293 #[allow(clippy::cognitive_complexity)] pub(super) async fn from_executor(
297 config: ServerConfig,
298 executor: Arc<Executor<A>>,
299 subscription_manager: Arc<SubscriptionManager>,
300 #[cfg(feature = "federation")] circuit_breaker: Option<
301 Arc<crate::federation::circuit_breaker::FederationCircuitBreakerManager>,
302 >,
303 #[cfg(not(feature = "federation"))] _circuit_breaker: Option<()>,
304 error_sanitizer: Arc<crate::config::error_sanitization::ErrorSanitizer>,
305 state_encryption: Option<Arc<crate::auth::state_encryption::StateEncryptionService>>,
306 pkce_store: Option<Arc<crate::auth::PkceStateStore>>,
307 oidc_server_client: Option<Arc<crate::auth::OidcServerClient>>,
308 schema_rate_limiter: Option<Arc<RateLimiter>>,
309 api_key_authenticator: Option<Arc<crate::api_key::ApiKeyAuthenticator>>,
310 revocation_manager: Option<Arc<crate::token_revocation::TokenRevocationManager>>,
311 trusted_docs: Option<Arc<crate::trusted_documents::TrustedDocumentStore>>,
312 #[cfg_attr(
314 not(any(feature = "observers", feature = "auth")),
315 allow(unused_variables)
316 )]
317 db_pool: Option<sqlx::PgPool>,
318 mut tasks: tokio::task::JoinSet<()>,
319 ) -> Result<Self> {
320 let oidc_validator = if let Some(ref auth_config) = config.auth {
322 info!(
323 issuer = %auth_config.issuer,
324 "Initializing OIDC authentication"
325 );
326 let validator = OidcValidator::new(auth_config.clone())
327 .await
328 .map_err(|e| ServerError::ConfigError(format!("Failed to initialize OIDC: {e}")))?;
329 Some(Arc::new(validator))
330 } else {
331 None
332 };
333
334 let hs256_auth = build_hs256_auth(&config)?;
336
337 let rate_limiter = if let Some(rl) = schema_rate_limiter {
339 Some(rl)
340 } else if let Some(ref rate_config) = config.rate_limiting {
341 if rate_config.enabled {
342 info!(
343 rps_per_ip = rate_config.rps_per_ip,
344 rps_per_user = rate_config.rps_per_user,
345 "Initializing rate limiting from server config"
346 );
347 Some(Arc::new(RateLimiter::new(rate_config.clone())))
348 } else {
349 info!("Rate limiting disabled by configuration");
350 None
351 }
352 } else {
353 None
354 };
355
356 #[cfg(feature = "observers")]
358 let observer_runtime = Self::init_observer_runtime(&config, db_pool.as_ref()).await?;
359
360 #[cfg(feature = "arrow")]
362 let flight_service = {
363 let mut service = FraiseQLFlightService::new();
364 if let Some(ref validator) = oidc_validator {
365 info!("Enabling OIDC authentication for Arrow Flight");
366 service.set_oidc_validator(validator.clone());
367 } else {
368 info!("Arrow Flight initialized without authentication (dev mode)");
369 }
370 Some(service)
371 };
372
373 #[cfg(feature = "auth")]
375 if pkce_store.is_some() && oidc_server_client.is_none() {
376 tracing::error!(
377 "pkce.enabled = true but [auth] is not configured or OIDC client init failed. \
378 Auth routes (/auth/start, /auth/callback) will NOT be mounted. \
379 Add [auth] with discovery_url, client_id, client_secret_env, and \
380 server_redirect_uri to fraiseql.toml and recompile the schema."
381 );
382 }
383
384 #[cfg(feature = "auth")]
386 Self::check_redis_requirement(pkce_store.as_ref())?;
387
388 #[cfg(feature = "auth")]
390 Self::spawn_pkce_cleanup(pkce_store.as_ref(), &mut tasks);
391
392 #[cfg(not(feature = "auth"))]
395 let _ = (state_encryption, pkce_store, oidc_server_client);
396 Ok(Self {
397 config,
398 executor,
399 subscription_manager,
400 subscription_lifecycle: Arc::new(crate::subscriptions::NoopLifecycle),
401 max_subscriptions_per_connection: None,
402 oidc_validator,
403 hs256_auth,
404 rate_limiter,
405 #[cfg(feature = "secrets")]
406 secrets_manager: None,
407 #[cfg(feature = "federation")]
408 circuit_breaker,
409 error_sanitizer,
410 #[cfg(feature = "auth")]
411 state_encryption,
412 #[cfg(feature = "auth")]
413 pkce_store,
414 #[cfg(feature = "auth")]
415 oidc_server_client,
416 #[cfg(feature = "auth")]
417 social_login: None,
418 #[cfg(feature = "auth")]
419 mfa_state: None,
420 #[cfg(feature = "auth")]
421 anon_signup_state: None,
422 api_key_authenticator,
423 revocation_manager,
424 apq_store: None,
425 trusted_docs,
426 #[cfg(feature = "observers")]
427 observer_runtime,
428 #[cfg(feature = "auth")]
429 enrichment_pool: db_pool.clone(),
430 #[cfg(feature = "observers")]
431 db_pool,
432 storage_state: None,
433 realtime_state: None,
434 tenant_executor_factory: None,
435 #[cfg(feature = "arrow")]
436 flight_service,
437 #[cfg(feature = "mcp")]
438 mcp_config: None,
439 pool_tuning_config: None,
440 adapter_cache_enabled: false,
441 broadcast_manager: None,
442 presence_manager: None,
443 storage_backend: None,
444 storage_max_upload_bytes: 100 * 1024 * 1024, #[cfg(feature = "functions")]
446 function_store: None,
447 #[cfg(feature = "functions")]
448 function_runtime: None,
449 usage: Arc::clone(crate::usage::aggregator::global_aggregator()),
450 tasks,
451 })
452 }
453
454 #[cfg(feature = "auth")]
459 pub(super) fn spawn_pkce_cleanup(
460 pkce_store: Option<&Arc<crate::auth::PkceStateStore>>,
461 tasks: &mut tokio::task::JoinSet<()>,
462 ) {
463 use std::time::Duration;
464
465 use tokio::time::MissedTickBehavior;
466
467 if let Some(store) = pkce_store {
468 let store_clone = Arc::clone(store);
469 tasks.spawn(async move {
470 let mut ticker = tokio::time::interval(Duration::from_secs(300));
471 ticker.set_missed_tick_behavior(MissedTickBehavior::Skip);
472 loop {
473 ticker.tick().await;
474 store_clone.cleanup_expired().await;
475 }
476 });
477 }
478 }
479
480 #[must_use]
482 pub fn with_subscription_lifecycle(
483 mut self,
484 lifecycle: Arc<dyn crate::subscriptions::SubscriptionLifecycle>,
485 ) -> Self {
486 self.subscription_lifecycle = lifecycle;
487 self
488 }
489
490 #[must_use]
492 pub const fn with_max_subscriptions_per_connection(mut self, max: u32) -> Self {
493 self.max_subscriptions_per_connection = Some(max);
494 self
495 }
496
497 #[must_use]
507 pub fn with_tenant_executor_factory(
508 mut self,
509 factory: crate::tenancy::TenantExecutorFactory<A>,
510 ) -> Self {
511 self.tenant_executor_factory = Some(factory);
512 self
513 }
514
515 #[must_use]
521 pub fn with_realtime(mut self, state: crate::realtime::server::RealtimeState) -> Self {
522 self.realtime_state = Some(state);
523 self
524 }
525
526 #[must_use]
528 pub fn with_broadcast(mut self, config: crate::subscriptions::BroadcastConfig) -> Self {
529 self.broadcast_manager =
530 Some(Arc::new(crate::subscriptions::BroadcastManager::new(config)));
531 self
532 }
533
534 #[must_use]
536 pub fn with_presence(mut self, config: crate::subscriptions::PresenceConfig) -> Self {
537 self.presence_manager = Some(Arc::new(crate::subscriptions::PresenceManager::new(config)));
538 self
539 }
540
541 pub fn with_pool_tuning(
550 mut self,
551 config: crate::config::pool_tuning::PoolPressureMonitorConfig,
552 ) -> std::result::Result<Self, String> {
553 config.validate()?;
554 self.pool_tuning_config = Some(config);
555 Ok(self)
556 }
557
558 #[cfg(feature = "auth")]
572 #[must_use]
573 pub fn with_social_login(
574 mut self,
575 social_login: Arc<crate::auth::social::SocialLoginState>,
576 ) -> Self {
577 self.social_login = Some(social_login);
578 self
579 }
580
581 #[cfg(feature = "auth")]
587 #[must_use]
588 pub fn with_anon_signup(mut self, state: Arc<crate::auth::AnonSignupState>) -> Self {
589 self.anon_signup_state = Some(state);
590 self
591 }
592
593 #[cfg(feature = "auth")]
602 #[must_use]
603 pub fn with_mfa(mut self, mfa_state: Arc<crate::auth::MfaRouteState>) -> Self {
604 self.mfa_state = Some(mfa_state);
605 self
606 }
607
608 #[must_use]
617 pub fn with_storage(mut self, backend: Arc<dyn crate::storage::StorageBackend>) -> Self {
618 self.storage_backend = Some(backend);
619 self
620 }
621
622 #[must_use]
627 pub const fn with_storage_max_upload_bytes(mut self, bytes: usize) -> Self {
628 self.storage_max_upload_bytes = bytes;
629 self
630 }
631
632 #[must_use]
643 pub fn with_storage_state(mut self, state: fraiseql_storage::StorageState) -> Self {
644 self.storage_state = Some(state);
645 self
646 }
647
648 #[must_use]
656 pub fn with_revocation_manager(
657 mut self,
658 manager: Arc<crate::token_revocation::TokenRevocationManager>,
659 ) -> Self {
660 self.revocation_manager = Some(manager);
661 self
662 }
663
664 #[cfg(feature = "functions")]
670 #[must_use]
671 pub fn with_functions(
672 mut self,
673 store: Arc<dyn fraiseql_functions::FunctionStore>,
674 runtime: Arc<dyn fraiseql_functions::runtime::SendFunctionRuntime>,
675 ) -> Self {
676 self.function_store = Some(store);
677 self.function_runtime = Some(runtime);
678 self
679 }
680
681 #[cfg(feature = "secrets")]
685 pub fn set_secrets_manager(&mut self, manager: Arc<crate::secrets_manager::SecretsManager>) {
686 self.secrets_manager = Some(manager);
687 info!("Secrets manager attached to server");
688 }
689
690 #[cfg(feature = "mcp")]
700 pub async fn serve_mcp_stdio(self) -> Result<()> {
701 use rmcp::ServiceExt;
702
703 let mcp_cfg = self.mcp_config.ok_or_else(|| {
704 ServerError::ConfigError(
705 "FRAISEQL_MCP_STDIO=1 but MCP is not configured. \
706 Add [mcp] enabled = true to fraiseql.toml and recompile the schema."
707 .into(),
708 )
709 })?;
710
711 let schema = Arc::new(self.executor.schema().clone());
712 let executor = self.executor.clone();
713
714 let service = crate::mcp::handler::FraiseQLMcpService::new(schema, executor, mcp_cfg)
715 .with_oidc_validator(self.oidc_validator.clone());
716
717 info!("MCP stdio transport starting — reading from stdin, writing to stdout");
718
719 let running = service
720 .serve((tokio::io::stdin(), tokio::io::stdout()))
721 .await
722 .map_err(|e| ServerError::ConfigError(format!("MCP stdio init failed: {e}")))?;
723
724 running
725 .waiting()
726 .await
727 .map_err(|e| ServerError::ConfigError(format!("MCP stdio error: {e}")))?;
728
729 Ok(())
730 }
731}
732
733pub fn page_size_precedence(env: Option<&str>, compiled: Option<u32>) -> Option<u32> {
740 if let Some(raw) = env {
741 let trimmed = raw.trim();
742 if trimmed.eq_ignore_ascii_case("none") || trimmed == "0" {
743 return None;
744 }
745 if let Ok(n) = trimmed.parse::<u32>() {
746 return Some(n);
747 }
748 }
750 compiled.or(RuntimeConfig::default().max_page_size)
751}