manta-cli 1.64.0

Another CLI for ALPS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
//! Smoke tests for the HTTP server layer.
//!
//! These tests build the Axum router with a stub backend (real
//! CSM/OCHAMI struct, dummy URLs) and call it via
//! `tower::ServiceExt::oneshot` without starting a TCP listener
//! or doing TLS negotiation.
//!
//! What is verified:
//!   - Health endpoint is reachable and unauthenticated
//!   - Every other route enforces Bearer-token authentication
//!   - Unknown routes return 404, wrong methods return 405
//!   - Request-body validation fires before backend calls
//!   - Vault/K8s-dependent routes return 501 when not configured

use std::sync::Arc;

use axum::{
  body::Body,
  http::{Method, Request, StatusCode, header},
};
use http_body_util::BodyExt as _;
use tower::ServiceExt as _;

use crate::{
  manta_backend_dispatcher::StaticBackendDispatcher,
  server::{ServerState, routes::build_router},
};

// ---------------------------------------------------------------------------
// Test helpers
// ---------------------------------------------------------------------------

/// Build a router backed by a stub CSM backend with no real URLs.
/// Backend methods are never called because all non-health tests
/// either fail at auth or at Axum's request extraction layer first.
fn router() -> axum::Router {
  let backend =
    StaticBackendDispatcher::new("csm", "http://stub.invalid", b"", None).unwrap();
  let state = Arc::new(ServerState {
    backend,
    site_name: "test".to_string(),
    shasta_base_url: "http://stub.invalid".to_string(),
    shasta_root_cert: vec![],
    socks5_proxy: None,
    vault_base_url: None,
    gitea_base_url: "http://stub.invalid".to_string(),
    k8s_api_url: None,
    console_inactivity_timeout: std::time::Duration::from_secs(1800),
  });
  build_router(state)
}

/// Same as `router()` but with vault and k8s URLs set, used to
/// reach the "requires vault/k8s" code paths.
fn router_with_vault() -> axum::Router {
  let backend =
    StaticBackendDispatcher::new("csm", "http://stub.invalid", b"", None).unwrap();
  let state = Arc::new(ServerState {
    backend,
    site_name: "test".to_string(),
    shasta_base_url: "http://stub.invalid".to_string(),
    shasta_root_cert: vec![],
    socks5_proxy: None,
    vault_base_url: Some("http://vault.stub.invalid".to_string()),
    gitea_base_url: "http://stub.invalid".to_string(),
    k8s_api_url: Some("http://k8s.stub.invalid".to_string()),
    console_inactivity_timeout: std::time::Duration::from_secs(1800),
  });
  build_router(state)
}

async fn body_string(body: Body) -> String {
  let bytes = body.collect().await.unwrap().to_bytes();
  String::from_utf8_lossy(&bytes).into_owned()
}

fn get(uri: &str) -> Request<Body> {
  Request::builder()
    .method(Method::GET)
    .uri(uri)
    .body(Body::empty())
    .unwrap()
}

fn get_auth(uri: &str) -> Request<Body> {
  Request::builder()
    .method(Method::GET)
    .uri(uri)
    .header(header::AUTHORIZATION, "Bearer test-token")
    .body(Body::empty())
    .unwrap()
}

fn delete_auth(uri: &str) -> Request<Body> {
  Request::builder()
    .method(Method::DELETE)
    .uri(uri)
    .header(header::AUTHORIZATION, "Bearer test-token")
    .body(Body::empty())
    .unwrap()
}

fn post_json(uri: &str, body: &str) -> Request<Body> {
  Request::builder()
    .method(Method::POST)
    .uri(uri)
    .header(header::CONTENT_TYPE, "application/json")
    .header(header::AUTHORIZATION, "Bearer test-token")
    .body(Body::from(body.to_string()))
    .unwrap()
}

// ---------------------------------------------------------------------------
// Health check
// ---------------------------------------------------------------------------

#[tokio::test]
async fn health_returns_200_without_auth() {
  let resp = router().oneshot(get("/api/v1/health")).await.unwrap();
  assert_eq!(resp.status(), StatusCode::OK);
}

#[tokio::test]
async fn health_body_contains_status_ok() {
  let resp = router().oneshot(get("/api/v1/health")).await.unwrap();
  let body = body_string(resp.into_body()).await;
  assert!(body.contains("\"ok\""), "body was: {}", body);
}

// ---------------------------------------------------------------------------
// Unknown routes return 404
// ---------------------------------------------------------------------------

#[tokio::test]
async fn unknown_route_returns_404() {
  let resp = router()
    .oneshot(get("/api/v1/does-not-exist"))
    .await
    .unwrap();
  assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn wrong_api_version_returns_404() {
  let resp = router()
    .oneshot(get("/api/v2/sessions"))
    .await
    .unwrap();
  assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}

// ---------------------------------------------------------------------------
// Wrong HTTP method returns 405
// ---------------------------------------------------------------------------

#[tokio::test]
async fn get_on_post_only_route_returns_405() {
  let resp = router()
    .oneshot(get("/api/v1/power"))
    .await
    .unwrap();
  assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
}

#[tokio::test]
async fn post_on_get_only_route_returns_405() {
  // POST /clusters is not a registered route; only GET is allowed.
  let resp = router()
    .oneshot(
      Request::builder()
        .method(Method::POST)
        .uri("/api/v1/clusters")
        .body(Body::empty())
        .unwrap(),
    )
    .await
    .unwrap();
  assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
}

#[tokio::test]
async fn delete_health_returns_405() {
  let resp = router()
    .oneshot(
      Request::builder()
        .method(Method::DELETE)
        .uri("/api/v1/health")
        .body(Body::empty())
        .unwrap(),
    )
    .await
    .unwrap();
  assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
}

// ---------------------------------------------------------------------------
// Authentication enforcement — GET endpoints
//
// GET endpoints have no body extractors, so the handler always runs
// and the first thing it does is check the Authorization header.
// ---------------------------------------------------------------------------

async fn assert_401_without_auth(uri: &str) {
  let resp = router().oneshot(get(uri)).await.unwrap();
  assert_eq!(
    resp.status(),
    StatusCode::UNAUTHORIZED,
    "expected 401 for GET {}",
    uri
  );
}

#[tokio::test]
async fn get_sessions_requires_auth() {
  assert_401_without_auth("/api/v1/sessions").await;
}

#[tokio::test]
async fn get_configurations_requires_auth() {
  assert_401_without_auth("/api/v1/configurations").await;
}

#[tokio::test]
async fn get_groups_requires_auth() {
  assert_401_without_auth("/api/v1/groups").await;
}

#[tokio::test]
async fn get_images_requires_auth() {
  assert_401_without_auth("/api/v1/images").await;
}

#[tokio::test]
async fn get_templates_requires_auth() {
  assert_401_without_auth("/api/v1/templates").await;
}

#[tokio::test]
async fn get_boot_parameters_requires_auth() {
  assert_401_without_auth("/api/v1/boot-parameters").await;
}

#[tokio::test]
async fn get_kernel_parameters_requires_auth() {
  assert_401_without_auth("/api/v1/kernel-parameters").await;
}

#[tokio::test]
async fn get_redfish_endpoints_requires_auth() {
  assert_401_without_auth("/api/v1/redfish-endpoints").await;
}

#[tokio::test]
async fn get_clusters_requires_auth() {
  assert_401_without_auth("/api/v1/clusters").await;
}

#[tokio::test]
async fn get_hardware_clusters_requires_auth() {
  assert_401_without_auth("/api/v1/hardware-clusters").await;
}

// ---------------------------------------------------------------------------
// Authentication enforcement — DELETE endpoints without body
// ---------------------------------------------------------------------------

#[tokio::test]
async fn delete_node_requires_auth() {
  let resp = router()
    .oneshot(
      Request::builder()
        .method(Method::DELETE)
        .uri("/api/v1/nodes/x3000c0s1b0n0")
        .body(Body::empty())
        .unwrap(),
    )
    .await
    .unwrap();
  assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}

#[tokio::test]
async fn delete_group_requires_auth() {
  let resp = router()
    .oneshot(
      Request::builder()
        .method(Method::DELETE)
        .uri("/api/v1/groups/my-group")
        .body(Body::empty())
        .unwrap(),
    )
    .await
    .unwrap();
  assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}

#[tokio::test]
async fn delete_session_requires_auth() {
  let resp = router()
    .oneshot(
      Request::builder()
        .method(Method::DELETE)
        .uri("/api/v1/sessions/my-session")
        .body(Body::empty())
        .unwrap(),
    )
    .await
    .unwrap();
  assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}

#[tokio::test]
async fn delete_redfish_endpoint_requires_auth() {
  let resp = router()
    .oneshot(
      Request::builder()
        .method(Method::DELETE)
        .uri("/api/v1/redfish-endpoints/x3000c0s1b0")
        .body(Body::empty())
        .unwrap(),
    )
    .await
    .unwrap();
  assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}

// ---------------------------------------------------------------------------
// Request-body validation
//
// These requests include a valid Bearer token. The Axum JSON
// extractor fires before the handler body, so missing required
// fields return 422 Unprocessable Entity before the backend is
// touched.
// ---------------------------------------------------------------------------

#[tokio::test]
async fn post_nodes_missing_required_fields_returns_422() {
  let resp = router()
    .oneshot(post_json("/api/v1/nodes", "{}"))
    .await
    .unwrap();
  assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
}

#[tokio::test]
async fn post_ephemeral_env_missing_image_id_returns_422() {
  let resp = router()
    .oneshot(post_json("/api/v1/ephemeral-env", "{}"))
    .await
    .unwrap();
  assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
}

#[tokio::test]
async fn post_power_unknown_action_returns_422() {
  // "fly" is not a valid PowerAction enum variant — serde rejects it with 422.
  let resp = router()
    .oneshot(post_json(
      "/api/v1/power",
      r#"{"action":"fly","targets":["x3000c0s1b0n0"],"target_type":"nodes"}"#,
    ))
    .await
    .unwrap();
  assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
}

#[tokio::test]
async fn post_power_missing_action_returns_422() {
  let resp = router()
    .oneshot(post_json(
      "/api/v1/power",
      r#"{"targets":["x3000c0s1b0n0"],"target_type":"nodes"}"#,
    ))
    .await
    .unwrap();
  assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
}

#[tokio::test]
async fn post_template_session_missing_required_fields_returns_422() {
  let resp = router()
    .oneshot(post_json(
      "/api/v1/templates/my-template/sessions",
      r#"{"dry_run":false}"#,
    ))
    .await
    .unwrap();
  assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
}

#[tokio::test]
async fn post_sat_file_missing_content_returns_422() {
  let resp = router()
    .oneshot(post_json("/api/v1/sat-file", "{}"))
    .await
    .unwrap();
  assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
}

// ---------------------------------------------------------------------------
// Missing required query parameters
//
// GET /nodes and GET /hardware-nodes have a required `xname`/`xnames`
// query parameter. Authenticated requests that omit it get 400 Bad Request.
// ---------------------------------------------------------------------------

#[tokio::test]
async fn get_nodes_without_xname_returns_400() {
  let resp = router()
    .oneshot(get_auth("/api/v1/nodes"))
    .await
    .unwrap();
  assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}

#[tokio::test]
async fn get_hardware_nodes_without_xnames_returns_400() {
  let resp = router()
    .oneshot(get_auth("/api/v1/hardware-nodes"))
    .await
    .unwrap();
  assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}

// ---------------------------------------------------------------------------
// Optional-config endpoints return 501 when vault/k8s not configured
// ---------------------------------------------------------------------------

#[tokio::test]
async fn get_session_logs_without_k8s_config_returns_501() {
  let resp = router()
    .oneshot(get_auth("/api/v1/sessions/my-session/logs"))
    .await
    .unwrap();
  assert_eq!(resp.status(), StatusCode::NOT_IMPLEMENTED);
}

#[tokio::test]
async fn post_sat_file_without_vault_config_returns_501() {
  let resp = router()
    .oneshot(post_json(
      "/api/v1/sat-file",
      r#"{"sat_file_content":"schema: 1.0\n"}"#,
    ))
    .await
    .unwrap();
  assert_eq!(resp.status(), StatusCode::NOT_IMPLEMENTED);
}

// When vault IS configured but k8s is not, sat-file still returns 501.
#[tokio::test]
async fn post_sat_file_without_k8s_config_returns_501() {
  let backend =
    StaticBackendDispatcher::new("csm", "http://stub.invalid", b"", None).unwrap();
  let state = Arc::new(ServerState {
    backend,
    site_name: "test".to_string(),
    shasta_base_url: "http://stub.invalid".to_string(),
    shasta_root_cert: vec![],
    socks5_proxy: None,
    vault_base_url: Some("http://vault.stub.invalid".to_string()),
    gitea_base_url: "http://stub.invalid".to_string(),
    k8s_api_url: None, // k8s not set
    console_inactivity_timeout: std::time::Duration::from_secs(1800),
  });
  let resp = build_router(state)
    .oneshot(post_json(
      "/api/v1/sat-file",
      r#"{"sat_file_content":"schema: 1.0\n"}"#,
    ))
    .await
    .unwrap();
  assert_eq!(resp.status(), StatusCode::NOT_IMPLEMENTED);
}

// ---------------------------------------------------------------------------
// Route existence — authenticated requests must not return 404 or 405
// ---------------------------------------------------------------------------

async fn assert_route_exists(method: Method, uri: &str) {
  let req = Request::builder()
    .method(method)
    .uri(uri)
    .header(header::AUTHORIZATION, "Bearer test-token")
    .header(header::CONTENT_TYPE, "application/json")
    .body(Body::empty())
    .unwrap();
  let resp = router().oneshot(req).await.unwrap();
  assert_ne!(
    resp.status(),
    StatusCode::NOT_FOUND,
    "route not found: {}",
    uri
  );
  assert_ne!(
    resp.status(),
    StatusCode::METHOD_NOT_ALLOWED,
    "method not allowed: {}",
    uri
  );
}

#[tokio::test]
async fn all_get_routes_are_registered() {
  for uri in &[
    "/api/v1/sessions",
    "/api/v1/configurations",
    "/api/v1/groups",
    "/api/v1/images",
    "/api/v1/templates",
    "/api/v1/boot-parameters",
    "/api/v1/kernel-parameters",
    "/api/v1/redfish-endpoints",
    "/api/v1/clusters",
    "/api/v1/hardware-clusters",
    "/api/v1/health",
    "/api/v1/nodes/x3000c0s1b0n0/console",
    "/api/v1/sessions/my-session/console",
  ] {
    assert_route_exists(Method::GET, uri).await;
  }
}

#[tokio::test]
async fn all_post_routes_are_registered() {
  for uri in &[
    "/api/v1/sessions",
    "/api/v1/sessions/apply",
    "/api/v1/nodes",
    "/api/v1/groups",
    "/api/v1/groups/test/members",
    "/api/v1/boot-parameters",
    "/api/v1/redfish-endpoints",
    "/api/v1/boot-config",
    "/api/v1/kernel-parameters/apply",
    "/api/v1/kernel-parameters/add",
    "/api/v1/migrate/nodes",
    "/api/v1/migrate/backup",
    "/api/v1/migrate/restore",
    "/api/v1/ephemeral-env",
    "/api/v1/power",
    "/api/v1/templates/my-template/sessions",
    "/api/v1/sat-file",
    "/api/v1/hardware-clusters/my-cluster/members",
    "/api/v1/hardware-clusters/my-cluster/configuration",
  ] {
    assert_route_exists(Method::POST, uri).await;
  }
}

#[tokio::test]
async fn all_delete_routes_are_registered() {
  for uri in &[
    "/api/v1/nodes/x3000c0s1b0n0",
    "/api/v1/groups/my-group",
    "/api/v1/groups/my-group/members",
    "/api/v1/boot-parameters",
    "/api/v1/kernel-parameters",
    "/api/v1/redfish-endpoints/x3000c0s1b0",
    "/api/v1/sessions/my-session",
    "/api/v1/images",
    "/api/v1/configurations",
    "/api/v1/hardware-clusters/my-cluster/members",
  ] {
    assert_route_exists(Method::DELETE, uri).await;
  }
}

// ---------------------------------------------------------------------------
// Auth enforcement for the 6 new endpoints
// ---------------------------------------------------------------------------

#[tokio::test]
async fn add_kernel_parameters_requires_auth() {
  let resp = router()
    .oneshot(
      Request::builder()
        .method(Method::POST)
        .uri("/api/v1/kernel-parameters/add")
        .header(header::CONTENT_TYPE, "application/json")
        .body(Body::from(r#"{"params":"quiet"}"#))
        .unwrap(),
    )
    .await
    .unwrap();
  assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}

#[tokio::test]
async fn delete_kernel_parameters_requires_auth() {
  let resp = router()
    .oneshot(
      Request::builder()
        .method(Method::DELETE)
        .uri("/api/v1/kernel-parameters")
        .header(header::CONTENT_TYPE, "application/json")
        .body(Body::from(r#"{"params":"quiet"}"#))
        .unwrap(),
    )
    .await
    .unwrap();
  assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}

#[tokio::test]
async fn add_hw_component_requires_auth() {
  let resp = router()
    .oneshot(
      Request::builder()
        .method(Method::POST)
        .uri("/api/v1/hardware-clusters/my-cluster/members")
        .header(header::CONTENT_TYPE, "application/json")
        .body(Body::from(r#"{"parent_cluster":"p","pattern":"a100:2"}"#))
        .unwrap(),
    )
    .await
    .unwrap();
  assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}

#[tokio::test]
async fn delete_hw_component_requires_auth() {
  let resp = router()
    .oneshot(
      Request::builder()
        .method(Method::DELETE)
        .uri("/api/v1/hardware-clusters/my-cluster/members")
        .header(header::CONTENT_TYPE, "application/json")
        .body(Body::from(r#"{"parent_cluster":"p","pattern":"a100:2"}"#))
        .unwrap(),
    )
    .await
    .unwrap();
  assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}

#[tokio::test]
async fn apply_hw_configuration_requires_auth() {
  let resp = router()
    .oneshot(
      Request::builder()
        .method(Method::POST)
        .uri("/api/v1/hardware-clusters/my-cluster/configuration")
        .header(header::CONTENT_TYPE, "application/json")
        .body(Body::from(r#"{"parent_cluster":"p","pattern":"a100:2"}"#))
        .unwrap(),
    )
    .await
    .unwrap();
  assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}

#[tokio::test]
async fn apply_session_requires_auth() {
  let resp = router()
    .oneshot(
      Request::builder()
        .method(Method::POST)
        .uri("/api/v1/sessions/apply")
        .header(header::CONTENT_TYPE, "application/json")
        .body(Body::from(
          r#"{"repo_names":["cray/foo"],"repo_last_commit_ids":["abc"]}"#,
        ))
        .unwrap(),
    )
    .await
    .unwrap();
  assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}

// ---------------------------------------------------------------------------
// Body validation (422) for new endpoints
// ---------------------------------------------------------------------------

#[tokio::test]
async fn add_kernel_parameters_missing_params_returns_422() {
  let resp = router()
    .oneshot(post_json("/api/v1/kernel-parameters/add", "{}"))
    .await
    .unwrap();
  assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
}

#[tokio::test]
async fn delete_kernel_parameters_missing_params_returns_422() {
  let resp = router()
    .oneshot(post_json("/api/v1/kernel-parameters", "{}"))
    .await
    .unwrap();
  // DELETE /kernel-parameters — wrong method from post_json (POST), expect 405
  assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
}

#[tokio::test]
async fn add_hw_component_missing_body_returns_422() {
  let resp = router()
    .oneshot(post_json("/api/v1/hardware-clusters/my-cluster/members", "{}"))
    .await
    .unwrap();
  assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
}

#[tokio::test]
async fn apply_hw_configuration_missing_body_returns_422() {
  let resp = router()
    .oneshot(post_json(
      "/api/v1/hardware-clusters/my-cluster/configuration",
      "{}",
    ))
    .await
    .unwrap();
  assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
}

#[tokio::test]
async fn apply_session_missing_repo_fields_returns_422() {
  let resp = router()
    .oneshot(post_json("/api/v1/sessions/apply", "{}"))
    .await
    .unwrap();
  assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
}

// ---------------------------------------------------------------------------
// apply_session — 501 when vault not configured
// ---------------------------------------------------------------------------

#[tokio::test]
async fn apply_session_without_vault_returns_501() {
  let resp = router()
    .oneshot(post_json(
      "/api/v1/sessions/apply",
      r#"{"repo_names":["cray/foo"],"repo_last_commit_ids":["abc123"]}"#,
    ))
    .await
    .unwrap();
  assert_eq!(resp.status(), StatusCode::NOT_IMPLEMENTED);
}

// ---------------------------------------------------------------------------
// WebSocket console auth tests
// ---------------------------------------------------------------------------

/// Build a minimal WebSocket upgrade GET request (no actual TCP connection).
/// `WebSocketUpgrade` requires these headers to extract successfully, which
/// lets handler-body checks (auth, 501 guards) run and return HTTP errors.
fn ws_upgrade(uri: &str) -> Request<Body> {
  Request::builder()
    .method(Method::GET)
    .uri(uri)
    .header(header::CONNECTION, "Upgrade")
    .header(header::UPGRADE, "websocket")
    .header("Sec-WebSocket-Version", "13")
    .header("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==")
    .body(Body::empty())
    .unwrap()
}


#[tokio::test]
async fn console_node_without_auth_returns_401() {
  let resp = router()
    .oneshot(ws_upgrade("/api/v1/nodes/x3000c0s1b0n0/console"))
    .await
    .unwrap();
  assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}

#[tokio::test]
async fn console_session_without_auth_returns_401() {
  let resp = router()
    .oneshot(ws_upgrade("/api/v1/sessions/my-session/console"))
    .await
    .unwrap();
  assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}


// ---------------------------------------------------------------------------
// Error mapping unit tests
// ---------------------------------------------------------------------------

#[test]
fn to_handler_error_not_found_variants() {
  use crate::server::handlers::to_handler_error;
  use axum::http::StatusCode;
  use manta_backend_dispatcher::error::Error;

  assert_eq!(to_handler_error(Error::NotFound("session foo".into())).0, StatusCode::NOT_FOUND);
  assert_eq!(to_handler_error(Error::SessionNotFound).0, StatusCode::NOT_FOUND);
  assert_eq!(to_handler_error(Error::ConfigurationNotFound).0, StatusCode::NOT_FOUND);
}

#[test]
fn to_handler_error_conflict_variants() {
  use crate::server::handlers::to_handler_error;
  use axum::http::StatusCode;
  use manta_backend_dispatcher::error::Error;

  assert_eq!(to_handler_error(Error::Conflict("group foo".into())).0, StatusCode::CONFLICT);
  assert_eq!(to_handler_error(Error::ConfigurationAlreadyExistsError("cfg".into())).0, StatusCode::CONFLICT);
}

#[test]
fn to_handler_error_bad_request_and_internal() {
  use crate::server::handlers::to_handler_error;
  use axum::http::StatusCode;
  use manta_backend_dispatcher::error::Error;

  assert_eq!(to_handler_error(Error::BadRequest("bad input".into())).0, StatusCode::BAD_REQUEST);
  assert_eq!(to_handler_error(Error::Message("something broke".into())).0, StatusCode::INTERNAL_SERVER_ERROR);
}