elasticctl-api 0.1.3

Typed detection-rule model and endpoint wrappers for Elastic Security.
Documentation
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
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
use elasticctl_api::model::Rule;
use elasticctl_api::rules::{self, BulkAction, RuleFilter};
use elasticctl_core::{ErrorKind, Profile, Transport};
use serde_json::json;
use wiremock::matchers::{
    body_partial_json, method, path, path_regex, query_param, query_param_is_missing,
};
use wiremock::{Mock, MockServer, ResponseTemplate};

fn profile_for(server: &MockServer) -> Profile {
    Profile {
        kibana_url: server.uri(),
        es_url: None,
        api_key: Some("essu_test".into()),
        username: None,
        password: None,
        space: "default".into(),
        verify: true,
        timeout_secs: 5,
    }
}

fn transport(server: &MockServer) -> Transport {
    Transport::new(&profile_for(server)).unwrap()
}

fn rule_json(id: &str) -> serde_json::Value {
    json!({"rule_id": id, "name": format!("rule {id}"), "type": "query", "risk_score": 21})
}

/// A `_find` response with `total` and exactly these rules. Partition tests
/// need one returned rule per counted rule to avoid a short-read failure.
fn find_body(total: u64, data: Vec<serde_json::Value>) -> serde_json::Value {
    json!({"page": 1, "perPage": 10000, "total": total, "data": data})
}

/// `count` rules named `{prefix}-0` through `{prefix}-{count - 1}`. The slice
/// data matches its total exactly.
fn rules_of(prefix: &str, count: u64) -> Vec<serde_json::Value> {
    (0..count)
        .map(|i| rule_json(&format!("{prefix}-{i}")))
        .collect()
}

#[test]
fn an_empty_filter_produces_no_kql() {
    assert_eq!(RuleFilter::default().to_kql(), None);
}

#[test]
fn filters_combine_with_and() {
    let f = RuleFilter {
        enabled: Some(true),
        severity: Some("high".into()),
        ..Default::default()
    };
    let kql = f.to_kql().unwrap();
    assert!(kql.contains("alert.attributes.enabled: true"), "{kql}");
    assert!(
        kql.contains("alert.attributes.params.severity: \"high\""),
        "{kql}"
    );
    assert!(kql.contains(" AND "), "{kql}");
}

#[test]
fn a_name_filter_produces_the_recorded_kql_path() {
    let f = RuleFilter {
        name: Some("Suspicious PowerShell".into()),
        ..Default::default()
    };
    assert_eq!(
        f.to_kql().unwrap(),
        "alert.attributes.name: \"Suspicious PowerShell\""
    );
}

#[test]
fn a_name_filter_escapes_a_quote() {
    let f = RuleFilter {
        name: Some("a\"b".into()),
        ..Default::default()
    };
    let kql = f.to_kql().unwrap();
    let mut expected = String::from("alert.attributes.name: \"a");
    expected.push('\\');
    expected.push('"');
    expected.push_str("b\"");
    assert_eq!(kql, expected);
}

#[test]
fn a_name_filter_combines_with_the_others() {
    let f = RuleFilter {
        name: Some("X".into()),
        enabled: Some(true),
        ..Default::default()
    };
    let kql = f.to_kql().unwrap();
    assert!(kql.contains("alert.attributes.name: \"X\""), "{kql}");
    assert!(kql.contains(" AND "), "{kql}");
}

#[tokio::test]
async fn find_page_returns_rules_and_the_total() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/detection_engine/rules/_find"))
        .and(query_param("page", "1"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "page": 1, "perPage": 20, "total": 2, "data": [rule_json("a"), rule_json("b")]
        })))
        .mount(&server)
        .await;

    let (rules, total) = rules::find_page(&transport(&server), &RuleFilter::default(), 1, 20)
        .await
        .unwrap();
    assert_eq!(rules.len(), 2);
    assert_eq!(total, 2);
}

/// The corpus is read once at the result window, not paged. `.expect(1)` fails
/// if page walking returns.
#[tokio::test]
async fn find_all_reads_the_corpus_in_one_request_at_the_result_window() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/detection_engine/rules/_find"))
        .and(query_param("page", "1"))
        .and(query_param("per_page", "10000"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "page": 1, "perPage": 10000, "total": 3,
            "data": [rule_json("a"), rule_json("b"), rule_json("c")]
        })))
        .expect(1)
        .mount(&server)
        .await;

    let all = rules::find_all(&transport(&server), &RuleFilter::default())
        .await
        .unwrap();
    assert_eq!(all.len(), 3);
}

/// A corpus above the window is read once per rule type. Six types hold one
/// rule and `new_terms` holds 9,995, so seven slices return all 10,001 rules.
#[tokio::test]
async fn find_all_partitions_a_corpus_above_the_window_by_rule_type() {
    let server = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path("/api/detection_engine/rules/_find"))
        .and(query_param_is_missing("filter"))
        .respond_with(ResponseTemplate::new(200).set_body_json(find_body(10001, vec![])))
        .mount(&server)
        .await;

    for (rule_type, count) in [
        ("query", 1u64),
        ("eql", 1),
        ("esql", 1),
        ("threshold", 1),
        ("threat_match", 1),
        ("machine_learning", 1),
        ("new_terms", 9995),
    ] {
        Mock::given(method("GET"))
            .and(path("/api/detection_engine/rules/_find"))
            .and(query_param(
                "filter",
                format!("alert.attributes.params.type: \"{rule_type}\""),
            ))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(find_body(count, rules_of(rule_type, count))),
            )
            .mount(&server)
            .await;
    }

    let all = rules::find_all(&transport(&server), &RuleFilter::default())
        .await
        .unwrap();
    assert_eq!(all.len(), 10001);
    assert!(
        all.iter().any(|r| r.rule_id().unwrap() == "query-0"),
        "the first type's rules must come back"
    );
    assert!(
        all.iter().any(|r| r.rule_id().unwrap() == "new_terms-9994"),
        "the last type's rules must come back too"
    );
}

/// A type still over the window is partitioned by `enabled`. A caller's
/// `rule_type` selects one type slice before that partition.
#[tokio::test]
async fn find_all_splits_an_oversized_type_by_enabled() {
    let server = MockServer::start().await;
    let filter = RuleFilter {
        rule_type: Some("query".into()),
        ..Default::default()
    };

    // The initial read and type slice use the same oversized filter.
    Mock::given(method("GET"))
        .and(path("/api/detection_engine/rules/_find"))
        .and(query_param(
            "filter",
            "alert.attributes.params.type: \"query\"",
        ))
        .respond_with(ResponseTemplate::new(200).set_body_json(find_body(10001, vec![])))
        .mount(&server)
        .await;

    Mock::given(method("GET"))
        .and(path("/api/detection_engine/rules/_find"))
        .and(query_param(
            "filter",
            "alert.attributes.enabled: true AND alert.attributes.params.type: \"query\"",
        ))
        .respond_with(ResponseTemplate::new(200).set_body_json(find_body(2, rules_of("on", 2))))
        .mount(&server)
        .await;

    Mock::given(method("GET"))
        .and(path("/api/detection_engine/rules/_find"))
        .and(query_param(
            "filter",
            "alert.attributes.enabled: false AND alert.attributes.params.type: \"query\"",
        ))
        .respond_with(
            ResponseTemplate::new(200).set_body_json(find_body(9999, rules_of("off", 9999))),
        )
        .mount(&server)
        .await;

    let all = rules::find_all(&transport(&server), &filter).await.unwrap();
    assert_eq!(all.len(), 10001);
}

/// Slice totals must equal the corpus total. Here seven slices return 7 rules
/// for a corpus of 10,001, so the short read is refused.
#[tokio::test]
async fn find_all_refuses_slice_totals_that_do_not_sum_to_the_corpus() {
    let server = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path("/api/detection_engine/rules/_find"))
        .and(query_param_is_missing("filter"))
        .respond_with(ResponseTemplate::new(200).set_body_json(find_body(10001, vec![])))
        .mount(&server)
        .await;

    for rule_type in [
        "query",
        "eql",
        "esql",
        "threshold",
        "threat_match",
        "machine_learning",
        "new_terms",
    ] {
        Mock::given(method("GET"))
            .and(path("/api/detection_engine/rules/_find"))
            .and(query_param(
                "filter",
                format!("alert.attributes.params.type: \"{rule_type}\""),
            ))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(find_body(1, rules_of(rule_type, 1))),
            )
            .mount(&server)
            .await;
    }

    let err = rules::find_all(&transport(&server), &RuleFilter::default())
        .await
        .unwrap_err();
    assert_eq!(err.kind, ErrorKind::Http);
    assert!(
        err.message.contains("10001") && err.message.contains("sum to 7"),
        "the error must name both the corpus count and the slice sum: {}",
        err.message
    );
}

/// A slice above the window after both partitions cannot be served. The error
/// names the count and limit, without suggesting `rules export` as an escape.
#[tokio::test]
async fn find_all_refuses_a_slice_still_over_the_window() {
    let server = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path("/api/detection_engine/rules/_find"))
        .and(query_param_is_missing("filter"))
        .respond_with(ResponseTemplate::new(200).set_body_json(find_body(10001, vec![])))
        .mount(&server)
        .await;

    Mock::given(method("GET"))
        .and(path("/api/detection_engine/rules/_find"))
        .and(query_param(
            "filter",
            "alert.attributes.params.type: \"query\"",
        ))
        .respond_with(ResponseTemplate::new(200).set_body_json(find_body(10001, vec![])))
        .mount(&server)
        .await;

    Mock::given(method("GET"))
        .and(path("/api/detection_engine/rules/_find"))
        .and(query_param(
            "filter",
            "alert.attributes.enabled: true AND alert.attributes.params.type: \"query\"",
        ))
        .respond_with(ResponseTemplate::new(200).set_body_json(find_body(10001, vec![])))
        .mount(&server)
        .await;

    let err = rules::find_all(&transport(&server), &RuleFilter::default())
        .await
        .unwrap_err();
    assert_eq!(err.kind, ErrorKind::Unsupported);
    assert!(
        err.message.contains("10001") && err.message.contains("10000"),
        "the error must name both the slice size and the window limit: {}",
        err.message
    );
    assert!(
        !err.message.contains("rules export"),
        "the error must not point at a command with its own 10,000 cap: {}",
        err.message
    );
}

/// A server that counts more rules than it serves contradicts itself. A short
/// list is indistinguishable from deleted rules.
#[tokio::test]
async fn find_all_refuses_a_short_read() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/detection_engine/rules/_find"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "page": 1, "perPage": 10000, "total": 999, "data": []
        })))
        .expect(1)
        .mount(&server)
        .await;

    let err = rules::find_all(&transport(&server), &RuleFilter::default())
        .await
        .unwrap_err();
    assert!(
        err.message.contains("999"),
        "the error must name the count the server claimed: {}",
        err.message
    );
}

/// An empty space is not a short read.
#[tokio::test]
async fn find_all_accepts_an_honestly_empty_corpus() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/detection_engine/rules/_find"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "page": 1, "perPage": 10000, "total": 0, "data": []
        })))
        .mount(&server)
        .await;

    assert!(
        rules::find_all(&transport(&server), &RuleFilter::default())
            .await
            .unwrap()
            .is_empty()
    );
}

#[tokio::test]
async fn get_queries_by_rule_id_not_by_server_id() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/detection_engine/rules"))
        .and(query_param("rule_id", "abc"))
        .respond_with(ResponseTemplate::new(200).set_body_json(rule_json("abc")))
        .mount(&server)
        .await;

    let r = rules::get(&transport(&server), "abc").await.unwrap();
    assert_eq!(r.rule_id().unwrap(), "abc");
}

/// An API rule with volatile fields that create and update must not forward.
fn rule_with_volatile_fields(id: &str) -> Rule {
    Rule::from_value(json!({
        "rule_id": id, "name": format!("rule {id}"), "type": "query", "risk_score": 21,
        "id": "server-side-id", "created_at": "2026-01-01T00:00:00.000Z",
        "created_by": "someone", "updated_at": "2026-01-01T00:00:00.000Z",
        "updated_by": "someone", "revision": 3, "version": 4
    }))
    .unwrap()
}

#[tokio::test]
async fn create_posts_to_the_rules_endpoint_and_returns_the_parsed_rule() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/api/detection_engine/rules"))
        .respond_with(ResponseTemplate::new(200).set_body_json(rule_json("a")))
        .mount(&server)
        .await;

    let rule = Rule::from_value(rule_json("a")).unwrap();
    let r = rules::create(&transport(&server), &rule).await.unwrap();
    assert_eq!(r.rule_id().unwrap(), "a");
}

#[tokio::test]
async fn create_strips_volatile_fields_from_the_request_body() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/api/detection_engine/rules"))
        .respond_with(ResponseTemplate::new(200).set_body_json(rule_json("a")))
        .mount(&server)
        .await;

    rules::create(&transport(&server), &rule_with_volatile_fields("a"))
        .await
        .unwrap();

    let requests = server.received_requests().await.unwrap();
    assert_eq!(requests.len(), 1);
    let body: serde_json::Value = requests[0].body_json().unwrap();
    assert!(body.get("id").is_none(), "volatile id must not be sent");
    assert!(body.get("created_at").is_none());
    assert!(body.get("updated_by").is_none());
    assert_eq!(body["rule_id"], "a", "the stable identity must survive");
}

#[tokio::test]
async fn update_puts_to_the_rules_endpoint_and_returns_the_parsed_rule() {
    let server = MockServer::start().await;
    Mock::given(method("PUT"))
        .and(path("/api/detection_engine/rules"))
        .respond_with(ResponseTemplate::new(200).set_body_json(rule_json("a")))
        .mount(&server)
        .await;

    let rule = Rule::from_value(rule_json("a")).unwrap();
    let r = rules::update(&transport(&server), &rule).await.unwrap();
    assert_eq!(r.rule_id().unwrap(), "a");
}

#[tokio::test]
async fn update_strips_volatile_fields_from_the_request_body() {
    let server = MockServer::start().await;
    Mock::given(method("PUT"))
        .and(path("/api/detection_engine/rules"))
        .respond_with(ResponseTemplate::new(200).set_body_json(rule_json("a")))
        .mount(&server)
        .await;

    rules::update(&transport(&server), &rule_with_volatile_fields("a"))
        .await
        .unwrap();

    let requests = server.received_requests().await.unwrap();
    assert_eq!(requests.len(), 1);
    let body: serde_json::Value = requests[0].body_json().unwrap();
    assert!(body.get("id").is_none(), "volatile id must not be sent");
    assert!(body.get("created_at").is_none());
    assert!(body.get("updated_by").is_none());
    assert_eq!(body["rule_id"], "a", "the stable identity must survive");
}

#[tokio::test]
async fn patch_targets_the_stable_rule_id() {
    let server = MockServer::start().await;
    Mock::given(method("PATCH"))
        .and(path("/api/detection_engine/rules"))
        .and(body_partial_json(
            json!({"rule_id": "abc", "enabled": true}),
        ))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "rule_id": "abc", "name": "r", "enabled": true
        })))
        .mount(&server)
        .await;

    let r = rules::patch(&transport(&server), "abc", &json!({"enabled": true}))
        .await
        .unwrap();
    assert!(r.enabled());
}

#[tokio::test]
async fn bulk_targets_rule_ids_through_the_query_form() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/api/detection_engine/rules/_bulk_action"))
        .and(body_partial_json(json!({"action": "disable"})))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "success": true, "rules_count": 2,
            "attributes": {"summary": {"succeeded": 2, "failed": 0, "skipped": 0, "total": 2}}
        })))
        .mount(&server)
        .await;

    let ids = vec!["a".to_string(), "b".to_string()];
    let out = rules::bulk_by_rule_ids(&transport(&server), BulkAction::Disable, &ids, false)
        .await
        .unwrap();
    assert_eq!(out.succeeded, 2);
    assert_eq!(out.total, 2);

    let requests = server.received_requests().await.unwrap();
    assert_eq!(requests.len(), 1);
    let body: serde_json::Value = requests[0].body_json().unwrap();
    let query = body["query"].as_str().unwrap();
    assert!(
        query.contains("alert.attributes.params.ruleId"),
        "must target the stable rule_id through the query form: {query}"
    );
    assert!(
        query.contains("\"a\"") && query.contains("\"b\""),
        "both ids must appear in the query: {query}"
    );
    assert!(
        body.get("ids").is_none(),
        "must not target the volatile server-side ids"
    );
}

#[tokio::test]
async fn bulk_dry_run_sets_the_query_parameter() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/api/detection_engine/rules/_bulk_action"))
        .and(query_param("dry_run", "true"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "attributes": {"summary": {"succeeded": 1, "failed": 0, "skipped": 0, "total": 1}}
        })))
        .mount(&server)
        .await;

    let ids = vec!["a".to_string()];
    let out = rules::bulk_by_rule_ids(&transport(&server), BulkAction::Enable, &ids, true)
        .await
        .unwrap();
    assert_eq!(out.succeeded, 1);
}

#[tokio::test]
async fn bulk_with_no_targets_makes_no_request() {
    // An empty selection must not query every rule.
    let server = MockServer::start().await;
    let out = rules::bulk_by_rule_ids(&transport(&server), BulkAction::Delete, &[], false)
        .await
        .unwrap();
    assert_eq!(out.total, 0);
    assert!(
        server.received_requests().await.unwrap().is_empty(),
        "no request may be sent"
    );
}

#[tokio::test]
async fn export_separates_rules_from_the_trailer() {
    let server = MockServer::start().await;
    let body = format!(
        "{}\n{}\n",
        serde_json::to_string(&rule_json("a")).unwrap(),
        r#"{"exported_count":1,"exported_rules_count":1,"missing_rules_count":0}"#
    );
    Mock::given(method("POST"))
        .and(path("/api/detection_engine/rules/_export"))
        .respond_with(ResponseTemplate::new(200).set_body_string(body))
        .mount(&server)
        .await;

    let (rules, summary) = rules::export(&transport(&server), None).await.unwrap();
    assert_eq!(rules.len(), 1);
    assert_eq!(summary.unwrap().exported_rules_count, 1);
}

#[tokio::test]
async fn a_scoped_export_sends_the_objects_body() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/api/detection_engine/rules/_export"))
        .and(body_partial_json(
            json!({"objects": [{"rule_id": "a"}, {"rule_id": "b"}]}),
        ))
        .respond_with(ResponseTemplate::new(200).set_body_string(concat!(
            r#"{"rule_id":"a","name":"A"}"#,
            "\n",
            r#"{"exported_count":1,"exported_rules_count":1,"missing_rules":[{"rule_id":"b"}],"missing_rules_count":1}"#,
            "\n"
        )))
        .mount(&server)
        .await;

    let ids = vec!["a".to_string(), "b".to_string()];
    let (rules, summary) = rules::export(&transport(&server), Some(&ids))
        .await
        .unwrap();
    assert_eq!(rules.len(), 1);
    let summary = summary.unwrap();
    assert_eq!(summary.missing_rules_count, 1);
    assert_eq!(summary.missing_rules[0]["rule_id"], "b");
}

/// An unscoped export posts no body, preserving the established request shape.
#[tokio::test]
async fn an_unscoped_export_sends_no_body() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/api/detection_engine/rules/_export"))
        .respond_with(ResponseTemplate::new(200).set_body_string(
            "{\"exported_count\":0,\"exported_rules_count\":0,\"missing_rules_count\":0}\n",
        ))
        .mount(&server)
        .await;

    rules::export(&transport(&server), None).await.unwrap();
    let requests = server.received_requests().await.unwrap();
    assert_eq!(requests.len(), 1);
    assert!(
        requests[0].body.is_empty(),
        "an unscoped export must post no body: {:?}",
        String::from_utf8_lossy(&requests[0].body)
    );
}

#[tokio::test]
async fn existing_rule_ids_reports_only_the_ids_the_server_knows() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/detection_engine/rules/_find"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "page": 1, "perPage": 3, "total": 1, "data": [rule_json("b")]
        })))
        .mount(&server)
        .await;

    let ids = vec!["a".to_string(), "b".to_string(), "c".to_string()];
    let found = rules::existing_rule_ids(&transport(&server), &ids)
        .await
        .unwrap();
    assert_eq!(found.len(), 1);
    assert!(found.contains("b"));
}

#[tokio::test]
async fn existing_rule_ids_sends_no_request_for_an_empty_list() {
    let server = MockServer::start().await;
    assert!(
        rules::existing_rule_ids(&transport(&server), &[])
            .await
            .unwrap()
            .is_empty()
    );
    assert!(
        server.received_requests().await.unwrap().is_empty(),
        "an empty list must never become an unscoped find"
    );
}

#[tokio::test]
async fn import_reflects_overwrite_true_in_the_query_string() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/api/detection_engine/rules/_import"))
        .and(query_param("overwrite", "true"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "success": true, "success_count": 1, "errors": []
        })))
        .mount(&server)
        .await;

    let ndjson = format!("{}\n", serde_json::to_string(&rule_json("a")).unwrap());
    let result = rules::import(&transport(&server), &ndjson, true)
        .await
        .unwrap();
    assert_eq!(result["success_count"], 1);
}

#[tokio::test]
async fn import_reflects_overwrite_false_in_the_query_string() {
    // Overwrite replaces existing rules, so the settings must stay distinct.
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/api/detection_engine/rules/_import"))
        .and(query_param("overwrite", "false"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "success": true, "success_count": 1, "errors": []
        })))
        .mount(&server)
        .await;

    let ndjson = format!("{}\n", serde_json::to_string(&rule_json("a")).unwrap());
    let result = rules::import(&transport(&server), &ndjson, false)
        .await
        .unwrap();
    assert_eq!(result["success_count"], 1);
}

#[tokio::test]
async fn import_sends_the_ndjson_as_a_multipart_upload() {
    // Kibana import requires a multipart file upload, not a JSON body.
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/api/detection_engine/rules/_import"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "success": true, "success_count": 1, "errors": []
        })))
        .mount(&server)
        .await;

    let ndjson = format!("{}\n", serde_json::to_string(&rule_json("abc")).unwrap());
    rules::import(&transport(&server), &ndjson, true)
        .await
        .unwrap();

    let requests = server.received_requests().await.unwrap();
    assert_eq!(requests.len(), 1);
    let content_type = requests[0]
        .headers
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or_default();
    assert!(
        content_type.starts_with("multipart/form-data"),
        "{content_type}"
    );
    let body = String::from_utf8_lossy(&requests[0].body);
    assert!(body.contains("\"rule_id\":\"abc\""), "{body}");
}

#[tokio::test]
async fn a_failing_import_is_a_classified_error() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/api/detection_engine/rules/_import"))
        .respond_with(ResponseTemplate::new(400).set_body_json(json!({
            "message": "invalid ndjson"
        })))
        .mount(&server)
        .await;

    let err = rules::import(&transport(&server), "not ndjson", true)
        .await
        .unwrap_err();
    assert_eq!(err.kind, elasticctl_core::ErrorKind::Http);
    assert!(err.message.contains("invalid ndjson"), "{}", err.message);
}

#[tokio::test]
async fn a_404_from_get_is_a_not_found_error() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/detection_engine/rules"))
        .respond_with(ResponseTemplate::new(404).set_body_json(json!({"message": "not found"})))
        .mount(&server)
        .await;

    let err = rules::get(&transport(&server), "missing")
        .await
        .unwrap_err();
    assert_eq!(err.kind, elasticctl_core::ErrorKind::NotFound);
}

/// Replay the recorded exchange. A hand-written mock would test assumptions,
/// not the preview alerts index response.
#[tokio::test]
async fn preview_hits_parses_the_recorded_response() {
    let fixture: serde_json::Value = serde_json::from_str(
        &std::fs::read_to_string(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../tests/fixtures/serverless-9.6.0/rules_preview_hits.json"
        ))
        .expect("rules_preview_hits fixture"),
    )
    .expect("fixture is JSON");

    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path_regex(
            r"^/\.preview\.alerts-security\.alerts-default/_search$",
        ))
        .respond_with(ResponseTemplate::new(200).set_body_json(fixture["response"].clone()))
        .mount(&server)
        .await;

    let mut profile = profile_for(&server);
    profile.es_url = Some(server.uri());
    let t = Transport::new(&profile).unwrap();

    let hits = rules::preview_hits(&t, "default", "pv-1", 3).await.unwrap();
    assert!(hits.total >= 1, "the recorded response carries hits");
    assert!(!hits.sample.is_empty(), "a sample must carry the documents");
    assert!(
        hits.sample[0].get("_source").is_some(),
        "a sample entry is the alert document, not a summary of it: {:?}",
        hits.sample[0]
    );
}

#[tokio::test]
async fn preview_hits_queries_the_space_scoped_preview_index_by_preview_id() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/.preview.alerts-security.alerts-soc/_search"))
        .and(body_partial_json(json!({
            "size": 0,
            "track_total_hits": true,
            "query": {"term": {"kibana.alert.rule.uuid": "pv-9"}}
        })))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "hits": {"total": {"value": 302, "relation": "eq"}, "hits": []}
        })))
        .mount(&server)
        .await;

    let mut profile = profile_for(&server);
    profile.es_url = Some(server.uri());
    let t = Transport::new(&profile).unwrap();

    let hits = rules::preview_hits(&t, "soc", "pv-9", 0).await.unwrap();
    assert_eq!(hits.total, 302);
    assert!(hits.sample.is_empty(), "size 0 asks for no documents");
}

#[tokio::test]
async fn preview_hits_treats_an_empty_space_as_default() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/.preview.alerts-security.alerts-default/_search"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "hits": {"total": {"value": 0}, "hits": []}
        })))
        .mount(&server)
        .await;
    let mut profile = profile_for(&server);
    profile.es_url = Some(server.uri());
    let t = Transport::new(&profile).unwrap();

    assert_eq!(
        rules::preview_hits(&t, "", "pv-1", 0).await.unwrap().total,
        0
    );
}