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 koan_core::artist_info::start();
64
65 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 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, 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
107const REQUEST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
114
115const MAX_INFLIGHT_QUERIES: usize = 64;
119
120const MAX_QUERY_BODY: usize = 2 << 20;
124
125fn load_perimeter<S>(router: axum::Router<S>) -> axum::Router<S>
130where
131 S: Clone + Send + Sync + 'static,
132{
133 router
134 .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 .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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
172pub enum Profile {
173 Headless,
176 Tui,
178 Embedded,
183}
184
185pub struct ApiServerOpts {
187 pub state: Arc<SharedPlayerState>,
188 pub cmd_tx: Sender<PlayerCommand>,
189 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 pub hosts: Vec<String>,
201 pub session: Option<&'static str>,
205}
206
207pub struct ApiServer {
210 addr: std::net::SocketAddr,
211 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 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 let setup_wizard = cfg.graphql.setup_wizard && profile == Profile::Headless;
259 let bind = bind.unwrap_or(cfg.graphql.bind);
260 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 if demo && !auth_enabled {
283 return Err("server.demo needs graphql.auth_enabled".into());
284 }
285
286 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 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 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 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 if bind.is_unspecified() && port != 0 {
341 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 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 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 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 koan_core::scrobbling::start(pool.path().to_path_buf());
435 let _ = crate::push::pusher();
438
439 let stop = tokio_util::sync::CancellationToken::new();
441 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 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 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 .layer(axum::middleware::from_fn_with_state(
539 browser_policy.clone(),
540 browser_guard,
541 ))
542 .with_state(schema);
543
544 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 .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 let auth_app = auth_router(auth_route_state);
576
577 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 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 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 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 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 #[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 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 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 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 pub fn host_key(&self) -> Option<&str> {
760 self.host_key.as_deref()
761 }
762
763 pub fn addr(&self) -> std::net::SocketAddr {
765 self.addr
766 }
767
768 pub fn stop(mut self) {
771 self.stop.cancel();
772 self.join();
773 }
774
775 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#[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#[derive(Default)]
838pub(crate) struct BrowserPolicy {
839 origins: Vec<String>,
840 hosts: Vec<String>,
841 learned: parking_lot::RwLock<Vec<String>>,
843 relearn: std::sync::OnceLock<Relearn>,
845 learned_at: parking_lot::Mutex<Option<std::time::Instant>>,
848}
849
850type Relearn = Box<dyn Fn() -> Vec<String> + Send + Sync>;
851
852const 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 bare.eq_ignore_ascii_case("localhost") || bare.parse::<std::net::IpAddr>().is_ok()
870 }
871
872 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 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 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
914fn 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
929async 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 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
958async 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 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
1003static OUTDATED: std::sync::LazyLock<tokio_util::sync::CancellationToken> =
1007 std::sync::LazyLock::new(tokio_util::sync::CancellationToken::new);
1008
1009async 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
1031const DRAIN: std::time::Duration = std::time::Duration::from_secs(10);
1033
1034async 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 request = request.data(user);
1051 schema.execute(request).await.into()
1052}
1053
1054async 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 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 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
1133pub 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
1183pub 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#[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 #[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 #[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 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 #[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 #[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 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 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 #[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 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 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 #[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}