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, build_schema};
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 let _db = koan_core::db::connection::Database::open_default().expect("failed to open database");
31 let db_path = koan_core::config::db_path();
32 let pool = Arc::new(Pool::new(db_path.clone()));
33
34 let (state, _timeline, _viz, cmd_tx) = Player::spawn();
35
36 let watched = db_path.clone();
39 koan_core::helpers::spawn_library_watch(db_path, move |running| {
40 if !running {
43 crate::clients::fulfil_from(&watched);
44 if let Ok(db) = koan_core::db::connection::Database::open_existing(&watched) {
45 crate::clients::changed_if_library_moved(&db.conn);
46 }
47 }
48 });
49
50 if let Err(e) = run_api_blocking(ApiServerOpts {
51 state,
52 cmd_tx,
53 pool,
54 port,
55 bind,
56 subsonic_port,
57 playground,
58 viz: None, headless: true,
60 }) {
61 eprintln!("koan: {}", e);
62 std::process::exit(1);
63 }
64}
65
66const REQUEST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
73
74const MAX_INFLIGHT_QUERIES: usize = 64;
78
79const MAX_QUERY_BODY: usize = 2 << 20;
83
84fn load_perimeter<S>(router: axum::Router<S>) -> axum::Router<S>
89where
90 S: Clone + Send + Sync + 'static,
91{
92 router
93 .layer(tower_http::catch_panic::CatchPanicLayer::new())
96 .layer(tower_http::limit::RequestBodyLimitLayer::new(
97 MAX_QUERY_BODY,
98 ))
99 .layer(tower_http::timeout::TimeoutLayer::with_status_code(
100 axum::http::StatusCode::REQUEST_TIMEOUT,
101 REQUEST_TIMEOUT,
102 ))
103 .layer(
107 tower::ServiceBuilder::new()
108 .layer(axum::error_handling::HandleErrorLayer::new(
109 |err: tower::BoxError| async move {
110 if err.is::<tower::load_shed::error::Overloaded>() {
111 (
112 axum::http::StatusCode::SERVICE_UNAVAILABLE,
113 "server at capacity",
114 )
115 } else {
116 (
117 axum::http::StatusCode::INTERNAL_SERVER_ERROR,
118 "internal error",
119 )
120 }
121 },
122 ))
123 .load_shed()
124 .concurrency_limit(MAX_INFLIGHT_QUERIES),
125 )
126}
127
128pub struct ApiServerOpts {
130 pub state: Arc<SharedPlayerState>,
131 pub cmd_tx: Sender<PlayerCommand>,
132 pub pool: Arc<Pool>,
135 pub port: Option<u16>,
136 pub bind: Option<std::net::IpAddr>,
137 pub subsonic_port: Option<u16>,
138 pub playground: bool,
139 pub viz: Option<Arc<VizSnapshot>>,
140 pub headless: bool,
142}
143
144fn run_api_blocking(opts: ApiServerOpts) -> Result<(), String> {
150 let ApiServerOpts {
151 state,
152 cmd_tx,
153 pool,
154 port,
155 bind,
156 subsonic_port,
157 playground,
158 viz,
159 headless,
160 } = opts;
161 use axum::routing::{get, post};
162
163 let cfg = Config::load().unwrap_or_default();
164 let port = port.unwrap_or(cfg.graphql.port);
165 let bind = bind.unwrap_or(cfg.graphql.bind);
166 let subsonic_port = subsonic_port.or(cfg.subsonic.port);
167 let playground_enabled = playground || cfg.graphql.playground;
168 let auth_enabled = cfg.graphql.auth_enabled;
169
170 let (private_pem, public_pem) = if auth_enabled {
176 let kp = auth::load_or_generate_keypair().map_err(|e| {
177 format!(
178 "auth_enabled = true but the keypair could not be loaded or created: {}",
179 e
180 )
181 })?;
182 if kp.0.is_empty() || kp.1.is_empty() {
185 return Err("auth_enabled = true but the keypair files are empty. \
186 Run `koan auth regenerate-keys`."
187 .into());
188 }
189 kp
190 } else {
191 auth::load_or_generate_keypair().unwrap_or_default()
194 };
195
196 let _ = std::fs::remove_file(auth::keypair_dir().join("subsonic.key"));
199
200 let access_ttl = parse_duration_secs(&cfg.graphql.access_token_ttl).unwrap_or(900);
201 let refresh_ttl = parse_duration_secs(&cfg.graphql.refresh_token_ttl).unwrap_or(2_592_000);
202
203 let introspection_key = if playground_enabled && auth_enabled {
207 Some(Arc::new(auth::random_token().map_err(|e| {
208 format!("failed to generate introspection key: {}", e)
209 })?))
210 } else {
211 None
212 };
213
214 let auth_state = AuthState {
215 public_pem: Arc::new(public_pem.clone()),
216 auth_enabled,
217 introspection_key: introspection_key.clone(),
218 pool: pool.clone(),
219 };
220
221 crate::auth::set_signing_keys(Arc::new(private_pem.clone()), Arc::new(public_pem.clone()));
222
223 let auth_route_state = AuthRouteState {
224 pool: pool.clone(),
225 private_pem: Arc::new(private_pem),
226 public_pem: Arc::new(public_pem),
227 access_ttl_secs: access_ttl,
228 refresh_ttl_secs: refresh_ttl,
229 cookie_secure: cfg.graphql.cookie_secure,
230 login_limiter: Arc::new(RateLimiter::default()),
231 };
232
233 let shutdown = tokio_util::sync::CancellationToken::new();
234 let mcp_routes = crate::mcp::router(
235 state.clone(),
236 cmd_tx.clone(),
237 auth_state.clone(),
238 cfg.sharing.public_url.clone(),
239 headless,
240 shutdown.clone(),
241 );
242 let schema = build_schema(state, cmd_tx, pool.clone(), viz);
243
244 if auth_enabled {
245 log::info!(
246 "Auth enabled (Ed25519 JWT, access TTL {}s, refresh TTL {}s)",
247 access_ttl,
248 refresh_ttl
249 );
250 } else {
251 log::info!("Auth disabled — all requests treated as admin");
252 }
253
254 let browser_policy = Arc::new(BrowserPolicy {
255 origins: cfg.graphql.cors_origins.clone(),
256 hosts: cfg.graphql.allowed_hosts.clone(),
257 });
258
259 if cfg.graphql.cors_origins.is_empty() {
260 log::info!("CORS: no origins configured — browsers get no cross-origin access");
261 }
262
263 let rt = tokio::runtime::Runtime::new().expect("failed to create tokio runtime");
264 rt.block_on(async {
265 let query_route = load_perimeter(axum::Router::new().route("/graphql", post(graphql_handler)));
270
271 let gql_app = axum::Router::new()
272 .merge(query_route)
273 .route("/graphql/ws", get(graphql_ws_handler))
274 .layer(axum::middleware::from_fn_with_state(
275 auth_state.clone(),
276 auth_middleware,
277 ))
278 .layer(axum::middleware::from_fn_with_state(
281 browser_policy.clone(),
282 browser_guard,
283 ))
284 .with_state(schema);
285
286 let covers = Arc::new(crate::covers::Covers::in_config_dir());
290 let ui_routes = crate::ui::router(
291 pool.clone(),
292 auth_route_state.clone(),
293 auth_enabled,
294 covers.clone(),
295 cfg.sharing.public_url.clone(),
296 cfg.mcp.redirect_hosts.clone(),
297 );
298
299 let auth_app = auth_router(auth_route_state);
301
302 let origins: Vec<axum::http::HeaderValue> = cfg
305 .graphql
306 .cors_origins
307 .iter()
308 .filter_map(|o| o.parse().ok())
309 .collect();
310 let cors = tower_http::cors::CorsLayer::new()
311 .allow_origin(origins)
312 .allow_methods([
313 axum::http::Method::GET,
314 axum::http::Method::POST,
315 axum::http::Method::OPTIONS,
316 ])
317 .allow_headers([
318 axum::http::header::AUTHORIZATION,
319 axum::http::header::CONTENT_TYPE,
320 axum::http::HeaderName::from_static("x-introspection-key"),
321 ])
322 .allow_credentials(true);
323
324
325 let share_routes = crate::share::router(
329 pool.clone(),
330 cfg.sharing.public_url.clone(),
331 covers.clone(),
332 )
333 .merge(crate::push::router(pool.clone(), covers.clone()));
334 let subsonic_merged = crate::subsonic::subsonic_router(pool, covers);
339 let subsonic_on_main = subsonic_merged.is_some();
340 let subsonic_dedicated = subsonic_merged.clone();
341
342 let mut app = auth_app
343 .merge(gql_app)
344 .merge(share_routes)
345 .merge(ui_routes)
346 .merge(mcp_routes);
347 if let Some(sub) = subsonic_merged {
348 app = app.merge(sub);
349 }
350 if playground_enabled {
351 app = app.route(
352 "/graphql",
353 get(graphql_playground).with_state(introspection_key.clone()),
354 );
355 }
356 let app = app.layer(cors).layer(axum::middleware::from_fn_with_state(
360 browser_policy.clone(),
361 host_guard,
362 ));
363
364 let playground_url = if playground_enabled {
366 if let Some(ref key) = introspection_key {
367 format!("http://{}:{}/graphql?introspection-key={}", bind, port, key)
368 } else {
369 format!("http://{}:{}/graphql", bind, port)
370 }
371 } else {
372 format!("http://{}:{}/graphql", bind, port)
373 };
374
375 let gql_addr = std::net::SocketAddr::new(bind, port);
376
377 let gql_listener = match tokio::net::TcpListener::bind(gql_addr).await {
378 Ok(l) => {
379 log::info!("GraphQL API on http://{}:{}/graphql", bind, port);
380 if subsonic_on_main {
381 log::info!("Subsonic REST on http://{}:{}/rest/", bind, port);
382 }
383 if playground_enabled {
384 log::info!("GraphiQL: {}", playground_url);
385 #[cfg(target_os = "macos")]
387 let _ = std::process::Command::new("open").arg(&playground_url).spawn();
388 #[cfg(target_os = "linux")]
389 let _ = std::process::Command::new("xdg-open").arg(&playground_url).spawn();
390 }
391 l
392 }
393 Err(e) => {
394 return Err(format!(
395 "failed to bind GraphQL port {port} — {e} (another instance running?)"
396 ));
397 }
398 };
399 let gql_server = axum::serve(
400 gql_listener,
401 app.into_make_service_with_connect_info::<std::net::SocketAddr>(),
402 )
403 .with_graceful_shutdown(async move {
404 shutdown_signal().await;
405 shutdown.cancel();
406 });
407
408 let extra_sub_port = subsonic_port.filter(|p| *p != port);
411 if let Some(sub_port) = extra_sub_port
412 && let Some(sub_app) = subsonic_dedicated
413 {
414 let sub_addr = std::net::SocketAddr::new(bind, sub_port);
415 match tokio::net::TcpListener::bind(sub_addr).await {
416 Ok(sub_listener) => {
417 log::info!(
418 "Subsonic REST also on http://{}:{}/rest/ (dedicated port)",
419 bind,
420 sub_port,
421 );
422 let sub_server = axum::serve(
425 sub_listener,
426 sub_app.into_make_service_with_connect_info::<std::net::SocketAddr>(),
427 )
428 .with_graceful_shutdown(shutdown_signal());
429
430 tokio::select! {
431 r = gql_server => { if let Err(e) = r { log::error!("GraphQL server error: {e}"); } },
432 r = sub_server => { if let Err(e) = r { log::error!("Subsonic server error: {e}"); } },
433 _ = drain_deadline() => log::info!("shutting down with connections still open"),
434 }
435 return Ok(());
436 }
437 Err(e) => {
438 log::warn!(
439 "Dedicated Subsonic port {} unavailable — {}. Mounted on GraphQL port only.",
440 sub_port,
441 e,
442 );
443 }
444 }
445 }
446
447 tokio::select! {
448 r = gql_server => { if let Err(e) = r { log::error!("GraphQL server error: {e}"); } },
449 _ = drain_deadline() => log::info!("shutting down with connections still open"),
450 }
451 Ok(())
452 })
453}
454
455pub fn start_api_background(
458 state: Arc<SharedPlayerState>,
459 cmd_tx: Sender<PlayerCommand>,
460 db_path: PathBuf,
461 port: Option<u16>,
462 bind: Option<std::net::IpAddr>,
463 subsonic_port: Option<u16>,
464 playground: bool,
465) {
466 if let Err(e) = run_api_blocking(ApiServerOpts {
469 state,
470 cmd_tx,
471 pool: Arc::new(Pool::new(db_path)),
472 port,
473 bind,
474 subsonic_port,
475 playground,
476 viz: None,
477 headless: false,
478 }) {
479 log::error!("API server not started: {}", e);
480 }
481}
482
483pub(crate) struct BrowserPolicy {
492 origins: Vec<String>,
493 hosts: Vec<String>,
494}
495
496impl BrowserPolicy {
497 fn host_allowed(&self, host: &str) -> bool {
498 if self.hosts.iter().any(|h| h.eq_ignore_ascii_case(host)) {
499 return true;
500 }
501 let bare = strip_port(host);
502 if self.hosts.iter().any(|h| h.eq_ignore_ascii_case(bare)) {
503 return true;
504 }
505 bare.eq_ignore_ascii_case("localhost") || bare.parse::<std::net::IpAddr>().is_ok()
508 }
509
510 fn origin_allowed(&self, origin: &str, host: Option<&str>) -> bool {
513 if self.origins.iter().any(|o| o == origin) {
514 return true;
515 }
516 match (origin.split_once("://"), host) {
517 (Some((_, authority)), Some(host)) => authority.eq_ignore_ascii_case(host),
518 _ => false,
519 }
520 }
521}
522
523fn strip_port(host: &str) -> &str {
525 if let Some(rest) = host.strip_prefix('[') {
526 return rest.split(']').next().unwrap_or(rest);
527 }
528 match host.rsplit_once(':') {
529 Some((h, port)) if !port.is_empty() && port.bytes().all(|b| b.is_ascii_digit()) => h,
530 _ => host,
531 }
532}
533
534fn header_str(request: &axum::extract::Request, name: axum::http::HeaderName) -> Option<&str> {
535 request.headers().get(name).and_then(|v| v.to_str().ok())
536}
537
538async fn host_guard(
540 axum::extract::State(policy): axum::extract::State<Arc<BrowserPolicy>>,
541 request: axum::extract::Request,
542 next: axum::middleware::Next,
543) -> axum::response::Response {
544 use axum::response::IntoResponse;
545
546 let host = header_str(&request, axum::http::header::HOST)
549 .map(str::to_owned)
550 .or_else(|| request.uri().host().map(str::to_owned));
551
552 if let Some(ref host) = host
553 && !policy.host_allowed(host)
554 {
555 log::warn!("rejected request for unrecognised Host: {}", host);
556 return (axum::http::StatusCode::FORBIDDEN, "host not allowed").into_response();
557 }
558
559 next.run(request).await
560}
561
562async fn browser_guard(
571 axum::extract::State(policy): axum::extract::State<Arc<BrowserPolicy>>,
572 request: axum::extract::Request,
573 next: axum::middleware::Next,
574) -> axum::response::Response {
575 use axum::response::IntoResponse;
576
577 let host = header_str(&request, axum::http::header::HOST).map(str::to_owned);
578 if let Some(origin) = header_str(&request, axum::http::header::ORIGIN)
580 && !policy.origin_allowed(origin, host.as_deref())
581 {
582 log::warn!(
583 "rejected GraphQL request from disallowed Origin: {}",
584 origin
585 );
586 return (axum::http::StatusCode::FORBIDDEN, "origin not allowed").into_response();
587 }
588
589 if request.method() == axum::http::Method::POST && !is_graphql_content_type(&request) {
590 return (
591 axum::http::StatusCode::UNSUPPORTED_MEDIA_TYPE,
592 "content type must be application/json or application/graphql",
593 )
594 .into_response();
595 }
596
597 next.run(request).await
598}
599
600fn is_graphql_content_type(request: &axum::extract::Request) -> bool {
601 header_str(request, axum::http::header::CONTENT_TYPE).is_some_and(|ct| {
602 let ct = ct.trim().to_ascii_lowercase();
603 ct.starts_with("application/json") || ct.starts_with("application/graphql")
604 })
605}
606
607async fn shutdown_signal() {
611 #[cfg(unix)]
612 {
613 use tokio::signal::unix::{SignalKind, signal};
614 let mut terminate = signal(SignalKind::terminate()).expect("failed to listen for SIGTERM");
615 tokio::select! {
616 r = tokio::signal::ctrl_c() => r.expect("failed to listen for ctrl+c"),
617 _ = terminate.recv() => {}
618 }
619 }
620 #[cfg(not(unix))]
621 tokio::signal::ctrl_c()
622 .await
623 .expect("failed to listen for ctrl+c");
624}
625
626const DRAIN: std::time::Duration = std::time::Duration::from_secs(10);
628
629async fn drain_deadline() {
633 shutdown_signal().await;
634 tokio::time::sleep(DRAIN).await;
635}
636
637async fn graphql_handler(
638 axum::Extension(user): axum::Extension<AuthUser>,
639 axum::extract::State(schema): axum::extract::State<KoanSchema>,
640 headers: axum::http::HeaderMap,
641 req: async_graphql_axum::GraphQLRequest,
642) -> async_graphql_axum::GraphQLResponse {
643 let mut request = req.into_inner();
644 if let Some(origin) = crate::origin::origin(&headers, None) {
645 request = request.data(super::RequestOrigin(origin));
646 }
647 request = request.data(user);
650 schema.execute(request).await.into()
651}
652
653async fn graphql_ws_handler(
654 axum::Extension(user): axum::Extension<AuthUser>,
655 axum::extract::State(schema): axum::extract::State<KoanSchema>,
656 protocol: async_graphql_axum::GraphQLProtocol,
657 websocket: axum::extract::WebSocketUpgrade,
658) -> axum::response::Response {
659 websocket
660 .protocols(async_graphql::http::ALL_WEBSOCKET_PROTOCOLS)
661 .on_upgrade(move |stream| {
662 let stream = async_graphql_axum::GraphQLWebSocket::new(stream, schema, protocol)
663 .on_connection_init(move |_| async move {
664 let mut data = async_graphql::Data::default();
665 data.insert(user);
666 Ok(data)
667 });
668 async move {
669 stream.serve().await;
670 }
671 })
672}
673
674async fn graphql_playground(
675 axum::extract::Query(params): axum::extract::Query<std::collections::HashMap<String, String>>,
676 axum::extract::State(key): axum::extract::State<Option<Arc<String>>>,
677) -> axum::response::Response {
678 use axum::response::IntoResponse;
679
680 if let Some(ref expected) = key {
682 let provided = params.get("introspection-key");
683 if provided.map(|k| k.as_str()) != Some(expected.as_str()) {
684 return (
685 axum::http::StatusCode::FORBIDDEN,
686 "invalid or missing introspection-key",
687 )
688 .into_response();
689 }
690 }
691
692 let mut source = async_graphql::http::GraphiQLSource::build().endpoint("/graphql");
695 if let Some(ref k) = key {
696 source = source.header("X-Introspection-Key", k.as_str());
697 }
698
699 axum::response::Html(source.finish()).into_response()
700}
701
702pub fn cmd_serve_daemon(
704 port: Option<u16>,
705 bind: Option<std::net::IpAddr>,
706 subsonic_port: Option<u16>,
707 playground: bool,
708) {
709 use std::fs;
710 use std::process::Command;
711
712 let cfg = Config::load().unwrap_or_default();
713 let port_val = port.unwrap_or(cfg.graphql.port);
714 let bind_val = bind.unwrap_or(cfg.graphql.bind);
715
716 let exe = std::env::current_exe().expect("failed to get current exe path");
717 let mut cmd = Command::new(exe);
718
719 cmd.arg("--headless");
720 cmd.arg("--port").arg(port_val.to_string());
721 cmd.arg("--bind").arg(bind_val.to_string());
722 if let Some(sp) = subsonic_port {
723 cmd.arg("--subsonic").arg(sp.to_string());
724 }
725 if playground || cfg.graphql.playground {
726 cmd.arg("--playground");
727 }
728
729 cmd.stdin(std::process::Stdio::null());
730 cmd.stdout(std::process::Stdio::null());
731 cmd.stderr(std::process::Stdio::null());
732
733 let mut child = cmd.spawn().expect("failed to spawn daemon process");
734 let pid = child.id();
735
736 let pid_path = koan_core::config::config_dir().join("koan-serve.pid");
737 fs::write(&pid_path, pid.to_string()).ok();
738
739 std::thread::spawn(move || {
740 let _ = child.wait();
741 });
742
743 eprintln!("kōan daemon started (pid {}) on port {}", pid, port_val);
744 if let Some(sp) = subsonic_port {
745 eprintln!(" Subsonic REST on port {}", sp);
746 }
747 eprintln!(" PID file: {}", pid_path.display());
748}
749
750pub async fn execute_in_process(
759 schema: &KoanSchema,
760 query: &str,
761 variables: Option<serde_json::Value>,
762 caller: AuthUser,
763) -> serde_json::Value {
764 let mut request = async_graphql::Request::new(query).data(caller);
765 if let Some(serde_json::Value::Object(map)) = variables {
766 let mut gql_vars = async_graphql::Variables::default();
767 for (k, v) in map {
768 gql_vars.insert(
769 async_graphql::Name::new(&k),
770 async_graphql::Value::from_json(v).unwrap_or(async_graphql::Value::Null),
771 );
772 }
773 request = request.variables(gql_vars);
774 }
775 let response = schema.execute(request).await;
776 serde_json::to_value(&response).unwrap_or(serde_json::Value::Null)
777}
778
779#[cfg(test)]
784mod tests {
785 use super::*;
786 use axum::body::Body;
787 use axum::http::{Request as HttpRequest, StatusCode};
788 use axum::routing::{get, post};
789 use tower::ServiceExt as _;
790
791 fn policy() -> Arc<BrowserPolicy> {
792 Arc::new(BrowserPolicy {
793 origins: vec!["https://music.example.com".into()],
794 hosts: vec!["koan.local".into()],
795 })
796 }
797
798 async fn ok() -> &'static str {
799 "ok"
800 }
801
802 fn routes() -> axum::Router<Arc<BrowserPolicy>> {
803 axum::Router::new()
804 .route("/graphql", post(ok).get(ok))
805 .route("/graphql/ws", get(ok))
806 }
807
808 async fn run_host(req: HttpRequest<Body>) -> StatusCode {
809 let app = routes()
810 .layer(axum::middleware::from_fn_with_state(policy(), host_guard))
811 .with_state(policy());
812 app.oneshot(req).await.unwrap().status()
813 }
814
815 async fn run_browser(req: HttpRequest<Body>) -> StatusCode {
816 let app = routes()
817 .layer(axum::middleware::from_fn_with_state(
818 policy(),
819 browser_guard,
820 ))
821 .with_state(policy());
822 app.oneshot(req).await.unwrap().status()
823 }
824
825 fn json_post(uri: &str) -> axum::http::request::Builder {
826 HttpRequest::post(uri).header(axum::http::header::CONTENT_TYPE, "application/json")
827 }
828
829 #[test]
832 fn host_policy_accepts_loopback_literals_and_configured_names() {
833 let p = policy();
834 assert!(p.host_allowed("localhost:4000"));
835 assert!(p.host_allowed("127.0.0.1:4000"));
836 assert!(p.host_allowed("192.168.1.20:4000"));
837 assert!(p.host_allowed("[::1]:4000"));
838 assert!(p.host_allowed("koan.local"));
839 assert!(p.host_allowed("koan.local:4000"));
840 }
841
842 #[test]
843 fn host_policy_rejects_attacker_controlled_names() {
844 let p = policy();
845 assert!(!p.host_allowed("evil.com"));
846 assert!(!p.host_allowed("rebind.evil.com:4000"));
847 assert!(!p.host_allowed("koan.local.evil.com"));
848 }
849
850 #[tokio::test]
851 async fn host_guard_rejects_foreign_host() {
852 let req = json_post("/graphql")
853 .header(axum::http::header::HOST, "rebind.evil.com")
854 .body(Body::empty())
855 .unwrap();
856 assert_eq!(run_host(req).await, StatusCode::FORBIDDEN);
857 }
858
859 #[tokio::test]
860 async fn host_guard_allows_known_host_and_missing_host() {
861 let req = json_post("/graphql")
862 .header(axum::http::header::HOST, "127.0.0.1:4000")
863 .body(Body::empty())
864 .unwrap();
865 assert_eq!(run_host(req).await, StatusCode::OK);
866
867 let req = json_post("/graphql").body(Body::empty()).unwrap();
868 assert_eq!(run_host(req).await, StatusCode::OK);
869 }
870
871 #[tokio::test]
874 async fn ws_upgrade_from_foreign_origin_is_rejected() {
875 let req = HttpRequest::get("/graphql/ws")
876 .header(axum::http::header::HOST, "127.0.0.1:4000")
877 .header(axum::http::header::ORIGIN, "https://evil.com")
878 .body(Body::empty())
879 .unwrap();
880 assert_eq!(run_browser(req).await, StatusCode::FORBIDDEN);
881 }
882
883 #[tokio::test]
884 async fn ws_upgrade_without_origin_is_allowed() {
885 let req = HttpRequest::get("/graphql/ws")
886 .header(axum::http::header::HOST, "127.0.0.1:4000")
887 .body(Body::empty())
888 .unwrap();
889 assert_eq!(run_browser(req).await, StatusCode::OK);
890 }
891
892 #[tokio::test]
893 async fn configured_and_same_origin_are_allowed() {
894 let req = HttpRequest::get("/graphql/ws")
895 .header(axum::http::header::HOST, "127.0.0.1:4000")
896 .header(axum::http::header::ORIGIN, "https://music.example.com")
897 .body(Body::empty())
898 .unwrap();
899 assert_eq!(run_browser(req).await, StatusCode::OK);
900
901 let req = json_post("/graphql")
903 .header(axum::http::header::HOST, "127.0.0.1:4000")
904 .header(axum::http::header::ORIGIN, "http://127.0.0.1:4000")
905 .body(Body::empty())
906 .unwrap();
907 assert_eq!(run_browser(req).await, StatusCode::OK);
908 }
909
910 #[tokio::test]
913 async fn text_plain_post_is_rejected() {
914 let req = HttpRequest::post("/graphql")
915 .header(axum::http::header::CONTENT_TYPE, "text/plain")
916 .body(Body::from(r#"{"query":"mutation{clearQueue{ok}}"}"#))
917 .unwrap();
918 assert_eq!(run_browser(req).await, StatusCode::UNSUPPORTED_MEDIA_TYPE);
919 }
920
921 #[tokio::test]
922 async fn post_without_content_type_is_rejected() {
923 let req = HttpRequest::post("/graphql").body(Body::empty()).unwrap();
924 assert_eq!(run_browser(req).await, StatusCode::UNSUPPORTED_MEDIA_TYPE);
925 }
926
927 #[tokio::test]
930 async fn load_perimeter_refuses_an_oversized_query_body() {
931 async fn parse(_: async_graphql_axum::GraphQLRequest) -> StatusCode {
932 StatusCode::OK
933 }
934 let app = load_perimeter(axum::Router::new().route("/graphql", post(parse)));
935 let body = |padding: usize| {
938 let chunks = [
939 axum::body::Bytes::from_static(br#"{"query":"{__typename}""#),
940 axum::body::Bytes::from(vec![b' '; padding]),
941 axum::body::Bytes::from_static(b"}"),
942 ];
943 Body::from_stream(tokio_stream::iter(chunks.map(Ok::<_, std::io::Error>)))
944 };
945 let req = json_post("/graphql").body(body(1 << 10)).unwrap();
946 assert_eq!(
947 app.clone().oneshot(req).await.unwrap().status(),
948 StatusCode::OK
949 );
950 let req = json_post("/graphql").body(body(3 << 20)).unwrap();
951 assert_ne!(app.oneshot(req).await.unwrap().status(), StatusCode::OK);
952 }
953
954 #[tokio::test]
955 async fn load_perimeter_passes_requests_and_turns_panics_into_500s() {
956 async fn boom() -> &'static str {
957 panic!("resolver exploded");
958 }
959
960 let app = load_perimeter(
961 axum::Router::new()
962 .route("/graphql", post(ok))
963 .route("/boom", post(boom)),
964 );
965
966 let req = json_post("/graphql").body(Body::empty()).unwrap();
967 assert_eq!(
968 app.clone().oneshot(req).await.unwrap().status(),
969 StatusCode::OK
970 );
971
972 let req = json_post("/boom").body(Body::empty()).unwrap();
974 assert_eq!(
975 app.oneshot(req).await.unwrap().status(),
976 StatusCode::INTERNAL_SERVER_ERROR
977 );
978 }
979
980 #[tokio::test]
981 async fn json_post_is_accepted() {
982 let req = json_post("/graphql").body(Body::empty()).unwrap();
983 assert_eq!(run_browser(req).await, StatusCode::OK);
984
985 let req = HttpRequest::post("/graphql")
986 .header(
987 axum::http::header::CONTENT_TYPE,
988 "application/json; charset=utf-8",
989 )
990 .body(Body::empty())
991 .unwrap();
992 assert_eq!(run_browser(req).await, StatusCode::OK);
993 }
994}