Skip to main content

koan_server/graphql/
server.rs

1use std::path::PathBuf;
2use std::sync::Arc;
3
4use crossbeam_channel::Sender;
5use koan_core::audio::viz::VizSnapshot;
6use koan_core::auth::{self, parse_duration_secs};
7use koan_core::config::Config;
8use koan_core::db::pool::Pool;
9use koan_core::player::commands::PlayerCommand;
10use koan_core::player::state::SharedPlayerState;
11
12use super::KoanSchema;
13use crate::auth::AuthUser;
14use crate::auth::middleware::{AuthState, auth_middleware};
15use crate::auth::routes::{AuthRouteState, RateLimiter, auth_router};
16
17// ---------------------------------------------------------------------------
18// `koan --headless` entry point (standalone headless server)
19// ---------------------------------------------------------------------------
20
21/// A server hands out links to itself — invites, shares, sign-ins — and is
22/// known to its clients by one address, which it cannot work out for itself.
23fn require_server_url() {
24    let why = match Config::cached().server_url() {
25        None => "server.url is not set. Set it, or KOAN_SERVER__URL, to the address clients reach this server at, e.g. https://koan.example.com".to_owned(),
26        Some(url) if !url.starts_with("https://") && !url.starts_with("http://") => {
27            format!("server.url is {url:?}, which is not an http:// or https:// address")
28        }
29        Some(url) => match crate::base::problem(&url) {
30            Some(why) => format!("server.url is {url:?}: {why}"),
31            None => return,
32        },
33    };
34    log::error!("{why}");
35    eprintln!("koan: {why}");
36    std::process::exit(1);
37}
38
39pub fn cmd_serve(
40    port: Option<u16>,
41    bind: Option<std::net::IpAddr>,
42    subsonic_port: Option<u16>,
43    playground: bool,
44) {
45    use koan_core::player::Player;
46
47    require_server_url();
48    // Open, and migrate, before binding: a database this build cannot read,
49    // such as one a newer koan has migrated, stops it here with the reason
50    // rather than serving errors.
51    if let Err(e) = koan_core::db::connection::Database::open_default() {
52        log::error!("cannot open the database: {e}");
53        eprintln!("koan: cannot open the database: {e}");
54        std::process::exit(1);
55    }
56    let db_path = koan_core::config::db_path();
57    let pool = Arc::new(Pool::new(db_path.clone()));
58    koan_core::db::pool::on_outdated(|| OUTDATED.cancel());
59
60    let (state, _timeline, _viz, cmd_tx) = Player::spawn();
61    // Resolves the library's artist bios and photos ahead of the clients
62    // asking for them.
63    koan_core::artist_info::start();
64
65    // A server has no one to press "scan": index at start and whenever the
66    // library folders change, as the macOS app does.
67    let watched = db_path.clone();
68    let jobs = super::jobs::JobRegistry::default();
69    let record = super::jobs::record_watch(&jobs);
70    koan_core::helpers::spawn_library_watch(db_path, move |scan| {
71        record(&scan);
72        // A scan that just finished may have brought in an album someone asked
73        // to have queued when it arrived.
74        if let koan_core::helpers::WatchScan::Finished(_) = scan {
75            crate::clients::fulfil_from(&watched);
76            if let Ok(db) = koan_core::db::connection::Database::open_existing(&watched) {
77                crate::clients::changed_if_library_moved(&db.conn);
78            }
79        }
80    });
81
82    let started = ApiServer::start_with(
83        ApiServerOpts {
84            state,
85            cmd_tx,
86            pool,
87            port,
88            bind,
89            subsonic_port,
90            playground,
91            viz: None, // headless — no viz analyzer
92            profile: Profile::Headless,
93            hosts: Vec::new(),
94            session: None,
95        },
96        jobs,
97    );
98    match started {
99        Ok(server) => server.wait(),
100        Err(e) => {
101            eprintln!("koan: {}", e);
102            std::process::exit(1);
103        }
104    }
105}
106
107// ---------------------------------------------------------------------------
108// Shared API server logic — used by both headless and TUI+API modes
109// ---------------------------------------------------------------------------
110
111/// Ceiling on a single GraphQL query. Anything longer than this —
112/// a library scan, a remote sync — runs as a job instead.
113const REQUEST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
114
115/// Queries executing at once. Resolvers do their SQLite and HTTP work on the
116/// blocking pool, so this bounds concurrent work rather than protecting the
117/// runtime's workers from it.
118const MAX_INFLIGHT_QUERIES: usize = 64;
119
120/// Largest query body accepted. async-graphql reads the whole body before
121/// parsing it, with no limit of its own. A query is text; even a playlist of
122/// thousands of ids is a fraction of this.
123const MAX_QUERY_BODY: usize = 2 << 20;
124
125/// Timeout, panic catch, body limit and load shed for the query route.
126///
127/// Not applied to `/graphql/ws`: a subscription is meant to outlive any request
128/// timeout.
129fn load_perimeter<S>(router: axum::Router<S>) -> axum::Router<S>
130where
131    S: Clone + Send + Sync + 'static,
132{
133    router
134        // Innermost so it is inside the timeout: a panicking resolver becomes a
135        // 500 rather than a silently dropped connection.
136        .layer(tower_http::catch_panic::CatchPanicLayer::new())
137        .layer(tower_http::limit::RequestBodyLimitLayer::new(
138            MAX_QUERY_BODY,
139        ))
140        .layer(tower_http::timeout::TimeoutLayer::with_status_code(
141            axum::http::StatusCode::REQUEST_TIMEOUT,
142            REQUEST_TIMEOUT,
143        ))
144        // Shed rather than queue. A concurrency limit on its own parks callers
145        // on a semaphore, so an overloaded server answers every client slowly
146        // instead of telling the surplus to come back.
147        .layer(
148            tower::ServiceBuilder::new()
149                .layer(axum::error_handling::HandleErrorLayer::new(
150                    |err: tower::BoxError| async move {
151                        if err.is::<tower::load_shed::error::Overloaded>() {
152                            (
153                                axum::http::StatusCode::SERVICE_UNAVAILABLE,
154                                "server at capacity",
155                            )
156                        } else {
157                            (
158                                axum::http::StatusCode::INTERNAL_SERVER_ERROR,
159                                "internal error",
160                            )
161                        }
162                    },
163                ))
164                .load_shed()
165                .concurrency_limit(MAX_INFLIGHT_QUERIES),
166        )
167}
168
169/// Who the server runs for, which decides what it takes from the `[graphql]`,
170/// `[subsonic]` and `[server]` settings.
171#[derive(Clone, Copy, Debug, PartialEq, Eq)]
172pub enum Profile {
173    /// `koan --headless`: a server and nothing else. Its player is heard by
174    /// nobody.
175    Headless,
176    /// Beside the TUI, on the TUI's player.
177    Tui,
178    /// Inside an app sharing its library, on the app's player. Subsonic is
179    /// always on and only accounts sign in to it. The app owns the process, so
180    /// signals are left to it, and the settings a headless deployment uses
181    /// (demo, proxy sign-in, the playground) do not apply.
182    Embedded,
183}
184
185/// Options for the API server — avoids too-many-arguments.
186pub struct ApiServerOpts {
187    pub state: Arc<SharedPlayerState>,
188    pub cmd_tx: Sender<PlayerCommand>,
189    /// Shared by every route that reads the library outside GraphQL, and by
190    /// the MCP listener when there is one.
191    pub pool: Arc<Pool>,
192    pub port: Option<u16>,
193    pub bind: Option<std::net::IpAddr>,
194    pub subsonic_port: Option<u16>,
195    pub playground: bool,
196    pub viz: Option<Arc<VizSnapshot>>,
197    pub profile: Profile,
198    /// Names this server is reached by beyond `graphql.allowed_hosts`, such as
199    /// the Mac's Bonjour name.
200    pub hosts: Vec<String>,
201    /// Whose saved session `savePlaybackState` writes: the files prefix of
202    /// the device whose player this is (`LinkIdentity::files`). None where
203    /// nothing restores one, as on a headless server.
204    pub session: Option<&'static str>,
205}
206
207/// A running API server. Dropping it asks the server to stop and does not
208/// wait for it.
209pub struct ApiServer {
210    addr: std::net::SocketAddr,
211    /// What the app hosting an embedded server administers it with: an API
212    /// key good for the first admin, made for this run and never written down.
213    host_key: Option<String>,
214    stop: tokio_util::sync::CancellationToken,
215    thread: Option<std::thread::JoinHandle<()>>,
216    browser_policy: Arc<BrowserPolicy>,
217}
218
219impl ApiServer {
220    /// Bind the listeners, then serve on a thread of its own.
221    ///
222    /// `Err` means the server refused to start, on a misconfiguration or a port
223    /// it could not bind, and the caller has to surface it — never a silent
224    /// downgrade to an unauthenticated server. Nothing process-wide is touched
225    /// until the main port is bound.
226    ///
227    /// `jobs` is made by the caller, so a library watch started before the
228    /// server records its scans from the first.
229    pub fn start(opts: ApiServerOpts) -> Result<Self, String> {
230        Self::start_with(opts, Default::default())
231    }
232
233    pub(crate) fn start_with(
234        opts: ApiServerOpts,
235        jobs: super::jobs::JobRegistry,
236    ) -> Result<Self, String> {
237        let ApiServerOpts {
238            state,
239            cmd_tx,
240            pool,
241            port,
242            bind,
243            subsonic_port,
244            playground,
245            viz,
246            profile,
247            hosts,
248            session,
249        } = opts;
250        use axum::routing::{get, post};
251
252        let cfg = Config::cached();
253        let embedded = profile == Profile::Embedded;
254        let port = port.unwrap_or(cfg.graphql.port);
255        // The wizard is for a server with no shell to hand, in a container. One
256        // beside a terminal session or inside an app would open its /setup to
257        // any local process with nothing on screen to say so.
258        let setup_wizard = cfg.graphql.setup_wizard && profile == Profile::Headless;
259        let bind = bind.unwrap_or(cfg.graphql.bind);
260        // An app's server has one port, the one it was given.
261        let subsonic_port = if embedded {
262            None
263        } else {
264            subsonic_port.or(cfg.subsonic.port)
265        };
266        let subsonic_enabled = embedded || cfg.subsonic.enabled;
267        let playground_enabled = !embedded && (playground || cfg.graphql.playground);
268        let auth_enabled = cfg.graphql.auth_enabled;
269        let demo = cfg.server.demo;
270
271        if embedded && !auth_enabled {
272            return Err(
273                "graphql.auth_enabled is off, which would make anyone who reaches \
274                 this port an admin"
275                    .into(),
276            );
277        }
278        if demo && embedded {
279            return Err("server.demo is for a headless server".into());
280        }
281        // A demo is one shared account; without sign-in everyone would be admin.
282        if demo && !auth_enabled {
283            return Err("server.demo needs graphql.auth_enabled".into());
284        }
285
286        // Load or generate Ed25519 keypair for JWT signing. A server's first
287        // start makes its own: it is this server's signing key and nothing
288        // else, a fresh one invalidates no token (there can be none yet), and a
289        // server in a container has no terminal to run `koan auth setup` in
290        // before it starts. Accounts are still created deliberately; until one
291        // exists, nothing signs in.
292        let (private_pem, public_pem) = if auth_enabled {
293            let kp = auth::load_or_generate_keypair().map_err(|e| {
294                format!(
295                    "auth_enabled = true but the keypair could not be loaded or created: {}",
296                    e
297                )
298            })?;
299            // An empty or truncated key file would otherwise leave every request an
300            // unauthenticated admin, which is the opposite of what was asked for.
301            if kp.0.is_empty() || kp.1.is_empty() {
302                return Err("auth_enabled = true but the keypair files are empty. \
303                     Run `koan auth regenerate-keys`."
304                    .into());
305            }
306            kp
307        } else {
308            // When auth is disabled, we still need dummy keys for the route state
309            // (routes exist but won't be hit by middleware). Generate if available.
310            auth::load_or_generate_keypair().unwrap_or_default()
311        };
312
313        let access_ttl = parse_duration_secs(&cfg.graphql.access_token_ttl).unwrap_or(900);
314        let refresh_ttl = parse_duration_secs(&cfg.graphql.refresh_token_ttl).unwrap_or(2_592_000);
315
316        // Process-scoped introspection key for playground access. It is a bearer
317        // credential compared verbatim, so it has to be full-entropy random — a
318        // UUID would leak the server start time and cut the guessable space.
319        let introspection_key = if playground_enabled && auth_enabled {
320            Some(Arc::new(auth::random_token().map_err(|e| {
321                format!("failed to generate introspection key: {}", e)
322            })?))
323        } else {
324            None
325        };
326
327        let proxy_auth = if embedded {
328            None
329        } else {
330            crate::ui::ProxyAuth::from_config(
331                &cfg.graphql.proxy_auth_header,
332                &cfg.graphql.proxy_auth_from,
333            )?
334        };
335
336        // A listener on every interface may share its port with another
337        // process's on loopback, which then answers everything sent to
338        // 127.0.0.1: an app's own administration and Funnel among it. Such a
339        // port counts as taken.
340        if bind.is_unspecified() && port != 0 {
341            // `::` takes IPv4 as well, so both loopbacks count.
342            let loopbacks: &[std::net::IpAddr] = match bind {
343                std::net::IpAddr::V4(_) => &[std::net::Ipv4Addr::LOCALHOST.into()],
344                std::net::IpAddr::V6(_) => &[
345                    std::net::Ipv4Addr::LOCALHOST.into(),
346                    std::net::Ipv6Addr::LOCALHOST.into(),
347                ],
348            };
349            for loopback in loopbacks {
350                std::net::TcpListener::bind((*loopback, port))
351                    .map_err(|e| format!("port {port} is already in use on this machine — {e}"))?;
352            }
353        }
354        let gql_listener = std::net::TcpListener::bind((bind, port))
355            .and_then(|l| l.set_nonblocking(true).map(|()| l))
356            .map_err(|e| {
357                format!("failed to bind GraphQL port {port} — {e} (another instance running?)")
358            })?;
359        let addr = gql_listener
360            .local_addr()
361            .map_err(|e| format!("failed to read the GraphQL listener's address — {e}"))?;
362
363        // `--subsonic <port>` set to something other than the GraphQL port adds
364        // a dedicated Subsonic listener.
365        let sub_listener = subsonic_port
366            .filter(|p| subsonic_enabled && *p != port)
367            .and_then(|sub_port| {
368                match std::net::TcpListener::bind((bind, sub_port))
369                    .and_then(|l| l.set_nonblocking(true).map(|()| l))
370                {
371                    Ok(l) => Some(l),
372                    Err(e) => {
373                        log::warn!(
374                            "Dedicated Subsonic port {sub_port} unavailable — {e}. Mounted on GraphQL port only."
375                        );
376                        None
377                    }
378                }
379            });
380
381        let rt = tokio::runtime::Runtime::new()
382            .map_err(|e| format!("could not start the API server's runtime — {e}"))?;
383        let (gql_listener, sub_listener) = {
384            let _in = rt.enter();
385            let gql = tokio::net::TcpListener::from_std(gql_listener)
386                .map_err(|e| format!("failed to listen on {addr} — {e}"))?;
387            let sub = sub_listener.and_then(|l| match tokio::net::TcpListener::from_std(l) {
388                Ok(l) => Some(l),
389                Err(e) => {
390                    log::warn!("Dedicated Subsonic listener unusable — {e}");
391                    None
392                }
393            });
394            (gql, sub)
395        };
396
397        let host_key = embedded
398            .then(auth::random_token)
399            .transpose()
400            .map_err(|e| format!("failed to generate the host key: {e}"))?;
401
402        if demo {
403            let db = pool.get().map_err(|e| format!("demo: {e}"))?;
404            crate::demo::start(&db.conn).map_err(|e| format!("demo: {e}"))?;
405        }
406
407        // What once encrypted account passwords for Subsonic token auth. Nothing
408        // is encrypted with it any more; a copy left on disk is a liability.
409        let _ = std::fs::remove_file(auth::keypair_dir().join("subsonic.key"));
410
411        crate::auth::set_signing_keys(Arc::new(private_pem.clone()), Arc::new(public_pem.clone()));
412
413        let auth_state = AuthState {
414            public_pem: Arc::new(public_pem.clone()),
415            auth_enabled,
416            introspection_key: introspection_key.clone(),
417            pool: pool.clone(),
418        };
419
420        // One for every door a password comes through, so its limits are shared.
421        let users = Arc::new(crate::auth::password::PasswordVerifier::new(pool.clone()));
422        let auth_route_state = AuthRouteState {
423            users: users.clone(),
424            pool: pool.clone(),
425            private_pem: Arc::new(private_pem),
426            public_pem: Arc::new(public_pem),
427            access_ttl_secs: access_ttl,
428            refresh_ttl_secs: refresh_ttl,
429            cookie_secure: cfg.graphql.cookie_secure,
430            login_limiter: Arc::new(RateLimiter::default()),
431        };
432
433        // Plays accounts forward to ListenBrainz; it sleeps while none do.
434        koan_core::scrobbling::start(pool.path().to_path_buf());
435        // Made here, off the runtime: the relay's client is a blocking one,
436        // which cannot be built inside it, and the routes ask for it there.
437        let _ = crate::push::pusher();
438
439        // Ends graceful shutdown, every open session and the MCP streams.
440        let stop = tokio_util::sync::CancellationToken::new();
441        // An app sharing its library serves its own apps; the web UI and MCP
442        // are for a server people reach with a browser or an assistant.
443        let mcp_routes = (!embedded).then(|| {
444            crate::mcp::router(
445                state.clone(),
446                cmd_tx.clone(),
447                auth_state.clone(),
448                cfg.server_url(),
449                profile == Profile::Headless,
450                session,
451                stop.clone(),
452            )
453        });
454        let covers = Arc::new(crate::covers::Covers::in_config_dir());
455        let schema = super::build_schema_sharing(
456            state,
457            cmd_tx,
458            pool.clone(),
459            viz,
460            jobs.clone(),
461            session,
462            Some(covers.clone()),
463        );
464
465        if auth_enabled {
466            log::info!(
467                "Auth enabled (Ed25519 JWT, access TTL {}s, refresh TTL {}s)",
468                access_ttl,
469                refresh_ttl
470            );
471            let no_accounts = pool
472                .get()
473                .ok()
474                .and_then(|db| koan_core::db::queries::auth::has_users(&db.conn).ok())
475                == Some(false);
476            if no_accounts && setup_wizard {
477                log::warn!(
478                    "No accounts yet: whoever opens /setup first becomes the admin. \
479                     Set graphql.setup_wizard = false to make it with `koan auth setup` instead."
480                );
481            }
482        } else {
483            log::info!("Auth disabled — all requests treated as admin");
484        }
485
486        let mut allowed_hosts = cfg.graphql.allowed_hosts.clone();
487        allowed_hosts.extend(hosts);
488        // On a home network every device has a private address; only a tunnel
489        // client on this machine forwards for anyone.
490        let forwarded_from = if embedded {
491            crate::auth::routes::ForwardedFrom::Loopback
492        } else {
493            crate::auth::routes::ForwardedFrom::Private
494        };
495        let browser_policy = Arc::new(BrowserPolicy {
496            origins: cfg.graphql.cors_origins.clone(),
497            hosts: allowed_hosts,
498            ..Default::default()
499        });
500
501        if cfg.graphql.cors_origins.is_empty() {
502            log::info!("CORS: no origins configured — browsers get no cross-origin access");
503        }
504
505        let serving = stop.clone();
506        let serving_key = host_key.clone();
507        let kept_policy = browser_policy.clone();
508        let thread = std::thread::Builder::new()
509            .name("koan-api".into())
510            .spawn(move || {
511                let stop = serving;
512                rt.block_on(async {
513                    if !embedded {
514                        let stop = stop.clone();
515                        tokio::spawn(async move {
516                            shutdown_signal().await;
517                            stop.cancel();
518                        });
519                    }
520
521                    // GraphQL routes — protected by auth middleware.
522                    //
523                    // The query route carries the load perimeter; the WebSocket route does
524                    // not, because a subscription is meant to outlive any request timeout.
525                    let query_route =
526                        load_perimeter(axum::Router::new().route("/graphql", post(graphql_handler)));
527
528                    let gql_app = axum::Router::new()
529                        .merge(query_route)
530                        .route("/graphql/ws", get(graphql_ws_handler))
531                        .layer(axum::Extension(stop.clone()))
532                        .layer(axum::middleware::from_fn_with_state(
533                            auth_state.clone(),
534                            auth_middleware,
535                        ))
536                        // Runs before auth: a rejected request should never reach a
537                        // credential check, let alone execute.
538                        .layer(axum::middleware::from_fn_with_state(
539                            browser_policy.clone(),
540                            browser_guard,
541                        ))
542                        .with_state(schema);
543
544                    // The web UI checks its own session (a page load without one is sent
545                    // to sign in rather than refused), so it sits outside the GraphQL auth
546                    // layer. Built before the auth routes take their state.
547                    // A standing server keeps every album's grid cover ready; an
548                    // app sharing its own library, and the API beside the
549                    // terminal UI, make them as asked.
550                    if profile == Profile::Headless {
551                        covers.warm(pool.clone());
552                    }
553                    let ui_routes = (!embedded).then(|| crate::ui::router(
554                        pool.clone(),
555                        auth_route_state.clone(),
556                        auth_enabled,
557                        setup_wizard,
558                        covers.clone(),
559                        cfg.server_url(),
560                        cfg.mcp.redirect_hosts.clone(),
561                        proxy_auth,
562                        jobs,
563                    )
564                    // A template that fails to render panics; this makes it a 500.
565                    .layer(tower_http::catch_panic::CatchPanicLayer::new()));
566                    let ui_routes = ui_routes.map(|ui| {
567                        if demo {
568                            ui.layer(axum::middleware::from_fn(crate::demo::guard))
569                        } else {
570                            ui
571                        }
572                    });
573
574                    // Auth routes — always accessible (no auth middleware).
575                    let auth_app = auth_router(auth_route_state);
576
577                    // CORS. An empty origin list emits no `Access-Control-Allow-Origin` at
578                    // all; a wildcard would let any web page read this library.
579                    let origins: Vec<axum::http::HeaderValue> = cfg
580                        .graphql
581                        .cors_origins
582                        .iter()
583                        .filter_map(|o| o.parse().ok())
584                        .collect();
585                    let cors = tower_http::cors::CorsLayer::new()
586                        .allow_origin(origins)
587                        .allow_methods([
588                            axum::http::Method::GET,
589                            axum::http::Method::POST,
590                            axum::http::Method::OPTIONS,
591                        ])
592                        .allow_headers([
593                            axum::http::header::AUTHORIZATION,
594                            axum::http::header::CONTENT_TYPE,
595                            axum::http::HeaderName::from_static("x-introspection-key"),
596                        ])
597                        .allow_credentials(true);
598
599                    // Public by design, so outside the auth layers: each route answers for
600                    // one share's own tracks, or the one cover a notification's signed
601                    // link names, and nothing else. The Host guard still applies.
602                    // An app's own server reads the address as each page is
603                    // asked for, since the app changes it as it runs.
604                    let share_url = match embedded {
605                        true => crate::ServerUrl::Live,
606                        false => crate::ServerUrl::Fixed(cfg.server_url()),
607                    };
608                    let edge = axum::middleware::from_fn_with_state(
609                        crate::base::Base::of(&share_url),
610                        crate::base::edge,
611                    );
612                    let share_routes =
613                        crate::share::router(pool.clone(), share_url, covers.clone())
614                            .layer(tower_http::catch_panic::CatchPanicLayer::new());
615                    // Subsonic on the GraphQL port whenever it is enabled: the remote
616                    // TUI bridge builds its stream URL off the GraphQL base. Built once
617                    // and cloned for the dedicated listener, since each build reads the
618                    // config from disk.
619                    // The demo guard goes on Subsonic itself, so a dedicated Subsonic
620                    // port has it too, and on the web UI above.
621                    let subsonic_merged = subsonic_enabled
622                        .then(|| {
623                            crate::subsonic::subsonic_router(
624                                pool,
625                                covers,
626                                users,
627                                profile,
628                                stop.clone(),
629                                serving_key,
630                            )
631                        })
632                        .map(|sub| {
633                            if demo {
634                                sub.layer(axum::middleware::from_fn(crate::demo::guard))
635                            } else {
636                                sub
637                            }
638                        });
639                    let subsonic_dedicated = subsonic_merged.clone();
640
641                    // An app's own server serves its apps: Subsonic and the
642                    // share pages. GraphQL and its sign-in would let any
643                    // account drive the app's own player.
644                    let mut app = match embedded {
645                        true => share_routes,
646                        false => auth_app.merge(gql_app).merge(share_routes),
647                    };
648                    if let Some(ui) = ui_routes {
649                        app = app.merge(ui);
650                    }
651                    if let Some(mcp) = mcp_routes {
652                        app = app.merge(mcp);
653                    }
654                    if let Some(sub) = subsonic_merged {
655                        app = app.merge(sub);
656                    }
657                    if playground_enabled {
658                        app = app.route(
659                            "/graphql",
660                            get(graphql_playground).with_state((
661                                introspection_key.clone(),
662                                crate::base::path_of(cfg.server_url().as_deref()),
663                            )),
664                        );
665                    }
666                    // Outermost: a request whose `Host` we do not recognise is refused
667                    // before anything else looks at it. Without this a DNS-rebinding page
668                    // reaches the API as same-origin and CORS stops mattering.
669                    let app = app
670                        .layer(cors)
671                        .layer(axum::middleware::from_fn_with_state(
672                            browser_policy.clone(),
673                            host_guard,
674                        ))
675                        .layer(axum::Extension(forwarded_from));
676
677                    log::info!("GraphQL API on http://{addr}/graphql");
678                    if subsonic_enabled {
679                        log::info!("Subsonic REST on http://{addr}/rest/");
680                    }
681                    if playground_enabled {
682                        let playground_url = match introspection_key {
683                            Some(ref key) => {
684                                format!("http://{addr}/graphql?introspection-key={key}")
685                            }
686                            None => format!("http://{addr}/graphql"),
687                        };
688                        log::info!("GraphiQL: {}", playground_url);
689                        // Open browser on macOS/Linux.
690                        #[cfg(target_os = "macos")]
691                        let _ = std::process::Command::new("open").arg(&playground_url).spawn();
692                        #[cfg(target_os = "linux")]
693                        let _ = std::process::Command::new("xdg-open")
694                            .arg(&playground_url)
695                            .spawn();
696                    }
697                    let gql_server = axum::serve(
698                        gql_listener,
699                        axum::ServiceExt::<axum::extract::Request>::into_make_service_with_connect_info::<std::net::SocketAddr>(
700                            tower::Layer::layer(&edge, app),
701                        ),
702                    )
703                    .with_graceful_shutdown(stop.clone().cancelled_owned());
704
705                    if let Some((sub_listener, sub_app)) = sub_listener.zip(subsonic_dedicated) {
706                        if let Ok(a) = sub_listener.local_addr() {
707                            log::info!("Subsonic REST also on http://{a}/rest/ (dedicated port)");
708                        }
709                        // With connection info, as the main listener: the sign-in
710                        // throttle keys on the client's address.
711                        let sub_server = axum::serve(
712                            sub_listener,
713                            axum::ServiceExt::<axum::extract::Request>::into_make_service_with_connect_info::<std::net::SocketAddr>(
714                                tower::Layer::layer(&edge, sub_app),
715                            ),
716                        )
717                        .with_graceful_shutdown(stop.clone().cancelled_owned());
718
719                        tokio::select! {
720                            r = gql_server => { if let Err(e) = r { log::error!("GraphQL server error: {e}"); } },
721                            r = sub_server => { if let Err(e) = r { log::error!("Subsonic server error: {e}"); } },
722                            _ = drain_deadline(&stop) => log::info!("shutting down with connections still open"),
723                        }
724                        return;
725                    }
726
727                    tokio::select! {
728                        r = gql_server => { if let Err(e) = r { log::error!("GraphQL server error: {e}"); } },
729                        _ = drain_deadline(&stop) => log::info!("shutting down with connections still open"),
730                    }
731                });
732                // Blocking work still running (a scan job, a stream's file read)
733                // is left to finish on its own rather than holding up the stop.
734                rt.shutdown_timeout(DRAIN);
735            })
736            .map_err(|e| format!("could not start the API server thread — {e}"))?;
737
738        Ok(Self {
739            addr,
740            host_key,
741            stop,
742            thread: Some(thread),
743            browser_policy: kept_policy,
744        })
745    }
746
747    /// Names this server answers to that move while it runs, such as the
748    /// device's Tailscale name, which exists only while Tailscale is up, and
749    /// a Funnel's address. `names` is asked again when a request names a host
750    /// not otherwise allowed, off the async threads and at most once every
751    /// `RELEARN` however many such requests arrive, and its answer replaces
752    /// the last.
753    pub fn follow_hosts(&self, names: impl Fn() -> Vec<String> + Send + Sync + 'static) {
754        let _ = self.browser_policy.relearn.set(Box::new(names));
755        self.browser_policy.learn();
756    }
757
758    /// See `host_key` on the struct. `None` but for an embedded server.
759    pub fn host_key(&self) -> Option<&str> {
760        self.host_key.as_deref()
761    }
762
763    /// The address the main listener is bound to.
764    pub fn addr(&self) -> std::net::SocketAddr {
765        self.addr
766    }
767
768    /// Stop accepting, close open sessions, and wait for the server to finish:
769    /// at most `DRAIN` for connections, then `DRAIN` for blocking work.
770    pub fn stop(mut self) {
771        self.stop.cancel();
772        self.join();
773    }
774
775    /// Wait until the server stops on its own: on a signal, for the profiles
776    /// that listen for them.
777    pub fn wait(mut self) {
778        self.join();
779    }
780
781    fn join(&mut self) {
782        if let Some(thread) = self.thread.take()
783            && thread.join().is_err()
784        {
785            log::error!("API server thread panicked");
786        }
787    }
788}
789
790impl Drop for ApiServer {
791    fn drop(&mut self) {
792        self.stop.cancel();
793    }
794}
795
796/// Start the API server beside the TUI, blocking until it stops.
797/// Called from a background thread when TUI mode has API enabled. `session`
798/// is whose saved session `savePlaybackState` writes: the caller's, or none.
799#[allow(clippy::too_many_arguments)]
800pub fn start_api_background(
801    state: Arc<SharedPlayerState>,
802    cmd_tx: Sender<PlayerCommand>,
803    db_path: PathBuf,
804    port: Option<u16>,
805    bind: Option<std::net::IpAddr>,
806    subsonic_port: Option<u16>,
807    playground: bool,
808    session: Option<&'static str>,
809) {
810    let started = ApiServer::start(ApiServerOpts {
811        state,
812        cmd_tx,
813        pool: Arc::new(Pool::new(db_path)),
814        port,
815        bind,
816        subsonic_port,
817        playground,
818        viz: None,
819        profile: Profile::Tui,
820        hosts: Vec::new(),
821        session,
822    });
823    match started {
824        Ok(server) => server.wait(),
825        Err(e) => log::error!("API server not started: {}", e),
826    }
827}
828
829// ---------------------------------------------------------------------------
830// Browser perimeter
831// ---------------------------------------------------------------------------
832
833/// What this server will answer to when the caller is a browser.
834///
835/// Two separate questions: which `Host` values name this server (DNS rebinding),
836/// and which `Origin` values may talk to it (CSRF, cross-site WebSockets).
837#[derive(Default)]
838pub(crate) struct BrowserPolicy {
839    origins: Vec<String>,
840    hosts: Vec<String>,
841    /// The names `relearn` last gave, beside `hosts`.
842    learned: parking_lot::RwLock<Vec<String>>,
843    /// See `ApiServer::follow_hosts`.
844    relearn: std::sync::OnceLock<Relearn>,
845    /// When `relearn` was last asked; held while it is, so requests arriving
846    /// together ask once.
847    learned_at: parking_lot::Mutex<Option<std::time::Instant>>,
848}
849
850type Relearn = Box<dyn Fn() -> Vec<String> + Send + Sync>;
851
852/// The least time between two askings of a server's moving names.
853const RELEARN: std::time::Duration = std::time::Duration::from_secs(5);
854
855impl BrowserPolicy {
856    fn host_allowed(&self, host: &str) -> bool {
857        let bare = strip_port(host);
858        let learned = self.learned.read();
859        if self
860            .hosts
861            .iter()
862            .chain(learned.iter())
863            .any(|h| h.eq_ignore_ascii_case(host) || h.eq_ignore_ascii_case(bare))
864        {
865            return true;
866        }
867        // A rebinding attack needs a name it controls; literals and localhost
868        // resolve to this machine by definition.
869        bare.eq_ignore_ascii_case("localhost") || bare.parse::<std::net::IpAddr>().is_ok()
870    }
871
872    /// An origin is allowed if it is configured, or if it is simply this server
873    /// talking to itself — which is what the bundled playground does.
874    fn origin_allowed(&self, origin: &str, host: Option<&str>) -> bool {
875        if self.origins.iter().any(|o| o == origin) {
876            return true;
877        }
878        match (origin.split_once("://"), host) {
879            (Some((_, authority)), Some(host)) => authority.eq_ignore_ascii_case(host),
880            _ => false,
881        }
882    }
883}
884
885impl BrowserPolicy {
886    /// Whether a host refused now may be allowed once the moving names are
887    /// asked again.
888    /// Never waits: while another request is asking (the Tailscale CLI can
889    /// take seconds), this one is refused rather than holding an async
890    /// worker. `learn` itself runs on the blocking pool.
891    fn may_relearn(&self) -> bool {
892        self.relearn.get().is_some()
893            && self
894                .learned_at
895                .try_lock()
896                .is_some_and(|at| at.is_none_or(|at| at.elapsed() >= RELEARN))
897    }
898
899    /// Ask the moving names again, unless they were asked within `RELEARN`.
900    /// Blocking.
901    fn learn(&self) {
902        let Some(relearn) = self.relearn.get() else {
903            return;
904        };
905        let mut at = self.learned_at.lock();
906        if at.is_some_and(|at| at.elapsed() < RELEARN) {
907            return;
908        }
909        *self.learned.write() = relearn();
910        *at = Some(std::time::Instant::now());
911    }
912}
913
914/// `example.com:4000` -> `example.com`, `[::1]:4000` -> `::1`.
915fn strip_port(host: &str) -> &str {
916    if let Some(rest) = host.strip_prefix('[') {
917        return rest.split(']').next().unwrap_or(rest);
918    }
919    match host.rsplit_once(':') {
920        Some((h, port)) if !port.is_empty() && port.bytes().all(|b| b.is_ascii_digit()) => h,
921        _ => host,
922    }
923}
924
925fn header_str(request: &axum::extract::Request, name: axum::http::HeaderName) -> Option<&str> {
926    request.headers().get(name).and_then(|v| v.to_str().ok())
927}
928
929/// Reject requests carrying an unrecognised `Host`.
930async fn host_guard(
931    axum::extract::State(policy): axum::extract::State<Arc<BrowserPolicy>>,
932    request: axum::extract::Request,
933    next: axum::middleware::Next,
934) -> axum::response::Response {
935    use axum::response::IntoResponse;
936
937    // No `Host` at all means no browser: only HTTP/1.0 and raw tooling omit it,
938    // and neither can be steered by an attacker page.
939    let host = header_str(&request, axum::http::header::HOST)
940        .map(str::to_owned)
941        .or_else(|| request.uri().host().map(str::to_owned));
942
943    if let Some(ref host) = host
944        && !policy.host_allowed(host)
945        && !(policy.may_relearn() && {
946            let asked = policy.clone();
947            let _ = tokio::task::spawn_blocking(move || asked.learn()).await;
948            policy.host_allowed(host)
949        })
950    {
951        log::warn!("rejected request for unrecognised Host: {}", host);
952        return (axum::http::StatusCode::FORBIDDEN, "host not allowed").into_response();
953    }
954
955    next.run(request).await
956}
957
958/// Reject cross-site GraphQL traffic.
959///
960/// Two holes, one guard. A WebSocket handshake is exempt from CORS entirely, so
961/// a foreign page can open `/graphql/ws`, have the browser attach the session
962/// cookie, and read every response. And a POST whose content type is
963/// CORS-safelisted (`text/plain`) is sent without a preflight, yet
964/// async-graphql parses it as JSON regardless — so the mutation lands even
965/// though the reply is unreadable.
966async fn browser_guard(
967    axum::extract::State(policy): axum::extract::State<Arc<BrowserPolicy>>,
968    request: axum::extract::Request,
969    next: axum::middleware::Next,
970) -> axum::response::Response {
971    use axum::response::IntoResponse;
972
973    let host = header_str(&request, axum::http::header::HOST).map(str::to_owned);
974    // No `Origin` means a non-browser client, which CSRF cannot reach.
975    if let Some(origin) = header_str(&request, axum::http::header::ORIGIN)
976        && !policy.origin_allowed(origin, host.as_deref())
977    {
978        log::warn!(
979            "rejected GraphQL request from disallowed Origin: {}",
980            origin
981        );
982        return (axum::http::StatusCode::FORBIDDEN, "origin not allowed").into_response();
983    }
984
985    if request.method() == axum::http::Method::POST && !is_graphql_content_type(&request) {
986        return (
987            axum::http::StatusCode::UNSUPPORTED_MEDIA_TYPE,
988            "content type must be application/json or application/graphql",
989        )
990            .into_response();
991    }
992
993    next.run(request).await
994}
995
996fn is_graphql_content_type(request: &axum::extract::Request) -> bool {
997    header_str(request, axum::http::header::CONTENT_TYPE).is_some_and(|ct| {
998        let ct = ct.trim().to_ascii_lowercase();
999        ct.starts_with("application/json") || ct.starts_with("application/graphql")
1000    })
1001}
1002
1003/// Cancelled when the database turns out to have been upgraded by a newer
1004/// koan, as the one replacing this server does when it starts: this build
1005/// can no longer serve it, so it drains and exits as on SIGTERM.
1006static OUTDATED: std::sync::LazyLock<tokio_util::sync::CancellationToken> =
1007    std::sync::LazyLock::new(tokio_util::sync::CancellationToken::new);
1008
1009/// Resolves on SIGINT, SIGTERM where there is one, or the database being
1010/// upgraded past this build. SIGTERM is how a service manager stops a
1011/// process, and as PID 1 in a container an unhandled one is dropped by the
1012/// kernel, leaving the server running until it is killed.
1013async fn shutdown_signal() {
1014    #[cfg(unix)]
1015    {
1016        use tokio::signal::unix::{SignalKind, signal};
1017        let mut terminate = signal(SignalKind::terminate()).expect("failed to listen for SIGTERM");
1018        tokio::select! {
1019            r = tokio::signal::ctrl_c() => r.expect("failed to listen for ctrl+c"),
1020            _ = terminate.recv() => {}
1021            _ = OUTDATED.cancelled() => {}
1022        }
1023    }
1024    #[cfg(not(unix))]
1025    tokio::select! {
1026        r = tokio::signal::ctrl_c() => r.expect("failed to listen for ctrl+c"),
1027        _ = OUTDATED.cancelled() => {}
1028    }
1029}
1030
1031/// How long shutdown waits for open connections before giving up on them.
1032const DRAIN: std::time::Duration = std::time::Duration::from_secs(10);
1033
1034/// Resolves `DRAIN` after the server is told to stop. Graceful shutdown waits for every
1035/// connection to close, and subscription websockets and audio streams never
1036/// close on their own, so without a deadline the wait ends only in a kill.
1037async fn drain_deadline(stop: &tokio_util::sync::CancellationToken) {
1038    stop.cancelled().await;
1039    tokio::time::sleep(DRAIN).await;
1040}
1041
1042async fn graphql_handler(
1043    axum::Extension(user): axum::Extension<AuthUser>,
1044    axum::extract::State(schema): axum::extract::State<KoanSchema>,
1045    req: async_graphql_axum::GraphQLRequest,
1046) -> async_graphql_axum::GraphQLResponse {
1047    let mut request = req.into_inner();
1048    // The auth middleware always injects AuthUser (anonymous_admin when auth is
1049    // disabled, or a real user when auth is enabled). No fallback needed here.
1050    request = request.data(user);
1051    schema.execute(request).await.into()
1052}
1053
1054/// Subscriptions over a WebSocket, as the account the upgrade request
1055/// authenticated. Closed when that account changes or its token lapses (see
1056/// `Lease`), and when the server stops; otherwise, as when auth is off, it
1057/// stays open.
1058async fn graphql_ws_handler(
1059    axum::Extension(user): axum::Extension<AuthUser>,
1060    lease: Option<axum::Extension<crate::auth::Lease>>,
1061    axum::Extension(stop): axum::Extension<tokio_util::sync::CancellationToken>,
1062    axum::extract::State(schema): axum::extract::State<KoanSchema>,
1063    protocol: async_graphql_axum::GraphQLProtocol,
1064    websocket: axum::extract::WebSocketUpgrade,
1065) -> axum::response::Response {
1066    use axum::extract::ws::{CloseFrame, Message, close_code};
1067    use futures_util::{SinkExt, StreamExt};
1068    websocket
1069        .protocols(async_graphql::http::ALL_WEBSOCKET_PROTOCOLS)
1070        .on_upgrade(move |socket| async move {
1071            let (mut sink, stream) = socket.split();
1072            let serve = async_graphql_axum::GraphQLWebSocket::new_with_pair(
1073                &mut sink, stream, schema, protocol,
1074            )
1075            .on_connection_init(move |_| async move {
1076                let mut data = async_graphql::Data::default();
1077                data.insert(user);
1078                Ok(data)
1079            })
1080            .serve();
1081            let ended = async {
1082                match lease {
1083                    Some(axum::Extension(lease)) => lease.ended().await,
1084                    None => std::future::pending().await,
1085                }
1086            };
1087            let close = tokio::select! {
1088                _ = serve => None,
1089                _ = ended => Some((close_code::NORMAL, "sign in again")),
1090                _ = stop.cancelled() => Some((close_code::AWAY, "server stopping")),
1091            };
1092            if let Some((code, reason)) = close {
1093                let _ = sink
1094                    .send(Message::Close(Some(CloseFrame {
1095                        code,
1096                        reason: reason.into(),
1097                    })))
1098                    .await;
1099            }
1100        })
1101}
1102
1103async fn graphql_playground(
1104    axum::extract::Query(params): axum::extract::Query<std::collections::HashMap<String, String>>,
1105    axum::extract::State((key, base)): axum::extract::State<(Option<Arc<String>>, String)>,
1106) -> axum::response::Response {
1107    use axum::response::IntoResponse;
1108
1109    // If an introspection key exists, require it in the URL.
1110    if let Some(ref expected) = key {
1111        let provided = params.get("introspection-key");
1112        if provided.map(|k| k.as_str()) != Some(expected.as_str()) {
1113            return (
1114                axum::http::StatusCode::FORBIDDEN,
1115                "invalid or missing introspection-key",
1116            )
1117                .into_response();
1118        }
1119    }
1120
1121    // Use async-graphql's built-in GraphiQL (self-contained, no CDN). It
1122    // resolves the endpoint against the origin, so the base path is named.
1123    // Inject the introspection key as a default header so all queries are authed.
1124    let endpoint = format!("{base}/graphql");
1125    let mut source = async_graphql::http::GraphiQLSource::build().endpoint(&endpoint);
1126    if let Some(ref k) = key {
1127        source = source.header("X-Introspection-Key", k.as_str());
1128    }
1129
1130    axum::response::Html(source.finish()).into_response()
1131}
1132
1133/// Run the server as a background daemon (fork + detach).
1134pub fn cmd_serve_daemon(
1135    port: Option<u16>,
1136    bind: Option<std::net::IpAddr>,
1137    subsonic_port: Option<u16>,
1138    playground: bool,
1139) {
1140    use std::fs;
1141    use std::process::Command;
1142
1143    require_server_url();
1144
1145    let cfg = Config::cached();
1146    let port_val = port.unwrap_or(cfg.graphql.port);
1147    let bind_val = bind.unwrap_or(cfg.graphql.bind);
1148
1149    let exe = std::env::current_exe().expect("failed to get current exe path");
1150    let mut cmd = Command::new(exe);
1151
1152    cmd.arg("--headless");
1153    cmd.arg("--port").arg(port_val.to_string());
1154    cmd.arg("--bind").arg(bind_val.to_string());
1155    if let Some(sp) = subsonic_port {
1156        cmd.arg("--subsonic").arg(sp.to_string());
1157    }
1158    if playground || cfg.graphql.playground {
1159        cmd.arg("--playground");
1160    }
1161
1162    cmd.stdin(std::process::Stdio::null());
1163    cmd.stdout(std::process::Stdio::null());
1164    cmd.stderr(std::process::Stdio::null());
1165
1166    let mut child = cmd.spawn().expect("failed to spawn daemon process");
1167    let pid = child.id();
1168
1169    let pid_path = koan_core::config::config_dir().join("koan-serve.pid");
1170    fs::write(&pid_path, pid.to_string()).ok();
1171
1172    std::thread::spawn(move || {
1173        let _ = child.wait();
1174    });
1175
1176    eprintln!("kōan daemon started (pid {}) on port {}", pid, port_val);
1177    if let Some(sp) = subsonic_port {
1178        eprintln!("  Subsonic REST on port {}", sp);
1179    }
1180    eprintln!("  PID file: {}", pid_path.display());
1181}
1182
1183// ---------------------------------------------------------------------------
1184// In-process execution (for MCP `graphql` tool)
1185// ---------------------------------------------------------------------------
1186
1187/// Execute a GraphQL query in-process (no HTTP round-trip).
1188///
1189/// There is no credential to check, so the caller states who the query runs as
1190/// and at what role — see `mcp::mcp_role`.
1191pub async fn execute_in_process(
1192    schema: &KoanSchema,
1193    query: &str,
1194    variables: Option<serde_json::Value>,
1195    caller: AuthUser,
1196) -> serde_json::Value {
1197    let mut request = async_graphql::Request::new(query).data(caller);
1198    if let Some(serde_json::Value::Object(map)) = variables {
1199        let mut gql_vars = async_graphql::Variables::default();
1200        for (k, v) in map {
1201            gql_vars.insert(
1202                async_graphql::Name::new(&k),
1203                async_graphql::Value::from_json(v).unwrap_or(async_graphql::Value::Null),
1204            );
1205        }
1206        request = request.variables(gql_vars);
1207    }
1208    let response = schema.execute(request).await;
1209    serde_json::to_value(&response).unwrap_or(serde_json::Value::Null)
1210}
1211
1212// ---------------------------------------------------------------------------
1213// Tests
1214// ---------------------------------------------------------------------------
1215
1216#[cfg(test)]
1217mod tests {
1218    use super::*;
1219    use axum::body::Body;
1220    use axum::http::{Request as HttpRequest, StatusCode};
1221    use axum::routing::{get, post};
1222    use tower::ServiceExt as _;
1223
1224    fn policy() -> Arc<BrowserPolicy> {
1225        Arc::new(BrowserPolicy {
1226            origins: vec!["https://music.example.com".into()],
1227            hosts: vec!["koan.local".into()],
1228            ..Default::default()
1229        })
1230    }
1231
1232    async fn ok() -> &'static str {
1233        "ok"
1234    }
1235
1236    fn routes() -> axum::Router<Arc<BrowserPolicy>> {
1237        axum::Router::new()
1238            .route("/graphql", post(ok).get(ok))
1239            .route("/graphql/ws", get(ok))
1240    }
1241
1242    async fn run_host(req: HttpRequest<Body>) -> StatusCode {
1243        let app = routes()
1244            .layer(axum::middleware::from_fn_with_state(policy(), host_guard))
1245            .with_state(policy());
1246        app.oneshot(req).await.unwrap().status()
1247    }
1248
1249    async fn run_browser(req: HttpRequest<Body>) -> StatusCode {
1250        let app = routes()
1251            .layer(axum::middleware::from_fn_with_state(
1252                policy(),
1253                browser_guard,
1254            ))
1255            .with_state(policy());
1256        app.oneshot(req).await.unwrap().status()
1257    }
1258
1259    fn json_post(uri: &str) -> axum::http::request::Builder {
1260        HttpRequest::post(uri).header(axum::http::header::CONTENT_TYPE, "application/json")
1261    }
1262
1263    // -- Host allowlist (DNS rebinding) --
1264
1265    /// A name that comes up while the server runs, as the Tailscale name
1266    /// does when Tailscale starts, is allowed once the names are asked
1267    /// again, which a request naming it does; another name stays refused.
1268    #[tokio::test]
1269    async fn moving_names_are_learned_from_the_request_that_names_them() {
1270        let up = Arc::new(std::sync::atomic::AtomicBool::new(false));
1271        let policy = Arc::new(BrowserPolicy {
1272            hosts: vec!["koan.local".into()],
1273            ..Default::default()
1274        });
1275        let tailscale = up.clone();
1276        let _ = policy.relearn.set(Box::new(move || {
1277            match tailscale.load(std::sync::atomic::Ordering::Relaxed) {
1278                true => vec!["mac.tailnet.ts.net".into()],
1279                false => Vec::new(),
1280            }
1281        }));
1282        let app = routes()
1283            .layer(axum::middleware::from_fn_with_state(
1284                policy.clone(),
1285                host_guard,
1286            ))
1287            .with_state(policy.clone());
1288        let ask = |host: &str| {
1289            HttpRequest::get("/graphql")
1290                .header(axum::http::header::HOST, host)
1291                .body(Body::empty())
1292                .unwrap()
1293        };
1294
1295        let status = app
1296            .clone()
1297            .oneshot(ask("mac.tailnet.ts.net"))
1298            .await
1299            .unwrap()
1300            .status();
1301        assert_eq!(status, StatusCode::FORBIDDEN, "Tailscale is stopped");
1302        up.store(true, std::sync::atomic::Ordering::Relaxed);
1303        *policy.learned_at.lock() = None;
1304        let status = app
1305            .clone()
1306            .oneshot(ask("mac.tailnet.ts.net"))
1307            .await
1308            .unwrap()
1309            .status();
1310        assert_eq!(status, StatusCode::OK, "learned once Tailscale is up");
1311        let status = app
1312            .clone()
1313            .oneshot(ask("evil.example"))
1314            .await
1315            .unwrap()
1316            .status();
1317        assert_eq!(status, StatusCode::FORBIDDEN);
1318    }
1319
1320    #[test]
1321    fn host_policy_accepts_loopback_literals_and_configured_names() {
1322        let p = policy();
1323        assert!(p.host_allowed("localhost:4000"));
1324        assert!(p.host_allowed("127.0.0.1:4000"));
1325        assert!(p.host_allowed("192.168.1.20:4000"));
1326        assert!(p.host_allowed("[::1]:4000"));
1327        assert!(p.host_allowed("koan.local"));
1328        assert!(p.host_allowed("koan.local:4000"));
1329    }
1330
1331    #[test]
1332    fn host_policy_rejects_attacker_controlled_names() {
1333        let p = policy();
1334        assert!(!p.host_allowed("evil.com"));
1335        assert!(!p.host_allowed("rebind.evil.com:4000"));
1336        assert!(!p.host_allowed("koan.local.evil.com"));
1337    }
1338
1339    #[tokio::test]
1340    async fn host_guard_rejects_foreign_host() {
1341        let req = json_post("/graphql")
1342            .header(axum::http::header::HOST, "rebind.evil.com")
1343            .body(Body::empty())
1344            .unwrap();
1345        assert_eq!(run_host(req).await, StatusCode::FORBIDDEN);
1346    }
1347
1348    #[tokio::test]
1349    async fn host_guard_allows_known_host_and_missing_host() {
1350        let req = json_post("/graphql")
1351            .header(axum::http::header::HOST, "127.0.0.1:4000")
1352            .body(Body::empty())
1353            .unwrap();
1354        assert_eq!(run_host(req).await, StatusCode::OK);
1355
1356        let req = json_post("/graphql").body(Body::empty()).unwrap();
1357        assert_eq!(run_host(req).await, StatusCode::OK);
1358    }
1359
1360    // -- Cross-site WebSocket --
1361
1362    #[tokio::test]
1363    async fn ws_upgrade_from_foreign_origin_is_rejected() {
1364        let req = HttpRequest::get("/graphql/ws")
1365            .header(axum::http::header::HOST, "127.0.0.1:4000")
1366            .header(axum::http::header::ORIGIN, "https://evil.com")
1367            .body(Body::empty())
1368            .unwrap();
1369        assert_eq!(run_browser(req).await, StatusCode::FORBIDDEN);
1370    }
1371
1372    #[tokio::test]
1373    async fn ws_upgrade_without_origin_is_allowed() {
1374        let req = HttpRequest::get("/graphql/ws")
1375            .header(axum::http::header::HOST, "127.0.0.1:4000")
1376            .body(Body::empty())
1377            .unwrap();
1378        assert_eq!(run_browser(req).await, StatusCode::OK);
1379    }
1380
1381    #[tokio::test]
1382    async fn configured_and_same_origin_are_allowed() {
1383        let req = HttpRequest::get("/graphql/ws")
1384            .header(axum::http::header::HOST, "127.0.0.1:4000")
1385            .header(axum::http::header::ORIGIN, "https://music.example.com")
1386            .body(Body::empty())
1387            .unwrap();
1388        assert_eq!(run_browser(req).await, StatusCode::OK);
1389
1390        // The bundled playground posts to the host it was served from.
1391        let req = json_post("/graphql")
1392            .header(axum::http::header::HOST, "127.0.0.1:4000")
1393            .header(axum::http::header::ORIGIN, "http://127.0.0.1:4000")
1394            .body(Body::empty())
1395            .unwrap();
1396        assert_eq!(run_browser(req).await, StatusCode::OK);
1397    }
1398
1399    // -- CSRF via a CORS-safelisted content type --
1400
1401    #[tokio::test]
1402    async fn text_plain_post_is_rejected() {
1403        let req = HttpRequest::post("/graphql")
1404            .header(axum::http::header::CONTENT_TYPE, "text/plain")
1405            .body(Body::from(r#"{"query":"mutation{clearQueue{ok}}"}"#))
1406            .unwrap();
1407        assert_eq!(run_browser(req).await, StatusCode::UNSUPPORTED_MEDIA_TYPE);
1408    }
1409
1410    #[tokio::test]
1411    async fn post_without_content_type_is_rejected() {
1412        let req = HttpRequest::post("/graphql").body(Body::empty()).unwrap();
1413        assert_eq!(run_browser(req).await, StatusCode::UNSUPPORTED_MEDIA_TYPE);
1414    }
1415
1416    // -- Load perimeter --
1417
1418    #[tokio::test]
1419    async fn load_perimeter_refuses_an_oversized_query_body() {
1420        async fn parse(_: async_graphql_axum::GraphQLRequest) -> StatusCode {
1421            StatusCode::OK
1422        }
1423        let app = load_perimeter(axum::Router::new().route("/graphql", post(parse)));
1424        // A valid query padded with whitespace, streamed so no Content-Length
1425        // warns the limit ahead of the bytes.
1426        let body = |padding: usize| {
1427            let chunks = [
1428                axum::body::Bytes::from_static(br#"{"query":"{__typename}""#),
1429                axum::body::Bytes::from(vec![b' '; padding]),
1430                axum::body::Bytes::from_static(b"}"),
1431            ];
1432            Body::from_stream(tokio_stream::iter(chunks.map(Ok::<_, std::io::Error>)))
1433        };
1434        let req = json_post("/graphql").body(body(1 << 10)).unwrap();
1435        assert_eq!(
1436            app.clone().oneshot(req).await.unwrap().status(),
1437            StatusCode::OK
1438        );
1439        let req = json_post("/graphql").body(body(3 << 20)).unwrap();
1440        assert_ne!(app.oneshot(req).await.unwrap().status(), StatusCode::OK);
1441    }
1442
1443    #[tokio::test]
1444    async fn load_perimeter_passes_requests_and_turns_panics_into_500s() {
1445        async fn boom() -> &'static str {
1446            panic!("resolver exploded");
1447        }
1448
1449        let app = load_perimeter(
1450            axum::Router::new()
1451                .route("/graphql", post(ok))
1452                .route("/boom", post(boom)),
1453        );
1454
1455        let req = json_post("/graphql").body(Body::empty()).unwrap();
1456        assert_eq!(
1457            app.clone().oneshot(req).await.unwrap().status(),
1458            StatusCode::OK
1459        );
1460
1461        // Without CatchPanicLayer this drops the connection with nothing logged.
1462        let req = json_post("/boom").body(Body::empty()).unwrap();
1463        assert_eq!(
1464            app.oneshot(req).await.unwrap().status(),
1465            StatusCode::INTERNAL_SERVER_ERROR
1466        );
1467    }
1468
1469    #[tokio::test]
1470    async fn json_post_is_accepted() {
1471        let req = json_post("/graphql").body(Body::empty()).unwrap();
1472        assert_eq!(run_browser(req).await, StatusCode::OK);
1473
1474        let req = HttpRequest::post("/graphql")
1475            .header(
1476                axum::http::header::CONTENT_TYPE,
1477                "application/json; charset=utf-8",
1478            )
1479            .body(Body::empty())
1480            .unwrap();
1481        assert_eq!(run_browser(req).await, StatusCode::OK);
1482    }
1483
1484    /// A server in an app is stopped and started again within one process:
1485    /// a stop ends its links rather than waiting them out, and leaves nothing
1486    /// behind that the next start trips over.
1487    #[test]
1488    fn an_embedded_server_ends_its_links_on_stop_and_starts_again() {
1489        use koan_core::auth::Role;
1490        use koan_core::db::connection::Database;
1491        use koan_core::player::commands::CommandChannel;
1492
1493        let _own = koan_core::config::SWITCHING
1494            .lock()
1495            .unwrap_or_else(|e| e.into_inner());
1496        let dir = tempfile::tempdir().unwrap();
1497        koan_core::config::set_config_dir(dir.path());
1498        let db_path = dir.path().join("koan.db");
1499        let db = Database::open(&db_path).unwrap();
1500        koan_core::db::schema::create_tables(&db.conn).unwrap();
1501        koan_core::db::queries::auth::create_user(&db.conn, "sharer", "hunter22", Role::Admin)
1502            .unwrap();
1503
1504        let start = || {
1505            ApiServer::start(ApiServerOpts {
1506                state: SharedPlayerState::new(),
1507                cmd_tx: CommandChannel::new().tx,
1508                pool: Arc::new(Pool::new(db_path.clone())),
1509                port: Some(0),
1510                bind: Some(std::net::Ipv4Addr::LOCALHOST.into()),
1511                subsonic_port: None,
1512                playground: false,
1513                viz: None,
1514                profile: Profile::Embedded,
1515                hosts: Vec::new(),
1516                session: None,
1517            })
1518            .unwrap()
1519        };
1520        // Subsonic answers, though `[subsonic]` is off by default.
1521        let ping = |addr: std::net::SocketAddr| {
1522            let body = reqwest::blocking::get(format!(
1523                "http://{addr}/rest/ping?u=sharer&p=hunter22&v=1.16.1&c=test&f=json"
1524            ))
1525            .unwrap()
1526            .text()
1527            .unwrap();
1528            assert!(body.contains(r#""status":"ok""#), "{body}");
1529        };
1530        let linked = || {
1531            crate::clients::registry()
1532                .list(Some("sharer"))
1533                .iter()
1534                .any(|c| c.device == "embedded-restart")
1535        };
1536
1537        let server = start();
1538        let addr = server.addr();
1539        ping(addr);
1540        let (mut socket, _) = tungstenite::connect(format!(
1541            "ws://{addr}/rest/koanLink?u=sharer&p=hunter22&v=1.16.1&c=test&device=embedded-restart"
1542        ))
1543        .unwrap();
1544        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
1545        while !linked() {
1546            assert!(
1547                std::time::Instant::now() < deadline,
1548                "the device never linked"
1549            );
1550            std::thread::sleep(std::time::Duration::from_millis(20));
1551        }
1552
1553        let stopping = std::time::Instant::now();
1554        server.stop();
1555        assert!(stopping.elapsed() < DRAIN, "stop waited out the drain");
1556        assert!(!linked(), "the link outlived the server");
1557        // The device is told, so it links again once the server is back.
1558        let closed = loop {
1559            match socket.read() {
1560                Ok(tungstenite::Message::Close(frame)) => break frame,
1561                Ok(_) => continue,
1562                Err(e) => panic!("no close frame: {e}"),
1563            }
1564        };
1565        assert_eq!(
1566            closed.map(|f| f.code),
1567            Some(tungstenite::protocol::frame::coding::CloseCode::Away)
1568        );
1569
1570        let again = start();
1571        ping(again.addr());
1572        again.stop();
1573    }
1574
1575    /// A port another process holds on loopback is taken, though the system
1576    /// would let a listener on every interface share it.
1577    #[test]
1578    fn an_embedded_server_refuses_a_port_held_on_loopback() {
1579        use koan_core::player::commands::CommandChannel;
1580
1581        let _own = koan_core::config::SWITCHING
1582            .lock()
1583            .unwrap_or_else(|e| e.into_inner());
1584        let dir = tempfile::tempdir().unwrap();
1585        koan_core::config::set_config_dir(dir.path());
1586        let held = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1587        let port = held.local_addr().unwrap().port();
1588        let started = ApiServer::start(ApiServerOpts {
1589            state: SharedPlayerState::new(),
1590            cmd_tx: CommandChannel::new().tx,
1591            pool: Arc::new(Pool::new(dir.path().join("koan.db"))),
1592            port: Some(port),
1593            bind: Some(std::net::Ipv4Addr::UNSPECIFIED.into()),
1594            subsonic_port: None,
1595            playground: false,
1596            viz: None,
1597            profile: Profile::Embedded,
1598            hosts: Vec::new(),
1599            session: None,
1600        });
1601        let Err(why) = started else {
1602            panic!("started beside another listener on port {port}");
1603        };
1604        assert!(why.contains("already in use"), "{why}");
1605    }
1606}