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