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 from disk.
268        let subsonic_merged = crate::subsonic::subsonic_router(db_path);
269        let subsonic_on_main = subsonic_merged.is_some();
270        let subsonic_dedicated = subsonic_merged.clone();
271
272        let mut app = auth_app.merge(gql_app);
273        if let Some(sub) = subsonic_merged {
274            app = app.merge(sub);
275        }
276        if playground_enabled {
277            app = app.route(
278                "/graphql",
279                get(graphql_playground).with_state(introspection_key.clone()),
280            );
281        }
282        // Outermost: a request whose `Host` we do not recognise is refused
283        // before anything else looks at it. Without this a DNS-rebinding page
284        // reaches the API as same-origin and CORS stops mattering.
285        let app = app.layer(cors).layer(axum::middleware::from_fn_with_state(
286            browser_policy.clone(),
287            host_guard,
288        ));
289
290        // Build playground URL with introspection key.
291        let playground_url = if playground_enabled {
292            if let Some(ref key) = introspection_key {
293                format!("http://{}:{}/graphql?introspection-key={}", bind, port, key)
294            } else {
295                format!("http://{}:{}/graphql", bind, port)
296            }
297        } else {
298            format!("http://{}:{}/graphql", bind, port)
299        };
300
301        let gql_addr = std::net::SocketAddr::new(bind, port);
302
303        let gql_listener = match tokio::net::TcpListener::bind(gql_addr).await {
304            Ok(l) => {
305                log::info!("GraphQL API on http://{}:{}/graphql", bind, port);
306                if subsonic_on_main {
307                    log::info!("Subsonic REST on http://{}:{}/rest/", bind, port);
308                }
309                if playground_enabled {
310                    log::info!("GraphiQL: {}", playground_url);
311                    // Open browser on macOS/Linux.
312                    #[cfg(target_os = "macos")]
313                    let _ = std::process::Command::new("open").arg(&playground_url).spawn();
314                    #[cfg(target_os = "linux")]
315                    let _ = std::process::Command::new("xdg-open").arg(&playground_url).spawn();
316                }
317                l
318            }
319            Err(e) => {
320                log::warn!(
321                    "API disabled: failed to bind GraphQL port {} — {} (another instance running?)",
322                    port,
323                    e,
324                );
325                return Ok(());
326            }
327        };
328        let gql_server = axum::serve(
329            gql_listener,
330            app.into_make_service_with_connect_info::<std::net::SocketAddr>(),
331        )
332        .with_graceful_shutdown(shutdown_signal());
333
334        // If `--subsonic <port>` is set AND differs from the GraphQL port,
335        // run an additional dedicated listener. This preserves the old
336        // behavior for users who want Subsonic on its own port.
337        let extra_sub_port = subsonic_port.filter(|p| *p != port);
338        if let Some(sub_port) = extra_sub_port
339            && let Some(sub_app) = subsonic_dedicated
340        {
341            let sub_addr = std::net::SocketAddr::new(bind, sub_port);
342            match tokio::net::TcpListener::bind(sub_addr).await {
343                Ok(sub_listener) => {
344                    log::info!(
345                        "Subsonic REST also on http://{}:{}/rest/ (dedicated port)",
346                        bind,
347                        sub_port,
348                    );
349                    let sub_server = axum::serve(sub_listener, sub_app)
350                        .with_graceful_shutdown(shutdown_signal());
351
352                    tokio::select! {
353                        r = gql_server => { if let Err(e) = r { log::error!("GraphQL server error: {e}"); } },
354                        r = sub_server => { if let Err(e) = r { log::error!("Subsonic server error: {e}"); } },
355                    }
356                    return Ok(());
357                }
358                Err(e) => {
359                    log::warn!(
360                        "Dedicated Subsonic port {} unavailable — {}. Mounted on GraphQL port only.",
361                        sub_port,
362                        e,
363                    );
364                }
365            }
366        }
367
368        if let Err(e) = gql_server.await {
369            log::error!("GraphQL server error: {e}");
370        }
371        Ok(())
372    })
373}
374
375/// Start the API server on the current thread (blocks forever).
376/// Called from a background thread when TUI mode has API enabled.
377///
378/// Accepts positional args for backward compatibility with koan-cli.
379/// Prefer `ApiServerOpts` for new call sites.
380pub fn start_api_background(
381    state: Arc<SharedPlayerState>,
382    cmd_tx: Sender<PlayerCommand>,
383    db_path: PathBuf,
384    port: Option<u16>,
385    bind: Option<std::net::IpAddr>,
386    subsonic_port: Option<u16>,
387    playground: bool,
388) {
389    // Runs on a spawned thread in TUI mode, where a panic would take the API
390    // down with nothing on screen to say so.
391    if let Err(e) = run_api_blocking(ApiServerOpts {
392        state,
393        cmd_tx,
394        db_path,
395        port,
396        bind,
397        subsonic_port,
398        playground,
399        viz: None,
400    }) {
401        log::error!("API server not started: {}", e);
402    }
403}
404
405// ---------------------------------------------------------------------------
406// Browser perimeter
407// ---------------------------------------------------------------------------
408
409/// What this server will answer to when the caller is a browser.
410///
411/// Two separate questions: which `Host` values name this server (DNS rebinding),
412/// and which `Origin` values may talk to it (CSRF, cross-site WebSockets).
413pub(crate) struct BrowserPolicy {
414    origins: Vec<String>,
415    hosts: Vec<String>,
416}
417
418impl BrowserPolicy {
419    fn host_allowed(&self, host: &str) -> bool {
420        if self.hosts.iter().any(|h| h.eq_ignore_ascii_case(host)) {
421            return true;
422        }
423        let bare = strip_port(host);
424        if self.hosts.iter().any(|h| h.eq_ignore_ascii_case(bare)) {
425            return true;
426        }
427        // A rebinding attack needs a name it controls; literals and localhost
428        // resolve to this machine by definition.
429        bare.eq_ignore_ascii_case("localhost") || bare.parse::<std::net::IpAddr>().is_ok()
430    }
431
432    /// An origin is allowed if it is configured, or if it is simply this server
433    /// talking to itself — which is what the bundled playground does.
434    fn origin_allowed(&self, origin: &str, host: Option<&str>) -> bool {
435        if self.origins.iter().any(|o| o == origin) {
436            return true;
437        }
438        match (origin.split_once("://"), host) {
439            (Some((_, authority)), Some(host)) => authority.eq_ignore_ascii_case(host),
440            _ => false,
441        }
442    }
443}
444
445/// `example.com:4000` -> `example.com`, `[::1]:4000` -> `::1`.
446fn strip_port(host: &str) -> &str {
447    if let Some(rest) = host.strip_prefix('[') {
448        return rest.split(']').next().unwrap_or(rest);
449    }
450    match host.rsplit_once(':') {
451        Some((h, port)) if !port.is_empty() && port.bytes().all(|b| b.is_ascii_digit()) => h,
452        _ => host,
453    }
454}
455
456fn header_str(request: &axum::extract::Request, name: axum::http::HeaderName) -> Option<&str> {
457    request.headers().get(name).and_then(|v| v.to_str().ok())
458}
459
460/// Reject requests carrying an unrecognised `Host`.
461async fn host_guard(
462    axum::extract::State(policy): axum::extract::State<Arc<BrowserPolicy>>,
463    request: axum::extract::Request,
464    next: axum::middleware::Next,
465) -> axum::response::Response {
466    use axum::response::IntoResponse;
467
468    // No `Host` at all means no browser: only HTTP/1.0 and raw tooling omit it,
469    // and neither can be steered by an attacker page.
470    let host = header_str(&request, axum::http::header::HOST)
471        .map(str::to_owned)
472        .or_else(|| request.uri().host().map(str::to_owned));
473
474    if let Some(ref host) = host
475        && !policy.host_allowed(host)
476    {
477        log::warn!("rejected request for unrecognised Host: {}", host);
478        return (axum::http::StatusCode::FORBIDDEN, "host not allowed").into_response();
479    }
480
481    next.run(request).await
482}
483
484/// Reject cross-site GraphQL traffic.
485///
486/// Two holes, one guard. A WebSocket handshake is exempt from CORS entirely, so
487/// a foreign page can open `/graphql/ws`, have the browser attach the session
488/// cookie, and read every response. And a POST whose content type is
489/// CORS-safelisted (`text/plain`) is sent without a preflight, yet
490/// async-graphql parses it as JSON regardless — so the mutation lands even
491/// though the reply is unreadable.
492async fn browser_guard(
493    axum::extract::State(policy): axum::extract::State<Arc<BrowserPolicy>>,
494    request: axum::extract::Request,
495    next: axum::middleware::Next,
496) -> axum::response::Response {
497    use axum::response::IntoResponse;
498
499    let host = header_str(&request, axum::http::header::HOST).map(str::to_owned);
500    // No `Origin` means a non-browser client, which CSRF cannot reach.
501    if let Some(origin) = header_str(&request, axum::http::header::ORIGIN)
502        && !policy.origin_allowed(origin, host.as_deref())
503    {
504        log::warn!(
505            "rejected GraphQL request from disallowed Origin: {}",
506            origin
507        );
508        return (axum::http::StatusCode::FORBIDDEN, "origin not allowed").into_response();
509    }
510
511    if request.method() == axum::http::Method::POST && !is_graphql_content_type(&request) {
512        return (
513            axum::http::StatusCode::UNSUPPORTED_MEDIA_TYPE,
514            "content type must be application/json or application/graphql",
515        )
516            .into_response();
517    }
518
519    next.run(request).await
520}
521
522fn is_graphql_content_type(request: &axum::extract::Request) -> bool {
523    header_str(request, axum::http::header::CONTENT_TYPE).is_some_and(|ct| {
524        let ct = ct.trim().to_ascii_lowercase();
525        ct.starts_with("application/json") || ct.starts_with("application/graphql")
526    })
527}
528
529async fn shutdown_signal() {
530    tokio::signal::ctrl_c()
531        .await
532        .expect("failed to listen for ctrl+c");
533}
534
535async fn graphql_handler(
536    axum::Extension(user): axum::Extension<AuthUser>,
537    axum::extract::State(schema): axum::extract::State<KoanSchema>,
538    req: async_graphql_axum::GraphQLRequest,
539) -> async_graphql_axum::GraphQLResponse {
540    let mut request = req.into_inner();
541    // The auth middleware always injects AuthUser (anonymous_admin when auth is
542    // disabled, or a real user when auth is enabled). No fallback needed here.
543    request = request.data(user);
544    schema.execute(request).await.into()
545}
546
547async fn graphql_ws_handler(
548    axum::Extension(user): axum::Extension<AuthUser>,
549    axum::extract::State(schema): axum::extract::State<KoanSchema>,
550    protocol: async_graphql_axum::GraphQLProtocol,
551    websocket: axum::extract::WebSocketUpgrade,
552) -> axum::response::Response {
553    websocket
554        .protocols(async_graphql::http::ALL_WEBSOCKET_PROTOCOLS)
555        .on_upgrade(move |stream| {
556            let stream = async_graphql_axum::GraphQLWebSocket::new(stream, schema, protocol)
557                .on_connection_init(move |_| async move {
558                    let mut data = async_graphql::Data::default();
559                    data.insert(user);
560                    Ok(data)
561                });
562            async move {
563                stream.serve().await;
564            }
565        })
566}
567
568async fn graphql_playground(
569    axum::extract::Query(params): axum::extract::Query<std::collections::HashMap<String, String>>,
570    axum::extract::State(key): axum::extract::State<Option<Arc<String>>>,
571) -> axum::response::Response {
572    use axum::response::IntoResponse;
573
574    // If an introspection key exists, require it in the URL.
575    if let Some(ref expected) = key {
576        let provided = params.get("introspection-key");
577        if provided.map(|k| k.as_str()) != Some(expected.as_str()) {
578            return (
579                axum::http::StatusCode::FORBIDDEN,
580                "invalid or missing introspection-key",
581            )
582                .into_response();
583        }
584    }
585
586    // Use async-graphql's built-in GraphiQL (self-contained, no CDN).
587    // Inject the introspection key as a default header so all queries are authed.
588    let mut source = async_graphql::http::GraphiQLSource::build().endpoint("/graphql");
589    if let Some(ref k) = key {
590        source = source.header("X-Introspection-Key", k.as_str());
591    }
592
593    axum::response::Html(source.finish()).into_response()
594}
595
596/// Run the server as a background daemon (fork + detach).
597pub fn cmd_serve_daemon(
598    port: Option<u16>,
599    bind: Option<std::net::IpAddr>,
600    subsonic_port: Option<u16>,
601    playground: bool,
602) {
603    use std::fs;
604    use std::process::Command;
605
606    let cfg = Config::load().unwrap_or_default();
607    let port_val = port.unwrap_or(cfg.graphql.port);
608    let bind_val = bind.unwrap_or(cfg.graphql.bind);
609
610    let exe = std::env::current_exe().expect("failed to get current exe path");
611    let mut cmd = Command::new(exe);
612    // Use the new unified CLI: `koan --headless --port <port>`
613    cmd.arg("--headless");
614    cmd.arg("--port").arg(port_val.to_string());
615    cmd.arg("--bind").arg(bind_val.to_string());
616    if let Some(sp) = subsonic_port {
617        cmd.arg("--subsonic").arg(sp.to_string());
618    }
619    if playground || cfg.graphql.playground {
620        cmd.arg("--playground");
621    }
622
623    cmd.stdin(std::process::Stdio::null());
624    cmd.stdout(std::process::Stdio::null());
625    cmd.stderr(std::process::Stdio::null());
626
627    let mut child = cmd.spawn().expect("failed to spawn daemon process");
628    let pid = child.id();
629
630    let pid_path = koan_core::config::config_dir().join("koan-serve.pid");
631    fs::write(&pid_path, pid.to_string()).ok();
632
633    std::thread::spawn(move || {
634        let _ = child.wait();
635    });
636
637    eprintln!("koan daemon started (pid {}) on port {}", pid, port_val);
638    if let Some(sp) = subsonic_port {
639        eprintln!("  Subsonic REST on port {}", sp);
640    }
641    eprintln!("  PID file: {}", pid_path.display());
642}
643
644// ---------------------------------------------------------------------------
645// In-process execution (for MCP `graphql` tool)
646// ---------------------------------------------------------------------------
647
648/// Execute a GraphQL query in-process (no HTTP round-trip).
649///
650/// There is no credential to check, so the caller states the role it wants the
651/// query executed at — see `mcp::mcp_role`.
652pub async fn execute_in_process(
653    schema: &KoanSchema,
654    query: &str,
655    variables: Option<serde_json::Value>,
656    role: koan_core::auth::Role,
657) -> serde_json::Value {
658    let mut request = async_graphql::Request::new(query);
659    request = request.data(AuthUser {
660        role,
661        ..AuthUser::anonymous_admin()
662    });
663    if let Some(serde_json::Value::Object(map)) = variables {
664        let mut gql_vars = async_graphql::Variables::default();
665        for (k, v) in map {
666            gql_vars.insert(
667                async_graphql::Name::new(&k),
668                async_graphql::Value::from_json(v).unwrap_or(async_graphql::Value::Null),
669            );
670        }
671        request = request.variables(gql_vars);
672    }
673    let response = schema.execute(request).await;
674    serde_json::to_value(&response).unwrap_or(serde_json::Value::Null)
675}
676
677// ---------------------------------------------------------------------------
678// Tests
679// ---------------------------------------------------------------------------
680
681#[cfg(test)]
682mod tests {
683    use super::*;
684    use axum::body::Body;
685    use axum::http::{Request as HttpRequest, StatusCode};
686    use axum::routing::{get, post};
687    use tower::ServiceExt as _;
688
689    fn policy() -> Arc<BrowserPolicy> {
690        Arc::new(BrowserPolicy {
691            origins: vec!["https://music.example.com".into()],
692            hosts: vec!["koan.local".into()],
693        })
694    }
695
696    async fn ok() -> &'static str {
697        "ok"
698    }
699
700    fn routes() -> axum::Router<Arc<BrowserPolicy>> {
701        axum::Router::new()
702            .route("/graphql", post(ok).get(ok))
703            .route("/graphql/ws", get(ok))
704    }
705
706    async fn run_host(req: HttpRequest<Body>) -> StatusCode {
707        let app = routes()
708            .layer(axum::middleware::from_fn_with_state(policy(), host_guard))
709            .with_state(policy());
710        app.oneshot(req).await.unwrap().status()
711    }
712
713    async fn run_browser(req: HttpRequest<Body>) -> StatusCode {
714        let app = routes()
715            .layer(axum::middleware::from_fn_with_state(
716                policy(),
717                browser_guard,
718            ))
719            .with_state(policy());
720        app.oneshot(req).await.unwrap().status()
721    }
722
723    fn json_post(uri: &str) -> axum::http::request::Builder {
724        HttpRequest::post(uri).header(axum::http::header::CONTENT_TYPE, "application/json")
725    }
726
727    // -- Host allowlist (DNS rebinding) --
728
729    #[test]
730    fn host_policy_accepts_loopback_literals_and_configured_names() {
731        let p = policy();
732        assert!(p.host_allowed("localhost:4000"));
733        assert!(p.host_allowed("127.0.0.1:4000"));
734        assert!(p.host_allowed("192.168.1.20:4000"));
735        assert!(p.host_allowed("[::1]:4000"));
736        assert!(p.host_allowed("koan.local"));
737        assert!(p.host_allowed("koan.local:4000"));
738    }
739
740    #[test]
741    fn host_policy_rejects_attacker_controlled_names() {
742        let p = policy();
743        assert!(!p.host_allowed("evil.com"));
744        assert!(!p.host_allowed("rebind.evil.com:4000"));
745        assert!(!p.host_allowed("koan.local.evil.com"));
746    }
747
748    #[tokio::test]
749    async fn host_guard_rejects_foreign_host() {
750        let req = json_post("/graphql")
751            .header(axum::http::header::HOST, "rebind.evil.com")
752            .body(Body::empty())
753            .unwrap();
754        assert_eq!(run_host(req).await, StatusCode::FORBIDDEN);
755    }
756
757    #[tokio::test]
758    async fn host_guard_allows_known_host_and_missing_host() {
759        let req = json_post("/graphql")
760            .header(axum::http::header::HOST, "127.0.0.1:4000")
761            .body(Body::empty())
762            .unwrap();
763        assert_eq!(run_host(req).await, StatusCode::OK);
764
765        let req = json_post("/graphql").body(Body::empty()).unwrap();
766        assert_eq!(run_host(req).await, StatusCode::OK);
767    }
768
769    // -- Cross-site WebSocket --
770
771    #[tokio::test]
772    async fn ws_upgrade_from_foreign_origin_is_rejected() {
773        let req = HttpRequest::get("/graphql/ws")
774            .header(axum::http::header::HOST, "127.0.0.1:4000")
775            .header(axum::http::header::ORIGIN, "https://evil.com")
776            .body(Body::empty())
777            .unwrap();
778        assert_eq!(run_browser(req).await, StatusCode::FORBIDDEN);
779    }
780
781    #[tokio::test]
782    async fn ws_upgrade_without_origin_is_allowed() {
783        let req = HttpRequest::get("/graphql/ws")
784            .header(axum::http::header::HOST, "127.0.0.1:4000")
785            .body(Body::empty())
786            .unwrap();
787        assert_eq!(run_browser(req).await, StatusCode::OK);
788    }
789
790    #[tokio::test]
791    async fn configured_and_same_origin_are_allowed() {
792        let req = HttpRequest::get("/graphql/ws")
793            .header(axum::http::header::HOST, "127.0.0.1:4000")
794            .header(axum::http::header::ORIGIN, "https://music.example.com")
795            .body(Body::empty())
796            .unwrap();
797        assert_eq!(run_browser(req).await, StatusCode::OK);
798
799        // The bundled playground posts to the host it was served from.
800        let req = json_post("/graphql")
801            .header(axum::http::header::HOST, "127.0.0.1:4000")
802            .header(axum::http::header::ORIGIN, "http://127.0.0.1:4000")
803            .body(Body::empty())
804            .unwrap();
805        assert_eq!(run_browser(req).await, StatusCode::OK);
806    }
807
808    // -- CSRF via a CORS-safelisted content type --
809
810    #[tokio::test]
811    async fn text_plain_post_is_rejected() {
812        let req = HttpRequest::post("/graphql")
813            .header(axum::http::header::CONTENT_TYPE, "text/plain")
814            .body(Body::from(r#"{"query":"mutation{clearQueue{ok}}"}"#))
815            .unwrap();
816        assert_eq!(run_browser(req).await, StatusCode::UNSUPPORTED_MEDIA_TYPE);
817    }
818
819    #[tokio::test]
820    async fn post_without_content_type_is_rejected() {
821        let req = HttpRequest::post("/graphql").body(Body::empty()).unwrap();
822        assert_eq!(run_browser(req).await, StatusCode::UNSUPPORTED_MEDIA_TYPE);
823    }
824
825    // -- Load perimeter --
826
827    #[tokio::test]
828    async fn load_perimeter_passes_requests_and_turns_panics_into_500s() {
829        async fn boom() -> &'static str {
830            panic!("resolver exploded");
831        }
832
833        let app = load_perimeter(
834            axum::Router::new()
835                .route("/graphql", post(ok))
836                .route("/boom", post(boom)),
837        );
838
839        let req = json_post("/graphql").body(Body::empty()).unwrap();
840        assert_eq!(
841            app.clone().oneshot(req).await.unwrap().status(),
842            StatusCode::OK
843        );
844
845        // Without CatchPanicLayer this drops the connection with nothing logged.
846        let req = json_post("/boom").body(Body::empty()).unwrap();
847        assert_eq!(
848            app.oneshot(req).await.unwrap().status(),
849            StatusCode::INTERNAL_SERVER_ERROR
850        );
851    }
852
853    #[tokio::test]
854    async fn json_post_is_accepted() {
855        let req = json_post("/graphql").body(Body::empty()).unwrap();
856        assert_eq!(run_browser(req).await, StatusCode::OK);
857
858        let req = HttpRequest::post("/graphql")
859            .header(
860                axum::http::header::CONTENT_TYPE,
861                "application/json; charset=utf-8",
862            )
863            .body(Body::empty())
864            .unwrap();
865        assert_eq!(run_browser(req).await, StatusCode::OK);
866    }
867}