Skip to main content

elasticctl_api/
rules_ops.rs

1//! Rules command orchestration, above the endpoint wrappers in `rules`.
2//!
3//! The `-cli` crate resolves context, applies the guard, and renders; this
4//! module does the work between them so a future MCP server can call the same
5//! functions and serialize the same structs.
6
7use crate::codec::{self, Format};
8use crate::model::{ListKey, Rule, exception_refs, server_defaults};
9use crate::normalize;
10use crate::ops::{DeleteOutcome, ExportOutcome, ImportPlan, ImportReport, MutationPlan};
11use crate::rules::{self, BulkAction, RuleFilter, RuleSource};
12use crate::selection;
13use elasticctl_core::{Error, ErrorKind, Result, Transport};
14use serde::Serialize;
15use serde_json::{Value, json};
16use std::path::Path;
17
18/// Kibana validates an exception pointer as a string before it re-resolves the
19/// reference against the target stack. This deterministic placeholder is
20/// upload-only: the server replaces it with the live container id.
21const EXCEPTION_POINTER_PLACEHOLDER: &str = "00000000-0000-0000-0000-000000000000";
22
23/// The report `list` renders: every matching rule, in server order.
24#[derive(Debug, Clone, PartialEq, Serialize)]
25pub struct RuleListReport {
26    pub total: usize,
27    pub rules: Vec<Rule>,
28}
29
30/// One name-ordered page of rules and the server's match total.
31#[derive(Debug, Clone)]
32pub struct RulePage {
33    pub total: u64,
34    pub rules: Vec<Rule>,
35}
36
37/// The report an `enable`/`disable` apply renders. Field order is the
38/// serialized JSON key order and is contractual: the root `Cargo.toml` enables
39/// `serde_json`'s `preserve_order`.
40#[derive(Debug, Clone, PartialEq, Serialize)]
41pub struct SetEnabledOutcome {
42    pub applied: bool,
43    pub succeeded: u64,
44    pub failed: u64,
45    pub skipped: u64,
46    pub total: u64,
47}
48
49/// One rule's validation entry.
50#[derive(Debug, Clone, PartialEq, Serialize)]
51pub struct RuleValidation {
52    pub rule_id: String,
53    pub name: String,
54    #[serde(rename = "type")]
55    pub rule_type: String,
56    pub defaults_applied: Vec<String>,
57}
58
59/// The report `validate` renders.
60#[derive(Debug, Clone, PartialEq, Serialize)]
61pub struct ValidateReport {
62    pub valid: bool,
63    pub count: usize,
64    pub rules: Vec<RuleValidation>,
65}
66
67/// The report a preview renders.
68#[derive(Debug, Clone, PartialEq, Serialize)]
69pub struct PreviewReport {
70    pub rule: String,
71    pub preview_id: Option<String>,
72    pub invocations: u32,
73    pub hits: Option<u64>,
74    pub errors: Vec<String>,
75    pub warnings: Vec<String>,
76    pub hits_error: Option<String>,
77    pub sample: Vec<Value>,
78}
79
80pub async fn list(t: &Transport, filter: &RuleFilter) -> Result<RuleListReport> {
81    let rules = rules::find_all(t, filter).await?;
82    if rules.is_empty() && is_unselected_source_query(filter) {
83        rules::verify_source_partition(t).await?;
84    }
85    let total = rules.len();
86    Ok(RuleListReport { total, rules })
87}
88
89/// Read at most `limit` rules in one request, ordered by name. MCP uses this
90/// because a whole-corpus read can exceed the response body cap.
91pub async fn list_page(t: &Transport, filter: &RuleFilter, limit: u32) -> Result<RulePage> {
92    let (rules, total) = rules::find_first_by_name(t, filter, limit).await?;
93    if rules.is_empty() && is_unselected_source_query(filter) {
94        rules::verify_source_partition(t).await?;
95    }
96    Ok(RulePage { total, rules })
97}
98
99/// A `rules list` filter has no positional selectors. Any remaining clause
100/// deliberately narrows the result and must not trigger a corpus proof.
101fn is_unselected_source_query(filter: &RuleFilter) -> bool {
102    matches!(filter.source, RuleSource::Custom | RuleSource::Prebuilt)
103        && filter.enabled.is_none()
104        && filter.rule_type.is_none()
105        && filter.severity.is_none()
106        && filter.tag.is_none()
107        && filter.name.is_none()
108        && filter.query.is_none()
109        && filter.search.is_none()
110}
111
112/// Resolve a selector and fetch the rule, canonicalized so output is stable.
113pub async fn get_one(t: &Transport, selector: &str) -> Result<Rule> {
114    let (_, rule) = selection::to_rule(t, selector).await?;
115    Ok(normalize::canonical(&rule))
116}
117
118/// Parse and validate a local file without contacting a server.
119///
120/// The codecs reject missing or non-string `rule_id` values. Keep the
121/// per-rule check because derived `Rule::Deserialize` bypasses that
122/// validation. Check every rule so one report names every invalid index.
123pub fn validate(path: &Path) -> Result<ValidateReport> {
124    let body = std::fs::read_to_string(path)
125        .map_err(|e| Error::new(ErrorKind::Error, format!("reading {}: {e}", path.display())))?;
126
127    let rules = match Format::from_path(path) {
128        Format::Yaml => codec::decode_yaml(&body)?,
129        Format::Ndjson => codec::decode_ndjson(&body)?.0,
130    };
131
132    let defaults = server_defaults();
133    let mut reports = Vec::with_capacity(rules.len());
134    let mut failures = Vec::new();
135
136    for (i, r) in rules.iter().enumerate() {
137        match r.rule_id() {
138            Ok(rule_id) => {
139                // Show server defaults applied to sparse rules.
140                let mut applied: Vec<String> = defaults
141                    .keys()
142                    .filter(|k| !r.as_map().contains_key(*k))
143                    .cloned()
144                    .collect();
145                applied.sort();
146                reports.push(RuleValidation {
147                    rule_id: rule_id.to_string(),
148                    name: r.name().to_string(),
149                    rule_type: r.rule_type().to_string(),
150                    defaults_applied: applied,
151                });
152            }
153            // Do not report a blank rule ID as valid.
154            Err(e) => failures.push(format!("rule at index {i}: {}", e.message)),
155        }
156    }
157
158    if !failures.is_empty() {
159        // An invalid rule invalidates the file. Return a classified error,
160        // not a partial success payload.
161        return Err(Error::new(ErrorKind::Error, failures.join("; ")));
162    }
163
164    Ok(ValidateReport {
165        valid: true,
166        count: rules.len(),
167        rules: reports,
168    })
169}
170
171/// Resolve every selector to its rule ID and rule before previewing, so the
172/// preview is accurate and unresolved selectors fail before mutation.
173async fn resolve_targets(t: &Transport, selectors: &[String]) -> Result<Vec<(String, Rule)>> {
174    let mut out = Vec::with_capacity(selectors.len());
175    for s in selectors {
176        out.push(selection::to_rule(t, s).await?);
177    }
178    Ok(out)
179}
180
181pub async fn plan_set_enabled(
182    t: &Transport,
183    selectors: &[String],
184    enable: bool,
185) -> Result<MutationPlan> {
186    let resolved = resolve_targets(t, selectors).await?;
187    let preview_details = resolved
188        .iter()
189        .map(|(id, r)| {
190            let from = if r.enabled() { "enabled" } else { "disabled" };
191            let to = if enable { "enabled" } else { "disabled" };
192            format!("{id}  {}  {from} -> {to}", r.name())
193        })
194        .collect();
195    let verb = if enable { "Enable" } else { "Disable" };
196    Ok(MutationPlan {
197        preview_action: format!("{verb} {} rule(s)", resolved.len()),
198        preview_details,
199        targets: resolved.into_iter().map(|(id, _)| id).collect(),
200    })
201}
202
203pub async fn apply_set_enabled(
204    t: &Transport,
205    plan: &MutationPlan,
206    enable: bool,
207) -> Result<SetEnabledOutcome> {
208    let action = if enable {
209        BulkAction::Enable
210    } else {
211        BulkAction::Disable
212    };
213    let o = rules::bulk_by_rule_ids(t, action, &plan.targets, false).await?;
214    Ok(SetEnabledOutcome {
215        applied: true,
216        succeeded: o.succeeded,
217        failed: o.failed,
218        skipped: o.skipped,
219        total: o.total,
220    })
221}
222
223pub async fn plan_delete(t: &Transport, selectors: &[String]) -> Result<MutationPlan> {
224    let resolved = resolve_targets(t, selectors).await?;
225    let preview_details = resolved
226        .iter()
227        .map(|(id, r)| format!("{id}  {}", r.name()))
228        .collect();
229    Ok(MutationPlan {
230        preview_action: format!("Delete {} rule(s)", resolved.len()),
231        preview_details,
232        targets: resolved.into_iter().map(|(id, _)| id).collect(),
233    })
234}
235
236/// Continue after per-rule failures so the result records every deletion and
237/// every rule that remains.
238pub async fn apply_delete(t: &Transport, plan: &MutationPlan) -> Result<DeleteOutcome> {
239    let mut deleted = Vec::new();
240    let mut failed = Vec::new();
241    for id in &plan.targets {
242        match rules::delete(t, id).await {
243            Ok(_) => deleted.push(json!({"rule_id": id})),
244            Err(e) => failed.push(json!({"rule_id": id, "error": e.message})),
245        }
246    }
247    Ok(DeleteOutcome {
248        applied: true,
249        deleted,
250        failed,
251        total: plan.targets.len(),
252    })
253}
254
255/// Fetch, canonicalize, and sort selected rules by rule ID. Exports from an
256/// unchanged stack are byte-identical for version-control review. Scoped by
257/// `source`; the `all` default lives on the clap flag (spec 5.5).
258///
259/// A source scope without a selector or tag resolves to the matching rule IDs
260/// first, so the subset export transfers only the subset (spec 4.3). A selector
261/// or tag is an explicit narrowing and overrides the source default, matching
262/// the state commands (spec 5.3).
263pub async fn export_rules(
264    t: &Transport,
265    selectors: &[String],
266    tag: Option<&str>,
267    source: RuleSource,
268    format: Format,
269) -> Result<ExportOutcome> {
270    let selection: Option<Vec<String>> =
271        if selectors.is_empty() && tag.is_none() && source != RuleSource::All {
272            let scoped = rules::find_all(
273                t,
274                &RuleFilter {
275                    source,
276                    ..Default::default()
277                },
278            )
279            .await?;
280            if scoped.is_empty() {
281                if matches!(source, RuleSource::Custom | RuleSource::Prebuilt) {
282                    rules::verify_source_partition(t).await?;
283                }
284                return Ok(ExportOutcome {
285                    body: String::new(),
286                    exported: 0,
287                    missing: Vec::new(),
288                });
289            }
290            Some(
291                scoped
292                    .iter()
293                    .filter_map(|r| r.rule_id().ok().map(str::to_owned))
294                    .collect(),
295            )
296        } else {
297            // Export reads from the stack, so every selector names a server rule.
298            selection::resolve(t, selectors, tag, None, &[], "export").await?
299        };
300
301    let mut bundle = rules::export(t, selection.as_deref()).await?;
302    for r in &mut bundle.rules {
303        *r = normalize::canonical(r);
304    }
305    normalize::sort_rules(&mut bundle.rules);
306
307    let body = match format {
308        // YAML carries rules only. A bundle with exception objects has no YAML
309        // form, so refuse rather than silently drop them (spec 5.2).
310        Format::Yaml => {
311            if !bundle.lists.is_empty() || !bundle.items.is_empty() {
312                return Err(Error::new(
313                    ErrorKind::Unsupported,
314                    format!(
315                        "this export carries {} exception list(s) and {} item(s), which the \
316                         YAML format cannot represent; re-run with --format-file ndjson",
317                        bundle.lists.len(),
318                        bundle.items.len()
319                    ),
320                ));
321            }
322            codec::encode_yaml(&bundle.rules)?
323        }
324        // The bundle's lists and items must survive the export or importing
325        // the file elsewhere recreates a rule pointing at a missing list.
326        Format::Ndjson => codec::encode_bundle(&bundle)?,
327    };
328
329    // A requested but missing rule was deleted after selection. Report it in
330    // `missing` so a short export has a nonzero exit code.
331    let missing = bundle
332        .summary
333        .as_ref()
334        .map(|s| s.missing_rules.clone())
335        .unwrap_or_default();
336
337    Ok(ExportOutcome {
338        body,
339        exported: bundle.rules.len() as u64,
340        missing,
341    })
342}
343
344/// Compute the import preview and the NDJSON to upload.
345///
346/// With `--skip-existing`, check existing rule IDs before the preview so it
347/// shows only rules that would import. That query is a read, so it belongs
348/// here and does not violate the no-write rule. The transport is `None` unless
349/// `skip_existing` is set, so a dry run that only reads the file never needs
350/// one.
351pub async fn plan_import(
352    t: Option<&Transport>,
353    path: &Path,
354    overwrite: bool,
355    skip_existing: bool,
356) -> Result<ImportPlan> {
357    let body = std::fs::read_to_string(path)
358        .map_err(|e| Error::new(ErrorKind::Error, format!("reading {}: {e}", path.display())))?;
359
360    let format = Format::from_path(path);
361    let mut bundle = match format {
362        // YAML has no exception-bundle representation. Preserve its existing
363        // rules-only behavior, then upload it as Kibana's required NDJSON.
364        Format::Yaml => codec::Bundle {
365            rules: codec::decode_yaml(&body)?,
366            ..Default::default()
367        },
368        // Rules export emits rules, exception containers, and exception items
369        // in one NDJSON bundle. Import must retain all three so Kibana can
370        // recreate containers and resolve their server-owned pointers.
371        Format::Ndjson => codec::decode_bundle(&body)?,
372    };
373    let total = bundle.rules.len();
374
375    let mut skipped: Vec<Value> = Vec::new();
376
377    if skip_existing {
378        let t = t.ok_or_else(|| {
379            Error::new(ErrorKind::Error, "import --skip-existing needs a transport")
380        })?;
381        let ids: Vec<String> = bundle
382            .rules
383            .iter()
384            .filter_map(|r| r.rule_id().ok().map(str::to_owned))
385            .collect();
386        let existing = rules::existing_rule_ids(t, &ids).await?;
387
388        let mut keep = Vec::with_capacity(bundle.rules.len());
389        for rule in std::mem::take(&mut bundle.rules) {
390            match rule.rule_id() {
391                Ok(id) if existing.contains(id) => {
392                    skipped.push(json!({"rule_id": id, "reason": "exists"}));
393                }
394                _ => keep.push(rule),
395            }
396        }
397        bundle.rules = keep;
398    }
399
400    if format == Format::Ndjson {
401        retain_referenced_exception_objects(&mut bundle);
402    }
403    add_upload_pointer_placeholders(&mut bundle);
404
405    let mut details: Vec<String> = bundle
406        .rules
407        .iter()
408        .map(|r| format!("{}  {}  import", r.rule_id().unwrap_or(""), r.name()))
409        .collect();
410    details.extend(skipped.iter().map(|s| {
411        format!(
412            "{}  skip (already exists)",
413            s["rule_id"].as_str().unwrap_or("")
414        )
415    }));
416
417    let qualifier = if overwrite {
418        ", overwriting existing".to_string()
419    } else if skip_existing && !skipped.is_empty() {
420        format!(", skipping {} that already exist", skipped.len())
421    } else {
422        String::new()
423    };
424    let preview = MutationPlan {
425        preview_action: format!(
426            "Import {} rule(s) from {}{qualifier}",
427            bundle.rules.len(),
428            path.display()
429        ),
430        preview_details: details,
431        targets: bundle
432            .rules
433            .iter()
434            .filter_map(|r| r.rule_id().ok().map(str::to_owned))
435            .collect(),
436    };
437
438    // Kibana's import takes NDJSON regardless of the source file's format.
439    // A source NDJSON bundle keeps its exception members; YAML remains rules
440    // only because that format cannot represent containers or items.
441    let ndjson = match format {
442        Format::Yaml => codec::encode_ndjson(&bundle.rules)?,
443        Format::Ndjson => codec::encode_bundle(&bundle)?,
444    };
445
446    Ok(ImportPlan {
447        preview,
448        ndjson,
449        total,
450        skipped,
451    })
452}
453
454/// Keep only containers and items a rule scheduled for upload references.
455/// `rules import` is guarded as a rule mutation, so an exception-only or
456/// unreferenced object must never become an unpreviewed side effect. Namespace
457/// is part of stable list identity, so equal `list_id` values in `single` and
458/// `agnostic` remain disjoint.
459fn retain_referenced_exception_objects(bundle: &mut codec::Bundle) {
460    let wanted: std::collections::BTreeSet<ListKey> = bundle
461        .rules
462        .iter()
463        .flat_map(exception_refs)
464        .map(|reference| ListKey {
465            list_id: reference.list_id,
466            namespace_type: reference.namespace_type,
467        })
468        .collect();
469
470    bundle
471        .lists
472        .retain(|list| list.key().is_ok_and(|key| wanted.contains(&key)));
473    bundle.items.retain(|item| {
474        item.list_id().is_ok_and(|list_id| {
475            wanted.contains(&ListKey {
476                list_id: list_id.to_string(),
477                namespace_type: item.namespace_type().to_string(),
478            })
479        })
480    });
481}
482
483/// Make every readable exception reference acceptable to Kibana's import
484/// schema. This deliberately changes only the transient upload bundle; source
485/// files remain pointer-free and malformed/unreadable entries survive intact.
486fn add_upload_pointer_placeholders(bundle: &mut codec::Bundle) {
487    for rule in &mut bundle.rules {
488        let Some(Value::Array(references)) = rule.as_map_mut().get_mut("exceptions_list") else {
489            continue;
490        };
491        for reference in references {
492            let Value::Object(reference) = reference else {
493                continue;
494            };
495            if reference.get("list_id").is_some_and(Value::is_string) {
496                reference.insert(
497                    "id".to_string(),
498                    Value::String(EXCEPTION_POINTER_PLACEHOLDER.to_string()),
499                );
500            }
501        }
502    }
503}
504
505/// Upload the NDJSON `plan_import` prepared.
506pub async fn apply_import(t: &Transport, ndjson: &str, overwrite: bool) -> Result<ImportReport> {
507    // Do not upload empty NDJSON when every rule already exists.
508    if ndjson.is_empty() {
509        return Ok(ImportReport {
510            succeeded: json!(0),
511            failed: json!([]),
512        });
513    }
514
515    let response = rules::import(t, ndjson, overwrite).await?;
516
517    // Normalize Kibana's response to the bulk-action shape so partial imports
518    // use the existing exit-code rule, refusing a malformed success body.
519    crate::ops::decode_import_report(&response, "rules")
520}
521
522/// Retry once only when the first search finds no hits.
523///
524/// The preview already completed each invocation. A newly written alert can
525/// miss the first search because of Elasticsearch's refresh interval. Retrying
526/// only zero hits avoids delay for matching rules and false zero results.
527async fn fetch_hits(
528    transport: &Transport,
529    space: &str,
530    preview_id: &str,
531    sample: usize,
532) -> Result<rules::PreviewHits> {
533    let first = rules::preview_hits(transport, space, preview_id, sample).await?;
534    if first.total > 0 {
535        return Ok(first);
536    }
537    tokio::time::sleep(std::time::Duration::from_secs(1)).await;
538    rules::preview_hits(transport, space, preview_id, sample).await
539}
540
541/// Preview a rule. An existing file path wins; otherwise the source is a rule
542/// ID or name from the stack. This supports unpushed local rules.
543pub async fn preview_rule(
544    t: &Transport,
545    source: &str,
546    invocations: u32,
547    sample: u32,
548    space: &str,
549) -> Result<PreviewReport> {
550    let path = Path::new(source);
551
552    let rule = if path.exists() {
553        let body = std::fs::read_to_string(path).map_err(|e| {
554            Error::new(ErrorKind::Error, format!("reading {}: {e}", path.display()))
555        })?;
556        let rules = match Format::from_path(path) {
557            Format::Yaml => codec::decode_yaml(&body)?,
558            Format::Ndjson => codec::decode_ndjson(&body)?.0,
559        };
560        rules.into_iter().next().ok_or_else(|| {
561            Error::new(
562                ErrorKind::Error,
563                format!("{} contains no rules", path.display()),
564            )
565        })?
566    } else {
567        selection::to_rule(t, source).await?.1
568    };
569
570    // The API requires an explicit end of the window it simulates over.
571    let timeframe_end = now_rfc3339();
572    let result = rules::preview(t, &rule, invocations, &timeframe_end).await?;
573
574    // Preserve the preview when reading hits fails. Set `hits` to null and
575    // report the error in `hits_error`.
576    let (hits, hits_error, sample_hits) = match &result.preview_id {
577        None => (
578            None,
579            Some("the server returned no preview_id".to_string()),
580            Vec::new(),
581        ),
582        Some(preview_id) => match fetch_hits(t, space, preview_id, sample as usize).await {
583            Ok(h) => (Some(h.total), None, h.sample),
584            Err(e) => (None, Some(e.message), Vec::new()),
585        },
586    };
587
588    Ok(PreviewReport {
589        rule: rule.name().to_string(),
590        preview_id: result.preview_id,
591        invocations,
592        hits,
593        errors: result.errors,
594        warnings: result.warnings,
595        hits_error,
596        sample: sample_hits,
597    })
598}
599
600fn now_rfc3339() -> String {
601    use std::time::{SystemTime, UNIX_EPOCH};
602    let secs = SystemTime::now()
603        .duration_since(UNIX_EPOCH)
604        .unwrap_or_default()
605        .as_secs();
606    // Format directly to avoid a date dependency; the API accepts UTC ISO-8601.
607    let days = secs / 86_400;
608    let rem = secs % 86_400;
609    let (y, m, d) = civil_from_days(days as i64);
610    format!(
611        "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}.000Z",
612        rem / 3600,
613        (rem % 3600) / 60,
614        rem % 60
615    )
616}
617
618/// Howard Hinnant's days-from-civil inverse, used without a date dependency.
619fn civil_from_days(z: i64) -> (i64, u32, u32) {
620    let z = z + 719_468;
621    let era = z.div_euclid(146_097);
622    let doe = z.rem_euclid(146_097);
623    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
624    let y = yoe + era * 400;
625    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
626    let mp = (5 * doy + 2) / 153;
627    let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
628    let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
629    (if m <= 2 { y + 1 } else { y }, m, d)
630}
631
632#[cfg(test)]
633mod date_tests {
634    use super::*;
635
636    /// Independently computed epoch days catch plausible arithmetic errors
637    /// that would shift a preview's `timeframeEnd`.
638    #[test]
639    fn civil_from_days_matches_independently_computed_epoch_days() {
640        let cases = [
641            (0, (1970, 1, 1), "epoch"),
642            (19782, (2024, 2, 29), "leap day"),
643            (11017, (2000, 3, 1), "century leap year (2000 % 400 == 0)"),
644            (20818, (2026, 12, 31), "year end"),
645            (20819, (2027, 1, 1), "year rollover"),
646            // 2100 is divisible by 100 but not 400, so it is not a leap year.
647            (47541, (2100, 3, 1), "century non-leap (2100 % 400 != 0)"),
648            (
649                47540,
650                (2100, 2, 28),
651                "day before the century non-leap rollover",
652            ),
653        ];
654
655        for (day, expected, label) in cases {
656            assert_eq!(civil_from_days(day), expected, "{label}: day {day}");
657        }
658    }
659
660    /// The API requires this exact `timeframeEnd` format.
661    #[test]
662    fn now_rfc3339_matches_the_shape_the_api_requires() {
663        let s = now_rfc3339();
664        let bytes = s.as_bytes();
665
666        assert_eq!(s.len(), 24, "{s}");
667        assert!(bytes[4] == b'-' && bytes[7] == b'-', "{s}");
668        assert_eq!(bytes[10], b'T', "{s}");
669        assert!(bytes[13] == b':' && bytes[16] == b':', "{s}");
670        assert_eq!(bytes[19], b'.', "{s}");
671        assert_eq!(&s[20..], "000Z", "{s}");
672        assert!(
673            s[..19]
674                .chars()
675                .enumerate()
676                .all(|(i, c)| { matches!(i, 4 | 7 | 10 | 13 | 16) || c.is_ascii_digit() }),
677            "every non-separator position must be a digit: {s}"
678        );
679    }
680}