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 auth_enabled {
288 log::info!(
289 "Auth enabled (Ed25519 JWT, access TTL {}s, refresh TTL {}s)",
290 access_ttl,
291 refresh_ttl
292 );
293 let no_accounts = pool
294 .get()
295 .ok()
296 .and_then(|db| koan_core::db::queries::auth::has_users(&db.conn).ok())
297 == Some(false);
298 if no_accounts && setup_wizard {
299 log::warn!(
300 "No accounts yet: whoever opens /setup first becomes the admin. \
301 Set graphql.setup_wizard = false to make it with `koan auth setup` instead."
302 );
303 }
304 } else {
305 log::info!("Auth disabled — all requests treated as admin");
306 }
307
308 let browser_policy = Arc::new(BrowserPolicy {
309 origins: cfg.graphql.cors_origins.clone(),
310 hosts: cfg.graphql.allowed_hosts.clone(),
311 });
312
313 if cfg.graphql.cors_origins.is_empty() {
314 log::info!("CORS: no origins configured — browsers get no cross-origin access");
315 }
316
317 let proxy_auth = crate::ui::ProxyAuth::from_config(
318 &cfg.graphql.proxy_auth_header,
319 &cfg.graphql.proxy_auth_from,
320 )?;
321
322 let rt = tokio::runtime::Runtime::new().expect("failed to create tokio runtime");
323 rt.block_on(async {
324 let query_route = load_perimeter(axum::Router::new().route("/graphql", post(graphql_handler)));
329
330 let gql_app = axum::Router::new()
331 .merge(query_route)
332 .route("/graphql/ws", get(graphql_ws_handler))
333 .layer(axum::middleware::from_fn_with_state(
334 auth_state.clone(),
335 auth_middleware,
336 ))
337 .layer(axum::middleware::from_fn_with_state(
340 browser_policy.clone(),
341 browser_guard,
342 ))
343 .with_state(schema);
344
345 let covers = Arc::new(crate::covers::Covers::in_config_dir());
349 let ui_routes = crate::ui::router(
350 pool.clone(),
351 auth_route_state.clone(),
352 auth_enabled,
353 setup_wizard,
354 covers.clone(),
355 cfg.server_url(),
356 cfg.mcp.redirect_hosts.clone(),
357 proxy_auth,
358 jobs,
359 )
360 .layer(tower_http::catch_panic::CatchPanicLayer::new());
362
363 let auth_app = auth_router(auth_route_state);
365
366 let origins: Vec<axum::http::HeaderValue> = cfg
369 .graphql
370 .cors_origins
371 .iter()
372 .filter_map(|o| o.parse().ok())
373 .collect();
374 let cors = tower_http::cors::CorsLayer::new()
375 .allow_origin(origins)
376 .allow_methods([
377 axum::http::Method::GET,
378 axum::http::Method::POST,
379 axum::http::Method::OPTIONS,
380 ])
381 .allow_headers([
382 axum::http::header::AUTHORIZATION,
383 axum::http::header::CONTENT_TYPE,
384 axum::http::HeaderName::from_static("x-introspection-key"),
385 ])
386 .allow_credentials(true);
387
388
389 let share_routes = crate::share::router(
393 pool.clone(),
394 cfg.server_url(),
395 covers.clone(),
396 )
397 .layer(tower_http::catch_panic::CatchPanicLayer::new());
398 let subsonic_merged = crate::subsonic::subsonic_router(pool, covers, users);
403 let subsonic_on_main = subsonic_merged.is_some();
404 let subsonic_dedicated = subsonic_merged.clone();
405
406 let mut app = auth_app
407 .merge(gql_app)
408 .merge(share_routes)
409 .merge(ui_routes)
410 .merge(mcp_routes);
411 if let Some(sub) = subsonic_merged {
412 app = app.merge(sub);
413 }
414 if playground_enabled {
415 app = app.route(
416 "/graphql",
417 get(graphql_playground).with_state(introspection_key.clone()),
418 );
419 }
420 let app = app.layer(cors).layer(axum::middleware::from_fn_with_state(
424 browser_policy.clone(),
425 host_guard,
426 ));
427
428 let playground_url = if playground_enabled {
430 if let Some(ref key) = introspection_key {
431 format!("http://{}:{}/graphql?introspection-key={}", bind, port, key)
432 } else {
433 format!("http://{}:{}/graphql", bind, port)
434 }
435 } else {
436 format!("http://{}:{}/graphql", bind, port)
437 };
438
439 let gql_addr = std::net::SocketAddr::new(bind, port);
440
441 let gql_listener = match tokio::net::TcpListener::bind(gql_addr).await {
442 Ok(l) => {
443 log::info!("GraphQL API on http://{}:{}/graphql", bind, port);
444 if subsonic_on_main {
445 log::info!("Subsonic REST on http://{}:{}/rest/", bind, port);
446 }
447 if playground_enabled {
448 log::info!("GraphiQL: {}", playground_url);
449 #[cfg(target_os = "macos")]
451 let _ = std::process::Command::new("open").arg(&playground_url).spawn();
452 #[cfg(target_os = "linux")]
453 let _ = std::process::Command::new("xdg-open").arg(&playground_url).spawn();
454 }
455 l
456 }
457 Err(e) => {
458 return Err(format!(
459 "failed to bind GraphQL port {port} — {e} (another instance running?)"
460 ));
461 }
462 };
463 let gql_server = axum::serve(
464 gql_listener,
465 app.into_make_service_with_connect_info::<std::net::SocketAddr>(),
466 )
467 .with_graceful_shutdown(async move {
468 shutdown_signal().await;
469 shutdown.cancel();
470 });
471
472 let extra_sub_port = subsonic_port.filter(|p| *p != port);
475 if let Some(sub_port) = extra_sub_port
476 && let Some(sub_app) = subsonic_dedicated
477 {
478 let sub_addr = std::net::SocketAddr::new(bind, sub_port);
479 match tokio::net::TcpListener::bind(sub_addr).await {
480 Ok(sub_listener) => {
481 log::info!(
482 "Subsonic REST also on http://{}:{}/rest/ (dedicated port)",
483 bind,
484 sub_port,
485 );
486 let sub_server = axum::serve(
489 sub_listener,
490 sub_app.into_make_service_with_connect_info::<std::net::SocketAddr>(),
491 )
492 .with_graceful_shutdown(shutdown_signal());
493
494 tokio::select! {
495 r = gql_server => { if let Err(e) = r { log::error!("GraphQL server error: {e}"); } },
496 r = sub_server => { if let Err(e) = r { log::error!("Subsonic server error: {e}"); } },
497 _ = drain_deadline() => log::info!("shutting down with connections still open"),
498 }
499 return Ok(());
500 }
501 Err(e) => {
502 log::warn!(
503 "Dedicated Subsonic port {} unavailable — {}. Mounted on GraphQL port only.",
504 sub_port,
505 e,
506 );
507 }
508 }
509 }
510
511 tokio::select! {
512 r = gql_server => { if let Err(e) = r { log::error!("GraphQL server error: {e}"); } },
513 _ = drain_deadline() => log::info!("shutting down with connections still open"),
514 }
515 Ok(())
516 })
517}
518
519pub fn start_api_background(
522 state: Arc<SharedPlayerState>,
523 cmd_tx: Sender<PlayerCommand>,
524 db_path: PathBuf,
525 port: Option<u16>,
526 bind: Option<std::net::IpAddr>,
527 subsonic_port: Option<u16>,
528 playground: bool,
529) {
530 if let Err(e) = run_api_blocking(
533 ApiServerOpts {
534 state,
535 cmd_tx,
536 pool: Arc::new(Pool::new(db_path)),
537 port,
538 bind,
539 subsonic_port,
540 playground,
541 viz: None,
542 headless: false,
543 },
544 Default::default(),
545 ) {
546 log::error!("API server not started: {}", e);
547 }
548}
549
550pub(crate) struct BrowserPolicy {
559 origins: Vec<String>,
560 hosts: Vec<String>,
561}
562
563impl BrowserPolicy {
564 fn host_allowed(&self, host: &str) -> bool {
565 if self.hosts.iter().any(|h| h.eq_ignore_ascii_case(host)) {
566 return true;
567 }
568 let bare = strip_port(host);
569 if self.hosts.iter().any(|h| h.eq_ignore_ascii_case(bare)) {
570 return true;
571 }
572 bare.eq_ignore_ascii_case("localhost") || bare.parse::<std::net::IpAddr>().is_ok()
575 }
576
577 fn origin_allowed(&self, origin: &str, host: Option<&str>) -> bool {
580 if self.origins.iter().any(|o| o == origin) {
581 return true;
582 }
583 match (origin.split_once("://"), host) {
584 (Some((_, authority)), Some(host)) => authority.eq_ignore_ascii_case(host),
585 _ => false,
586 }
587 }
588}
589
590fn strip_port(host: &str) -> &str {
592 if let Some(rest) = host.strip_prefix('[') {
593 return rest.split(']').next().unwrap_or(rest);
594 }
595 match host.rsplit_once(':') {
596 Some((h, port)) if !port.is_empty() && port.bytes().all(|b| b.is_ascii_digit()) => h,
597 _ => host,
598 }
599}
600
601fn header_str(request: &axum::extract::Request, name: axum::http::HeaderName) -> Option<&str> {
602 request.headers().get(name).and_then(|v| v.to_str().ok())
603}
604
605async fn host_guard(
607 axum::extract::State(policy): axum::extract::State<Arc<BrowserPolicy>>,
608 request: axum::extract::Request,
609 next: axum::middleware::Next,
610) -> axum::response::Response {
611 use axum::response::IntoResponse;
612
613 let host = header_str(&request, axum::http::header::HOST)
616 .map(str::to_owned)
617 .or_else(|| request.uri().host().map(str::to_owned));
618
619 if let Some(ref host) = host
620 && !policy.host_allowed(host)
621 {
622 log::warn!("rejected request for unrecognised Host: {}", host);
623 return (axum::http::StatusCode::FORBIDDEN, "host not allowed").into_response();
624 }
625
626 next.run(request).await
627}
628
629async fn browser_guard(
638 axum::extract::State(policy): axum::extract::State<Arc<BrowserPolicy>>,
639 request: axum::extract::Request,
640 next: axum::middleware::Next,
641) -> axum::response::Response {
642 use axum::response::IntoResponse;
643
644 let host = header_str(&request, axum::http::header::HOST).map(str::to_owned);
645 if let Some(origin) = header_str(&request, axum::http::header::ORIGIN)
647 && !policy.origin_allowed(origin, host.as_deref())
648 {
649 log::warn!(
650 "rejected GraphQL request from disallowed Origin: {}",
651 origin
652 );
653 return (axum::http::StatusCode::FORBIDDEN, "origin not allowed").into_response();
654 }
655
656 if request.method() == axum::http::Method::POST && !is_graphql_content_type(&request) {
657 return (
658 axum::http::StatusCode::UNSUPPORTED_MEDIA_TYPE,
659 "content type must be application/json or application/graphql",
660 )
661 .into_response();
662 }
663
664 next.run(request).await
665}
666
667fn is_graphql_content_type(request: &axum::extract::Request) -> bool {
668 header_str(request, axum::http::header::CONTENT_TYPE).is_some_and(|ct| {
669 let ct = ct.trim().to_ascii_lowercase();
670 ct.starts_with("application/json") || ct.starts_with("application/graphql")
671 })
672}
673
674static OUTDATED: std::sync::LazyLock<tokio_util::sync::CancellationToken> =
678 std::sync::LazyLock::new(tokio_util::sync::CancellationToken::new);
679
680async fn shutdown_signal() {
685 #[cfg(unix)]
686 {
687 use tokio::signal::unix::{SignalKind, signal};
688 let mut terminate = signal(SignalKind::terminate()).expect("failed to listen for SIGTERM");
689 tokio::select! {
690 r = tokio::signal::ctrl_c() => r.expect("failed to listen for ctrl+c"),
691 _ = terminate.recv() => {}
692 _ = OUTDATED.cancelled() => {}
693 }
694 }
695 #[cfg(not(unix))]
696 tokio::select! {
697 r = tokio::signal::ctrl_c() => r.expect("failed to listen for ctrl+c"),
698 _ = OUTDATED.cancelled() => {}
699 }
700}
701
702const DRAIN: std::time::Duration = std::time::Duration::from_secs(10);
704
705async fn drain_deadline() {
709 shutdown_signal().await;
710 tokio::time::sleep(DRAIN).await;
711}
712
713async fn graphql_handler(
714 axum::Extension(user): axum::Extension<AuthUser>,
715 axum::extract::State(schema): axum::extract::State<KoanSchema>,
716 req: async_graphql_axum::GraphQLRequest,
717) -> async_graphql_axum::GraphQLResponse {
718 let mut request = req.into_inner();
719 request = request.data(user);
722 schema.execute(request).await.into()
723}
724
725async fn graphql_ws_handler(
729 axum::Extension(user): axum::Extension<AuthUser>,
730 lease: Option<axum::Extension<crate::auth::Lease>>,
731 axum::extract::State(schema): axum::extract::State<KoanSchema>,
732 protocol: async_graphql_axum::GraphQLProtocol,
733 websocket: axum::extract::WebSocketUpgrade,
734) -> axum::response::Response {
735 use axum::extract::ws::{CloseFrame, Message, close_code};
736 use futures_util::{SinkExt, StreamExt};
737 websocket
738 .protocols(async_graphql::http::ALL_WEBSOCKET_PROTOCOLS)
739 .on_upgrade(move |socket| async move {
740 let (mut sink, stream) = socket.split();
741 let serve = async_graphql_axum::GraphQLWebSocket::new_with_pair(
742 &mut sink, stream, schema, protocol,
743 )
744 .on_connection_init(move |_| async move {
745 let mut data = async_graphql::Data::default();
746 data.insert(user);
747 Ok(data)
748 })
749 .serve();
750 let ended = async {
751 match lease {
752 Some(axum::Extension(lease)) => lease.ended().await,
753 None => std::future::pending().await,
754 }
755 };
756 let ended = tokio::select! {
757 _ = serve => false,
758 _ = ended => true,
759 };
760 if ended {
761 let _ = sink
762 .send(Message::Close(Some(CloseFrame {
763 code: close_code::NORMAL,
764 reason: "sign in again".into(),
765 })))
766 .await;
767 }
768 })
769}
770
771async fn graphql_playground(
772 axum::extract::Query(params): axum::extract::Query<std::collections::HashMap<String, String>>,
773 axum::extract::State(key): axum::extract::State<Option<Arc<String>>>,
774) -> axum::response::Response {
775 use axum::response::IntoResponse;
776
777 if let Some(ref expected) = key {
779 let provided = params.get("introspection-key");
780 if provided.map(|k| k.as_str()) != Some(expected.as_str()) {
781 return (
782 axum::http::StatusCode::FORBIDDEN,
783 "invalid or missing introspection-key",
784 )
785 .into_response();
786 }
787 }
788
789 let mut source = async_graphql::http::GraphiQLSource::build().endpoint("/graphql");
792 if let Some(ref k) = key {
793 source = source.header("X-Introspection-Key", k.as_str());
794 }
795
796 axum::response::Html(source.finish()).into_response()
797}
798
799pub fn cmd_serve_daemon(
801 port: Option<u16>,
802 bind: Option<std::net::IpAddr>,
803 subsonic_port: Option<u16>,
804 playground: bool,
805) {
806 use std::fs;
807 use std::process::Command;
808
809 require_server_url();
810
811 let cfg = Config::load().unwrap_or_default();
812 let port_val = port.unwrap_or(cfg.graphql.port);
813 let bind_val = bind.unwrap_or(cfg.graphql.bind);
814
815 let exe = std::env::current_exe().expect("failed to get current exe path");
816 let mut cmd = Command::new(exe);
817
818 cmd.arg("--headless");
819 cmd.arg("--port").arg(port_val.to_string());
820 cmd.arg("--bind").arg(bind_val.to_string());
821 if let Some(sp) = subsonic_port {
822 cmd.arg("--subsonic").arg(sp.to_string());
823 }
824 if playground || cfg.graphql.playground {
825 cmd.arg("--playground");
826 }
827
828 cmd.stdin(std::process::Stdio::null());
829 cmd.stdout(std::process::Stdio::null());
830 cmd.stderr(std::process::Stdio::null());
831
832 let mut child = cmd.spawn().expect("failed to spawn daemon process");
833 let pid = child.id();
834
835 let pid_path = koan_core::config::config_dir().join("koan-serve.pid");
836 fs::write(&pid_path, pid.to_string()).ok();
837
838 std::thread::spawn(move || {
839 let _ = child.wait();
840 });
841
842 eprintln!("kōan daemon started (pid {}) on port {}", pid, port_val);
843 if let Some(sp) = subsonic_port {
844 eprintln!(" Subsonic REST on port {}", sp);
845 }
846 eprintln!(" PID file: {}", pid_path.display());
847}
848
849pub async fn execute_in_process(
858 schema: &KoanSchema,
859 query: &str,
860 variables: Option<serde_json::Value>,
861 caller: AuthUser,
862) -> serde_json::Value {
863 let mut request = async_graphql::Request::new(query).data(caller);
864 if let Some(serde_json::Value::Object(map)) = variables {
865 let mut gql_vars = async_graphql::Variables::default();
866 for (k, v) in map {
867 gql_vars.insert(
868 async_graphql::Name::new(&k),
869 async_graphql::Value::from_json(v).unwrap_or(async_graphql::Value::Null),
870 );
871 }
872 request = request.variables(gql_vars);
873 }
874 let response = schema.execute(request).await;
875 serde_json::to_value(&response).unwrap_or(serde_json::Value::Null)
876}
877
878#[cfg(test)]
883mod tests {
884 use super::*;
885 use axum::body::Body;
886 use axum::http::{Request as HttpRequest, StatusCode};
887 use axum::routing::{get, post};
888 use tower::ServiceExt as _;
889
890 fn policy() -> Arc<BrowserPolicy> {
891 Arc::new(BrowserPolicy {
892 origins: vec!["https://music.example.com".into()],
893 hosts: vec!["koan.local".into()],
894 })
895 }
896
897 async fn ok() -> &'static str {
898 "ok"
899 }
900
901 fn routes() -> axum::Router<Arc<BrowserPolicy>> {
902 axum::Router::new()
903 .route("/graphql", post(ok).get(ok))
904 .route("/graphql/ws", get(ok))
905 }
906
907 async fn run_host(req: HttpRequest<Body>) -> StatusCode {
908 let app = routes()
909 .layer(axum::middleware::from_fn_with_state(policy(), host_guard))
910 .with_state(policy());
911 app.oneshot(req).await.unwrap().status()
912 }
913
914 async fn run_browser(req: HttpRequest<Body>) -> StatusCode {
915 let app = routes()
916 .layer(axum::middleware::from_fn_with_state(
917 policy(),
918 browser_guard,
919 ))
920 .with_state(policy());
921 app.oneshot(req).await.unwrap().status()
922 }
923
924 fn json_post(uri: &str) -> axum::http::request::Builder {
925 HttpRequest::post(uri).header(axum::http::header::CONTENT_TYPE, "application/json")
926 }
927
928 #[test]
931 fn host_policy_accepts_loopback_literals_and_configured_names() {
932 let p = policy();
933 assert!(p.host_allowed("localhost:4000"));
934 assert!(p.host_allowed("127.0.0.1:4000"));
935 assert!(p.host_allowed("192.168.1.20:4000"));
936 assert!(p.host_allowed("[::1]:4000"));
937 assert!(p.host_allowed("koan.local"));
938 assert!(p.host_allowed("koan.local:4000"));
939 }
940
941 #[test]
942 fn host_policy_rejects_attacker_controlled_names() {
943 let p = policy();
944 assert!(!p.host_allowed("evil.com"));
945 assert!(!p.host_allowed("rebind.evil.com:4000"));
946 assert!(!p.host_allowed("koan.local.evil.com"));
947 }
948
949 #[tokio::test]
950 async fn host_guard_rejects_foreign_host() {
951 let req = json_post("/graphql")
952 .header(axum::http::header::HOST, "rebind.evil.com")
953 .body(Body::empty())
954 .unwrap();
955 assert_eq!(run_host(req).await, StatusCode::FORBIDDEN);
956 }
957
958 #[tokio::test]
959 async fn host_guard_allows_known_host_and_missing_host() {
960 let req = json_post("/graphql")
961 .header(axum::http::header::HOST, "127.0.0.1:4000")
962 .body(Body::empty())
963 .unwrap();
964 assert_eq!(run_host(req).await, StatusCode::OK);
965
966 let req = json_post("/graphql").body(Body::empty()).unwrap();
967 assert_eq!(run_host(req).await, StatusCode::OK);
968 }
969
970 #[tokio::test]
973 async fn ws_upgrade_from_foreign_origin_is_rejected() {
974 let req = HttpRequest::get("/graphql/ws")
975 .header(axum::http::header::HOST, "127.0.0.1:4000")
976 .header(axum::http::header::ORIGIN, "https://evil.com")
977 .body(Body::empty())
978 .unwrap();
979 assert_eq!(run_browser(req).await, StatusCode::FORBIDDEN);
980 }
981
982 #[tokio::test]
983 async fn ws_upgrade_without_origin_is_allowed() {
984 let req = HttpRequest::get("/graphql/ws")
985 .header(axum::http::header::HOST, "127.0.0.1:4000")
986 .body(Body::empty())
987 .unwrap();
988 assert_eq!(run_browser(req).await, StatusCode::OK);
989 }
990
991 #[tokio::test]
992 async fn configured_and_same_origin_are_allowed() {
993 let req = HttpRequest::get("/graphql/ws")
994 .header(axum::http::header::HOST, "127.0.0.1:4000")
995 .header(axum::http::header::ORIGIN, "https://music.example.com")
996 .body(Body::empty())
997 .unwrap();
998 assert_eq!(run_browser(req).await, StatusCode::OK);
999
1000 let req = json_post("/graphql")
1002 .header(axum::http::header::HOST, "127.0.0.1:4000")
1003 .header(axum::http::header::ORIGIN, "http://127.0.0.1:4000")
1004 .body(Body::empty())
1005 .unwrap();
1006 assert_eq!(run_browser(req).await, StatusCode::OK);
1007 }
1008
1009 #[tokio::test]
1012 async fn text_plain_post_is_rejected() {
1013 let req = HttpRequest::post("/graphql")
1014 .header(axum::http::header::CONTENT_TYPE, "text/plain")
1015 .body(Body::from(r#"{"query":"mutation{clearQueue{ok}}"}"#))
1016 .unwrap();
1017 assert_eq!(run_browser(req).await, StatusCode::UNSUPPORTED_MEDIA_TYPE);
1018 }
1019
1020 #[tokio::test]
1021 async fn post_without_content_type_is_rejected() {
1022 let req = HttpRequest::post("/graphql").body(Body::empty()).unwrap();
1023 assert_eq!(run_browser(req).await, StatusCode::UNSUPPORTED_MEDIA_TYPE);
1024 }
1025
1026 #[tokio::test]
1029 async fn load_perimeter_refuses_an_oversized_query_body() {
1030 async fn parse(_: async_graphql_axum::GraphQLRequest) -> StatusCode {
1031 StatusCode::OK
1032 }
1033 let app = load_perimeter(axum::Router::new().route("/graphql", post(parse)));
1034 let body = |padding: usize| {
1037 let chunks = [
1038 axum::body::Bytes::from_static(br#"{"query":"{__typename}""#),
1039 axum::body::Bytes::from(vec![b' '; padding]),
1040 axum::body::Bytes::from_static(b"}"),
1041 ];
1042 Body::from_stream(tokio_stream::iter(chunks.map(Ok::<_, std::io::Error>)))
1043 };
1044 let req = json_post("/graphql").body(body(1 << 10)).unwrap();
1045 assert_eq!(
1046 app.clone().oneshot(req).await.unwrap().status(),
1047 StatusCode::OK
1048 );
1049 let req = json_post("/graphql").body(body(3 << 20)).unwrap();
1050 assert_ne!(app.oneshot(req).await.unwrap().status(), StatusCode::OK);
1051 }
1052
1053 #[tokio::test]
1054 async fn load_perimeter_passes_requests_and_turns_panics_into_500s() {
1055 async fn boom() -> &'static str {
1056 panic!("resolver exploded");
1057 }
1058
1059 let app = load_perimeter(
1060 axum::Router::new()
1061 .route("/graphql", post(ok))
1062 .route("/boom", post(boom)),
1063 );
1064
1065 let req = json_post("/graphql").body(Body::empty()).unwrap();
1066 assert_eq!(
1067 app.clone().oneshot(req).await.unwrap().status(),
1068 StatusCode::OK
1069 );
1070
1071 let req = json_post("/boom").body(Body::empty()).unwrap();
1073 assert_eq!(
1074 app.oneshot(req).await.unwrap().status(),
1075 StatusCode::INTERNAL_SERVER_ERROR
1076 );
1077 }
1078
1079 #[tokio::test]
1080 async fn json_post_is_accepted() {
1081 let req = json_post("/graphql").body(Body::empty()).unwrap();
1082 assert_eq!(run_browser(req).await, StatusCode::OK);
1083
1084 let req = HttpRequest::post("/graphql")
1085 .header(
1086 axum::http::header::CONTENT_TYPE,
1087 "application/json; charset=utf-8",
1088 )
1089 .body(Body::empty())
1090 .unwrap();
1091 assert_eq!(run_browser(req).await, StatusCode::OK);
1092 }
1093}