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::load().unwrap_or_default().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(_) => return,
30 };
31 log::error!("{why}");
32 eprintln!("koan: {why}");
33 std::process::exit(1);
34}
35
36pub fn cmd_serve(
37 port: Option<u16>,
38 bind: Option<std::net::IpAddr>,
39 subsonic_port: Option<u16>,
40 playground: bool,
41) {
42 use koan_core::player::Player;
43
44 require_server_url();
45 if let Err(e) = koan_core::db::connection::Database::open_default() {
49 log::error!("cannot open the database: {e}");
50 eprintln!("koan: cannot open the database: {e}");
51 std::process::exit(1);
52 }
53 let db_path = koan_core::config::db_path();
54 let pool = Arc::new(Pool::new(db_path.clone()));
55 koan_core::db::pool::on_outdated(|| OUTDATED.cancel());
56
57 let (state, _timeline, _viz, cmd_tx) = Player::spawn();
58
59 let watched = db_path.clone();
62 let jobs = super::jobs::JobRegistry::default();
63 let record = super::jobs::record_watch(&jobs);
64 koan_core::helpers::spawn_library_watch(db_path, move |scan| {
65 record(&scan);
66 if let koan_core::helpers::WatchScan::Finished(_) = scan {
69 crate::clients::fulfil_from(&watched);
70 if let Ok(db) = koan_core::db::connection::Database::open_existing(&watched) {
71 crate::clients::changed_if_library_moved(&db.conn);
72 }
73 }
74 });
75
76 if let Err(e) = run_api_blocking(
77 ApiServerOpts {
78 state,
79 cmd_tx,
80 pool,
81 port,
82 bind,
83 subsonic_port,
84 playground,
85 viz: None, headless: true,
87 },
88 jobs,
89 ) {
90 eprintln!("koan: {}", e);
91 std::process::exit(1);
92 }
93}
94
95const REQUEST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
102
103const MAX_INFLIGHT_QUERIES: usize = 64;
107
108const MAX_QUERY_BODY: usize = 2 << 20;
112
113fn load_perimeter<S>(router: axum::Router<S>) -> axum::Router<S>
118where
119 S: Clone + Send + Sync + 'static,
120{
121 router
122 .layer(tower_http::catch_panic::CatchPanicLayer::new())
125 .layer(tower_http::limit::RequestBodyLimitLayer::new(
126 MAX_QUERY_BODY,
127 ))
128 .layer(tower_http::timeout::TimeoutLayer::with_status_code(
129 axum::http::StatusCode::REQUEST_TIMEOUT,
130 REQUEST_TIMEOUT,
131 ))
132 .layer(
136 tower::ServiceBuilder::new()
137 .layer(axum::error_handling::HandleErrorLayer::new(
138 |err: tower::BoxError| async move {
139 if err.is::<tower::load_shed::error::Overloaded>() {
140 (
141 axum::http::StatusCode::SERVICE_UNAVAILABLE,
142 "server at capacity",
143 )
144 } else {
145 (
146 axum::http::StatusCode::INTERNAL_SERVER_ERROR,
147 "internal error",
148 )
149 }
150 },
151 ))
152 .load_shed()
153 .concurrency_limit(MAX_INFLIGHT_QUERIES),
154 )
155}
156
157pub struct ApiServerOpts {
159 pub state: Arc<SharedPlayerState>,
160 pub cmd_tx: Sender<PlayerCommand>,
161 pub pool: Arc<Pool>,
164 pub port: Option<u16>,
165 pub bind: Option<std::net::IpAddr>,
166 pub subsonic_port: Option<u16>,
167 pub playground: bool,
168 pub viz: Option<Arc<VizSnapshot>>,
169 pub headless: bool,
171}
172
173fn run_api_blocking(opts: ApiServerOpts, jobs: super::jobs::JobRegistry) -> Result<(), String> {
182 let ApiServerOpts {
183 state,
184 cmd_tx,
185 pool,
186 port,
187 bind,
188 subsonic_port,
189 playground,
190 viz,
191 headless,
192 } = opts;
193 use axum::routing::{get, post};
194
195 let cfg = Config::load().unwrap_or_default();
196 let port = port.unwrap_or(cfg.graphql.port);
197 let setup_wizard = cfg.graphql.setup_wizard && headless;
202 let bind = bind.unwrap_or(cfg.graphql.bind);
203 let subsonic_port = subsonic_port.or(cfg.subsonic.port);
204 let playground_enabled = playground || cfg.graphql.playground;
205 let auth_enabled = cfg.graphql.auth_enabled;
206
207 let (private_pem, public_pem) = if auth_enabled {
213 let kp = auth::load_or_generate_keypair().map_err(|e| {
214 format!(
215 "auth_enabled = true but the keypair could not be loaded or created: {}",
216 e
217 )
218 })?;
219 if kp.0.is_empty() || kp.1.is_empty() {
222 return Err("auth_enabled = true but the keypair files are empty. \
223 Run `koan auth regenerate-keys`."
224 .into());
225 }
226 kp
227 } else {
228 auth::load_or_generate_keypair().unwrap_or_default()
231 };
232
233 let _ = std::fs::remove_file(auth::keypair_dir().join("subsonic.key"));
236
237 let access_ttl = parse_duration_secs(&cfg.graphql.access_token_ttl).unwrap_or(900);
238 let refresh_ttl = parse_duration_secs(&cfg.graphql.refresh_token_ttl).unwrap_or(2_592_000);
239
240 let introspection_key = if playground_enabled && auth_enabled {
244 Some(Arc::new(auth::random_token().map_err(|e| {
245 format!("failed to generate introspection key: {}", e)
246 })?))
247 } else {
248 None
249 };
250
251 let auth_state = AuthState {
252 public_pem: Arc::new(public_pem.clone()),
253 auth_enabled,
254 introspection_key: introspection_key.clone(),
255 pool: pool.clone(),
256 };
257
258 crate::auth::set_signing_keys(Arc::new(private_pem.clone()), Arc::new(public_pem.clone()));
259
260 let users = Arc::new(crate::auth::password::PasswordVerifier::new(pool.clone()));
262 let auth_route_state = AuthRouteState {
263 users: users.clone(),
264 pool: pool.clone(),
265 private_pem: Arc::new(private_pem),
266 public_pem: Arc::new(public_pem),
267 access_ttl_secs: access_ttl,
268 refresh_ttl_secs: refresh_ttl,
269 cookie_secure: cfg.graphql.cookie_secure,
270 login_limiter: Arc::new(RateLimiter::default()),
271 };
272
273 koan_core::scrobbling::start(pool.path().to_path_buf());
275
276 let shutdown = tokio_util::sync::CancellationToken::new();
277 let mcp_routes = crate::mcp::router(
278 state.clone(),
279 cmd_tx.clone(),
280 auth_state.clone(),
281 cfg.server_url(),
282 headless,
283 shutdown.clone(),
284 );
285 let schema = super::build_schema_sharing(state, cmd_tx, pool.clone(), viz, jobs.clone());
286
287 if cfg.server.demo {
289 if !auth_enabled {
290 return Err("server.demo needs graphql.auth_enabled".into());
291 }
292 let db = pool.get().map_err(|e| format!("demo: {e}"))?;
293 crate::demo::start(&db.conn).map_err(|e| format!("demo: {e}"))?;
294 }
295 if auth_enabled {
296 log::info!(
297 "Auth enabled (Ed25519 JWT, access TTL {}s, refresh TTL {}s)",
298 access_ttl,
299 refresh_ttl
300 );
301 let no_accounts = pool
302 .get()
303 .ok()
304 .and_then(|db| koan_core::db::queries::auth::has_users(&db.conn).ok())
305 == Some(false);
306 if no_accounts && setup_wizard {
307 log::warn!(
308 "No accounts yet: whoever opens /setup first becomes the admin. \
309 Set graphql.setup_wizard = false to make it with `koan auth setup` instead."
310 );
311 }
312 } else {
313 log::info!("Auth disabled — all requests treated as admin");
314 }
315
316 let browser_policy = Arc::new(BrowserPolicy {
317 origins: cfg.graphql.cors_origins.clone(),
318 hosts: cfg.graphql.allowed_hosts.clone(),
319 });
320
321 if cfg.graphql.cors_origins.is_empty() {
322 log::info!("CORS: no origins configured — browsers get no cross-origin access");
323 }
324
325 let proxy_auth = crate::ui::ProxyAuth::from_config(
326 &cfg.graphql.proxy_auth_header,
327 &cfg.graphql.proxy_auth_from,
328 )?;
329
330 let rt = tokio::runtime::Runtime::new().expect("failed to create tokio runtime");
331 rt.block_on(async {
332 let query_route = load_perimeter(axum::Router::new().route("/graphql", post(graphql_handler)));
337
338 let gql_app = axum::Router::new()
339 .merge(query_route)
340 .route("/graphql/ws", get(graphql_ws_handler))
341 .layer(axum::middleware::from_fn_with_state(
342 auth_state.clone(),
343 auth_middleware,
344 ))
345 .layer(axum::middleware::from_fn_with_state(
348 browser_policy.clone(),
349 browser_guard,
350 ))
351 .with_state(schema);
352
353 let covers = Arc::new(crate::covers::Covers::in_config_dir());
357 let ui_routes = crate::ui::router(
358 pool.clone(),
359 auth_route_state.clone(),
360 auth_enabled,
361 setup_wizard,
362 covers.clone(),
363 cfg.server_url(),
364 cfg.mcp.redirect_hosts.clone(),
365 proxy_auth,
366 jobs,
367 )
368 .layer(tower_http::catch_panic::CatchPanicLayer::new());
370 let ui_routes = if cfg.server.demo {
371 ui_routes.layer(axum::middleware::from_fn(crate::demo::guard))
372 } else {
373 ui_routes
374 };
375
376 let auth_app = auth_router(auth_route_state);
378
379 let origins: Vec<axum::http::HeaderValue> = cfg
382 .graphql
383 .cors_origins
384 .iter()
385 .filter_map(|o| o.parse().ok())
386 .collect();
387 let cors = tower_http::cors::CorsLayer::new()
388 .allow_origin(origins)
389 .allow_methods([
390 axum::http::Method::GET,
391 axum::http::Method::POST,
392 axum::http::Method::OPTIONS,
393 ])
394 .allow_headers([
395 axum::http::header::AUTHORIZATION,
396 axum::http::header::CONTENT_TYPE,
397 axum::http::HeaderName::from_static("x-introspection-key"),
398 ])
399 .allow_credentials(true);
400
401
402 let share_routes = crate::share::router(
406 pool.clone(),
407 cfg.server_url(),
408 covers.clone(),
409 )
410 .layer(tower_http::catch_panic::CatchPanicLayer::new());
411 let subsonic_merged = crate::subsonic::subsonic_router(pool, covers, users).map(|sub| {
418 if cfg.server.demo {
419 sub.layer(axum::middleware::from_fn(crate::demo::guard))
420 } else {
421 sub
422 }
423 });
424 let subsonic_on_main = subsonic_merged.is_some();
425 let subsonic_dedicated = subsonic_merged.clone();
426
427 let mut app = auth_app
428 .merge(gql_app)
429 .merge(share_routes)
430 .merge(ui_routes)
431 .merge(mcp_routes);
432 if let Some(sub) = subsonic_merged {
433 app = app.merge(sub);
434 }
435 if playground_enabled {
436 app = app.route(
437 "/graphql",
438 get(graphql_playground).with_state(introspection_key.clone()),
439 );
440 }
441 let app = app.layer(cors).layer(axum::middleware::from_fn_with_state(
445 browser_policy.clone(),
446 host_guard,
447 ));
448
449 let playground_url = if playground_enabled {
451 if let Some(ref key) = introspection_key {
452 format!("http://{}:{}/graphql?introspection-key={}", bind, port, key)
453 } else {
454 format!("http://{}:{}/graphql", bind, port)
455 }
456 } else {
457 format!("http://{}:{}/graphql", bind, port)
458 };
459
460 let gql_addr = std::net::SocketAddr::new(bind, port);
461
462 let gql_listener = match tokio::net::TcpListener::bind(gql_addr).await {
463 Ok(l) => {
464 log::info!("GraphQL API on http://{}:{}/graphql", bind, port);
465 if subsonic_on_main {
466 log::info!("Subsonic REST on http://{}:{}/rest/", bind, port);
467 }
468 if playground_enabled {
469 log::info!("GraphiQL: {}", playground_url);
470 #[cfg(target_os = "macos")]
472 let _ = std::process::Command::new("open").arg(&playground_url).spawn();
473 #[cfg(target_os = "linux")]
474 let _ = std::process::Command::new("xdg-open").arg(&playground_url).spawn();
475 }
476 l
477 }
478 Err(e) => {
479 return Err(format!(
480 "failed to bind GraphQL port {port} — {e} (another instance running?)"
481 ));
482 }
483 };
484 let gql_server = axum::serve(
485 gql_listener,
486 app.into_make_service_with_connect_info::<std::net::SocketAddr>(),
487 )
488 .with_graceful_shutdown(async move {
489 shutdown_signal().await;
490 shutdown.cancel();
491 });
492
493 let extra_sub_port = subsonic_port.filter(|p| *p != port);
496 if let Some(sub_port) = extra_sub_port
497 && let Some(sub_app) = subsonic_dedicated
498 {
499 let sub_addr = std::net::SocketAddr::new(bind, sub_port);
500 match tokio::net::TcpListener::bind(sub_addr).await {
501 Ok(sub_listener) => {
502 log::info!(
503 "Subsonic REST also on http://{}:{}/rest/ (dedicated port)",
504 bind,
505 sub_port,
506 );
507 let sub_server = axum::serve(
510 sub_listener,
511 sub_app.into_make_service_with_connect_info::<std::net::SocketAddr>(),
512 )
513 .with_graceful_shutdown(shutdown_signal());
514
515 tokio::select! {
516 r = gql_server => { if let Err(e) = r { log::error!("GraphQL server error: {e}"); } },
517 r = sub_server => { if let Err(e) = r { log::error!("Subsonic server error: {e}"); } },
518 _ = drain_deadline() => log::info!("shutting down with connections still open"),
519 }
520 return Ok(());
521 }
522 Err(e) => {
523 log::warn!(
524 "Dedicated Subsonic port {} unavailable — {}. Mounted on GraphQL port only.",
525 sub_port,
526 e,
527 );
528 }
529 }
530 }
531
532 tokio::select! {
533 r = gql_server => { if let Err(e) = r { log::error!("GraphQL server error: {e}"); } },
534 _ = drain_deadline() => log::info!("shutting down with connections still open"),
535 }
536 Ok(())
537 })
538}
539
540pub fn start_api_background(
543 state: Arc<SharedPlayerState>,
544 cmd_tx: Sender<PlayerCommand>,
545 db_path: PathBuf,
546 port: Option<u16>,
547 bind: Option<std::net::IpAddr>,
548 subsonic_port: Option<u16>,
549 playground: bool,
550) {
551 if let Err(e) = run_api_blocking(
554 ApiServerOpts {
555 state,
556 cmd_tx,
557 pool: Arc::new(Pool::new(db_path)),
558 port,
559 bind,
560 subsonic_port,
561 playground,
562 viz: None,
563 headless: false,
564 },
565 Default::default(),
566 ) {
567 log::error!("API server not started: {}", e);
568 }
569}
570
571pub(crate) struct BrowserPolicy {
580 origins: Vec<String>,
581 hosts: Vec<String>,
582}
583
584impl BrowserPolicy {
585 fn host_allowed(&self, host: &str) -> bool {
586 if self.hosts.iter().any(|h| h.eq_ignore_ascii_case(host)) {
587 return true;
588 }
589 let bare = strip_port(host);
590 if self.hosts.iter().any(|h| h.eq_ignore_ascii_case(bare)) {
591 return true;
592 }
593 bare.eq_ignore_ascii_case("localhost") || bare.parse::<std::net::IpAddr>().is_ok()
596 }
597
598 fn origin_allowed(&self, origin: &str, host: Option<&str>) -> bool {
601 if self.origins.iter().any(|o| o == origin) {
602 return true;
603 }
604 match (origin.split_once("://"), host) {
605 (Some((_, authority)), Some(host)) => authority.eq_ignore_ascii_case(host),
606 _ => false,
607 }
608 }
609}
610
611fn strip_port(host: &str) -> &str {
613 if let Some(rest) = host.strip_prefix('[') {
614 return rest.split(']').next().unwrap_or(rest);
615 }
616 match host.rsplit_once(':') {
617 Some((h, port)) if !port.is_empty() && port.bytes().all(|b| b.is_ascii_digit()) => h,
618 _ => host,
619 }
620}
621
622fn header_str(request: &axum::extract::Request, name: axum::http::HeaderName) -> Option<&str> {
623 request.headers().get(name).and_then(|v| v.to_str().ok())
624}
625
626async fn host_guard(
628 axum::extract::State(policy): axum::extract::State<Arc<BrowserPolicy>>,
629 request: axum::extract::Request,
630 next: axum::middleware::Next,
631) -> axum::response::Response {
632 use axum::response::IntoResponse;
633
634 let host = header_str(&request, axum::http::header::HOST)
637 .map(str::to_owned)
638 .or_else(|| request.uri().host().map(str::to_owned));
639
640 if let Some(ref host) = host
641 && !policy.host_allowed(host)
642 {
643 log::warn!("rejected request for unrecognised Host: {}", host);
644 return (axum::http::StatusCode::FORBIDDEN, "host not allowed").into_response();
645 }
646
647 next.run(request).await
648}
649
650async fn browser_guard(
659 axum::extract::State(policy): axum::extract::State<Arc<BrowserPolicy>>,
660 request: axum::extract::Request,
661 next: axum::middleware::Next,
662) -> axum::response::Response {
663 use axum::response::IntoResponse;
664
665 let host = header_str(&request, axum::http::header::HOST).map(str::to_owned);
666 if let Some(origin) = header_str(&request, axum::http::header::ORIGIN)
668 && !policy.origin_allowed(origin, host.as_deref())
669 {
670 log::warn!(
671 "rejected GraphQL request from disallowed Origin: {}",
672 origin
673 );
674 return (axum::http::StatusCode::FORBIDDEN, "origin not allowed").into_response();
675 }
676
677 if request.method() == axum::http::Method::POST && !is_graphql_content_type(&request) {
678 return (
679 axum::http::StatusCode::UNSUPPORTED_MEDIA_TYPE,
680 "content type must be application/json or application/graphql",
681 )
682 .into_response();
683 }
684
685 next.run(request).await
686}
687
688fn is_graphql_content_type(request: &axum::extract::Request) -> bool {
689 header_str(request, axum::http::header::CONTENT_TYPE).is_some_and(|ct| {
690 let ct = ct.trim().to_ascii_lowercase();
691 ct.starts_with("application/json") || ct.starts_with("application/graphql")
692 })
693}
694
695static OUTDATED: std::sync::LazyLock<tokio_util::sync::CancellationToken> =
699 std::sync::LazyLock::new(tokio_util::sync::CancellationToken::new);
700
701async fn shutdown_signal() {
706 #[cfg(unix)]
707 {
708 use tokio::signal::unix::{SignalKind, signal};
709 let mut terminate = signal(SignalKind::terminate()).expect("failed to listen for SIGTERM");
710 tokio::select! {
711 r = tokio::signal::ctrl_c() => r.expect("failed to listen for ctrl+c"),
712 _ = terminate.recv() => {}
713 _ = OUTDATED.cancelled() => {}
714 }
715 }
716 #[cfg(not(unix))]
717 tokio::select! {
718 r = tokio::signal::ctrl_c() => r.expect("failed to listen for ctrl+c"),
719 _ = OUTDATED.cancelled() => {}
720 }
721}
722
723const DRAIN: std::time::Duration = std::time::Duration::from_secs(10);
725
726async fn drain_deadline() {
730 shutdown_signal().await;
731 tokio::time::sleep(DRAIN).await;
732}
733
734async fn graphql_handler(
735 axum::Extension(user): axum::Extension<AuthUser>,
736 axum::extract::State(schema): axum::extract::State<KoanSchema>,
737 req: async_graphql_axum::GraphQLRequest,
738) -> async_graphql_axum::GraphQLResponse {
739 let mut request = req.into_inner();
740 request = request.data(user);
743 schema.execute(request).await.into()
744}
745
746async fn graphql_ws_handler(
750 axum::Extension(user): axum::Extension<AuthUser>,
751 lease: Option<axum::Extension<crate::auth::Lease>>,
752 axum::extract::State(schema): axum::extract::State<KoanSchema>,
753 protocol: async_graphql_axum::GraphQLProtocol,
754 websocket: axum::extract::WebSocketUpgrade,
755) -> axum::response::Response {
756 use axum::extract::ws::{CloseFrame, Message, close_code};
757 use futures_util::{SinkExt, StreamExt};
758 websocket
759 .protocols(async_graphql::http::ALL_WEBSOCKET_PROTOCOLS)
760 .on_upgrade(move |socket| async move {
761 let (mut sink, stream) = socket.split();
762 let serve = async_graphql_axum::GraphQLWebSocket::new_with_pair(
763 &mut sink, stream, schema, protocol,
764 )
765 .on_connection_init(move |_| async move {
766 let mut data = async_graphql::Data::default();
767 data.insert(user);
768 Ok(data)
769 })
770 .serve();
771 let ended = async {
772 match lease {
773 Some(axum::Extension(lease)) => lease.ended().await,
774 None => std::future::pending().await,
775 }
776 };
777 let ended = tokio::select! {
778 _ = serve => false,
779 _ = ended => true,
780 };
781 if ended {
782 let _ = sink
783 .send(Message::Close(Some(CloseFrame {
784 code: close_code::NORMAL,
785 reason: "sign in again".into(),
786 })))
787 .await;
788 }
789 })
790}
791
792async fn graphql_playground(
793 axum::extract::Query(params): axum::extract::Query<std::collections::HashMap<String, String>>,
794 axum::extract::State(key): axum::extract::State<Option<Arc<String>>>,
795) -> axum::response::Response {
796 use axum::response::IntoResponse;
797
798 if let Some(ref expected) = key {
800 let provided = params.get("introspection-key");
801 if provided.map(|k| k.as_str()) != Some(expected.as_str()) {
802 return (
803 axum::http::StatusCode::FORBIDDEN,
804 "invalid or missing introspection-key",
805 )
806 .into_response();
807 }
808 }
809
810 let mut source = async_graphql::http::GraphiQLSource::build().endpoint("/graphql");
813 if let Some(ref k) = key {
814 source = source.header("X-Introspection-Key", k.as_str());
815 }
816
817 axum::response::Html(source.finish()).into_response()
818}
819
820pub fn cmd_serve_daemon(
822 port: Option<u16>,
823 bind: Option<std::net::IpAddr>,
824 subsonic_port: Option<u16>,
825 playground: bool,
826) {
827 use std::fs;
828 use std::process::Command;
829
830 require_server_url();
831
832 let cfg = Config::load().unwrap_or_default();
833 let port_val = port.unwrap_or(cfg.graphql.port);
834 let bind_val = bind.unwrap_or(cfg.graphql.bind);
835
836 let exe = std::env::current_exe().expect("failed to get current exe path");
837 let mut cmd = Command::new(exe);
838
839 cmd.arg("--headless");
840 cmd.arg("--port").arg(port_val.to_string());
841 cmd.arg("--bind").arg(bind_val.to_string());
842 if let Some(sp) = subsonic_port {
843 cmd.arg("--subsonic").arg(sp.to_string());
844 }
845 if playground || cfg.graphql.playground {
846 cmd.arg("--playground");
847 }
848
849 cmd.stdin(std::process::Stdio::null());
850 cmd.stdout(std::process::Stdio::null());
851 cmd.stderr(std::process::Stdio::null());
852
853 let mut child = cmd.spawn().expect("failed to spawn daemon process");
854 let pid = child.id();
855
856 let pid_path = koan_core::config::config_dir().join("koan-serve.pid");
857 fs::write(&pid_path, pid.to_string()).ok();
858
859 std::thread::spawn(move || {
860 let _ = child.wait();
861 });
862
863 eprintln!("kōan daemon started (pid {}) on port {}", pid, port_val);
864 if let Some(sp) = subsonic_port {
865 eprintln!(" Subsonic REST on port {}", sp);
866 }
867 eprintln!(" PID file: {}", pid_path.display());
868}
869
870pub async fn execute_in_process(
879 schema: &KoanSchema,
880 query: &str,
881 variables: Option<serde_json::Value>,
882 caller: AuthUser,
883) -> serde_json::Value {
884 let mut request = async_graphql::Request::new(query).data(caller);
885 if let Some(serde_json::Value::Object(map)) = variables {
886 let mut gql_vars = async_graphql::Variables::default();
887 for (k, v) in map {
888 gql_vars.insert(
889 async_graphql::Name::new(&k),
890 async_graphql::Value::from_json(v).unwrap_or(async_graphql::Value::Null),
891 );
892 }
893 request = request.variables(gql_vars);
894 }
895 let response = schema.execute(request).await;
896 serde_json::to_value(&response).unwrap_or(serde_json::Value::Null)
897}
898
899#[cfg(test)]
904mod tests {
905 use super::*;
906 use axum::body::Body;
907 use axum::http::{Request as HttpRequest, StatusCode};
908 use axum::routing::{get, post};
909 use tower::ServiceExt as _;
910
911 fn policy() -> Arc<BrowserPolicy> {
912 Arc::new(BrowserPolicy {
913 origins: vec!["https://music.example.com".into()],
914 hosts: vec!["koan.local".into()],
915 })
916 }
917
918 async fn ok() -> &'static str {
919 "ok"
920 }
921
922 fn routes() -> axum::Router<Arc<BrowserPolicy>> {
923 axum::Router::new()
924 .route("/graphql", post(ok).get(ok))
925 .route("/graphql/ws", get(ok))
926 }
927
928 async fn run_host(req: HttpRequest<Body>) -> StatusCode {
929 let app = routes()
930 .layer(axum::middleware::from_fn_with_state(policy(), host_guard))
931 .with_state(policy());
932 app.oneshot(req).await.unwrap().status()
933 }
934
935 async fn run_browser(req: HttpRequest<Body>) -> StatusCode {
936 let app = routes()
937 .layer(axum::middleware::from_fn_with_state(
938 policy(),
939 browser_guard,
940 ))
941 .with_state(policy());
942 app.oneshot(req).await.unwrap().status()
943 }
944
945 fn json_post(uri: &str) -> axum::http::request::Builder {
946 HttpRequest::post(uri).header(axum::http::header::CONTENT_TYPE, "application/json")
947 }
948
949 #[test]
952 fn host_policy_accepts_loopback_literals_and_configured_names() {
953 let p = policy();
954 assert!(p.host_allowed("localhost:4000"));
955 assert!(p.host_allowed("127.0.0.1:4000"));
956 assert!(p.host_allowed("192.168.1.20:4000"));
957 assert!(p.host_allowed("[::1]:4000"));
958 assert!(p.host_allowed("koan.local"));
959 assert!(p.host_allowed("koan.local:4000"));
960 }
961
962 #[test]
963 fn host_policy_rejects_attacker_controlled_names() {
964 let p = policy();
965 assert!(!p.host_allowed("evil.com"));
966 assert!(!p.host_allowed("rebind.evil.com:4000"));
967 assert!(!p.host_allowed("koan.local.evil.com"));
968 }
969
970 #[tokio::test]
971 async fn host_guard_rejects_foreign_host() {
972 let req = json_post("/graphql")
973 .header(axum::http::header::HOST, "rebind.evil.com")
974 .body(Body::empty())
975 .unwrap();
976 assert_eq!(run_host(req).await, StatusCode::FORBIDDEN);
977 }
978
979 #[tokio::test]
980 async fn host_guard_allows_known_host_and_missing_host() {
981 let req = json_post("/graphql")
982 .header(axum::http::header::HOST, "127.0.0.1:4000")
983 .body(Body::empty())
984 .unwrap();
985 assert_eq!(run_host(req).await, StatusCode::OK);
986
987 let req = json_post("/graphql").body(Body::empty()).unwrap();
988 assert_eq!(run_host(req).await, StatusCode::OK);
989 }
990
991 #[tokio::test]
994 async fn ws_upgrade_from_foreign_origin_is_rejected() {
995 let req = HttpRequest::get("/graphql/ws")
996 .header(axum::http::header::HOST, "127.0.0.1:4000")
997 .header(axum::http::header::ORIGIN, "https://evil.com")
998 .body(Body::empty())
999 .unwrap();
1000 assert_eq!(run_browser(req).await, StatusCode::FORBIDDEN);
1001 }
1002
1003 #[tokio::test]
1004 async fn ws_upgrade_without_origin_is_allowed() {
1005 let req = HttpRequest::get("/graphql/ws")
1006 .header(axum::http::header::HOST, "127.0.0.1:4000")
1007 .body(Body::empty())
1008 .unwrap();
1009 assert_eq!(run_browser(req).await, StatusCode::OK);
1010 }
1011
1012 #[tokio::test]
1013 async fn configured_and_same_origin_are_allowed() {
1014 let req = HttpRequest::get("/graphql/ws")
1015 .header(axum::http::header::HOST, "127.0.0.1:4000")
1016 .header(axum::http::header::ORIGIN, "https://music.example.com")
1017 .body(Body::empty())
1018 .unwrap();
1019 assert_eq!(run_browser(req).await, StatusCode::OK);
1020
1021 let req = json_post("/graphql")
1023 .header(axum::http::header::HOST, "127.0.0.1:4000")
1024 .header(axum::http::header::ORIGIN, "http://127.0.0.1:4000")
1025 .body(Body::empty())
1026 .unwrap();
1027 assert_eq!(run_browser(req).await, StatusCode::OK);
1028 }
1029
1030 #[tokio::test]
1033 async fn text_plain_post_is_rejected() {
1034 let req = HttpRequest::post("/graphql")
1035 .header(axum::http::header::CONTENT_TYPE, "text/plain")
1036 .body(Body::from(r#"{"query":"mutation{clearQueue{ok}}"}"#))
1037 .unwrap();
1038 assert_eq!(run_browser(req).await, StatusCode::UNSUPPORTED_MEDIA_TYPE);
1039 }
1040
1041 #[tokio::test]
1042 async fn post_without_content_type_is_rejected() {
1043 let req = HttpRequest::post("/graphql").body(Body::empty()).unwrap();
1044 assert_eq!(run_browser(req).await, StatusCode::UNSUPPORTED_MEDIA_TYPE);
1045 }
1046
1047 #[tokio::test]
1050 async fn load_perimeter_refuses_an_oversized_query_body() {
1051 async fn parse(_: async_graphql_axum::GraphQLRequest) -> StatusCode {
1052 StatusCode::OK
1053 }
1054 let app = load_perimeter(axum::Router::new().route("/graphql", post(parse)));
1055 let body = |padding: usize| {
1058 let chunks = [
1059 axum::body::Bytes::from_static(br#"{"query":"{__typename}""#),
1060 axum::body::Bytes::from(vec![b' '; padding]),
1061 axum::body::Bytes::from_static(b"}"),
1062 ];
1063 Body::from_stream(tokio_stream::iter(chunks.map(Ok::<_, std::io::Error>)))
1064 };
1065 let req = json_post("/graphql").body(body(1 << 10)).unwrap();
1066 assert_eq!(
1067 app.clone().oneshot(req).await.unwrap().status(),
1068 StatusCode::OK
1069 );
1070 let req = json_post("/graphql").body(body(3 << 20)).unwrap();
1071 assert_ne!(app.oneshot(req).await.unwrap().status(), StatusCode::OK);
1072 }
1073
1074 #[tokio::test]
1075 async fn load_perimeter_passes_requests_and_turns_panics_into_500s() {
1076 async fn boom() -> &'static str {
1077 panic!("resolver exploded");
1078 }
1079
1080 let app = load_perimeter(
1081 axum::Router::new()
1082 .route("/graphql", post(ok))
1083 .route("/boom", post(boom)),
1084 );
1085
1086 let req = json_post("/graphql").body(Body::empty()).unwrap();
1087 assert_eq!(
1088 app.clone().oneshot(req).await.unwrap().status(),
1089 StatusCode::OK
1090 );
1091
1092 let req = json_post("/boom").body(Body::empty()).unwrap();
1094 assert_eq!(
1095 app.oneshot(req).await.unwrap().status(),
1096 StatusCode::INTERNAL_SERVER_ERROR
1097 );
1098 }
1099
1100 #[tokio::test]
1101 async fn json_post_is_accepted() {
1102 let req = json_post("/graphql").body(Body::empty()).unwrap();
1103 assert_eq!(run_browser(req).await, StatusCode::OK);
1104
1105 let req = HttpRequest::post("/graphql")
1106 .header(
1107 axum::http::header::CONTENT_TYPE,
1108 "application/json; charset=utf-8",
1109 )
1110 .body(Body::empty())
1111 .unwrap();
1112 assert_eq!(run_browser(req).await, StatusCode::OK);
1113 }
1114}