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