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
17fn 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 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
62 let watched = db_path.clone();
65 let jobs = super::jobs::JobRegistry::default();
66 let record = super::jobs::record_watch(&jobs);
67 koan_core::helpers::spawn_library_watch(db_path, move |scan| {
68 record(&scan);
69 if let koan_core::helpers::WatchScan::Finished(_) = scan {
72 crate::clients::fulfil_from(&watched);
73 if let Ok(db) = koan_core::db::connection::Database::open_existing(&watched) {
74 crate::clients::changed_if_library_moved(&db.conn);
75 }
76 }
77 });
78
79 let started = ApiServer::start_with(
80 ApiServerOpts {
81 state,
82 cmd_tx,
83 pool,
84 port,
85 bind,
86 subsonic_port,
87 playground,
88 viz: None, profile: Profile::Headless,
90 hosts: Vec::new(),
91 session: None,
92 },
93 jobs,
94 );
95 match started {
96 Ok(server) => server.wait(),
97 Err(e) => {
98 eprintln!("koan: {}", e);
99 std::process::exit(1);
100 }
101 }
102}
103
104const REQUEST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
111
112const MAX_INFLIGHT_QUERIES: usize = 64;
116
117const MAX_QUERY_BODY: usize = 2 << 20;
121
122fn load_perimeter<S>(router: axum::Router<S>) -> axum::Router<S>
127where
128 S: Clone + Send + Sync + 'static,
129{
130 router
131 .layer(tower_http::catch_panic::CatchPanicLayer::new())
134 .layer(tower_http::limit::RequestBodyLimitLayer::new(
135 MAX_QUERY_BODY,
136 ))
137 .layer(tower_http::timeout::TimeoutLayer::with_status_code(
138 axum::http::StatusCode::REQUEST_TIMEOUT,
139 REQUEST_TIMEOUT,
140 ))
141 .layer(
145 tower::ServiceBuilder::new()
146 .layer(axum::error_handling::HandleErrorLayer::new(
147 |err: tower::BoxError| async move {
148 if err.is::<tower::load_shed::error::Overloaded>() {
149 (
150 axum::http::StatusCode::SERVICE_UNAVAILABLE,
151 "server at capacity",
152 )
153 } else {
154 (
155 axum::http::StatusCode::INTERNAL_SERVER_ERROR,
156 "internal error",
157 )
158 }
159 },
160 ))
161 .load_shed()
162 .concurrency_limit(MAX_INFLIGHT_QUERIES),
163 )
164}
165
166#[derive(Clone, Copy, Debug, PartialEq, Eq)]
169pub enum Profile {
170 Headless,
173 Tui,
175 Embedded,
180}
181
182pub struct ApiServerOpts {
184 pub state: Arc<SharedPlayerState>,
185 pub cmd_tx: Sender<PlayerCommand>,
186 pub pool: Arc<Pool>,
189 pub port: Option<u16>,
190 pub bind: Option<std::net::IpAddr>,
191 pub subsonic_port: Option<u16>,
192 pub playground: bool,
193 pub viz: Option<Arc<VizSnapshot>>,
194 pub profile: Profile,
195 pub hosts: Vec<String>,
198 pub session: Option<&'static str>,
202}
203
204pub struct ApiServer {
207 addr: std::net::SocketAddr,
208 host_key: Option<String>,
211 stop: tokio_util::sync::CancellationToken,
212 thread: Option<std::thread::JoinHandle<()>>,
213}
214
215impl ApiServer {
216 pub fn start(opts: ApiServerOpts) -> Result<Self, String> {
226 Self::start_with(opts, Default::default())
227 }
228
229 pub(crate) fn start_with(
230 opts: ApiServerOpts,
231 jobs: super::jobs::JobRegistry,
232 ) -> Result<Self, String> {
233 let ApiServerOpts {
234 state,
235 cmd_tx,
236 pool,
237 port,
238 bind,
239 subsonic_port,
240 playground,
241 viz,
242 profile,
243 hosts,
244 session,
245 } = opts;
246 use axum::routing::{get, post};
247
248 let cfg = Config::cached();
249 let embedded = profile == Profile::Embedded;
250 let port = port.unwrap_or(cfg.graphql.port);
251 let setup_wizard = cfg.graphql.setup_wizard && profile == Profile::Headless;
255 let bind = bind.unwrap_or(cfg.graphql.bind);
256 let subsonic_port = if embedded {
258 None
259 } else {
260 subsonic_port.or(cfg.subsonic.port)
261 };
262 let subsonic_enabled = embedded || cfg.subsonic.enabled;
263 let playground_enabled = !embedded && (playground || cfg.graphql.playground);
264 let auth_enabled = cfg.graphql.auth_enabled;
265 let demo = cfg.server.demo;
266
267 if embedded && !auth_enabled {
268 return Err(
269 "graphql.auth_enabled is off, which would make anyone who reaches \
270 this port an admin"
271 .into(),
272 );
273 }
274 if demo && embedded {
275 return Err("server.demo is for a headless server".into());
276 }
277 if demo && !auth_enabled {
279 return Err("server.demo needs graphql.auth_enabled".into());
280 }
281
282 let (private_pem, public_pem) = if auth_enabled {
289 let kp = auth::load_or_generate_keypair().map_err(|e| {
290 format!(
291 "auth_enabled = true but the keypair could not be loaded or created: {}",
292 e
293 )
294 })?;
295 if kp.0.is_empty() || kp.1.is_empty() {
298 return Err("auth_enabled = true but the keypair files are empty. \
299 Run `koan auth regenerate-keys`."
300 .into());
301 }
302 kp
303 } else {
304 auth::load_or_generate_keypair().unwrap_or_default()
307 };
308
309 let access_ttl = parse_duration_secs(&cfg.graphql.access_token_ttl).unwrap_or(900);
310 let refresh_ttl = parse_duration_secs(&cfg.graphql.refresh_token_ttl).unwrap_or(2_592_000);
311
312 let introspection_key = if playground_enabled && auth_enabled {
316 Some(Arc::new(auth::random_token().map_err(|e| {
317 format!("failed to generate introspection key: {}", e)
318 })?))
319 } else {
320 None
321 };
322
323 let proxy_auth = if embedded {
324 None
325 } else {
326 crate::ui::ProxyAuth::from_config(
327 &cfg.graphql.proxy_auth_header,
328 &cfg.graphql.proxy_auth_from,
329 )?
330 };
331
332 if bind.is_unspecified() && port != 0 {
337 let loopbacks: &[std::net::IpAddr] = match bind {
339 std::net::IpAddr::V4(_) => &[std::net::Ipv4Addr::LOCALHOST.into()],
340 std::net::IpAddr::V6(_) => &[
341 std::net::Ipv4Addr::LOCALHOST.into(),
342 std::net::Ipv6Addr::LOCALHOST.into(),
343 ],
344 };
345 for loopback in loopbacks {
346 std::net::TcpListener::bind((*loopback, port))
347 .map_err(|e| format!("port {port} is already in use on this machine — {e}"))?;
348 }
349 }
350 let gql_listener = std::net::TcpListener::bind((bind, port))
351 .and_then(|l| l.set_nonblocking(true).map(|()| l))
352 .map_err(|e| {
353 format!("failed to bind GraphQL port {port} — {e} (another instance running?)")
354 })?;
355 let addr = gql_listener
356 .local_addr()
357 .map_err(|e| format!("failed to read the GraphQL listener's address — {e}"))?;
358
359 let sub_listener = subsonic_port
362 .filter(|p| subsonic_enabled && *p != port)
363 .and_then(|sub_port| {
364 match std::net::TcpListener::bind((bind, sub_port))
365 .and_then(|l| l.set_nonblocking(true).map(|()| l))
366 {
367 Ok(l) => Some(l),
368 Err(e) => {
369 log::warn!(
370 "Dedicated Subsonic port {sub_port} unavailable — {e}. Mounted on GraphQL port only."
371 );
372 None
373 }
374 }
375 });
376
377 let rt = tokio::runtime::Runtime::new()
378 .map_err(|e| format!("could not start the API server's runtime — {e}"))?;
379 let (gql_listener, sub_listener) = {
380 let _in = rt.enter();
381 let gql = tokio::net::TcpListener::from_std(gql_listener)
382 .map_err(|e| format!("failed to listen on {addr} — {e}"))?;
383 let sub = sub_listener.and_then(|l| match tokio::net::TcpListener::from_std(l) {
384 Ok(l) => Some(l),
385 Err(e) => {
386 log::warn!("Dedicated Subsonic listener unusable — {e}");
387 None
388 }
389 });
390 (gql, sub)
391 };
392
393 let host_key = embedded
394 .then(auth::random_token)
395 .transpose()
396 .map_err(|e| format!("failed to generate the host key: {e}"))?;
397
398 if demo {
399 let db = pool.get().map_err(|e| format!("demo: {e}"))?;
400 crate::demo::start(&db.conn).map_err(|e| format!("demo: {e}"))?;
401 }
402
403 let _ = std::fs::remove_file(auth::keypair_dir().join("subsonic.key"));
406
407 crate::auth::set_signing_keys(Arc::new(private_pem.clone()), Arc::new(public_pem.clone()));
408
409 let auth_state = AuthState {
410 public_pem: Arc::new(public_pem.clone()),
411 auth_enabled,
412 introspection_key: introspection_key.clone(),
413 pool: pool.clone(),
414 };
415
416 let users = Arc::new(crate::auth::password::PasswordVerifier::new(pool.clone()));
418 let auth_route_state = AuthRouteState {
419 users: users.clone(),
420 pool: pool.clone(),
421 private_pem: Arc::new(private_pem),
422 public_pem: Arc::new(public_pem),
423 access_ttl_secs: access_ttl,
424 refresh_ttl_secs: refresh_ttl,
425 cookie_secure: cfg.graphql.cookie_secure,
426 login_limiter: Arc::new(RateLimiter::default()),
427 };
428
429 koan_core::scrobbling::start(pool.path().to_path_buf());
431 let _ = crate::push::pusher();
434
435 let stop = tokio_util::sync::CancellationToken::new();
437 let mcp_routes = (!embedded).then(|| {
440 crate::mcp::router(
441 state.clone(),
442 cmd_tx.clone(),
443 auth_state.clone(),
444 cfg.server_url(),
445 profile == Profile::Headless,
446 session,
447 stop.clone(),
448 )
449 });
450 let covers = Arc::new(crate::covers::Covers::in_config_dir());
451 let schema = super::build_schema_sharing(
452 state,
453 cmd_tx,
454 pool.clone(),
455 viz,
456 jobs.clone(),
457 session,
458 Some(covers.clone()),
459 );
460
461 if auth_enabled {
462 log::info!(
463 "Auth enabled (Ed25519 JWT, access TTL {}s, refresh TTL {}s)",
464 access_ttl,
465 refresh_ttl
466 );
467 let no_accounts = pool
468 .get()
469 .ok()
470 .and_then(|db| koan_core::db::queries::auth::has_users(&db.conn).ok())
471 == Some(false);
472 if no_accounts && setup_wizard {
473 log::warn!(
474 "No accounts yet: whoever opens /setup first becomes the admin. \
475 Set graphql.setup_wizard = false to make it with `koan auth setup` instead."
476 );
477 }
478 } else {
479 log::info!("Auth disabled — all requests treated as admin");
480 }
481
482 let mut allowed_hosts = cfg.graphql.allowed_hosts.clone();
483 allowed_hosts.extend(hosts);
484 let forwarded_from = if embedded {
487 crate::auth::routes::ForwardedFrom::Loopback
488 } else {
489 crate::auth::routes::ForwardedFrom::Private
490 };
491 let browser_policy = Arc::new(BrowserPolicy {
492 origins: cfg.graphql.cors_origins.clone(),
493 hosts: allowed_hosts,
494 });
495
496 if cfg.graphql.cors_origins.is_empty() {
497 log::info!("CORS: no origins configured — browsers get no cross-origin access");
498 }
499
500 let serving = stop.clone();
501 let serving_key = host_key.clone();
502 let thread = std::thread::Builder::new()
503 .name("koan-api".into())
504 .spawn(move || {
505 let stop = serving;
506 rt.block_on(async {
507 if !embedded {
508 let stop = stop.clone();
509 tokio::spawn(async move {
510 shutdown_signal().await;
511 stop.cancel();
512 });
513 }
514
515 let query_route =
520 load_perimeter(axum::Router::new().route("/graphql", post(graphql_handler)));
521
522 let gql_app = axum::Router::new()
523 .merge(query_route)
524 .route("/graphql/ws", get(graphql_ws_handler))
525 .layer(axum::Extension(stop.clone()))
526 .layer(axum::middleware::from_fn_with_state(
527 auth_state.clone(),
528 auth_middleware,
529 ))
530 .layer(axum::middleware::from_fn_with_state(
533 browser_policy.clone(),
534 browser_guard,
535 ))
536 .with_state(schema);
537
538 if profile == Profile::Headless {
545 covers.warm(pool.clone());
546 }
547 let ui_routes = (!embedded).then(|| crate::ui::router(
548 pool.clone(),
549 auth_route_state.clone(),
550 auth_enabled,
551 setup_wizard,
552 covers.clone(),
553 cfg.server_url(),
554 cfg.mcp.redirect_hosts.clone(),
555 proxy_auth,
556 jobs,
557 )
558 .layer(tower_http::catch_panic::CatchPanicLayer::new()));
560 let ui_routes = ui_routes.map(|ui| {
561 if demo {
562 ui.layer(axum::middleware::from_fn(crate::demo::guard))
563 } else {
564 ui
565 }
566 });
567
568 let auth_app = auth_router(auth_route_state);
570
571 let origins: Vec<axum::http::HeaderValue> = cfg
574 .graphql
575 .cors_origins
576 .iter()
577 .filter_map(|o| o.parse().ok())
578 .collect();
579 let cors = tower_http::cors::CorsLayer::new()
580 .allow_origin(origins)
581 .allow_methods([
582 axum::http::Method::GET,
583 axum::http::Method::POST,
584 axum::http::Method::OPTIONS,
585 ])
586 .allow_headers([
587 axum::http::header::AUTHORIZATION,
588 axum::http::header::CONTENT_TYPE,
589 axum::http::HeaderName::from_static("x-introspection-key"),
590 ])
591 .allow_credentials(true);
592
593 let share_url = match embedded {
599 true => crate::ServerUrl::Live,
600 false => crate::ServerUrl::Fixed(cfg.server_url()),
601 };
602 let edge = axum::middleware::from_fn_with_state(
603 crate::base::Base::of(&share_url),
604 crate::base::edge,
605 );
606 let share_routes =
607 crate::share::router(pool.clone(), share_url, covers.clone())
608 .layer(tower_http::catch_panic::CatchPanicLayer::new());
609 let subsonic_merged = subsonic_enabled
616 .then(|| {
617 crate::subsonic::subsonic_router(
618 pool,
619 covers,
620 users,
621 profile,
622 stop.clone(),
623 serving_key,
624 )
625 })
626 .map(|sub| {
627 if demo {
628 sub.layer(axum::middleware::from_fn(crate::demo::guard))
629 } else {
630 sub
631 }
632 });
633 let subsonic_dedicated = subsonic_merged.clone();
634
635 let mut app = match embedded {
639 true => share_routes,
640 false => auth_app.merge(gql_app).merge(share_routes),
641 };
642 if let Some(ui) = ui_routes {
643 app = app.merge(ui);
644 }
645 if let Some(mcp) = mcp_routes {
646 app = app.merge(mcp);
647 }
648 if let Some(sub) = subsonic_merged {
649 app = app.merge(sub);
650 }
651 if playground_enabled {
652 app = app.route(
653 "/graphql",
654 get(graphql_playground).with_state((
655 introspection_key.clone(),
656 crate::base::path_of(cfg.server_url().as_deref()),
657 )),
658 );
659 }
660 let app = app
664 .layer(cors)
665 .layer(axum::middleware::from_fn_with_state(
666 browser_policy.clone(),
667 host_guard,
668 ))
669 .layer(axum::Extension(forwarded_from));
670
671 log::info!("GraphQL API on http://{addr}/graphql");
672 if subsonic_enabled {
673 log::info!("Subsonic REST on http://{addr}/rest/");
674 }
675 if playground_enabled {
676 let playground_url = match introspection_key {
677 Some(ref key) => {
678 format!("http://{addr}/graphql?introspection-key={key}")
679 }
680 None => format!("http://{addr}/graphql"),
681 };
682 log::info!("GraphiQL: {}", playground_url);
683 #[cfg(target_os = "macos")]
685 let _ = std::process::Command::new("open").arg(&playground_url).spawn();
686 #[cfg(target_os = "linux")]
687 let _ = std::process::Command::new("xdg-open")
688 .arg(&playground_url)
689 .spawn();
690 }
691 let gql_server = axum::serve(
692 gql_listener,
693 axum::ServiceExt::<axum::extract::Request>::into_make_service_with_connect_info::<std::net::SocketAddr>(
694 tower::Layer::layer(&edge, app),
695 ),
696 )
697 .with_graceful_shutdown(stop.clone().cancelled_owned());
698
699 if let Some((sub_listener, sub_app)) = sub_listener.zip(subsonic_dedicated) {
700 if let Ok(a) = sub_listener.local_addr() {
701 log::info!("Subsonic REST also on http://{a}/rest/ (dedicated port)");
702 }
703 let sub_server = axum::serve(
706 sub_listener,
707 axum::ServiceExt::<axum::extract::Request>::into_make_service_with_connect_info::<std::net::SocketAddr>(
708 tower::Layer::layer(&edge, sub_app),
709 ),
710 )
711 .with_graceful_shutdown(stop.clone().cancelled_owned());
712
713 tokio::select! {
714 r = gql_server => { if let Err(e) = r { log::error!("GraphQL server error: {e}"); } },
715 r = sub_server => { if let Err(e) = r { log::error!("Subsonic server error: {e}"); } },
716 _ = drain_deadline(&stop) => log::info!("shutting down with connections still open"),
717 }
718 return;
719 }
720
721 tokio::select! {
722 r = gql_server => { if let Err(e) = r { log::error!("GraphQL server error: {e}"); } },
723 _ = drain_deadline(&stop) => log::info!("shutting down with connections still open"),
724 }
725 });
726 rt.shutdown_timeout(DRAIN);
729 })
730 .map_err(|e| format!("could not start the API server thread — {e}"))?;
731
732 Ok(Self {
733 addr,
734 host_key,
735 stop,
736 thread: Some(thread),
737 })
738 }
739
740 pub fn host_key(&self) -> Option<&str> {
742 self.host_key.as_deref()
743 }
744
745 pub fn addr(&self) -> std::net::SocketAddr {
747 self.addr
748 }
749
750 pub fn stop(mut self) {
753 self.stop.cancel();
754 self.join();
755 }
756
757 pub fn wait(mut self) {
760 self.join();
761 }
762
763 fn join(&mut self) {
764 if let Some(thread) = self.thread.take()
765 && thread.join().is_err()
766 {
767 log::error!("API server thread panicked");
768 }
769 }
770}
771
772impl Drop for ApiServer {
773 fn drop(&mut self) {
774 self.stop.cancel();
775 }
776}
777
778#[allow(clippy::too_many_arguments)]
782pub fn start_api_background(
783 state: Arc<SharedPlayerState>,
784 cmd_tx: Sender<PlayerCommand>,
785 db_path: PathBuf,
786 port: Option<u16>,
787 bind: Option<std::net::IpAddr>,
788 subsonic_port: Option<u16>,
789 playground: bool,
790 session: Option<&'static str>,
791) {
792 let started = ApiServer::start(ApiServerOpts {
793 state,
794 cmd_tx,
795 pool: Arc::new(Pool::new(db_path)),
796 port,
797 bind,
798 subsonic_port,
799 playground,
800 viz: None,
801 profile: Profile::Tui,
802 hosts: Vec::new(),
803 session,
804 });
805 match started {
806 Ok(server) => server.wait(),
807 Err(e) => log::error!("API server not started: {}", e),
808 }
809}
810
811pub(crate) struct BrowserPolicy {
820 origins: Vec<String>,
821 hosts: Vec<String>,
822}
823
824impl BrowserPolicy {
825 fn host_allowed(&self, host: &str) -> bool {
826 if self.hosts.iter().any(|h| h.eq_ignore_ascii_case(host)) {
827 return true;
828 }
829 let bare = strip_port(host);
830 if self.hosts.iter().any(|h| h.eq_ignore_ascii_case(bare)) {
831 return true;
832 }
833 bare.eq_ignore_ascii_case("localhost") || bare.parse::<std::net::IpAddr>().is_ok()
836 }
837
838 fn origin_allowed(&self, origin: &str, host: Option<&str>) -> bool {
841 if self.origins.iter().any(|o| o == origin) {
842 return true;
843 }
844 match (origin.split_once("://"), host) {
845 (Some((_, authority)), Some(host)) => authority.eq_ignore_ascii_case(host),
846 _ => false,
847 }
848 }
849}
850
851fn strip_port(host: &str) -> &str {
853 if let Some(rest) = host.strip_prefix('[') {
854 return rest.split(']').next().unwrap_or(rest);
855 }
856 match host.rsplit_once(':') {
857 Some((h, port)) if !port.is_empty() && port.bytes().all(|b| b.is_ascii_digit()) => h,
858 _ => host,
859 }
860}
861
862fn header_str(request: &axum::extract::Request, name: axum::http::HeaderName) -> Option<&str> {
863 request.headers().get(name).and_then(|v| v.to_str().ok())
864}
865
866async fn host_guard(
868 axum::extract::State(policy): axum::extract::State<Arc<BrowserPolicy>>,
869 request: axum::extract::Request,
870 next: axum::middleware::Next,
871) -> axum::response::Response {
872 use axum::response::IntoResponse;
873
874 let host = header_str(&request, axum::http::header::HOST)
877 .map(str::to_owned)
878 .or_else(|| request.uri().host().map(str::to_owned));
879
880 if let Some(ref host) = host
881 && !policy.host_allowed(host)
882 {
883 log::warn!("rejected request for unrecognised Host: {}", host);
884 return (axum::http::StatusCode::FORBIDDEN, "host not allowed").into_response();
885 }
886
887 next.run(request).await
888}
889
890async fn browser_guard(
899 axum::extract::State(policy): axum::extract::State<Arc<BrowserPolicy>>,
900 request: axum::extract::Request,
901 next: axum::middleware::Next,
902) -> axum::response::Response {
903 use axum::response::IntoResponse;
904
905 let host = header_str(&request, axum::http::header::HOST).map(str::to_owned);
906 if let Some(origin) = header_str(&request, axum::http::header::ORIGIN)
908 && !policy.origin_allowed(origin, host.as_deref())
909 {
910 log::warn!(
911 "rejected GraphQL request from disallowed Origin: {}",
912 origin
913 );
914 return (axum::http::StatusCode::FORBIDDEN, "origin not allowed").into_response();
915 }
916
917 if request.method() == axum::http::Method::POST && !is_graphql_content_type(&request) {
918 return (
919 axum::http::StatusCode::UNSUPPORTED_MEDIA_TYPE,
920 "content type must be application/json or application/graphql",
921 )
922 .into_response();
923 }
924
925 next.run(request).await
926}
927
928fn is_graphql_content_type(request: &axum::extract::Request) -> bool {
929 header_str(request, axum::http::header::CONTENT_TYPE).is_some_and(|ct| {
930 let ct = ct.trim().to_ascii_lowercase();
931 ct.starts_with("application/json") || ct.starts_with("application/graphql")
932 })
933}
934
935static OUTDATED: std::sync::LazyLock<tokio_util::sync::CancellationToken> =
939 std::sync::LazyLock::new(tokio_util::sync::CancellationToken::new);
940
941async fn shutdown_signal() {
946 #[cfg(unix)]
947 {
948 use tokio::signal::unix::{SignalKind, signal};
949 let mut terminate = signal(SignalKind::terminate()).expect("failed to listen for SIGTERM");
950 tokio::select! {
951 r = tokio::signal::ctrl_c() => r.expect("failed to listen for ctrl+c"),
952 _ = terminate.recv() => {}
953 _ = OUTDATED.cancelled() => {}
954 }
955 }
956 #[cfg(not(unix))]
957 tokio::select! {
958 r = tokio::signal::ctrl_c() => r.expect("failed to listen for ctrl+c"),
959 _ = OUTDATED.cancelled() => {}
960 }
961}
962
963const DRAIN: std::time::Duration = std::time::Duration::from_secs(10);
965
966async fn drain_deadline(stop: &tokio_util::sync::CancellationToken) {
970 stop.cancelled().await;
971 tokio::time::sleep(DRAIN).await;
972}
973
974async fn graphql_handler(
975 axum::Extension(user): axum::Extension<AuthUser>,
976 axum::extract::State(schema): axum::extract::State<KoanSchema>,
977 req: async_graphql_axum::GraphQLRequest,
978) -> async_graphql_axum::GraphQLResponse {
979 let mut request = req.into_inner();
980 request = request.data(user);
983 schema.execute(request).await.into()
984}
985
986async fn graphql_ws_handler(
991 axum::Extension(user): axum::Extension<AuthUser>,
992 lease: Option<axum::Extension<crate::auth::Lease>>,
993 axum::Extension(stop): axum::Extension<tokio_util::sync::CancellationToken>,
994 axum::extract::State(schema): axum::extract::State<KoanSchema>,
995 protocol: async_graphql_axum::GraphQLProtocol,
996 websocket: axum::extract::WebSocketUpgrade,
997) -> axum::response::Response {
998 use axum::extract::ws::{CloseFrame, Message, close_code};
999 use futures_util::{SinkExt, StreamExt};
1000 websocket
1001 .protocols(async_graphql::http::ALL_WEBSOCKET_PROTOCOLS)
1002 .on_upgrade(move |socket| async move {
1003 let (mut sink, stream) = socket.split();
1004 let serve = async_graphql_axum::GraphQLWebSocket::new_with_pair(
1005 &mut sink, stream, schema, protocol,
1006 )
1007 .on_connection_init(move |_| async move {
1008 let mut data = async_graphql::Data::default();
1009 data.insert(user);
1010 Ok(data)
1011 })
1012 .serve();
1013 let ended = async {
1014 match lease {
1015 Some(axum::Extension(lease)) => lease.ended().await,
1016 None => std::future::pending().await,
1017 }
1018 };
1019 let close = tokio::select! {
1020 _ = serve => None,
1021 _ = ended => Some((close_code::NORMAL, "sign in again")),
1022 _ = stop.cancelled() => Some((close_code::AWAY, "server stopping")),
1023 };
1024 if let Some((code, reason)) = close {
1025 let _ = sink
1026 .send(Message::Close(Some(CloseFrame {
1027 code,
1028 reason: reason.into(),
1029 })))
1030 .await;
1031 }
1032 })
1033}
1034
1035async fn graphql_playground(
1036 axum::extract::Query(params): axum::extract::Query<std::collections::HashMap<String, String>>,
1037 axum::extract::State((key, base)): axum::extract::State<(Option<Arc<String>>, String)>,
1038) -> axum::response::Response {
1039 use axum::response::IntoResponse;
1040
1041 if let Some(ref expected) = key {
1043 let provided = params.get("introspection-key");
1044 if provided.map(|k| k.as_str()) != Some(expected.as_str()) {
1045 return (
1046 axum::http::StatusCode::FORBIDDEN,
1047 "invalid or missing introspection-key",
1048 )
1049 .into_response();
1050 }
1051 }
1052
1053 let endpoint = format!("{base}/graphql");
1057 let mut source = async_graphql::http::GraphiQLSource::build().endpoint(&endpoint);
1058 if let Some(ref k) = key {
1059 source = source.header("X-Introspection-Key", k.as_str());
1060 }
1061
1062 axum::response::Html(source.finish()).into_response()
1063}
1064
1065pub fn cmd_serve_daemon(
1067 port: Option<u16>,
1068 bind: Option<std::net::IpAddr>,
1069 subsonic_port: Option<u16>,
1070 playground: bool,
1071) {
1072 use std::fs;
1073 use std::process::Command;
1074
1075 require_server_url();
1076
1077 let cfg = Config::cached();
1078 let port_val = port.unwrap_or(cfg.graphql.port);
1079 let bind_val = bind.unwrap_or(cfg.graphql.bind);
1080
1081 let exe = std::env::current_exe().expect("failed to get current exe path");
1082 let mut cmd = Command::new(exe);
1083
1084 cmd.arg("--headless");
1085 cmd.arg("--port").arg(port_val.to_string());
1086 cmd.arg("--bind").arg(bind_val.to_string());
1087 if let Some(sp) = subsonic_port {
1088 cmd.arg("--subsonic").arg(sp.to_string());
1089 }
1090 if playground || cfg.graphql.playground {
1091 cmd.arg("--playground");
1092 }
1093
1094 cmd.stdin(std::process::Stdio::null());
1095 cmd.stdout(std::process::Stdio::null());
1096 cmd.stderr(std::process::Stdio::null());
1097
1098 let mut child = cmd.spawn().expect("failed to spawn daemon process");
1099 let pid = child.id();
1100
1101 let pid_path = koan_core::config::config_dir().join("koan-serve.pid");
1102 fs::write(&pid_path, pid.to_string()).ok();
1103
1104 std::thread::spawn(move || {
1105 let _ = child.wait();
1106 });
1107
1108 eprintln!("kōan daemon started (pid {}) on port {}", pid, port_val);
1109 if let Some(sp) = subsonic_port {
1110 eprintln!(" Subsonic REST on port {}", sp);
1111 }
1112 eprintln!(" PID file: {}", pid_path.display());
1113}
1114
1115pub async fn execute_in_process(
1124 schema: &KoanSchema,
1125 query: &str,
1126 variables: Option<serde_json::Value>,
1127 caller: AuthUser,
1128) -> serde_json::Value {
1129 let mut request = async_graphql::Request::new(query).data(caller);
1130 if let Some(serde_json::Value::Object(map)) = variables {
1131 let mut gql_vars = async_graphql::Variables::default();
1132 for (k, v) in map {
1133 gql_vars.insert(
1134 async_graphql::Name::new(&k),
1135 async_graphql::Value::from_json(v).unwrap_or(async_graphql::Value::Null),
1136 );
1137 }
1138 request = request.variables(gql_vars);
1139 }
1140 let response = schema.execute(request).await;
1141 serde_json::to_value(&response).unwrap_or(serde_json::Value::Null)
1142}
1143
1144#[cfg(test)]
1149mod tests {
1150 use super::*;
1151 use axum::body::Body;
1152 use axum::http::{Request as HttpRequest, StatusCode};
1153 use axum::routing::{get, post};
1154 use tower::ServiceExt as _;
1155
1156 fn policy() -> Arc<BrowserPolicy> {
1157 Arc::new(BrowserPolicy {
1158 origins: vec!["https://music.example.com".into()],
1159 hosts: vec!["koan.local".into()],
1160 })
1161 }
1162
1163 async fn ok() -> &'static str {
1164 "ok"
1165 }
1166
1167 fn routes() -> axum::Router<Arc<BrowserPolicy>> {
1168 axum::Router::new()
1169 .route("/graphql", post(ok).get(ok))
1170 .route("/graphql/ws", get(ok))
1171 }
1172
1173 async fn run_host(req: HttpRequest<Body>) -> StatusCode {
1174 let app = routes()
1175 .layer(axum::middleware::from_fn_with_state(policy(), host_guard))
1176 .with_state(policy());
1177 app.oneshot(req).await.unwrap().status()
1178 }
1179
1180 async fn run_browser(req: HttpRequest<Body>) -> StatusCode {
1181 let app = routes()
1182 .layer(axum::middleware::from_fn_with_state(
1183 policy(),
1184 browser_guard,
1185 ))
1186 .with_state(policy());
1187 app.oneshot(req).await.unwrap().status()
1188 }
1189
1190 fn json_post(uri: &str) -> axum::http::request::Builder {
1191 HttpRequest::post(uri).header(axum::http::header::CONTENT_TYPE, "application/json")
1192 }
1193
1194 #[test]
1197 fn host_policy_accepts_loopback_literals_and_configured_names() {
1198 let p = policy();
1199 assert!(p.host_allowed("localhost:4000"));
1200 assert!(p.host_allowed("127.0.0.1:4000"));
1201 assert!(p.host_allowed("192.168.1.20:4000"));
1202 assert!(p.host_allowed("[::1]:4000"));
1203 assert!(p.host_allowed("koan.local"));
1204 assert!(p.host_allowed("koan.local:4000"));
1205 }
1206
1207 #[test]
1208 fn host_policy_rejects_attacker_controlled_names() {
1209 let p = policy();
1210 assert!(!p.host_allowed("evil.com"));
1211 assert!(!p.host_allowed("rebind.evil.com:4000"));
1212 assert!(!p.host_allowed("koan.local.evil.com"));
1213 }
1214
1215 #[tokio::test]
1216 async fn host_guard_rejects_foreign_host() {
1217 let req = json_post("/graphql")
1218 .header(axum::http::header::HOST, "rebind.evil.com")
1219 .body(Body::empty())
1220 .unwrap();
1221 assert_eq!(run_host(req).await, StatusCode::FORBIDDEN);
1222 }
1223
1224 #[tokio::test]
1225 async fn host_guard_allows_known_host_and_missing_host() {
1226 let req = json_post("/graphql")
1227 .header(axum::http::header::HOST, "127.0.0.1:4000")
1228 .body(Body::empty())
1229 .unwrap();
1230 assert_eq!(run_host(req).await, StatusCode::OK);
1231
1232 let req = json_post("/graphql").body(Body::empty()).unwrap();
1233 assert_eq!(run_host(req).await, StatusCode::OK);
1234 }
1235
1236 #[tokio::test]
1239 async fn ws_upgrade_from_foreign_origin_is_rejected() {
1240 let req = HttpRequest::get("/graphql/ws")
1241 .header(axum::http::header::HOST, "127.0.0.1:4000")
1242 .header(axum::http::header::ORIGIN, "https://evil.com")
1243 .body(Body::empty())
1244 .unwrap();
1245 assert_eq!(run_browser(req).await, StatusCode::FORBIDDEN);
1246 }
1247
1248 #[tokio::test]
1249 async fn ws_upgrade_without_origin_is_allowed() {
1250 let req = HttpRequest::get("/graphql/ws")
1251 .header(axum::http::header::HOST, "127.0.0.1:4000")
1252 .body(Body::empty())
1253 .unwrap();
1254 assert_eq!(run_browser(req).await, StatusCode::OK);
1255 }
1256
1257 #[tokio::test]
1258 async fn configured_and_same_origin_are_allowed() {
1259 let req = HttpRequest::get("/graphql/ws")
1260 .header(axum::http::header::HOST, "127.0.0.1:4000")
1261 .header(axum::http::header::ORIGIN, "https://music.example.com")
1262 .body(Body::empty())
1263 .unwrap();
1264 assert_eq!(run_browser(req).await, StatusCode::OK);
1265
1266 let req = json_post("/graphql")
1268 .header(axum::http::header::HOST, "127.0.0.1:4000")
1269 .header(axum::http::header::ORIGIN, "http://127.0.0.1:4000")
1270 .body(Body::empty())
1271 .unwrap();
1272 assert_eq!(run_browser(req).await, StatusCode::OK);
1273 }
1274
1275 #[tokio::test]
1278 async fn text_plain_post_is_rejected() {
1279 let req = HttpRequest::post("/graphql")
1280 .header(axum::http::header::CONTENT_TYPE, "text/plain")
1281 .body(Body::from(r#"{"query":"mutation{clearQueue{ok}}"}"#))
1282 .unwrap();
1283 assert_eq!(run_browser(req).await, StatusCode::UNSUPPORTED_MEDIA_TYPE);
1284 }
1285
1286 #[tokio::test]
1287 async fn post_without_content_type_is_rejected() {
1288 let req = HttpRequest::post("/graphql").body(Body::empty()).unwrap();
1289 assert_eq!(run_browser(req).await, StatusCode::UNSUPPORTED_MEDIA_TYPE);
1290 }
1291
1292 #[tokio::test]
1295 async fn load_perimeter_refuses_an_oversized_query_body() {
1296 async fn parse(_: async_graphql_axum::GraphQLRequest) -> StatusCode {
1297 StatusCode::OK
1298 }
1299 let app = load_perimeter(axum::Router::new().route("/graphql", post(parse)));
1300 let body = |padding: usize| {
1303 let chunks = [
1304 axum::body::Bytes::from_static(br#"{"query":"{__typename}""#),
1305 axum::body::Bytes::from(vec![b' '; padding]),
1306 axum::body::Bytes::from_static(b"}"),
1307 ];
1308 Body::from_stream(tokio_stream::iter(chunks.map(Ok::<_, std::io::Error>)))
1309 };
1310 let req = json_post("/graphql").body(body(1 << 10)).unwrap();
1311 assert_eq!(
1312 app.clone().oneshot(req).await.unwrap().status(),
1313 StatusCode::OK
1314 );
1315 let req = json_post("/graphql").body(body(3 << 20)).unwrap();
1316 assert_ne!(app.oneshot(req).await.unwrap().status(), StatusCode::OK);
1317 }
1318
1319 #[tokio::test]
1320 async fn load_perimeter_passes_requests_and_turns_panics_into_500s() {
1321 async fn boom() -> &'static str {
1322 panic!("resolver exploded");
1323 }
1324
1325 let app = load_perimeter(
1326 axum::Router::new()
1327 .route("/graphql", post(ok))
1328 .route("/boom", post(boom)),
1329 );
1330
1331 let req = json_post("/graphql").body(Body::empty()).unwrap();
1332 assert_eq!(
1333 app.clone().oneshot(req).await.unwrap().status(),
1334 StatusCode::OK
1335 );
1336
1337 let req = json_post("/boom").body(Body::empty()).unwrap();
1339 assert_eq!(
1340 app.oneshot(req).await.unwrap().status(),
1341 StatusCode::INTERNAL_SERVER_ERROR
1342 );
1343 }
1344
1345 #[tokio::test]
1346 async fn json_post_is_accepted() {
1347 let req = json_post("/graphql").body(Body::empty()).unwrap();
1348 assert_eq!(run_browser(req).await, StatusCode::OK);
1349
1350 let req = HttpRequest::post("/graphql")
1351 .header(
1352 axum::http::header::CONTENT_TYPE,
1353 "application/json; charset=utf-8",
1354 )
1355 .body(Body::empty())
1356 .unwrap();
1357 assert_eq!(run_browser(req).await, StatusCode::OK);
1358 }
1359
1360 #[test]
1364 fn an_embedded_server_ends_its_links_on_stop_and_starts_again() {
1365 use koan_core::auth::Role;
1366 use koan_core::db::connection::Database;
1367 use koan_core::player::commands::CommandChannel;
1368
1369 let _own = koan_core::config::SWITCHING
1370 .lock()
1371 .unwrap_or_else(|e| e.into_inner());
1372 let dir = tempfile::tempdir().unwrap();
1373 koan_core::config::set_config_dir(dir.path());
1374 let db_path = dir.path().join("koan.db");
1375 let db = Database::open(&db_path).unwrap();
1376 koan_core::db::schema::create_tables(&db.conn).unwrap();
1377 koan_core::db::queries::auth::create_user(&db.conn, "sharer", "hunter22", Role::Admin)
1378 .unwrap();
1379
1380 let start = || {
1381 ApiServer::start(ApiServerOpts {
1382 state: SharedPlayerState::new(),
1383 cmd_tx: CommandChannel::new().tx,
1384 pool: Arc::new(Pool::new(db_path.clone())),
1385 port: Some(0),
1386 bind: Some(std::net::Ipv4Addr::LOCALHOST.into()),
1387 subsonic_port: None,
1388 playground: false,
1389 viz: None,
1390 profile: Profile::Embedded,
1391 hosts: Vec::new(),
1392 session: None,
1393 })
1394 .unwrap()
1395 };
1396 let ping = |addr: std::net::SocketAddr| {
1398 let body = reqwest::blocking::get(format!(
1399 "http://{addr}/rest/ping?u=sharer&p=hunter22&v=1.16.1&c=test&f=json"
1400 ))
1401 .unwrap()
1402 .text()
1403 .unwrap();
1404 assert!(body.contains(r#""status":"ok""#), "{body}");
1405 };
1406 let linked = || {
1407 crate::clients::registry()
1408 .list(Some("sharer"))
1409 .iter()
1410 .any(|c| c.device == "embedded-restart")
1411 };
1412
1413 let server = start();
1414 let addr = server.addr();
1415 ping(addr);
1416 let (mut socket, _) = tungstenite::connect(format!(
1417 "ws://{addr}/rest/koanLink?u=sharer&p=hunter22&v=1.16.1&c=test&device=embedded-restart"
1418 ))
1419 .unwrap();
1420 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
1421 while !linked() {
1422 assert!(
1423 std::time::Instant::now() < deadline,
1424 "the device never linked"
1425 );
1426 std::thread::sleep(std::time::Duration::from_millis(20));
1427 }
1428
1429 let stopping = std::time::Instant::now();
1430 server.stop();
1431 assert!(stopping.elapsed() < DRAIN, "stop waited out the drain");
1432 assert!(!linked(), "the link outlived the server");
1433 let closed = loop {
1435 match socket.read() {
1436 Ok(tungstenite::Message::Close(frame)) => break frame,
1437 Ok(_) => continue,
1438 Err(e) => panic!("no close frame: {e}"),
1439 }
1440 };
1441 assert_eq!(
1442 closed.map(|f| f.code),
1443 Some(tungstenite::protocol::frame::coding::CloseCode::Away)
1444 );
1445
1446 let again = start();
1447 ping(again.addr());
1448 again.stop();
1449 }
1450
1451 #[test]
1454 fn an_embedded_server_refuses_a_port_held_on_loopback() {
1455 use koan_core::player::commands::CommandChannel;
1456
1457 let _own = koan_core::config::SWITCHING
1458 .lock()
1459 .unwrap_or_else(|e| e.into_inner());
1460 let dir = tempfile::tempdir().unwrap();
1461 koan_core::config::set_config_dir(dir.path());
1462 let held = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1463 let port = held.local_addr().unwrap().port();
1464 let started = ApiServer::start(ApiServerOpts {
1465 state: SharedPlayerState::new(),
1466 cmd_tx: CommandChannel::new().tx,
1467 pool: Arc::new(Pool::new(dir.path().join("koan.db"))),
1468 port: Some(port),
1469 bind: Some(std::net::Ipv4Addr::UNSPECIFIED.into()),
1470 subsonic_port: None,
1471 playground: false,
1472 viz: None,
1473 profile: Profile::Embedded,
1474 hosts: Vec::new(),
1475 session: None,
1476 });
1477 let Err(why) = started else {
1478 panic!("started beside another listener on port {port}");
1479 };
1480 assert!(why.contains("already in use"), "{why}");
1481 }
1482}