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