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    // Plays accounts forward to ListenBrainz; it sleeps while none do.
234    koan_core::scrobbling::start(pool.path().to_path_buf());
235
236    let shutdown = tokio_util::sync::CancellationToken::new();
237    let mcp_routes = crate::mcp::router(
238        state.clone(),
239        cmd_tx.clone(),
240        auth_state.clone(),
241        cfg.sharing.public_url.clone(),
242        headless,
243        shutdown.clone(),
244    );
245    let schema = build_schema(state, cmd_tx, pool.clone(), viz);
246
247    if auth_enabled {
248        log::info!(
249            "Auth enabled (Ed25519 JWT, access TTL {}s, refresh TTL {}s)",
250            access_ttl,
251            refresh_ttl
252        );
253    } else {
254        log::info!("Auth disabled — all requests treated as admin");
255    }
256
257    let browser_policy = Arc::new(BrowserPolicy {
258        origins: cfg.graphql.cors_origins.clone(),
259        hosts: cfg.graphql.allowed_hosts.clone(),
260    });
261
262    if cfg.graphql.cors_origins.is_empty() {
263        log::info!("CORS: no origins configured — browsers get no cross-origin access");
264    }
265
266    let rt = tokio::runtime::Runtime::new().expect("failed to create tokio runtime");
267    rt.block_on(async {
268        // GraphQL routes — protected by auth middleware.
269        //
270        // The query route carries the load perimeter; the WebSocket route does
271        // not, because a subscription is meant to outlive any request timeout.
272        let query_route = load_perimeter(axum::Router::new().route("/graphql", post(graphql_handler)));
273
274        let gql_app = axum::Router::new()
275            .merge(query_route)
276            .route("/graphql/ws", get(graphql_ws_handler))
277            .layer(axum::middleware::from_fn_with_state(
278                auth_state.clone(),
279                auth_middleware,
280            ))
281            // Runs before auth: a rejected request should never reach a
282            // credential check, let alone execute.
283            .layer(axum::middleware::from_fn_with_state(
284                browser_policy.clone(),
285                browser_guard,
286            ))
287            .with_state(schema);
288
289        // The web UI checks its own session (a page load without one is sent
290        // to sign in rather than refused), so it sits outside the GraphQL auth
291        // layer. Built before the auth routes take their state.
292        let covers = Arc::new(crate::covers::Covers::in_config_dir());
293        let ui_routes = crate::ui::router(
294            pool.clone(),
295            auth_route_state.clone(),
296            auth_enabled,
297            covers.clone(),
298            cfg.sharing.public_url.clone(),
299            cfg.mcp.redirect_hosts.clone(),
300        );
301
302        // Auth routes — always accessible (no auth middleware).
303        let auth_app = auth_router(auth_route_state);
304
305        // CORS. An empty origin list emits no `Access-Control-Allow-Origin` at
306        // all; a wildcard would let any web page read this library.
307        let origins: Vec<axum::http::HeaderValue> = cfg
308            .graphql
309            .cors_origins
310            .iter()
311            .filter_map(|o| o.parse().ok())
312            .collect();
313        let cors = tower_http::cors::CorsLayer::new()
314            .allow_origin(origins)
315            .allow_methods([
316                axum::http::Method::GET,
317                axum::http::Method::POST,
318                axum::http::Method::OPTIONS,
319            ])
320            .allow_headers([
321                axum::http::header::AUTHORIZATION,
322                axum::http::header::CONTENT_TYPE,
323                axum::http::HeaderName::from_static("x-introspection-key"),
324            ])
325            .allow_credentials(true);
326
327
328        // Public by design, so outside the auth layers: each route answers for
329        // one share's own tracks, or the one cover a notification's signed
330        // link names, and nothing else. The Host guard still applies.
331        let share_routes = crate::share::router(
332            pool.clone(),
333            cfg.sharing.public_url.clone(),
334            covers.clone(),
335        )
336        .merge(crate::push::router(pool.clone(), covers.clone()));
337        // Subsonic on the GraphQL port whenever `[subsonic]` is enabled: the
338        // remote TUI bridge builds its stream URL off the GraphQL base. Built
339        // once and cloned for the dedicated listener, since each build reads
340        // the config from disk.
341        let subsonic_merged = crate::subsonic::subsonic_router(pool, covers);
342        let subsonic_on_main = subsonic_merged.is_some();
343        let subsonic_dedicated = subsonic_merged.clone();
344
345        let mut app = auth_app
346            .merge(gql_app)
347            .merge(share_routes)
348            .merge(ui_routes)
349            .merge(mcp_routes);
350        if let Some(sub) = subsonic_merged {
351            app = app.merge(sub);
352        }
353        if playground_enabled {
354            app = app.route(
355                "/graphql",
356                get(graphql_playground).with_state(introspection_key.clone()),
357            );
358        }
359        // Outermost: a request whose `Host` we do not recognise is refused
360        // before anything else looks at it. Without this a DNS-rebinding page
361        // reaches the API as same-origin and CORS stops mattering.
362        let app = app.layer(cors).layer(axum::middleware::from_fn_with_state(
363            browser_policy.clone(),
364            host_guard,
365        ));
366
367        // Build playground URL with introspection key.
368        let playground_url = if playground_enabled {
369            if let Some(ref key) = introspection_key {
370                format!("http://{}:{}/graphql?introspection-key={}", bind, port, key)
371            } else {
372                format!("http://{}:{}/graphql", bind, port)
373            }
374        } else {
375            format!("http://{}:{}/graphql", bind, port)
376        };
377
378        let gql_addr = std::net::SocketAddr::new(bind, port);
379
380        let gql_listener = match tokio::net::TcpListener::bind(gql_addr).await {
381            Ok(l) => {
382                log::info!("GraphQL API on http://{}:{}/graphql", bind, port);
383                if subsonic_on_main {
384                    log::info!("Subsonic REST on http://{}:{}/rest/", bind, port);
385                }
386                if playground_enabled {
387                    log::info!("GraphiQL: {}", playground_url);
388                    // Open browser on macOS/Linux.
389                    #[cfg(target_os = "macos")]
390                    let _ = std::process::Command::new("open").arg(&playground_url).spawn();
391                    #[cfg(target_os = "linux")]
392                    let _ = std::process::Command::new("xdg-open").arg(&playground_url).spawn();
393                }
394                l
395            }
396            Err(e) => {
397                return Err(format!(
398                    "failed to bind GraphQL port {port} — {e} (another instance running?)"
399                ));
400            }
401        };
402        let gql_server = axum::serve(
403            gql_listener,
404            app.into_make_service_with_connect_info::<std::net::SocketAddr>(),
405        )
406        .with_graceful_shutdown(async move {
407            shutdown_signal().await;
408            shutdown.cancel();
409        });
410
411        // `--subsonic <port>` set to something other than the GraphQL port adds
412        // a dedicated Subsonic listener.
413        let extra_sub_port = subsonic_port.filter(|p| *p != port);
414        if let Some(sub_port) = extra_sub_port
415            && let Some(sub_app) = subsonic_dedicated
416        {
417            let sub_addr = std::net::SocketAddr::new(bind, sub_port);
418            match tokio::net::TcpListener::bind(sub_addr).await {
419                Ok(sub_listener) => {
420                    log::info!(
421                        "Subsonic REST also on http://{}:{}/rest/ (dedicated port)",
422                        bind,
423                        sub_port,
424                    );
425                    // With connection info, as the main listener: the sign-in
426                    // throttle keys on the client's address.
427                    let sub_server = axum::serve(
428                        sub_listener,
429                        sub_app.into_make_service_with_connect_info::<std::net::SocketAddr>(),
430                    )
431                    .with_graceful_shutdown(shutdown_signal());
432
433                    tokio::select! {
434                        r = gql_server => { if let Err(e) = r { log::error!("GraphQL server error: {e}"); } },
435                        r = sub_server => { if let Err(e) = r { log::error!("Subsonic server error: {e}"); } },
436                        _ = drain_deadline() => log::info!("shutting down with connections still open"),
437                    }
438                    return Ok(());
439                }
440                Err(e) => {
441                    log::warn!(
442                        "Dedicated Subsonic port {} unavailable — {}. Mounted on GraphQL port only.",
443                        sub_port,
444                        e,
445                    );
446                }
447            }
448        }
449
450        tokio::select! {
451            r = gql_server => { if let Err(e) = r { log::error!("GraphQL server error: {e}"); } },
452            _ = drain_deadline() => log::info!("shutting down with connections still open"),
453        }
454        Ok(())
455    })
456}
457
458/// Start the API server on the current thread (blocks forever).
459/// Called from a background thread when TUI mode has API enabled.
460pub fn start_api_background(
461    state: Arc<SharedPlayerState>,
462    cmd_tx: Sender<PlayerCommand>,
463    db_path: PathBuf,
464    port: Option<u16>,
465    bind: Option<std::net::IpAddr>,
466    subsonic_port: Option<u16>,
467    playground: bool,
468) {
469    // Runs on a spawned thread in TUI mode, where a panic would take the API
470    // down with nothing on screen to say so.
471    if let Err(e) = run_api_blocking(ApiServerOpts {
472        state,
473        cmd_tx,
474        pool: Arc::new(Pool::new(db_path)),
475        port,
476        bind,
477        subsonic_port,
478        playground,
479        viz: None,
480        headless: false,
481    }) {
482        log::error!("API server not started: {}", e);
483    }
484}
485
486// ---------------------------------------------------------------------------
487// Browser perimeter
488// ---------------------------------------------------------------------------
489
490/// What this server will answer to when the caller is a browser.
491///
492/// Two separate questions: which `Host` values name this server (DNS rebinding),
493/// and which `Origin` values may talk to it (CSRF, cross-site WebSockets).
494pub(crate) struct BrowserPolicy {
495    origins: Vec<String>,
496    hosts: Vec<String>,
497}
498
499impl BrowserPolicy {
500    fn host_allowed(&self, host: &str) -> bool {
501        if self.hosts.iter().any(|h| h.eq_ignore_ascii_case(host)) {
502            return true;
503        }
504        let bare = strip_port(host);
505        if self.hosts.iter().any(|h| h.eq_ignore_ascii_case(bare)) {
506            return true;
507        }
508        // A rebinding attack needs a name it controls; literals and localhost
509        // resolve to this machine by definition.
510        bare.eq_ignore_ascii_case("localhost") || bare.parse::<std::net::IpAddr>().is_ok()
511    }
512
513    /// An origin is allowed if it is configured, or if it is simply this server
514    /// talking to itself — which is what the bundled playground does.
515    fn origin_allowed(&self, origin: &str, host: Option<&str>) -> bool {
516        if self.origins.iter().any(|o| o == origin) {
517            return true;
518        }
519        match (origin.split_once("://"), host) {
520            (Some((_, authority)), Some(host)) => authority.eq_ignore_ascii_case(host),
521            _ => false,
522        }
523    }
524}
525
526/// `example.com:4000` -> `example.com`, `[::1]:4000` -> `::1`.
527fn strip_port(host: &str) -> &str {
528    if let Some(rest) = host.strip_prefix('[') {
529        return rest.split(']').next().unwrap_or(rest);
530    }
531    match host.rsplit_once(':') {
532        Some((h, port)) if !port.is_empty() && port.bytes().all(|b| b.is_ascii_digit()) => h,
533        _ => host,
534    }
535}
536
537fn header_str(request: &axum::extract::Request, name: axum::http::HeaderName) -> Option<&str> {
538    request.headers().get(name).and_then(|v| v.to_str().ok())
539}
540
541/// Reject requests carrying an unrecognised `Host`.
542async fn host_guard(
543    axum::extract::State(policy): axum::extract::State<Arc<BrowserPolicy>>,
544    request: axum::extract::Request,
545    next: axum::middleware::Next,
546) -> axum::response::Response {
547    use axum::response::IntoResponse;
548
549    // No `Host` at all means no browser: only HTTP/1.0 and raw tooling omit it,
550    // and neither can be steered by an attacker page.
551    let host = header_str(&request, axum::http::header::HOST)
552        .map(str::to_owned)
553        .or_else(|| request.uri().host().map(str::to_owned));
554
555    if let Some(ref host) = host
556        && !policy.host_allowed(host)
557    {
558        log::warn!("rejected request for unrecognised Host: {}", host);
559        return (axum::http::StatusCode::FORBIDDEN, "host not allowed").into_response();
560    }
561
562    next.run(request).await
563}
564
565/// Reject cross-site GraphQL traffic.
566///
567/// Two holes, one guard. A WebSocket handshake is exempt from CORS entirely, so
568/// a foreign page can open `/graphql/ws`, have the browser attach the session
569/// cookie, and read every response. And a POST whose content type is
570/// CORS-safelisted (`text/plain`) is sent without a preflight, yet
571/// async-graphql parses it as JSON regardless — so the mutation lands even
572/// though the reply is unreadable.
573async fn browser_guard(
574    axum::extract::State(policy): axum::extract::State<Arc<BrowserPolicy>>,
575    request: axum::extract::Request,
576    next: axum::middleware::Next,
577) -> axum::response::Response {
578    use axum::response::IntoResponse;
579
580    let host = header_str(&request, axum::http::header::HOST).map(str::to_owned);
581    // No `Origin` means a non-browser client, which CSRF cannot reach.
582    if let Some(origin) = header_str(&request, axum::http::header::ORIGIN)
583        && !policy.origin_allowed(origin, host.as_deref())
584    {
585        log::warn!(
586            "rejected GraphQL request from disallowed Origin: {}",
587            origin
588        );
589        return (axum::http::StatusCode::FORBIDDEN, "origin not allowed").into_response();
590    }
591
592    if request.method() == axum::http::Method::POST && !is_graphql_content_type(&request) {
593        return (
594            axum::http::StatusCode::UNSUPPORTED_MEDIA_TYPE,
595            "content type must be application/json or application/graphql",
596        )
597            .into_response();
598    }
599
600    next.run(request).await
601}
602
603fn is_graphql_content_type(request: &axum::extract::Request) -> bool {
604    header_str(request, axum::http::header::CONTENT_TYPE).is_some_and(|ct| {
605        let ct = ct.trim().to_ascii_lowercase();
606        ct.starts_with("application/json") || ct.starts_with("application/graphql")
607    })
608}
609
610/// Resolves on SIGINT, or SIGTERM where there is one. SIGTERM is how a service
611/// manager stops a process, and as PID 1 in a container an unhandled one is
612/// dropped by the kernel, leaving the server running until it is killed.
613async fn shutdown_signal() {
614    #[cfg(unix)]
615    {
616        use tokio::signal::unix::{SignalKind, signal};
617        let mut terminate = signal(SignalKind::terminate()).expect("failed to listen for SIGTERM");
618        tokio::select! {
619            r = tokio::signal::ctrl_c() => r.expect("failed to listen for ctrl+c"),
620            _ = terminate.recv() => {}
621        }
622    }
623    #[cfg(not(unix))]
624    tokio::signal::ctrl_c()
625        .await
626        .expect("failed to listen for ctrl+c");
627}
628
629/// How long shutdown waits for open connections before giving up on them.
630const DRAIN: std::time::Duration = std::time::Duration::from_secs(10);
631
632/// Resolves `DRAIN` after a shutdown signal. Graceful shutdown waits for every
633/// connection to close, and subscription websockets and audio streams never
634/// close on their own, so without a deadline the wait ends only in a kill.
635async fn drain_deadline() {
636    shutdown_signal().await;
637    tokio::time::sleep(DRAIN).await;
638}
639
640async fn graphql_handler(
641    axum::Extension(user): axum::Extension<AuthUser>,
642    axum::extract::State(schema): axum::extract::State<KoanSchema>,
643    headers: axum::http::HeaderMap,
644    req: async_graphql_axum::GraphQLRequest,
645) -> async_graphql_axum::GraphQLResponse {
646    let mut request = req.into_inner();
647    if let Some(origin) = crate::origin::origin(&headers, None) {
648        request = request.data(super::RequestOrigin(origin));
649    }
650    // The auth middleware always injects AuthUser (anonymous_admin when auth is
651    // disabled, or a real user when auth is enabled). No fallback needed here.
652    request = request.data(user);
653    schema.execute(request).await.into()
654}
655
656async fn graphql_ws_handler(
657    axum::Extension(user): axum::Extension<AuthUser>,
658    axum::extract::State(schema): axum::extract::State<KoanSchema>,
659    protocol: async_graphql_axum::GraphQLProtocol,
660    websocket: axum::extract::WebSocketUpgrade,
661) -> axum::response::Response {
662    websocket
663        .protocols(async_graphql::http::ALL_WEBSOCKET_PROTOCOLS)
664        .on_upgrade(move |stream| {
665            let stream = async_graphql_axum::GraphQLWebSocket::new(stream, schema, protocol)
666                .on_connection_init(move |_| async move {
667                    let mut data = async_graphql::Data::default();
668                    data.insert(user);
669                    Ok(data)
670                });
671            async move {
672                stream.serve().await;
673            }
674        })
675}
676
677async fn graphql_playground(
678    axum::extract::Query(params): axum::extract::Query<std::collections::HashMap<String, String>>,
679    axum::extract::State(key): axum::extract::State<Option<Arc<String>>>,
680) -> axum::response::Response {
681    use axum::response::IntoResponse;
682
683    // If an introspection key exists, require it in the URL.
684    if let Some(ref expected) = key {
685        let provided = params.get("introspection-key");
686        if provided.map(|k| k.as_str()) != Some(expected.as_str()) {
687            return (
688                axum::http::StatusCode::FORBIDDEN,
689                "invalid or missing introspection-key",
690            )
691                .into_response();
692        }
693    }
694
695    // Use async-graphql's built-in GraphiQL (self-contained, no CDN).
696    // Inject the introspection key as a default header so all queries are authed.
697    let mut source = async_graphql::http::GraphiQLSource::build().endpoint("/graphql");
698    if let Some(ref k) = key {
699        source = source.header("X-Introspection-Key", k.as_str());
700    }
701
702    axum::response::Html(source.finish()).into_response()
703}
704
705/// Run the server as a background daemon (fork + detach).
706pub fn cmd_serve_daemon(
707    port: Option<u16>,
708    bind: Option<std::net::IpAddr>,
709    subsonic_port: Option<u16>,
710    playground: bool,
711) {
712    use std::fs;
713    use std::process::Command;
714
715    let cfg = Config::load().unwrap_or_default();
716    let port_val = port.unwrap_or(cfg.graphql.port);
717    let bind_val = bind.unwrap_or(cfg.graphql.bind);
718
719    let exe = std::env::current_exe().expect("failed to get current exe path");
720    let mut cmd = Command::new(exe);
721
722    cmd.arg("--headless");
723    cmd.arg("--port").arg(port_val.to_string());
724    cmd.arg("--bind").arg(bind_val.to_string());
725    if let Some(sp) = subsonic_port {
726        cmd.arg("--subsonic").arg(sp.to_string());
727    }
728    if playground || cfg.graphql.playground {
729        cmd.arg("--playground");
730    }
731
732    cmd.stdin(std::process::Stdio::null());
733    cmd.stdout(std::process::Stdio::null());
734    cmd.stderr(std::process::Stdio::null());
735
736    let mut child = cmd.spawn().expect("failed to spawn daemon process");
737    let pid = child.id();
738
739    let pid_path = koan_core::config::config_dir().join("koan-serve.pid");
740    fs::write(&pid_path, pid.to_string()).ok();
741
742    std::thread::spawn(move || {
743        let _ = child.wait();
744    });
745
746    eprintln!("kōan daemon started (pid {}) on port {}", pid, port_val);
747    if let Some(sp) = subsonic_port {
748        eprintln!("  Subsonic REST on port {}", sp);
749    }
750    eprintln!("  PID file: {}", pid_path.display());
751}
752
753// ---------------------------------------------------------------------------
754// In-process execution (for MCP `graphql` tool)
755// ---------------------------------------------------------------------------
756
757/// Execute a GraphQL query in-process (no HTTP round-trip).
758///
759/// There is no credential to check, so the caller states who the query runs as
760/// and at what role — see `mcp::mcp_role`.
761pub async fn execute_in_process(
762    schema: &KoanSchema,
763    query: &str,
764    variables: Option<serde_json::Value>,
765    caller: AuthUser,
766) -> serde_json::Value {
767    let mut request = async_graphql::Request::new(query).data(caller);
768    if let Some(serde_json::Value::Object(map)) = variables {
769        let mut gql_vars = async_graphql::Variables::default();
770        for (k, v) in map {
771            gql_vars.insert(
772                async_graphql::Name::new(&k),
773                async_graphql::Value::from_json(v).unwrap_or(async_graphql::Value::Null),
774            );
775        }
776        request = request.variables(gql_vars);
777    }
778    let response = schema.execute(request).await;
779    serde_json::to_value(&response).unwrap_or(serde_json::Value::Null)
780}
781
782// ---------------------------------------------------------------------------
783// Tests
784// ---------------------------------------------------------------------------
785
786#[cfg(test)]
787mod tests {
788    use super::*;
789    use axum::body::Body;
790    use axum::http::{Request as HttpRequest, StatusCode};
791    use axum::routing::{get, post};
792    use tower::ServiceExt as _;
793
794    fn policy() -> Arc<BrowserPolicy> {
795        Arc::new(BrowserPolicy {
796            origins: vec!["https://music.example.com".into()],
797            hosts: vec!["koan.local".into()],
798        })
799    }
800
801    async fn ok() -> &'static str {
802        "ok"
803    }
804
805    fn routes() -> axum::Router<Arc<BrowserPolicy>> {
806        axum::Router::new()
807            .route("/graphql", post(ok).get(ok))
808            .route("/graphql/ws", get(ok))
809    }
810
811    async fn run_host(req: HttpRequest<Body>) -> StatusCode {
812        let app = routes()
813            .layer(axum::middleware::from_fn_with_state(policy(), host_guard))
814            .with_state(policy());
815        app.oneshot(req).await.unwrap().status()
816    }
817
818    async fn run_browser(req: HttpRequest<Body>) -> StatusCode {
819        let app = routes()
820            .layer(axum::middleware::from_fn_with_state(
821                policy(),
822                browser_guard,
823            ))
824            .with_state(policy());
825        app.oneshot(req).await.unwrap().status()
826    }
827
828    fn json_post(uri: &str) -> axum::http::request::Builder {
829        HttpRequest::post(uri).header(axum::http::header::CONTENT_TYPE, "application/json")
830    }
831
832    // -- Host allowlist (DNS rebinding) --
833
834    #[test]
835    fn host_policy_accepts_loopback_literals_and_configured_names() {
836        let p = policy();
837        assert!(p.host_allowed("localhost:4000"));
838        assert!(p.host_allowed("127.0.0.1:4000"));
839        assert!(p.host_allowed("192.168.1.20:4000"));
840        assert!(p.host_allowed("[::1]:4000"));
841        assert!(p.host_allowed("koan.local"));
842        assert!(p.host_allowed("koan.local:4000"));
843    }
844
845    #[test]
846    fn host_policy_rejects_attacker_controlled_names() {
847        let p = policy();
848        assert!(!p.host_allowed("evil.com"));
849        assert!(!p.host_allowed("rebind.evil.com:4000"));
850        assert!(!p.host_allowed("koan.local.evil.com"));
851    }
852
853    #[tokio::test]
854    async fn host_guard_rejects_foreign_host() {
855        let req = json_post("/graphql")
856            .header(axum::http::header::HOST, "rebind.evil.com")
857            .body(Body::empty())
858            .unwrap();
859        assert_eq!(run_host(req).await, StatusCode::FORBIDDEN);
860    }
861
862    #[tokio::test]
863    async fn host_guard_allows_known_host_and_missing_host() {
864        let req = json_post("/graphql")
865            .header(axum::http::header::HOST, "127.0.0.1:4000")
866            .body(Body::empty())
867            .unwrap();
868        assert_eq!(run_host(req).await, StatusCode::OK);
869
870        let req = json_post("/graphql").body(Body::empty()).unwrap();
871        assert_eq!(run_host(req).await, StatusCode::OK);
872    }
873
874    // -- Cross-site WebSocket --
875
876    #[tokio::test]
877    async fn ws_upgrade_from_foreign_origin_is_rejected() {
878        let req = HttpRequest::get("/graphql/ws")
879            .header(axum::http::header::HOST, "127.0.0.1:4000")
880            .header(axum::http::header::ORIGIN, "https://evil.com")
881            .body(Body::empty())
882            .unwrap();
883        assert_eq!(run_browser(req).await, StatusCode::FORBIDDEN);
884    }
885
886    #[tokio::test]
887    async fn ws_upgrade_without_origin_is_allowed() {
888        let req = HttpRequest::get("/graphql/ws")
889            .header(axum::http::header::HOST, "127.0.0.1:4000")
890            .body(Body::empty())
891            .unwrap();
892        assert_eq!(run_browser(req).await, StatusCode::OK);
893    }
894
895    #[tokio::test]
896    async fn configured_and_same_origin_are_allowed() {
897        let req = HttpRequest::get("/graphql/ws")
898            .header(axum::http::header::HOST, "127.0.0.1:4000")
899            .header(axum::http::header::ORIGIN, "https://music.example.com")
900            .body(Body::empty())
901            .unwrap();
902        assert_eq!(run_browser(req).await, StatusCode::OK);
903
904        // The bundled playground posts to the host it was served from.
905        let req = json_post("/graphql")
906            .header(axum::http::header::HOST, "127.0.0.1:4000")
907            .header(axum::http::header::ORIGIN, "http://127.0.0.1:4000")
908            .body(Body::empty())
909            .unwrap();
910        assert_eq!(run_browser(req).await, StatusCode::OK);
911    }
912
913    // -- CSRF via a CORS-safelisted content type --
914
915    #[tokio::test]
916    async fn text_plain_post_is_rejected() {
917        let req = HttpRequest::post("/graphql")
918            .header(axum::http::header::CONTENT_TYPE, "text/plain")
919            .body(Body::from(r#"{"query":"mutation{clearQueue{ok}}"}"#))
920            .unwrap();
921        assert_eq!(run_browser(req).await, StatusCode::UNSUPPORTED_MEDIA_TYPE);
922    }
923
924    #[tokio::test]
925    async fn post_without_content_type_is_rejected() {
926        let req = HttpRequest::post("/graphql").body(Body::empty()).unwrap();
927        assert_eq!(run_browser(req).await, StatusCode::UNSUPPORTED_MEDIA_TYPE);
928    }
929
930    // -- Load perimeter --
931
932    #[tokio::test]
933    async fn load_perimeter_refuses_an_oversized_query_body() {
934        async fn parse(_: async_graphql_axum::GraphQLRequest) -> StatusCode {
935            StatusCode::OK
936        }
937        let app = load_perimeter(axum::Router::new().route("/graphql", post(parse)));
938        // A valid query padded with whitespace, streamed so no Content-Length
939        // warns the limit ahead of the bytes.
940        let body = |padding: usize| {
941            let chunks = [
942                axum::body::Bytes::from_static(br#"{"query":"{__typename}""#),
943                axum::body::Bytes::from(vec![b' '; padding]),
944                axum::body::Bytes::from_static(b"}"),
945            ];
946            Body::from_stream(tokio_stream::iter(chunks.map(Ok::<_, std::io::Error>)))
947        };
948        let req = json_post("/graphql").body(body(1 << 10)).unwrap();
949        assert_eq!(
950            app.clone().oneshot(req).await.unwrap().status(),
951            StatusCode::OK
952        );
953        let req = json_post("/graphql").body(body(3 << 20)).unwrap();
954        assert_ne!(app.oneshot(req).await.unwrap().status(), StatusCode::OK);
955    }
956
957    #[tokio::test]
958    async fn load_perimeter_passes_requests_and_turns_panics_into_500s() {
959        async fn boom() -> &'static str {
960            panic!("resolver exploded");
961        }
962
963        let app = load_perimeter(
964            axum::Router::new()
965                .route("/graphql", post(ok))
966                .route("/boom", post(boom)),
967        );
968
969        let req = json_post("/graphql").body(Body::empty()).unwrap();
970        assert_eq!(
971            app.clone().oneshot(req).await.unwrap().status(),
972            StatusCode::OK
973        );
974
975        // Without CatchPanicLayer this drops the connection with nothing logged.
976        let req = json_post("/boom").body(Body::empty()).unwrap();
977        assert_eq!(
978            app.oneshot(req).await.unwrap().status(),
979            StatusCode::INTERNAL_SERVER_ERROR
980        );
981    }
982
983    #[tokio::test]
984    async fn json_post_is_accepted() {
985        let req = json_post("/graphql").body(Body::empty()).unwrap();
986        assert_eq!(run_browser(req).await, StatusCode::OK);
987
988        let req = HttpRequest::post("/graphql")
989            .header(
990                axum::http::header::CONTENT_TYPE,
991                "application/json; charset=utf-8",
992            )
993            .body(Body::empty())
994            .unwrap();
995        assert_eq!(run_browser(req).await, StatusCode::OK);
996    }
997}