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::player::commands::PlayerCommand;
9use koan_core::player::state::SharedPlayerState;
10
11use super::{KoanSchema, build_schema};
12use crate::auth::AuthUser;
13use crate::auth::middleware::{AuthState, auth_middleware};
14use crate::auth::routes::{AuthRouteState, LoginRateLimiter, auth_router};
15
16pub fn cmd_serve(
21 port: Option<u16>,
22 bind: Option<std::net::IpAddr>,
23 subsonic_port: Option<u16>,
24 playground: bool,
25) {
26 use koan_core::player::Player;
27
28 let _db = koan_core::db::connection::Database::open_default().expect("failed to open database");
30 let db_path = koan_core::config::db_path();
31
32 let (state, _timeline, _viz, cmd_tx) = Player::spawn();
33
34 if let Err(e) = run_api_blocking(ApiServerOpts {
35 state,
36 cmd_tx,
37 db_path,
38 port,
39 bind,
40 subsonic_port,
41 playground,
42 viz: None, }) {
44 eprintln!("koan: {}", e);
45 std::process::exit(1);
46 }
47}
48
49const REQUEST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
56
57const MAX_INFLIGHT_QUERIES: usize = 64;
61
62fn load_perimeter<S>(router: axum::Router<S>) -> axum::Router<S>
67where
68 S: Clone + Send + Sync + 'static,
69{
70 router
71 .layer(tower_http::catch_panic::CatchPanicLayer::new())
74 .layer(tower_http::timeout::TimeoutLayer::with_status_code(
75 axum::http::StatusCode::REQUEST_TIMEOUT,
76 REQUEST_TIMEOUT,
77 ))
78 .layer(
82 tower::ServiceBuilder::new()
83 .layer(axum::error_handling::HandleErrorLayer::new(
84 |err: tower::BoxError| async move {
85 if err.is::<tower::load_shed::error::Overloaded>() {
86 (
87 axum::http::StatusCode::SERVICE_UNAVAILABLE,
88 "server at capacity",
89 )
90 } else {
91 (
92 axum::http::StatusCode::INTERNAL_SERVER_ERROR,
93 "internal error",
94 )
95 }
96 },
97 ))
98 .load_shed()
99 .concurrency_limit(MAX_INFLIGHT_QUERIES),
100 )
101}
102
103pub struct ApiServerOpts {
105 pub state: Arc<SharedPlayerState>,
106 pub cmd_tx: Sender<PlayerCommand>,
107 pub db_path: PathBuf,
108 pub port: Option<u16>,
109 pub bind: Option<std::net::IpAddr>,
110 pub subsonic_port: Option<u16>,
111 pub playground: bool,
112 pub viz: Option<Arc<VizSnapshot>>,
113}
114
115fn run_api_blocking(opts: ApiServerOpts) -> Result<(), String> {
121 let ApiServerOpts {
122 state,
123 cmd_tx,
124 db_path,
125 port,
126 bind,
127 subsonic_port,
128 playground,
129 viz,
130 } = opts;
131 use axum::routing::{get, post};
132
133 let cfg = Config::load().unwrap_or_default();
134 let port = port.unwrap_or(cfg.graphql.port);
135 let bind = bind.unwrap_or(cfg.graphql.bind);
136 let playground_enabled = playground || cfg.graphql.playground;
137 let auth_enabled = cfg.graphql.auth_enabled;
138
139 let (private_pem, public_pem) = if auth_enabled {
141 let kp = auth::load_keypair().map_err(|e| {
142 format!(
143 "auth_enabled = true but the keypair could not be loaded: {}. \
144 Run `koan auth setup`.",
145 e
146 )
147 })?;
148 if kp.0.is_empty() || kp.1.is_empty() {
151 return Err("auth_enabled = true but the keypair files are empty. \
152 Run `koan auth regenerate-keys`."
153 .into());
154 }
155 kp
156 } else {
157 auth::load_or_generate_keypair().unwrap_or_default()
160 };
161
162 let access_ttl = parse_duration_secs(&cfg.graphql.access_token_ttl).unwrap_or(900);
163 let refresh_ttl = parse_duration_secs(&cfg.graphql.refresh_token_ttl).unwrap_or(2_592_000);
164
165 let introspection_key = if playground_enabled && auth_enabled {
169 Some(Arc::new(auth::random_token().map_err(|e| {
170 format!("failed to generate introspection key: {}", e)
171 })?))
172 } else {
173 None
174 };
175
176 let auth_state = AuthState {
177 public_pem: Arc::new(public_pem.clone()),
178 auth_enabled,
179 introspection_key: introspection_key.clone(),
180 };
181
182 let auth_route_state = AuthRouteState {
183 db_path: db_path.clone(),
184 private_pem: Arc::new(private_pem),
185 public_pem: Arc::new(public_pem),
186 access_ttl_secs: access_ttl,
187 refresh_ttl_secs: refresh_ttl,
188 cookie_secure: cfg.graphql.cookie_secure,
189 login_limiter: Arc::new(LoginRateLimiter::default()),
190 };
191
192 let schema = build_schema(state, cmd_tx, db_path.clone(), viz);
193
194 if auth_enabled {
195 log::info!(
196 "Auth enabled (Ed25519 JWT, access TTL {}s, refresh TTL {}s)",
197 access_ttl,
198 refresh_ttl
199 );
200 } else {
201 log::info!("Auth disabled — all requests treated as admin");
202 }
203
204 let browser_policy = Arc::new(BrowserPolicy {
205 origins: cfg.graphql.cors_origins.clone(),
206 hosts: cfg.graphql.allowed_hosts.clone(),
207 });
208
209 if cfg.graphql.cors_origins.is_empty() {
210 log::info!("CORS: no origins configured — browsers get no cross-origin access");
211 }
212
213 let rt = tokio::runtime::Runtime::new().expect("failed to create tokio runtime");
214 rt.block_on(async {
215 let query_route = load_perimeter(axum::Router::new().route("/graphql", post(graphql_handler)));
220
221 let gql_app = axum::Router::new()
222 .merge(query_route)
223 .route("/graphql/ws", get(graphql_ws_handler))
224 .layer(axum::middleware::from_fn_with_state(
225 auth_state.clone(),
226 auth_middleware,
227 ))
228 .layer(axum::middleware::from_fn_with_state(
231 browser_policy.clone(),
232 browser_guard,
233 ))
234 .with_state(schema);
235
236 let auth_app = auth_router(auth_route_state);
238
239 let origins: Vec<axum::http::HeaderValue> = cfg
243 .graphql
244 .cors_origins
245 .iter()
246 .filter_map(|o| o.parse().ok())
247 .collect();
248 let cors = tower_http::cors::CorsLayer::new()
249 .allow_origin(origins)
250 .allow_methods([
251 axum::http::Method::GET,
252 axum::http::Method::POST,
253 axum::http::Method::OPTIONS,
254 ])
255 .allow_headers([
256 axum::http::header::AUTHORIZATION,
257 axum::http::header::CONTENT_TYPE,
258 axum::http::HeaderName::from_static("x-introspection-key"),
259 ])
260 .allow_credentials(true);
261
262 let subsonic_merged = crate::subsonic::subsonic_router(db_path);
269 let subsonic_on_main = subsonic_merged.is_some();
270 let subsonic_dedicated = subsonic_merged.clone();
271
272 let mut app = auth_app.merge(gql_app);
273 if let Some(sub) = subsonic_merged {
274 app = app.merge(sub);
275 }
276 if playground_enabled {
277 app = app.route(
278 "/graphql",
279 get(graphql_playground).with_state(introspection_key.clone()),
280 );
281 }
282 let app = app.layer(cors).layer(axum::middleware::from_fn_with_state(
286 browser_policy.clone(),
287 host_guard,
288 ));
289
290 let playground_url = if playground_enabled {
292 if let Some(ref key) = introspection_key {
293 format!("http://{}:{}/graphql?introspection-key={}", bind, port, key)
294 } else {
295 format!("http://{}:{}/graphql", bind, port)
296 }
297 } else {
298 format!("http://{}:{}/graphql", bind, port)
299 };
300
301 let gql_addr = std::net::SocketAddr::new(bind, port);
302
303 let gql_listener = match tokio::net::TcpListener::bind(gql_addr).await {
304 Ok(l) => {
305 log::info!("GraphQL API on http://{}:{}/graphql", bind, port);
306 if subsonic_on_main {
307 log::info!("Subsonic REST on http://{}:{}/rest/", bind, port);
308 }
309 if playground_enabled {
310 log::info!("GraphiQL: {}", playground_url);
311 #[cfg(target_os = "macos")]
313 let _ = std::process::Command::new("open").arg(&playground_url).spawn();
314 #[cfg(target_os = "linux")]
315 let _ = std::process::Command::new("xdg-open").arg(&playground_url).spawn();
316 }
317 l
318 }
319 Err(e) => {
320 log::warn!(
321 "API disabled: failed to bind GraphQL port {} — {} (another instance running?)",
322 port,
323 e,
324 );
325 return Ok(());
326 }
327 };
328 let gql_server = axum::serve(
329 gql_listener,
330 app.into_make_service_with_connect_info::<std::net::SocketAddr>(),
331 )
332 .with_graceful_shutdown(shutdown_signal());
333
334 let extra_sub_port = subsonic_port.filter(|p| *p != port);
338 if let Some(sub_port) = extra_sub_port
339 && let Some(sub_app) = subsonic_dedicated
340 {
341 let sub_addr = std::net::SocketAddr::new(bind, sub_port);
342 match tokio::net::TcpListener::bind(sub_addr).await {
343 Ok(sub_listener) => {
344 log::info!(
345 "Subsonic REST also on http://{}:{}/rest/ (dedicated port)",
346 bind,
347 sub_port,
348 );
349 let sub_server = axum::serve(sub_listener, sub_app)
350 .with_graceful_shutdown(shutdown_signal());
351
352 tokio::select! {
353 r = gql_server => { if let Err(e) = r { log::error!("GraphQL server error: {e}"); } },
354 r = sub_server => { if let Err(e) = r { log::error!("Subsonic server error: {e}"); } },
355 }
356 return Ok(());
357 }
358 Err(e) => {
359 log::warn!(
360 "Dedicated Subsonic port {} unavailable — {}. Mounted on GraphQL port only.",
361 sub_port,
362 e,
363 );
364 }
365 }
366 }
367
368 if let Err(e) = gql_server.await {
369 log::error!("GraphQL server error: {e}");
370 }
371 Ok(())
372 })
373}
374
375pub fn start_api_background(
381 state: Arc<SharedPlayerState>,
382 cmd_tx: Sender<PlayerCommand>,
383 db_path: PathBuf,
384 port: Option<u16>,
385 bind: Option<std::net::IpAddr>,
386 subsonic_port: Option<u16>,
387 playground: bool,
388) {
389 if let Err(e) = run_api_blocking(ApiServerOpts {
392 state,
393 cmd_tx,
394 db_path,
395 port,
396 bind,
397 subsonic_port,
398 playground,
399 viz: None,
400 }) {
401 log::error!("API server not started: {}", e);
402 }
403}
404
405pub(crate) struct BrowserPolicy {
414 origins: Vec<String>,
415 hosts: Vec<String>,
416}
417
418impl BrowserPolicy {
419 fn host_allowed(&self, host: &str) -> bool {
420 if self.hosts.iter().any(|h| h.eq_ignore_ascii_case(host)) {
421 return true;
422 }
423 let bare = strip_port(host);
424 if self.hosts.iter().any(|h| h.eq_ignore_ascii_case(bare)) {
425 return true;
426 }
427 bare.eq_ignore_ascii_case("localhost") || bare.parse::<std::net::IpAddr>().is_ok()
430 }
431
432 fn origin_allowed(&self, origin: &str, host: Option<&str>) -> bool {
435 if self.origins.iter().any(|o| o == origin) {
436 return true;
437 }
438 match (origin.split_once("://"), host) {
439 (Some((_, authority)), Some(host)) => authority.eq_ignore_ascii_case(host),
440 _ => false,
441 }
442 }
443}
444
445fn strip_port(host: &str) -> &str {
447 if let Some(rest) = host.strip_prefix('[') {
448 return rest.split(']').next().unwrap_or(rest);
449 }
450 match host.rsplit_once(':') {
451 Some((h, port)) if !port.is_empty() && port.bytes().all(|b| b.is_ascii_digit()) => h,
452 _ => host,
453 }
454}
455
456fn header_str(request: &axum::extract::Request, name: axum::http::HeaderName) -> Option<&str> {
457 request.headers().get(name).and_then(|v| v.to_str().ok())
458}
459
460async fn host_guard(
462 axum::extract::State(policy): axum::extract::State<Arc<BrowserPolicy>>,
463 request: axum::extract::Request,
464 next: axum::middleware::Next,
465) -> axum::response::Response {
466 use axum::response::IntoResponse;
467
468 let host = header_str(&request, axum::http::header::HOST)
471 .map(str::to_owned)
472 .or_else(|| request.uri().host().map(str::to_owned));
473
474 if let Some(ref host) = host
475 && !policy.host_allowed(host)
476 {
477 log::warn!("rejected request for unrecognised Host: {}", host);
478 return (axum::http::StatusCode::FORBIDDEN, "host not allowed").into_response();
479 }
480
481 next.run(request).await
482}
483
484async fn browser_guard(
493 axum::extract::State(policy): axum::extract::State<Arc<BrowserPolicy>>,
494 request: axum::extract::Request,
495 next: axum::middleware::Next,
496) -> axum::response::Response {
497 use axum::response::IntoResponse;
498
499 let host = header_str(&request, axum::http::header::HOST).map(str::to_owned);
500 if let Some(origin) = header_str(&request, axum::http::header::ORIGIN)
502 && !policy.origin_allowed(origin, host.as_deref())
503 {
504 log::warn!(
505 "rejected GraphQL request from disallowed Origin: {}",
506 origin
507 );
508 return (axum::http::StatusCode::FORBIDDEN, "origin not allowed").into_response();
509 }
510
511 if request.method() == axum::http::Method::POST && !is_graphql_content_type(&request) {
512 return (
513 axum::http::StatusCode::UNSUPPORTED_MEDIA_TYPE,
514 "content type must be application/json or application/graphql",
515 )
516 .into_response();
517 }
518
519 next.run(request).await
520}
521
522fn is_graphql_content_type(request: &axum::extract::Request) -> bool {
523 header_str(request, axum::http::header::CONTENT_TYPE).is_some_and(|ct| {
524 let ct = ct.trim().to_ascii_lowercase();
525 ct.starts_with("application/json") || ct.starts_with("application/graphql")
526 })
527}
528
529async fn shutdown_signal() {
530 tokio::signal::ctrl_c()
531 .await
532 .expect("failed to listen for ctrl+c");
533}
534
535async fn graphql_handler(
536 axum::Extension(user): axum::Extension<AuthUser>,
537 axum::extract::State(schema): axum::extract::State<KoanSchema>,
538 req: async_graphql_axum::GraphQLRequest,
539) -> async_graphql_axum::GraphQLResponse {
540 let mut request = req.into_inner();
541 request = request.data(user);
544 schema.execute(request).await.into()
545}
546
547async fn graphql_ws_handler(
548 axum::Extension(user): axum::Extension<AuthUser>,
549 axum::extract::State(schema): axum::extract::State<KoanSchema>,
550 protocol: async_graphql_axum::GraphQLProtocol,
551 websocket: axum::extract::WebSocketUpgrade,
552) -> axum::response::Response {
553 websocket
554 .protocols(async_graphql::http::ALL_WEBSOCKET_PROTOCOLS)
555 .on_upgrade(move |stream| {
556 let stream = async_graphql_axum::GraphQLWebSocket::new(stream, schema, protocol)
557 .on_connection_init(move |_| async move {
558 let mut data = async_graphql::Data::default();
559 data.insert(user);
560 Ok(data)
561 });
562 async move {
563 stream.serve().await;
564 }
565 })
566}
567
568async fn graphql_playground(
569 axum::extract::Query(params): axum::extract::Query<std::collections::HashMap<String, String>>,
570 axum::extract::State(key): axum::extract::State<Option<Arc<String>>>,
571) -> axum::response::Response {
572 use axum::response::IntoResponse;
573
574 if let Some(ref expected) = key {
576 let provided = params.get("introspection-key");
577 if provided.map(|k| k.as_str()) != Some(expected.as_str()) {
578 return (
579 axum::http::StatusCode::FORBIDDEN,
580 "invalid or missing introspection-key",
581 )
582 .into_response();
583 }
584 }
585
586 let mut source = async_graphql::http::GraphiQLSource::build().endpoint("/graphql");
589 if let Some(ref k) = key {
590 source = source.header("X-Introspection-Key", k.as_str());
591 }
592
593 axum::response::Html(source.finish()).into_response()
594}
595
596pub fn cmd_serve_daemon(
598 port: Option<u16>,
599 bind: Option<std::net::IpAddr>,
600 subsonic_port: Option<u16>,
601 playground: bool,
602) {
603 use std::fs;
604 use std::process::Command;
605
606 let cfg = Config::load().unwrap_or_default();
607 let port_val = port.unwrap_or(cfg.graphql.port);
608 let bind_val = bind.unwrap_or(cfg.graphql.bind);
609
610 let exe = std::env::current_exe().expect("failed to get current exe path");
611 let mut cmd = Command::new(exe);
612 cmd.arg("--headless");
614 cmd.arg("--port").arg(port_val.to_string());
615 cmd.arg("--bind").arg(bind_val.to_string());
616 if let Some(sp) = subsonic_port {
617 cmd.arg("--subsonic").arg(sp.to_string());
618 }
619 if playground || cfg.graphql.playground {
620 cmd.arg("--playground");
621 }
622
623 cmd.stdin(std::process::Stdio::null());
624 cmd.stdout(std::process::Stdio::null());
625 cmd.stderr(std::process::Stdio::null());
626
627 let mut child = cmd.spawn().expect("failed to spawn daemon process");
628 let pid = child.id();
629
630 let pid_path = koan_core::config::config_dir().join("koan-serve.pid");
631 fs::write(&pid_path, pid.to_string()).ok();
632
633 std::thread::spawn(move || {
634 let _ = child.wait();
635 });
636
637 eprintln!("koan daemon started (pid {}) on port {}", pid, port_val);
638 if let Some(sp) = subsonic_port {
639 eprintln!(" Subsonic REST on port {}", sp);
640 }
641 eprintln!(" PID file: {}", pid_path.display());
642}
643
644pub async fn execute_in_process(
653 schema: &KoanSchema,
654 query: &str,
655 variables: Option<serde_json::Value>,
656 role: koan_core::auth::Role,
657) -> serde_json::Value {
658 let mut request = async_graphql::Request::new(query);
659 request = request.data(AuthUser {
660 role,
661 ..AuthUser::anonymous_admin()
662 });
663 if let Some(serde_json::Value::Object(map)) = variables {
664 let mut gql_vars = async_graphql::Variables::default();
665 for (k, v) in map {
666 gql_vars.insert(
667 async_graphql::Name::new(&k),
668 async_graphql::Value::from_json(v).unwrap_or(async_graphql::Value::Null),
669 );
670 }
671 request = request.variables(gql_vars);
672 }
673 let response = schema.execute(request).await;
674 serde_json::to_value(&response).unwrap_or(serde_json::Value::Null)
675}
676
677#[cfg(test)]
682mod tests {
683 use super::*;
684 use axum::body::Body;
685 use axum::http::{Request as HttpRequest, StatusCode};
686 use axum::routing::{get, post};
687 use tower::ServiceExt as _;
688
689 fn policy() -> Arc<BrowserPolicy> {
690 Arc::new(BrowserPolicy {
691 origins: vec!["https://music.example.com".into()],
692 hosts: vec!["koan.local".into()],
693 })
694 }
695
696 async fn ok() -> &'static str {
697 "ok"
698 }
699
700 fn routes() -> axum::Router<Arc<BrowserPolicy>> {
701 axum::Router::new()
702 .route("/graphql", post(ok).get(ok))
703 .route("/graphql/ws", get(ok))
704 }
705
706 async fn run_host(req: HttpRequest<Body>) -> StatusCode {
707 let app = routes()
708 .layer(axum::middleware::from_fn_with_state(policy(), host_guard))
709 .with_state(policy());
710 app.oneshot(req).await.unwrap().status()
711 }
712
713 async fn run_browser(req: HttpRequest<Body>) -> StatusCode {
714 let app = routes()
715 .layer(axum::middleware::from_fn_with_state(
716 policy(),
717 browser_guard,
718 ))
719 .with_state(policy());
720 app.oneshot(req).await.unwrap().status()
721 }
722
723 fn json_post(uri: &str) -> axum::http::request::Builder {
724 HttpRequest::post(uri).header(axum::http::header::CONTENT_TYPE, "application/json")
725 }
726
727 #[test]
730 fn host_policy_accepts_loopback_literals_and_configured_names() {
731 let p = policy();
732 assert!(p.host_allowed("localhost:4000"));
733 assert!(p.host_allowed("127.0.0.1:4000"));
734 assert!(p.host_allowed("192.168.1.20:4000"));
735 assert!(p.host_allowed("[::1]:4000"));
736 assert!(p.host_allowed("koan.local"));
737 assert!(p.host_allowed("koan.local:4000"));
738 }
739
740 #[test]
741 fn host_policy_rejects_attacker_controlled_names() {
742 let p = policy();
743 assert!(!p.host_allowed("evil.com"));
744 assert!(!p.host_allowed("rebind.evil.com:4000"));
745 assert!(!p.host_allowed("koan.local.evil.com"));
746 }
747
748 #[tokio::test]
749 async fn host_guard_rejects_foreign_host() {
750 let req = json_post("/graphql")
751 .header(axum::http::header::HOST, "rebind.evil.com")
752 .body(Body::empty())
753 .unwrap();
754 assert_eq!(run_host(req).await, StatusCode::FORBIDDEN);
755 }
756
757 #[tokio::test]
758 async fn host_guard_allows_known_host_and_missing_host() {
759 let req = json_post("/graphql")
760 .header(axum::http::header::HOST, "127.0.0.1:4000")
761 .body(Body::empty())
762 .unwrap();
763 assert_eq!(run_host(req).await, StatusCode::OK);
764
765 let req = json_post("/graphql").body(Body::empty()).unwrap();
766 assert_eq!(run_host(req).await, StatusCode::OK);
767 }
768
769 #[tokio::test]
772 async fn ws_upgrade_from_foreign_origin_is_rejected() {
773 let req = HttpRequest::get("/graphql/ws")
774 .header(axum::http::header::HOST, "127.0.0.1:4000")
775 .header(axum::http::header::ORIGIN, "https://evil.com")
776 .body(Body::empty())
777 .unwrap();
778 assert_eq!(run_browser(req).await, StatusCode::FORBIDDEN);
779 }
780
781 #[tokio::test]
782 async fn ws_upgrade_without_origin_is_allowed() {
783 let req = HttpRequest::get("/graphql/ws")
784 .header(axum::http::header::HOST, "127.0.0.1:4000")
785 .body(Body::empty())
786 .unwrap();
787 assert_eq!(run_browser(req).await, StatusCode::OK);
788 }
789
790 #[tokio::test]
791 async fn configured_and_same_origin_are_allowed() {
792 let req = HttpRequest::get("/graphql/ws")
793 .header(axum::http::header::HOST, "127.0.0.1:4000")
794 .header(axum::http::header::ORIGIN, "https://music.example.com")
795 .body(Body::empty())
796 .unwrap();
797 assert_eq!(run_browser(req).await, StatusCode::OK);
798
799 let req = json_post("/graphql")
801 .header(axum::http::header::HOST, "127.0.0.1:4000")
802 .header(axum::http::header::ORIGIN, "http://127.0.0.1:4000")
803 .body(Body::empty())
804 .unwrap();
805 assert_eq!(run_browser(req).await, StatusCode::OK);
806 }
807
808 #[tokio::test]
811 async fn text_plain_post_is_rejected() {
812 let req = HttpRequest::post("/graphql")
813 .header(axum::http::header::CONTENT_TYPE, "text/plain")
814 .body(Body::from(r#"{"query":"mutation{clearQueue{ok}}"}"#))
815 .unwrap();
816 assert_eq!(run_browser(req).await, StatusCode::UNSUPPORTED_MEDIA_TYPE);
817 }
818
819 #[tokio::test]
820 async fn post_without_content_type_is_rejected() {
821 let req = HttpRequest::post("/graphql").body(Body::empty()).unwrap();
822 assert_eq!(run_browser(req).await, StatusCode::UNSUPPORTED_MEDIA_TYPE);
823 }
824
825 #[tokio::test]
828 async fn load_perimeter_passes_requests_and_turns_panics_into_500s() {
829 async fn boom() -> &'static str {
830 panic!("resolver exploded");
831 }
832
833 let app = load_perimeter(
834 axum::Router::new()
835 .route("/graphql", post(ok))
836 .route("/boom", post(boom)),
837 );
838
839 let req = json_post("/graphql").body(Body::empty()).unwrap();
840 assert_eq!(
841 app.clone().oneshot(req).await.unwrap().status(),
842 StatusCode::OK
843 );
844
845 let req = json_post("/boom").body(Body::empty()).unwrap();
847 assert_eq!(
848 app.oneshot(req).await.unwrap().status(),
849 StatusCode::INTERNAL_SERVER_ERROR
850 );
851 }
852
853 #[tokio::test]
854 async fn json_post_is_accepted() {
855 let req = json_post("/graphql").body(Body::empty()).unwrap();
856 assert_eq!(run_browser(req).await, StatusCode::OK);
857
858 let req = HttpRequest::post("/graphql")
859 .header(
860 axum::http::header::CONTENT_TYPE,
861 "application/json; charset=utf-8",
862 )
863 .body(Body::empty())
864 .unwrap();
865 assert_eq!(run_browser(req).await, StatusCode::OK);
866 }
867}