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