Skip to main content

koan_server/graphql/
server.rs

1use std::path::PathBuf;
2use std::sync::Arc;
3
4use crossbeam_channel::Sender;
5use koan_core::audio::viz::VizSnapshot;
6use koan_core::auth::{self, parse_duration_secs};
7use koan_core::config::Config;
8use koan_core::player::commands::PlayerCommand;
9use koan_core::player::state::SharedPlayerState;
10
11use super::{KoanSchema, build_schema};
12use crate::auth::AuthUser;
13use crate::auth::middleware::{AuthState, auth_middleware};
14use crate::auth::routes::{AuthRouteState, LoginRateLimiter, auth_router};
15
16// ---------------------------------------------------------------------------
17// `koan --headless` entry point (standalone headless server)
18// ---------------------------------------------------------------------------
19
20pub fn cmd_serve(
21    port: Option<u16>,
22    bind: Option<std::net::IpAddr>,
23    subsonic_port: Option<u16>,
24    playground: bool,
25) {
26    use koan_core::player::Player;
27
28    // Validate DB is accessible before starting the server.
29    let _db = koan_core::db::connection::Database::open_default().expect("failed to open database");
30    let db_path = koan_core::config::db_path();
31
32    let (state, _timeline, _viz, cmd_tx) = Player::spawn();
33
34    if let Err(e) = run_api_blocking(ApiServerOpts {
35        state,
36        cmd_tx,
37        db_path,
38        port,
39        bind,
40        subsonic_port,
41        playground,
42        viz: None, // headless — no viz analyzer
43    }) {
44        eprintln!("koan: {}", e);
45        std::process::exit(1);
46    }
47}
48
49// ---------------------------------------------------------------------------
50// Shared API server logic — used by both headless and TUI+API modes
51// ---------------------------------------------------------------------------
52
53/// Ceiling on a single GraphQL query. Anything genuinely longer than this —
54/// a library scan, a remote sync — runs as a job instead.
55const REQUEST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
56
57/// Queries executing at once. Resolvers now do their SQLite and HTTP work on
58/// the blocking pool, so this bounds concurrent work rather than protecting the
59/// runtime's workers from it.
60const MAX_INFLIGHT_QUERIES: usize = 64;
61
62/// Timeout, panic catch and load shed for the query route.
63///
64/// Not applied to `/graphql/ws`: a subscription is meant to outlive any request
65/// timeout.
66fn load_perimeter<S>(router: axum::Router<S>) -> axum::Router<S>
67where
68    S: Clone + Send + Sync + 'static,
69{
70    router
71        // Innermost so it is inside the timeout: a panicking resolver becomes a
72        // 500 rather than a silently dropped connection.
73        .layer(tower_http::catch_panic::CatchPanicLayer::new())
74        .layer(tower_http::timeout::TimeoutLayer::with_status_code(
75            axum::http::StatusCode::REQUEST_TIMEOUT,
76            REQUEST_TIMEOUT,
77        ))
78        // Shed rather than queue. A concurrency limit on its own parks callers
79        // on a semaphore, so an overloaded server answers every client slowly
80        // instead of telling the surplus to come back.
81        .layer(
82            tower::ServiceBuilder::new()
83                .layer(axum::error_handling::HandleErrorLayer::new(
84                    |err: tower::BoxError| async move {
85                        if err.is::<tower::load_shed::error::Overloaded>() {
86                            (
87                                axum::http::StatusCode::SERVICE_UNAVAILABLE,
88                                "server at capacity",
89                            )
90                        } else {
91                            (
92                                axum::http::StatusCode::INTERNAL_SERVER_ERROR,
93                                "internal error",
94                            )
95                        }
96                    },
97                ))
98                .load_shed()
99                .concurrency_limit(MAX_INFLIGHT_QUERIES),
100        )
101}
102
103/// Options for the API server — avoids too-many-arguments.
104pub struct ApiServerOpts {
105    pub state: Arc<SharedPlayerState>,
106    pub cmd_tx: Sender<PlayerCommand>,
107    pub db_path: PathBuf,
108    pub port: Option<u16>,
109    pub bind: Option<std::net::IpAddr>,
110    pub subsonic_port: Option<u16>,
111    pub playground: bool,
112    pub viz: Option<Arc<VizSnapshot>>,
113}
114
115/// Run the GraphQL (+ optional Subsonic) API server, blocking the current thread.
116/// Called from `cmd_serve` (headless) and `start_api_background` (TUI companion).
117///
118/// `Err` means the server refused to start on a misconfiguration the caller has
119/// to surface — never a silent downgrade to an unauthenticated server.
120fn run_api_blocking(opts: ApiServerOpts) -> Result<(), String> {
121    let ApiServerOpts {
122        state,
123        cmd_tx,
124        db_path,
125        port,
126        bind,
127        subsonic_port,
128        playground,
129        viz,
130    } = opts;
131    use axum::routing::{get, post};
132
133    let cfg = Config::load().unwrap_or_default();
134    let port = port.unwrap_or(cfg.graphql.port);
135    let bind = bind.unwrap_or(cfg.graphql.bind);
136    let playground_enabled = playground || cfg.graphql.playground;
137    let auth_enabled = cfg.graphql.auth_enabled;
138
139    // Load or generate Ed25519 keypair for JWT signing.
140    let (private_pem, public_pem) = if auth_enabled {
141        let kp = auth::load_keypair().map_err(|e| {
142            format!(
143                "auth_enabled = true but the keypair could not be loaded: {}. \
144                 Run `koan auth setup`.",
145                e
146            )
147        })?;
148        // An empty or truncated key file would otherwise leave every request an
149        // unauthenticated admin, which is the opposite of what was asked for.
150        if kp.0.is_empty() || kp.1.is_empty() {
151            return Err("auth_enabled = true but the keypair files are empty. \
152                 Run `koan auth regenerate-keys`."
153                .into());
154        }
155        kp
156    } else {
157        // When auth is disabled, we still need dummy keys for the route state
158        // (routes exist but won't be hit by middleware). Generate if available.
159        auth::load_or_generate_keypair().unwrap_or_default()
160    };
161
162    let access_ttl = parse_duration_secs(&cfg.graphql.access_token_ttl).unwrap_or(900);
163    let refresh_ttl = parse_duration_secs(&cfg.graphql.refresh_token_ttl).unwrap_or(2_592_000);
164
165    // Process-scoped introspection key for playground access. It is a bearer
166    // credential compared verbatim, so it has to be full-entropy random — a
167    // UUID would leak the server start time and cut the guessable space.
168    let introspection_key = if playground_enabled && auth_enabled {
169        Some(Arc::new(auth::random_token().map_err(|e| {
170            format!("failed to generate introspection key: {}", e)
171        })?))
172    } else {
173        None
174    };
175
176    let auth_state = AuthState {
177        public_pem: Arc::new(public_pem.clone()),
178        auth_enabled,
179        introspection_key: introspection_key.clone(),
180    };
181
182    let auth_route_state = AuthRouteState {
183        db_path: db_path.clone(),
184        private_pem: Arc::new(private_pem),
185        public_pem: Arc::new(public_pem),
186        access_ttl_secs: access_ttl,
187        refresh_ttl_secs: refresh_ttl,
188        cookie_secure: cfg.graphql.cookie_secure,
189        login_limiter: Arc::new(LoginRateLimiter::default()),
190    };
191
192    let schema = build_schema(state, cmd_tx, db_path.clone(), viz);
193
194    if auth_enabled {
195        log::info!(
196            "Auth enabled (Ed25519 JWT, access TTL {}s, refresh TTL {}s)",
197            access_ttl,
198            refresh_ttl
199        );
200    } else {
201        log::info!("Auth disabled — all requests treated as admin");
202    }
203
204    let browser_policy = Arc::new(BrowserPolicy {
205        origins: cfg.graphql.cors_origins.clone(),
206        hosts: cfg.graphql.allowed_hosts.clone(),
207    });
208
209    if cfg.graphql.cors_origins.is_empty() {
210        log::info!("CORS: no origins configured — browsers get no cross-origin access");
211    }
212
213    let rt = tokio::runtime::Runtime::new().expect("failed to create tokio runtime");
214    rt.block_on(async {
215        // GraphQL routes — protected by auth middleware.
216        //
217        // The query route carries the load perimeter; the WebSocket route does
218        // not, because a subscription is meant to outlive any request timeout.
219        let query_route = load_perimeter(axum::Router::new().route("/graphql", post(graphql_handler)));
220
221        let gql_app = axum::Router::new()
222            .merge(query_route)
223            .route("/graphql/ws", get(graphql_ws_handler))
224            .layer(axum::middleware::from_fn_with_state(
225                auth_state.clone(),
226                auth_middleware,
227            ))
228            // Runs before auth: a rejected request should never reach a
229            // credential check, let alone execute.
230            .layer(axum::middleware::from_fn_with_state(
231                browser_policy.clone(),
232                browser_guard,
233            ))
234            .with_state(schema);
235
236        // Auth routes — always accessible (no auth middleware).
237        let auth_app = auth_router(auth_route_state);
238
239        // CORS. An empty origin list emits no `Access-Control-Allow-Origin` at
240        // all: the previous wildcard handed every web page on the internet the
241        // ability to read this library.
242        let origins: Vec<axum::http::HeaderValue> = cfg
243            .graphql
244            .cors_origins
245            .iter()
246            .filter_map(|o| o.parse().ok())
247            .collect();
248        let cors = tower_http::cors::CorsLayer::new()
249            .allow_origin(origins)
250            .allow_methods([
251                axum::http::Method::GET,
252                axum::http::Method::POST,
253                axum::http::Method::OPTIONS,
254            ])
255            .allow_headers([
256                axum::http::header::AUTHORIZATION,
257                axum::http::header::CONTENT_TYPE,
258                axum::http::HeaderName::from_static("x-introspection-key"),
259            ])
260            .allow_credentials(true);
261
262        // Subsonic REST routes — always mounted on the GraphQL port when
263        // remote creds are configured. Previously only available on the
264        // dedicated `--subsonic <port>` listener, which broke `koan play
265        // --server <url>` because the remote TUI bridge builds its stream
266        // URL off the GraphQL base.
267        // Built once and cloned: each build re-read the config and, on macOS,
268        // prompted the keychain for the Subsonic secret.
269        let subsonic_merged = crate::subsonic::subsonic_router(db_path);
270        let subsonic_on_main = subsonic_merged.is_some();
271        let subsonic_dedicated = subsonic_merged.clone();
272
273        let mut app = auth_app.merge(gql_app);
274        if let Some(sub) = subsonic_merged {
275            app = app.merge(sub);
276        }
277        if playground_enabled {
278            app = app.route(
279                "/graphql",
280                get(graphql_playground).with_state(introspection_key.clone()),
281            );
282        }
283        // Outermost: a request whose `Host` we do not recognise is refused
284        // before anything else looks at it. Without this a DNS-rebinding page
285        // reaches the API as same-origin and CORS stops mattering.
286        let app = app.layer(cors).layer(axum::middleware::from_fn_with_state(
287            browser_policy.clone(),
288            host_guard,
289        ));
290
291        // Build playground URL with introspection key.
292        let playground_url = if playground_enabled {
293            if let Some(ref key) = introspection_key {
294                format!("http://{}:{}/graphql?introspection-key={}", bind, port, key)
295            } else {
296                format!("http://{}:{}/graphql", bind, port)
297            }
298        } else {
299            format!("http://{}:{}/graphql", bind, port)
300        };
301
302        let gql_addr = std::net::SocketAddr::new(bind, port);
303
304        let gql_listener = match tokio::net::TcpListener::bind(gql_addr).await {
305            Ok(l) => {
306                log::info!("GraphQL API on http://{}:{}/graphql", bind, port);
307                if subsonic_on_main {
308                    log::info!("Subsonic REST on http://{}:{}/rest/", bind, port);
309                }
310                if playground_enabled {
311                    log::info!("GraphiQL: {}", playground_url);
312                    // Open browser on macOS/Linux.
313                    #[cfg(target_os = "macos")]
314                    let _ = std::process::Command::new("open").arg(&playground_url).spawn();
315                    #[cfg(target_os = "linux")]
316                    let _ = std::process::Command::new("xdg-open").arg(&playground_url).spawn();
317                }
318                l
319            }
320            Err(e) => {
321                log::warn!(
322                    "API disabled: failed to bind GraphQL port {} — {} (another instance running?)",
323                    port,
324                    e,
325                );
326                return Ok(());
327            }
328        };
329        let gql_server = axum::serve(
330            gql_listener,
331            app.into_make_service_with_connect_info::<std::net::SocketAddr>(),
332        )
333        .with_graceful_shutdown(shutdown_signal());
334
335        // If `--subsonic <port>` is set AND differs from the GraphQL port,
336        // run an additional dedicated listener. This preserves the old
337        // behavior for users who want Subsonic on its own port.
338        let extra_sub_port = subsonic_port.filter(|p| *p != port);
339        if let Some(sub_port) = extra_sub_port
340            && let Some(sub_app) = subsonic_dedicated
341        {
342            let sub_addr = std::net::SocketAddr::new(bind, sub_port);
343            match tokio::net::TcpListener::bind(sub_addr).await {
344                Ok(sub_listener) => {
345                    log::info!(
346                        "Subsonic REST also on http://{}:{}/rest/ (dedicated port)",
347                        bind,
348                        sub_port,
349                    );
350                    let sub_server = axum::serve(sub_listener, sub_app)
351                        .with_graceful_shutdown(shutdown_signal());
352
353                    tokio::select! {
354                        r = gql_server => { if let Err(e) = r { log::error!("GraphQL server error: {e}"); } },
355                        r = sub_server => { if let Err(e) = r { log::error!("Subsonic server error: {e}"); } },
356                    }
357                    return Ok(());
358                }
359                Err(e) => {
360                    log::warn!(
361                        "Dedicated Subsonic port {} unavailable — {}. Mounted on GraphQL port only.",
362                        sub_port,
363                        e,
364                    );
365                }
366            }
367        }
368
369        if let Err(e) = gql_server.await {
370            log::error!("GraphQL server error: {e}");
371        }
372        Ok(())
373    })
374}
375
376/// Start the API server on the current thread (blocks forever).
377/// Called from a background thread when TUI mode has API enabled.
378///
379/// Accepts positional args for backward compatibility with koan-cli.
380/// Prefer `ApiServerOpts` for new call sites.
381pub fn start_api_background(
382    state: Arc<SharedPlayerState>,
383    cmd_tx: Sender<PlayerCommand>,
384    db_path: PathBuf,
385    port: Option<u16>,
386    bind: Option<std::net::IpAddr>,
387    subsonic_port: Option<u16>,
388    playground: bool,
389) {
390    // Runs on a spawned thread in TUI mode, where a panic would take the API
391    // down with nothing on screen to say so.
392    if let Err(e) = run_api_blocking(ApiServerOpts {
393        state,
394        cmd_tx,
395        db_path,
396        port,
397        bind,
398        subsonic_port,
399        playground,
400        viz: None,
401    }) {
402        log::error!("API server not started: {}", e);
403    }
404}
405
406// ---------------------------------------------------------------------------
407// Browser perimeter
408// ---------------------------------------------------------------------------
409
410/// What this server will answer to when the caller is a browser.
411///
412/// Two separate questions: which `Host` values name this server (DNS rebinding),
413/// and which `Origin` values may talk to it (CSRF, cross-site WebSockets).
414pub(crate) struct BrowserPolicy {
415    origins: Vec<String>,
416    hosts: Vec<String>,
417}
418
419impl BrowserPolicy {
420    fn host_allowed(&self, host: &str) -> bool {
421        if self.hosts.iter().any(|h| h.eq_ignore_ascii_case(host)) {
422            return true;
423        }
424        let bare = strip_port(host);
425        if self.hosts.iter().any(|h| h.eq_ignore_ascii_case(bare)) {
426            return true;
427        }
428        // A rebinding attack needs a name it controls; literals and localhost
429        // resolve to this machine by definition.
430        bare.eq_ignore_ascii_case("localhost") || bare.parse::<std::net::IpAddr>().is_ok()
431    }
432
433    /// An origin is allowed if it is configured, or if it is simply this server
434    /// talking to itself — which is what the bundled playground does.
435    fn origin_allowed(&self, origin: &str, host: Option<&str>) -> bool {
436        if self.origins.iter().any(|o| o == origin) {
437            return true;
438        }
439        match (origin.split_once("://"), host) {
440            (Some((_, authority)), Some(host)) => authority.eq_ignore_ascii_case(host),
441            _ => false,
442        }
443    }
444}
445
446/// `example.com:4000` -> `example.com`, `[::1]:4000` -> `::1`.
447fn strip_port(host: &str) -> &str {
448    if let Some(rest) = host.strip_prefix('[') {
449        return rest.split(']').next().unwrap_or(rest);
450    }
451    match host.rsplit_once(':') {
452        Some((h, port)) if !port.is_empty() && port.bytes().all(|b| b.is_ascii_digit()) => h,
453        _ => host,
454    }
455}
456
457fn header_str(request: &axum::extract::Request, name: axum::http::HeaderName) -> Option<&str> {
458    request.headers().get(name).and_then(|v| v.to_str().ok())
459}
460
461/// Reject requests carrying an unrecognised `Host`.
462async fn host_guard(
463    axum::extract::State(policy): axum::extract::State<Arc<BrowserPolicy>>,
464    request: axum::extract::Request,
465    next: axum::middleware::Next,
466) -> axum::response::Response {
467    use axum::response::IntoResponse;
468
469    // No `Host` at all means no browser: only HTTP/1.0 and raw tooling omit it,
470    // and neither can be steered by an attacker page.
471    let host = header_str(&request, axum::http::header::HOST)
472        .map(str::to_owned)
473        .or_else(|| request.uri().host().map(str::to_owned));
474
475    if let Some(ref host) = host
476        && !policy.host_allowed(host)
477    {
478        log::warn!("rejected request for unrecognised Host: {}", host);
479        return (axum::http::StatusCode::FORBIDDEN, "host not allowed").into_response();
480    }
481
482    next.run(request).await
483}
484
485/// Reject cross-site GraphQL traffic.
486///
487/// Two holes, one guard. A WebSocket handshake is exempt from CORS entirely, so
488/// a foreign page can open `/graphql/ws`, have the browser attach the session
489/// cookie, and read every response. And a POST whose content type is
490/// CORS-safelisted (`text/plain`) is sent without a preflight, yet
491/// async-graphql parses it as JSON regardless — so the mutation lands even
492/// though the reply is unreadable.
493async fn browser_guard(
494    axum::extract::State(policy): axum::extract::State<Arc<BrowserPolicy>>,
495    request: axum::extract::Request,
496    next: axum::middleware::Next,
497) -> axum::response::Response {
498    use axum::response::IntoResponse;
499
500    let host = header_str(&request, axum::http::header::HOST).map(str::to_owned);
501    // No `Origin` means a non-browser client, which CSRF cannot reach.
502    if let Some(origin) = header_str(&request, axum::http::header::ORIGIN)
503        && !policy.origin_allowed(origin, host.as_deref())
504    {
505        log::warn!(
506            "rejected GraphQL request from disallowed Origin: {}",
507            origin
508        );
509        return (axum::http::StatusCode::FORBIDDEN, "origin not allowed").into_response();
510    }
511
512    if request.method() == axum::http::Method::POST && !is_graphql_content_type(&request) {
513        return (
514            axum::http::StatusCode::UNSUPPORTED_MEDIA_TYPE,
515            "content type must be application/json or application/graphql",
516        )
517            .into_response();
518    }
519
520    next.run(request).await
521}
522
523fn is_graphql_content_type(request: &axum::extract::Request) -> bool {
524    header_str(request, axum::http::header::CONTENT_TYPE).is_some_and(|ct| {
525        let ct = ct.trim().to_ascii_lowercase();
526        ct.starts_with("application/json") || ct.starts_with("application/graphql")
527    })
528}
529
530async fn shutdown_signal() {
531    tokio::signal::ctrl_c()
532        .await
533        .expect("failed to listen for ctrl+c");
534}
535
536async fn graphql_handler(
537    axum::Extension(user): axum::Extension<AuthUser>,
538    axum::extract::State(schema): axum::extract::State<KoanSchema>,
539    req: async_graphql_axum::GraphQLRequest,
540) -> async_graphql_axum::GraphQLResponse {
541    let mut request = req.into_inner();
542    // The auth middleware always injects AuthUser (anonymous_admin when auth is
543    // disabled, or a real user when auth is enabled). No fallback needed here.
544    request = request.data(user);
545    schema.execute(request).await.into()
546}
547
548async fn graphql_ws_handler(
549    axum::Extension(user): axum::Extension<AuthUser>,
550    axum::extract::State(schema): axum::extract::State<KoanSchema>,
551    protocol: async_graphql_axum::GraphQLProtocol,
552    websocket: axum::extract::WebSocketUpgrade,
553) -> axum::response::Response {
554    websocket
555        .protocols(async_graphql::http::ALL_WEBSOCKET_PROTOCOLS)
556        .on_upgrade(move |stream| {
557            let stream = async_graphql_axum::GraphQLWebSocket::new(stream, schema, protocol)
558                .on_connection_init(move |_| async move {
559                    let mut data = async_graphql::Data::default();
560                    data.insert(user);
561                    Ok(data)
562                });
563            async move {
564                stream.serve().await;
565            }
566        })
567}
568
569async fn graphql_playground(
570    axum::extract::Query(params): axum::extract::Query<std::collections::HashMap<String, String>>,
571    axum::extract::State(key): axum::extract::State<Option<Arc<String>>>,
572) -> axum::response::Response {
573    use axum::response::IntoResponse;
574
575    // If an introspection key exists, require it in the URL.
576    if let Some(ref expected) = key {
577        let provided = params.get("introspection-key");
578        if provided.map(|k| k.as_str()) != Some(expected.as_str()) {
579            return (
580                axum::http::StatusCode::FORBIDDEN,
581                "invalid or missing introspection-key",
582            )
583                .into_response();
584        }
585    }
586
587    // Use async-graphql's built-in GraphiQL (self-contained, no CDN).
588    // Inject the introspection key as a default header so all queries are authed.
589    let mut source = async_graphql::http::GraphiQLSource::build().endpoint("/graphql");
590    if let Some(ref k) = key {
591        source = source.header("X-Introspection-Key", k.as_str());
592    }
593
594    axum::response::Html(source.finish()).into_response()
595}
596
597/// Run the server as a background daemon (fork + detach).
598pub fn cmd_serve_daemon(
599    port: Option<u16>,
600    bind: Option<std::net::IpAddr>,
601    subsonic_port: Option<u16>,
602    playground: bool,
603) {
604    use std::fs;
605    use std::process::Command;
606
607    let cfg = Config::load().unwrap_or_default();
608    let port_val = port.unwrap_or(cfg.graphql.port);
609    let bind_val = bind.unwrap_or(cfg.graphql.bind);
610
611    let exe = std::env::current_exe().expect("failed to get current exe path");
612    let mut cmd = Command::new(exe);
613    // Use the new unified CLI: `koan --headless --port <port>`
614    cmd.arg("--headless");
615    cmd.arg("--port").arg(port_val.to_string());
616    cmd.arg("--bind").arg(bind_val.to_string());
617    if let Some(sp) = subsonic_port {
618        cmd.arg("--subsonic").arg(sp.to_string());
619    }
620    if playground || cfg.graphql.playground {
621        cmd.arg("--playground");
622    }
623
624    cmd.stdin(std::process::Stdio::null());
625    cmd.stdout(std::process::Stdio::null());
626    cmd.stderr(std::process::Stdio::null());
627
628    let mut child = cmd.spawn().expect("failed to spawn daemon process");
629    let pid = child.id();
630
631    let pid_path = koan_core::config::config_dir().join("koan-serve.pid");
632    fs::write(&pid_path, pid.to_string()).ok();
633
634    std::thread::spawn(move || {
635        let _ = child.wait();
636    });
637
638    eprintln!("koan daemon started (pid {}) on port {}", pid, port_val);
639    if let Some(sp) = subsonic_port {
640        eprintln!("  Subsonic REST on port {}", sp);
641    }
642    eprintln!("  PID file: {}", pid_path.display());
643}
644
645// ---------------------------------------------------------------------------
646// In-process execution (for MCP `graphql` tool)
647// ---------------------------------------------------------------------------
648
649/// Execute a GraphQL query in-process (no HTTP round-trip).
650///
651/// There is no credential to check, so the caller states the role it wants the
652/// query executed at — see `mcp::mcp_role`.
653pub async fn execute_in_process(
654    schema: &KoanSchema,
655    query: &str,
656    variables: Option<serde_json::Value>,
657    role: koan_core::auth::Role,
658) -> serde_json::Value {
659    let mut request = async_graphql::Request::new(query);
660    request = request.data(AuthUser {
661        role,
662        ..AuthUser::anonymous_admin()
663    });
664    if let Some(serde_json::Value::Object(map)) = variables {
665        let mut gql_vars = async_graphql::Variables::default();
666        for (k, v) in map {
667            gql_vars.insert(
668                async_graphql::Name::new(&k),
669                async_graphql::Value::from_json(v).unwrap_or(async_graphql::Value::Null),
670            );
671        }
672        request = request.variables(gql_vars);
673    }
674    let response = schema.execute(request).await;
675    serde_json::to_value(&response).unwrap_or(serde_json::Value::Null)
676}
677
678// ---------------------------------------------------------------------------
679// Tests
680// ---------------------------------------------------------------------------
681
682#[cfg(test)]
683mod tests {
684    use super::*;
685    use axum::body::Body;
686    use axum::http::{Request as HttpRequest, StatusCode};
687    use axum::routing::{get, post};
688    use tower::ServiceExt as _;
689
690    fn policy() -> Arc<BrowserPolicy> {
691        Arc::new(BrowserPolicy {
692            origins: vec!["https://music.example.com".into()],
693            hosts: vec!["koan.local".into()],
694        })
695    }
696
697    async fn ok() -> &'static str {
698        "ok"
699    }
700
701    fn routes() -> axum::Router<Arc<BrowserPolicy>> {
702        axum::Router::new()
703            .route("/graphql", post(ok).get(ok))
704            .route("/graphql/ws", get(ok))
705    }
706
707    async fn run_host(req: HttpRequest<Body>) -> StatusCode {
708        let app = routes()
709            .layer(axum::middleware::from_fn_with_state(policy(), host_guard))
710            .with_state(policy());
711        app.oneshot(req).await.unwrap().status()
712    }
713
714    async fn run_browser(req: HttpRequest<Body>) -> StatusCode {
715        let app = routes()
716            .layer(axum::middleware::from_fn_with_state(
717                policy(),
718                browser_guard,
719            ))
720            .with_state(policy());
721        app.oneshot(req).await.unwrap().status()
722    }
723
724    fn json_post(uri: &str) -> axum::http::request::Builder {
725        HttpRequest::post(uri).header(axum::http::header::CONTENT_TYPE, "application/json")
726    }
727
728    // -- Host allowlist (DNS rebinding) --
729
730    #[test]
731    fn host_policy_accepts_loopback_literals_and_configured_names() {
732        let p = policy();
733        assert!(p.host_allowed("localhost:4000"));
734        assert!(p.host_allowed("127.0.0.1:4000"));
735        assert!(p.host_allowed("192.168.1.20:4000"));
736        assert!(p.host_allowed("[::1]:4000"));
737        assert!(p.host_allowed("koan.local"));
738        assert!(p.host_allowed("koan.local:4000"));
739    }
740
741    #[test]
742    fn host_policy_rejects_attacker_controlled_names() {
743        let p = policy();
744        assert!(!p.host_allowed("evil.com"));
745        assert!(!p.host_allowed("rebind.evil.com:4000"));
746        assert!(!p.host_allowed("koan.local.evil.com"));
747    }
748
749    #[tokio::test]
750    async fn host_guard_rejects_foreign_host() {
751        let req = json_post("/graphql")
752            .header(axum::http::header::HOST, "rebind.evil.com")
753            .body(Body::empty())
754            .unwrap();
755        assert_eq!(run_host(req).await, StatusCode::FORBIDDEN);
756    }
757
758    #[tokio::test]
759    async fn host_guard_allows_known_host_and_missing_host() {
760        let req = json_post("/graphql")
761            .header(axum::http::header::HOST, "127.0.0.1:4000")
762            .body(Body::empty())
763            .unwrap();
764        assert_eq!(run_host(req).await, StatusCode::OK);
765
766        let req = json_post("/graphql").body(Body::empty()).unwrap();
767        assert_eq!(run_host(req).await, StatusCode::OK);
768    }
769
770    // -- Cross-site WebSocket --
771
772    #[tokio::test]
773    async fn ws_upgrade_from_foreign_origin_is_rejected() {
774        let req = HttpRequest::get("/graphql/ws")
775            .header(axum::http::header::HOST, "127.0.0.1:4000")
776            .header(axum::http::header::ORIGIN, "https://evil.com")
777            .body(Body::empty())
778            .unwrap();
779        assert_eq!(run_browser(req).await, StatusCode::FORBIDDEN);
780    }
781
782    #[tokio::test]
783    async fn ws_upgrade_without_origin_is_allowed() {
784        let req = HttpRequest::get("/graphql/ws")
785            .header(axum::http::header::HOST, "127.0.0.1:4000")
786            .body(Body::empty())
787            .unwrap();
788        assert_eq!(run_browser(req).await, StatusCode::OK);
789    }
790
791    #[tokio::test]
792    async fn configured_and_same_origin_are_allowed() {
793        let req = HttpRequest::get("/graphql/ws")
794            .header(axum::http::header::HOST, "127.0.0.1:4000")
795            .header(axum::http::header::ORIGIN, "https://music.example.com")
796            .body(Body::empty())
797            .unwrap();
798        assert_eq!(run_browser(req).await, StatusCode::OK);
799
800        // The bundled playground posts to the host it was served from.
801        let req = json_post("/graphql")
802            .header(axum::http::header::HOST, "127.0.0.1:4000")
803            .header(axum::http::header::ORIGIN, "http://127.0.0.1:4000")
804            .body(Body::empty())
805            .unwrap();
806        assert_eq!(run_browser(req).await, StatusCode::OK);
807    }
808
809    // -- CSRF via a CORS-safelisted content type --
810
811    #[tokio::test]
812    async fn text_plain_post_is_rejected() {
813        let req = HttpRequest::post("/graphql")
814            .header(axum::http::header::CONTENT_TYPE, "text/plain")
815            .body(Body::from(r#"{"query":"mutation{clearQueue{ok}}"}"#))
816            .unwrap();
817        assert_eq!(run_browser(req).await, StatusCode::UNSUPPORTED_MEDIA_TYPE);
818    }
819
820    #[tokio::test]
821    async fn post_without_content_type_is_rejected() {
822        let req = HttpRequest::post("/graphql").body(Body::empty()).unwrap();
823        assert_eq!(run_browser(req).await, StatusCode::UNSUPPORTED_MEDIA_TYPE);
824    }
825
826    // -- Load perimeter --
827
828    #[tokio::test]
829    async fn load_perimeter_passes_requests_and_turns_panics_into_500s() {
830        async fn boom() -> &'static str {
831            panic!("resolver exploded");
832        }
833
834        let app = load_perimeter(
835            axum::Router::new()
836                .route("/graphql", post(ok))
837                .route("/boom", post(boom)),
838        );
839
840        let req = json_post("/graphql").body(Body::empty()).unwrap();
841        assert_eq!(
842            app.clone().oneshot(req).await.unwrap().status(),
843            StatusCode::OK
844        );
845
846        // Without CatchPanicLayer this drops the connection with nothing logged.
847        let req = json_post("/boom").body(Body::empty()).unwrap();
848        assert_eq!(
849            app.oneshot(req).await.unwrap().status(),
850            StatusCode::INTERNAL_SERVER_ERROR
851        );
852    }
853
854    #[tokio::test]
855    async fn json_post_is_accepted() {
856        let req = json_post("/graphql").body(Body::empty()).unwrap();
857        assert_eq!(run_browser(req).await, StatusCode::OK);
858
859        let req = HttpRequest::post("/graphql")
860            .header(
861                axum::http::header::CONTENT_TYPE,
862                "application/json; charset=utf-8",
863            )
864            .body(Body::empty())
865            .unwrap();
866        assert_eq!(run_browser(req).await, StatusCode::OK);
867    }
868}