fraiseql-server 2.15.0

HTTP server for FraiseQL v2 GraphQL engine
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
//! Base, studio, admin, introspection, metrics, and design audit routes.

use std::sync::Arc;

use axum::{
    Router, middleware,
    routing::{get, post, put},
};
use fraiseql_core::security::{IntrospectionPolicy, OidcValidator};
use tracing::{info, warn};

use super::super::{
    BearerAuthState, PlaygroundState, Server, SubscriptionState, admin_auth_middleware, api,
    bearer_auth_middleware, health_handler, introspection_handler, liveness_handler,
    metrics_handler, metrics_json_handler, oidc_auth_middleware, playground_handler,
    readiness_handler, required_auth_middleware, subscription_handler,
};
use crate::routes::graphql::AppState;

impl Server {
    /// Mount base routes (health, readiness), studio, admin API, playground,
    /// security.txt, subscriptions, introspection, metrics, and
    /// design audit endpoints.
    #[allow(clippy::cognitive_complexity)] // Reason: many optional subsystems with feature gates
    pub(super) fn mount_base_and_admin_routes(&self, mut app: Router, state: &AppState) -> Router {
        // Build base routes (always available without auth)
        let base_routes = Router::new()
            .route(&self.config.health_path, get(health_handler))
            // No `::<A>`: liveness takes no state, because a liveness probe that can
            // reach a database is a liveness probe that restarts pods over an outage
            // it cannot fix (#1217).
            .route(&self.config.liveness_path, get(liveness_handler))
            .route(&self.config.readiness_path, get(readiness_handler))
            .with_state(state.clone());
        app = app.merge(base_routes);

        // Studio admin dashboard — always mounted at /studio (SPA shell, no auth)
        {
            use crate::routes::studio::{studio_asset_handler, studio_handler};
            let studio_router = Router::new()
                .route("/studio", get(studio_handler))
                .route("/studio/assets/{file}", get(studio_asset_handler))
                .route("/studio/{*path}", get(studio_handler));
            info!("Studio admin dashboard mounted at /studio");
            app = app.merge(studio_router);
        }

        // Studio admin API — /admin/v1/* (protected by admin bearer token when configured)
        if self.config.admin_api_enabled {
            if let Some(ref token) = self.config.admin_token {
                app = self.mount_studio_admin_api(app, state, token);
            }
        }

        // JWKS force-refresh — operator response to a known IdP key compromise (#361).
        // Auth-gated by the admin bearer token; mounted only when an OIDC validator is
        // configured (there is otherwise nothing to refresh).
        if self.config.admin_api_enabled {
            if let (Some(token), Some(validator)) =
                (self.config.admin_token.as_ref(), self.oidc_validator.as_ref())
            {
                app = self.mount_jwks_refresh(app, token, validator);
            }
        }

        // Conditionally add playground route (with optional independent auth).
        if self.config.playground_enabled {
            app = self.mount_playground(app, state);
        }

        // Conditionally add /.well-known/security.txt (RFC 9116)
        if let Some(ref contact) = self.config.security_contact {
            info!(
                contact = %contact,
                "/.well-known/security.txt endpoint enabled"
            );
            let security_router = Router::new()
                .route(
                    "/.well-known/security.txt",
                    get(crate::routes::well_known::security_txt_handler),
                )
                .with_state(contact.clone());
            app = app.merge(security_router);
        }

        // Conditionally add subscription route (WebSocket).
        if self.config.subscriptions_enabled {
            app = self.mount_subscriptions(app, state);
        }

        // Conditionally add the REST `/introspection` endpoint. The mount
        // decision uses the same `IntrospectionPolicy::from_config` derivation
        // the GraphQL request-path gate uses (#453), so REST and GraphQL agree
        // by construction: a non-`Disabled` policy is exactly
        // `introspection_enabled == true`. The endpoint's own auth requirement
        // (`InternalOnly` vs `Allowed`) is applied inside `mount_introspection`
        // from `introspection_require_auth`.
        if IntrospectionPolicy::from_config(
            self.config.introspection_enabled,
            self.config.introspection_require_auth,
        ) != IntrospectionPolicy::Disabled
        {
            app = self.mount_introspection(app, state);
        }

        // Conditionally add metrics routes
        if self.config.metrics_enabled {
            app = self.mount_metrics(app, state);
        }

        // Conditionally add admin routes (protected by bearer token).
        if self.config.admin_api_enabled {
            app = self.mount_admin_api(app, state);
        }

        // Conditionally add design audit endpoints
        app = self.mount_design_audit(app, state);

        app
    }

    fn mount_studio_admin_api(&self, app: Router, state: &AppState, token: &str) -> Router {
        use crate::routes::studio::{
            admin::{
                health_handler as studio_health_handler, schema_handler as studio_schema_handler,
            },
            auth_users::{
                invite_user_handler, list_users_handler, mfa_status_handler, revoke_user_handler,
            },
            data::{mutate_handler as data_mutate_handler, query_handler as data_query_handler},
            function_ops::{
                delete_secret_handler, function_logs_handler, invoke_function_handler,
                list_functions_handler, list_secrets_handler, set_secret_handler,
            },
            metrics_summary::summary_handler as metrics_summary_handler,
            storage_browser::{
                delete_object_handler, list_buckets_handler, list_objects_handler, presign_handler,
            },
        };
        let auth = BearerAuthState::with_max_failures(
            token.to_string(),
            self.config.admin_auth_max_failures,
        );
        let studio_admin_router = Router::new()
            // Schema + health
            .route("/admin/v1/schema", get(studio_schema_handler))
            .route("/admin/v1/health/detailed", get(studio_health_handler))
            // Data browser
            .route("/admin/v1/data/{entity}/query", post(data_query_handler))
            .route("/admin/v1/data/{entity}/mutate", post(data_mutate_handler))
            // Auth user management
            .route("/admin/v1/users", get(list_users_handler))
            .route("/admin/v1/users/invite", post(invite_user_handler))
            .route("/admin/v1/users/{id}/revoke", post(revoke_user_handler))
            .route("/admin/v1/users/{id}/mfa", get(mfa_status_handler))
            // Storage browser
            .route("/admin/v1/storage/buckets", get(list_buckets_handler))
            .route("/admin/v1/storage/objects", get(list_objects_handler))
            .route("/admin/v1/storage/objects/sign", post(presign_handler))
            .route("/admin/v1/storage/objects", axum::routing::delete(delete_object_handler))
            // Function operations
            .route("/admin/v1/functions", get(list_functions_handler))
            .route("/admin/v1/functions/{name}/invoke", post(invoke_function_handler))
            .route("/admin/v1/functions/{name}/logs", get(function_logs_handler))
            .route("/admin/v1/functions/{name}/secrets", get(list_secrets_handler))
            .route(
                "/admin/v1/functions/{name}/secrets/{key}",
                put(set_secret_handler).delete(delete_secret_handler),
            )
            // Metrics summary
            .route("/admin/v1/metrics/summary", get(metrics_summary_handler))
            .route_layer(middleware::from_fn_with_state(auth, bearer_auth_middleware))
            .with_state(state.clone());
        info!("Studio admin API mounted at /admin/v1/* (bearer token required)");
        app.merge(studio_admin_router)
    }

    /// Mount `POST /admin/v1/auth/refresh-jwks` (#361): force an immediate JWKS
    /// refetch so an operator can close the stolen-key replay window the moment a
    /// key compromise is detected, instead of waiting up to `jwks_cache_ttl_secs`
    /// or restarting every replica. Gated by the admin bearer token.
    fn mount_jwks_refresh(
        &self,
        app: Router,
        token: &str,
        validator: &Arc<OidcValidator>,
    ) -> Router {
        let auth = BearerAuthState::with_max_failures(
            token.to_string(),
            self.config.admin_auth_max_failures,
        );
        let router = Router::new()
            .route(
                "/admin/v1/auth/refresh-jwks",
                post(crate::routes::jwks_admin::refresh_jwks_handler),
            )
            .route_layer(middleware::from_fn_with_state(auth, bearer_auth_middleware))
            .with_state(Arc::clone(validator));
        info!(
            "JWKS refresh endpoint mounted: POST /admin/v1/auth/refresh-jwks (admin token required)"
        );
        app.merge(router)
    }

    fn mount_playground(&self, mut app: Router, _state: &AppState) -> Router {
        let playground_require_auth = self
            .config
            .playground_require_auth
            .unwrap_or(self.config.introspection_require_auth);

        let playground_state =
            PlaygroundState::new(self.config.graphql_path.clone(), self.config.playground_tool);

        if playground_require_auth {
            if let Some(ref validator) = self.oidc_validator {
                info!(
                    playground_path = %self.config.playground_path,
                    playground_tool = ?self.config.playground_tool,
                    "GraphQL playground enabled (OIDC auth required)"
                );
                let auth_state = self.oidc_auth_state(validator.clone());
                let playground_router = Router::new()
                    .route(&self.config.playground_path, get(playground_handler))
                    .route_layer(middleware::from_fn_with_state(auth_state, oidc_auth_middleware))
                    .with_state(playground_state);
                app = app.merge(playground_router);
            } else {
                warn!(
                    playground_path = %self.config.playground_path,
                    "playground_require_auth is true but no OIDC configured — playground disabled"
                );
            }
        } else {
            info!(
                playground_path = %self.config.playground_path,
                playground_tool = ?self.config.playground_tool,
                "GraphQL playground enabled (no auth required)"
            );
            let playground_router = Router::new()
                .route(&self.config.playground_path, get(playground_handler))
                .with_state(playground_state);
            app = app.merge(playground_router);
        }
        app
    }

    fn mount_subscriptions(&self, mut app: Router, state: &AppState) -> Router {
        // Mirror the GraphQL handler's tenant dispatch on the subscription
        // upgrade: install the Host-domain registry and drive strict cross-source
        // validation from the schema's RLS configuration (#331).
        let strict_tenant_validation = self.executor.schema().has_rls_configured();

        // #596: row-level visibility policies, resolved once from the compiled schema.
        let subscription_policies = Arc::new(
            crate::routes::subscriptions::build_subscription_policies(self.executor.schema()),
        );

        // #611: a live policy source so a hot-reload's subscription_policy change reaches
        // NEW subscriptions on the next subscribe, not only on restart. It reads the same
        // reload-aware executor ArcSwap the query plane swaps in `AppState::reload_schema`;
        // the mount-time `subscription_policies` above stays as the fallback. Already-
        // connected subscriptions re-derive on the `policy_reload` bump below (layer-2).
        let executor_swap = state.executor.clone();
        let live_subscription_policies: crate::routes::subscriptions::LiveSubscriptionPolicies =
            Arc::new(move || {
                Arc::new(crate::routes::subscriptions::build_subscription_policies(
                    executor_swap.load().schema(),
                ))
            });

        let schema_swap = state.executor.clone();
        let live_schema: crate::routes::subscriptions::LiveSchema =
            Arc::new(move || Arc::new(schema_swap.load().schema().clone()));

        // Ruling AA 4: the executor serving now plans each subscription.
        let planner_swap = state.executor.clone();
        let live_executor: crate::routes::subscriptions::LiveExecutor =
            Arc::new(move || planner_swap.load_full());

        #[allow(unused_mut)]
        // Reason: `mut` is needed when the auth feature is enabled
        let mut subscription_state = SubscriptionState::new(self.subscription_manager.clone())
            .with_lifecycle(self.subscription_lifecycle.clone())
            .with_max_subscriptions(self.max_subscriptions_per_connection)
            .with_tenant_context(state.domain_registry().clone(), strict_tenant_validation)
            // #422: enforce the operation-level authorizer (if any) at subscribe-time.
            .with_authorizer(self.executor.config().authorizer.clone())
            // #596: server-owned row-visibility policies (fail-closed at subscribe time).
            .with_subscription_policies(subscription_policies)
            // #611: read live policies per new subscription so a hot-reload applies promptly.
            .with_live_subscription_policies(Some(live_subscription_policies))
            // #1154: validate a subscription document's variable definitions against
            // the schema that is actually serving, so § 5.8.2 on /ws follows a
            // hot-reload exactly as the policies above do.
            .with_live_schema(Some(live_schema))
            // Ruling AA 4: every local subscription is planned as a read of its type.
            .with_live_executor(Some(live_executor))
            // #611 (layer 2): notify already-connected subscriptions on hot-reload so
            // they re-derive against the new policies or are terminated fail-closed.
            .with_policy_reload(Some(state.subscribe_policy_reload()))
            // #571: complete + close live streams gracefully when shutdown begins.
            .with_drain_signal(Some(self.subscription_drain.subscribe()))
            // ADR-0018: let a service account authenticate the /ws upgrade with its secret.
            .with_service_account_authenticator(state.service_account_authenticator.clone())
            // #771: authorization for the life of the stream — periodic expiry +
            // revocation re-check, driven by the same revocation manager the HTTP
            // middleware consults.
            .with_revocation_manager(state.revocation_manager.clone())
            .with_auth_recheck_interval(std::time::Duration::from_secs(
                self.config.subscription_auth_recheck_secs,
            ))
            // M-tenant-ws-suspended: reject subscribes / pause delivery for a
            // suspended tenant, mirroring the GraphQL data plane's 503.
            .with_tenant_status_source(
                state
                    .tenant_registry()
                    .map(|r| Arc::clone(r) as Arc<dyn crate::routes::graphql::TenantStatusSource>),
            );

        // #596/#539: hand the subscription path the enriched-identity resolver so a
        // policy-declaring subscription derives its owner boundary server-side. Mirrors
        // the GraphQL handler's `AppState.identity_resolver`.
        #[cfg(feature = "auth")]
        {
            subscription_state =
                subscription_state.with_identity_resolver(state.identity_resolver.clone());
        }

        let subscription_require_auth = self
            .config
            .subscription_require_auth
            .unwrap_or(self.config.introspection_require_auth);

        if subscription_require_auth {
            if let Some(ref validator) = self.oidc_validator {
                info!(
                    subscription_path = %self.config.subscription_path,
                    "GraphQL subscriptions enabled (graphql-transport-ws + graphql-ws protocols, OIDC auth required)"
                );
                let auth_state = self.oidc_auth_state(validator.clone());
                let subscription_router = Router::new()
                    .route(&self.config.subscription_path, get(subscription_handler))
                    .route_layer(middleware::from_fn_with_state(auth_state, oidc_auth_middleware))
                    .with_state(subscription_state);
                app = app.merge(subscription_router);
            } else {
                warn!(
                    subscription_path = %self.config.subscription_path,
                    "subscription_require_auth is true but no OIDC configured — subscriptions disabled"
                );
            }
        } else {
            info!(
                subscription_path = %self.config.subscription_path,
                "GraphQL subscriptions enabled (graphql-transport-ws + graphql-ws protocols)"
            );
            let subscription_router = Router::new()
                .route(&self.config.subscription_path, get(subscription_handler))
                .with_state(subscription_state);
            app = app.merge(subscription_router);
        }
        app
    }

    fn mount_introspection(&self, mut app: Router, state: &AppState) -> Router {
        let metadata_require_auth = self
            .config
            .metadata_require_auth
            .unwrap_or(self.config.introspection_require_auth);
        let schema_export_require_auth = self
            .config
            .schema_export_require_auth
            .unwrap_or(self.config.introspection_require_auth);

        if self.config.introspection_require_auth {
            if let Some(ref validator) = self.oidc_validator {
                info!(
                    introspection_path = %self.config.introspection_path,
                    "Introspection endpoint enabled (OIDC auth required)"
                );
                let auth_state = self.oidc_auth_state(validator.clone());
                let introspection_router = Router::new()
                    .route(&self.config.introspection_path, get(introspection_handler))
                    .route_layer(middleware::from_fn_with_state(
                        auth_state,
                        required_auth_middleware,
                    ))
                    .with_state(state.clone());
                app = app.merge(introspection_router);
            } else {
                warn!(
                    "introspection_require_auth is true but no OIDC configured - introspection disabled"
                );
            }
        } else {
            info!(
                introspection_path = %self.config.introspection_path,
                "Introspection endpoint enabled (no auth required - USE ONLY IN DEVELOPMENT)"
            );
            let introspection_router = Router::new()
                .route(&self.config.introspection_path, get(introspection_handler))
                .with_state(state.clone());
            app = app.merge(introspection_router);
        }

        // Mount schema export endpoints with independent auth control.
        if schema_export_require_auth {
            if let Some(ref validator) = self.oidc_validator {
                info!("Schema export endpoints enabled (OIDC auth required)");
                let auth_state = self.oidc_auth_state(validator.clone());
                let schema_router = Router::new()
                    .route("/api/v1/schema.graphql", get(api::schema::export_sdl_handler))
                    .route("/api/v1/schema.json", get(api::schema::export_json_handler))
                    .route_layer(middleware::from_fn_with_state(
                        auth_state,
                        required_auth_middleware,
                    ))
                    .with_state(state.clone());
                app = app.merge(schema_router);
            } else {
                warn!(
                    "schema_export_require_auth is true but no OIDC configured - schema export disabled"
                );
            }
        } else {
            info!("Schema export endpoints enabled (no auth required)");
            let schema_router = Router::new()
                .route("/api/v1/schema.graphql", get(api::schema::export_sdl_handler))
                .route("/api/v1/schema.json", get(api::schema::export_json_handler))
                .with_state(state.clone());
            app = app.merge(schema_router);
        }

        // Mount metadata endpoint with independent auth control
        if metadata_require_auth {
            if let Some(ref validator) = self.oidc_validator {
                info!("Schema metadata endpoint enabled (OIDC auth required)");
                let auth_state = self.oidc_auth_state(validator.clone());
                let metadata_router = Router::new()
                    .route("/api/v1/schema/metadata", get(api::metadata::metadata_handler))
                    .route_layer(middleware::from_fn_with_state(
                        auth_state,
                        required_auth_middleware,
                    ))
                    .with_state(state.clone());
                app = app.merge(metadata_router);
            } else {
                warn!(
                    "metadata_require_auth is true but no OIDC configured - metadata endpoint disabled"
                );
            }
        } else {
            info!("Schema metadata endpoint enabled (no auth required)");
            let metadata_router = Router::new()
                .route("/api/v1/schema/metadata", get(api::metadata::metadata_handler))
                .with_state(state.clone());
            app = app.merge(metadata_router);
        }
        app
    }

    fn mount_metrics(&self, mut app: Router, state: &AppState) -> Router {
        if let Some(ref token) = self.config.metrics_token {
            info!(
                metrics_path = %self.config.metrics_path,
                metrics_json_path = %self.config.metrics_json_path,
                "Metrics endpoints enabled (bearer token required)"
            );

            let auth_state = BearerAuthState::with_max_failures(
                token.clone(),
                self.config.admin_auth_max_failures,
            );

            let metrics_router = Router::new()
                .route(&self.config.metrics_path, get(metrics_handler))
                .route(&self.config.metrics_json_path, get(metrics_json_handler))
                .route_layer(middleware::from_fn_with_state(auth_state, bearer_auth_middleware))
                .with_state(state.clone());

            app = app.merge(metrics_router);
        } else {
            warn!(
                "metrics_enabled is true but metrics_token is not set - metrics endpoints disabled"
            );
        }
        app
    }

    fn mount_admin_api(&self, mut app: Router, state: &AppState) -> Router {
        if let Some(ref write_token) = self.config.admin_token {
            // Destructive-operation router — always uses admin_token.
            let write_auth = BearerAuthState::with_max_failures(
                write_token.clone(),
                self.config.admin_auth_max_failures,
            );
            let admin_write_router = Router::new()
                .route("/api/v1/admin/reload-schema", post(api::admin::reload_schema_handler))
                .route("/api/v1/admin/cache/clear", post(api::admin::cache_clear_handler))
                .route(
                    "/api/v1/admin/query-stats/reset",
                    post(api::query_stats::query_stats_reset_handler),
                )
                // Tenant management write endpoints (multi-tenant mode)
                .route(
                    "/api/v1/admin/tenants/{key}",
                    put(api::tenant_admin::upsert_tenant_handler)
                        .delete(api::tenant_admin::delete_tenant_handler),
                )
                .route(
                    "/api/v1/admin/tenants/{key}/suspend",
                    post(api::tenant_admin::suspend_tenant_handler),
                )
                .route(
                    "/api/v1/admin/tenants/{key}/resume",
                    post(api::tenant_admin::resume_tenant_handler),
                )
                // Domain management write endpoints (multi-tenant mode)
                .route(
                    "/api/v1/admin/domains/{domain}",
                    put(api::tenant_admin::upsert_domain_handler)
                        .delete(api::tenant_admin::delete_domain_handler),
                )
                .route_layer(middleware::from_fn_with_state(write_auth, bearer_auth_middleware))
                .with_state(state.clone());
            app = app.merge(admin_write_router);

            // Read-only router
            let read_token = self.config.admin_readonly_token.as_ref().unwrap_or(write_token);

            if self.config.admin_readonly_token.is_none() {
                warn!(
                    admin_write_routes = "reload-schema, cache/clear",
                    admin_read_routes =
                        "cache/stats, config, explain, query/explain, grafana-dashboard",
                    "Admin API running in single-token mode: admin_token grants ALL operations \
                     including destructive ones. Set admin_readonly_token to scope access."
                );
            } else {
                info!(
                    "Admin API running in split-token mode: \
                     admin_token=write-only, admin_readonly_token=read-only"
                );
            }

            let read_auth = BearerAuthState::with_max_failures(
                read_token.clone(),
                self.config.admin_auth_max_failures,
            );
            let admin_read_router = Router::new()
                .route("/api/v1/admin/cache/stats", get(api::admin::cache_stats_handler))
                .route("/api/v1/admin/config", get(api::admin::config_handler))
                .route("/api/v1/admin/explain", post(api::admin::explain_handler))
                // Tenant management read endpoints (multi-tenant mode)
                .route("/api/v1/admin/tenants", get(api::tenant_admin::list_tenants_handler))
                .route("/api/v1/admin/tenants/{key}", get(api::tenant_admin::get_tenant_handler))
                .route(
                    "/api/v1/admin/tenants/{key}/health",
                    get(api::tenant_admin::tenant_health_handler),
                )
                .route(
                    "/api/v1/admin/tenants/{key}/events",
                    get(api::tenant_admin::tenant_events_handler),
                )
                // Domain management read endpoints (multi-tenant mode)
                .route("/api/v1/admin/domains", get(api::tenant_admin::list_domains_handler))
                .route("/api/v1/query/explain", post(api::query::explain_handler))
                .route(
                    "/api/v1/admin/grafana-dashboard",
                    get(api::admin::grafana_dashboard_handler),
                )
                .route("/api/v1/admin/usage", get(api::usage::usage_handler))
                .route("/api/v1/admin/query-stats", get(api::query_stats::query_stats_handler))
                .route(
                    "/api/v1/admin/query-stats/{queryid}",
                    get(api::query_stats::query_stats_detail_handler),
                )
                .route_layer(middleware::from_fn_with_state(read_auth, bearer_auth_middleware))
                .with_state(state.clone());
            app = app.merge(admin_read_router);

            app = self.mount_storage_policy_admin(app, write_token);
            app = self.mount_admin_sql_console(app, state, write_token);

            info!("Admin API endpoints enabled (bearer token required)");
        } else {
            warn!(
                "admin_api_enabled is true but admin_token is not set - admin endpoints disabled"
            );
        }
        app
    }

    /// Per-bucket storage policies over the Admin API (#974).
    ///
    /// Mounted on its own router because these handlers are stateful in
    /// `StorageState`, not `AppState` — but on the *same* token split as the
    /// rest of `/api/v1/admin`: reading which policy governs a bucket is a
    /// read-token operation, replacing or deleting it is a write-token one.
    /// That separation is the reason this lives here rather than beside the
    /// storage browser on Studio's single-token `/admin/v1/storage/*`.
    ///
    /// Absent entirely when the deployment configures no storage, rather than
    /// answering 404 from a route that exists.
    fn mount_storage_policy_admin(&self, mut app: Router, write_token: &str) -> Router {
        use api::storage_policies::{
            delete_bucket_policy_handler, get_bucket_policy_handler, put_bucket_policy_handler,
        };

        const POLICIES_PATH: &str = "/api/v1/admin/storage/{bucket}/policies";

        let Some(ref storage_state) = self.storage_state else {
            return app;
        };

        let write_auth = BearerAuthState::with_max_failures(
            write_token.to_string(),
            self.config.admin_auth_max_failures,
        );
        let write_router = Router::new()
            .route(
                POLICIES_PATH,
                put(put_bucket_policy_handler).delete(delete_bucket_policy_handler),
            )
            .route_layer(middleware::from_fn_with_state(write_auth, bearer_auth_middleware))
            .with_state(storage_state.clone());

        let read_token = self.config.admin_readonly_token.as_deref().unwrap_or(write_token);
        let read_auth = BearerAuthState::with_max_failures(
            read_token.to_string(),
            self.config.admin_auth_max_failures,
        );
        let read_router = Router::new()
            .route(POLICIES_PATH, get(get_bucket_policy_handler))
            .route_layer(middleware::from_fn_with_state(read_auth, bearer_auth_middleware))
            .with_state(storage_state.clone());

        app = app.merge(write_router).merge(read_router);
        info!(
            path = POLICIES_PATH,
            "Storage bucket policy admin endpoints enabled (GET under the read token, \
             PUT/DELETE under the write token)"
        );
        app
    }

    /// The operator SQL console — `POST /api/v1/admin/sql` (#962).
    ///
    /// Mounted only when the `admin-sql` feature is compiled in **and**
    /// `[admin_sql] enabled = true`. It is reached from inside the
    /// `admin_token`-guarded branch above, so a server without an admin token has
    /// already returned before this is called; `ServerConfig::validate` refuses
    /// the same three conditions at boot, so an operator who misconfigures it
    /// learns from the boot error rather than from a 404.
    ///
    /// Its own router because it is the one admin route that both tokens may
    /// reach and that behaves differently for each: `admin_dual_auth_middleware`
    /// authenticates against both and tells the handler which one matched. That
    /// is also why it cannot live on either of the two routers above — a path can
    /// be mounted once.
    #[cfg(feature = "admin-sql")]
    fn mount_admin_sql_console(
        &self,
        mut app: Router,
        state: &AppState,
        write_token: &str,
    ) -> Router {
        use crate::{
            middleware::{AdminDualAuthState, admin_dual_auth_middleware},
            routes::api::admin_sql::{AdminSqlState, admin_sql_handler},
        };

        const SQL_PATH: &str = "/api/v1/admin/sql";

        let Some(ref config) = self.config.admin_sql else {
            return app;
        };
        if !config.enabled {
            return app;
        }

        let auth = AdminDualAuthState::new(
            write_token.to_string(),
            self.config.admin_readonly_token.clone(),
            self.config.admin_auth_max_failures,
        );
        let console = Router::new()
            .route(SQL_PATH, post(admin_sql_handler))
            .route_layer(middleware::from_fn_with_state(auth, admin_dual_auth_middleware))
            .with_state(AdminSqlState {
                app:    state.clone(),
                config: config.clone(),
            });

        warn!(
            path = SQL_PATH,
            statement_timeout_ms = config.statement_timeout_ms,
            max_rows = config.max_rows,
            allow_commit = config.allow_commit,
            readonly_token_configured = self.config.admin_readonly_token.is_some(),
            "Admin SQL console ENABLED: this endpoint executes operator-supplied SQL. \
             Statements roll back unless `commit: true` is sent; admin_readonly_token runs \
             READ ONLY. Every execution is written to the audit ledger."
        );
        app = app.merge(console);
        app
    }

    /// No-op when the `admin-sql` feature is off.
    ///
    /// A configured-but-uncompiled console is refused at boot by
    /// `ServerConfig::validate`, so reaching here with `[admin_sql] enabled =
    /// true` is impossible — this arm exists so the mount site reads the same in
    /// both builds.
    #[cfg(not(feature = "admin-sql"))]
    #[allow(clippy::unused_self)] // Reason: mirrors the enabled arm's signature
    const fn mount_admin_sql_console(
        &self,
        app: Router,
        _state: &AppState,
        _write_token: &str,
    ) -> Router {
        app
    }

    fn mount_design_audit(&self, mut app: Router, state: &AppState) -> Router {
        if self.config.design_api_require_auth {
            if let Some(ref validator) = self.oidc_validator {
                info!("Design audit API endpoints enabled (admin scope 'fraiseql:admin' required)");
                let auth_state = self.oidc_auth_state(validator.clone());
                let design_router = Router::new()
                    .route("/design/federation-audit", post(api::design::federation_audit_handler))
                    .route("/design/cost-audit", post(api::design::cost_audit_handler))
                    .route("/design/cache-audit", post(api::design::cache_audit_handler))
                    .route("/design/auth-audit", post(api::design::auth_audit_handler))
                    .route(
                        "/design/compilation-audit",
                        post(api::design::compilation_audit_handler),
                    )
                    .route("/design/audit", post(api::design::overall_design_audit_handler))
                    .route_layer(middleware::from_fn_with_state(auth_state, admin_auth_middleware))
                    .with_state(state.clone());
                app = app.nest("/api/v1", design_router);
            } else {
                warn!(
                    "SECURITY: design_api_require_auth is true but no OIDC configured — \
                     design API endpoints are DISABLED. Configure an OIDC validator \
                     or set design_api_require_auth = false (development only)."
                );
            }
        } else {
            info!("Design audit API endpoints enabled (no auth required)");
            let design_router = Router::new()
                .route("/design/federation-audit", post(api::design::federation_audit_handler))
                .route("/design/cost-audit", post(api::design::cost_audit_handler))
                .route("/design/cache-audit", post(api::design::cache_audit_handler))
                .route("/design/auth-audit", post(api::design::auth_audit_handler))
                .route("/design/compilation-audit", post(api::design::compilation_audit_handler))
                .route("/design/audit", post(api::design::overall_design_audit_handler))
                .with_state(state.clone());
            app = app.nest("/api/v1", design_router);
        }
        app
    }
}