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