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