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