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