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