1use 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
18const EXCEPTION_POINTER_PLACEHOLDER: &str = "00000000-0000-0000-0000-000000000000";
22
23#[derive(Debug, Clone, PartialEq, Serialize)]
25pub struct RuleListReport {
26 pub total: usize,
27 pub rules: Vec<Rule>,
28}
29
30#[derive(Debug, Clone)]
32pub struct RulePage {
33 pub total: u64,
34 pub rules: Vec<Rule>,
35}
36
37#[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#[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#[derive(Debug, Clone, PartialEq, Serialize)]
61pub struct ValidateReport {
62 pub valid: bool,
63 pub count: usize,
64 pub rules: Vec<RuleValidation>,
65}
66
67#[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
89pub 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
99fn 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
112pub 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
118pub 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 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 Err(e) => failures.push(format!("rule at index {i}: {}", e.message)),
155 }
156 }
157
158 if !failures.is_empty() {
159 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
171async 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
236pub 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
255pub 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 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 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 Format::Ndjson => codec::encode_bundle(&bundle)?,
327 };
328
329 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
344pub 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 Format::Yaml => codec::Bundle {
365 rules: codec::decode_yaml(&body)?,
366 ..Default::default()
367 },
368 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 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
454fn 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
483fn 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
505pub async fn apply_import(t: &Transport, ndjson: &str, overwrite: bool) -> Result<ImportReport> {
507 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 crate::ops::decode_import_report(&response, "rules")
520}
521
522async 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
541pub 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 let timeframe_end = now_rfc3339();
572 let result = rules::preview(t, &rule, invocations, &timeframe_end).await?;
573
574 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 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
618fn 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 #[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 (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 #[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}