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