Skip to main content

koan_server/graphql/
server.rs

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