elasticctl-api 0.7.5

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
//! Dashboard artifact import planning and apply.

use super::{
    BTreeMap, BTreeSet, DashboardSpec, Error, ErrorKind, Path, Result, Serialize, Transport, Value,
    dashboards, data_views, invalid_plan, validate,
};

/// The immutable, guard-ready import work computed from one portable
/// dashboard artifact.
#[derive(Debug, Clone, PartialEq)]
pub struct DashboardImportPlan {
    pub preview: crate::ops::MutationPlan,
    pub specs: Vec<DashboardSpec>,
    pub before: BTreeMap<String, Option<DashboardSpec>>,
    pub skipped: Vec<Value>,
    pub total: usize,
    pub overwrite: bool,
}

/// The per-object result of applying a guarded dashboard import.
///
/// Field order is rendered JSON order and is contractual.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct DashboardImportReport {
    pub applied: bool,
    pub succeeded: Vec<Value>,
    pub skipped: Vec<Value>,
    pub failed: Vec<Value>,
    pub lossy: Vec<Value>,
    pub total: usize,
}
/// Fully validate an artifact and collect the precise import work to show in
/// the mutation guard. The supplied transport is optional only for a local
/// no-conflict plan with no data-view references.
pub async fn plan_import(
    transport: Option<&Transport>,
    path: &Path,
    overwrite: bool,
    skip_existing: bool,
) -> Result<DashboardImportPlan> {
    let mut specs = validate(path)?;
    if specs.is_empty() {
        return Err(Error::new(
            ErrorKind::Error,
            "dashboard import needs at least one dashboard",
        ));
    }
    if overwrite && skip_existing {
        return Err(Error::new(
            ErrorKind::Error,
            "--overwrite and --skip-existing cannot be used together",
        ));
    }

    let references: BTreeSet<_> = specs
        .iter()
        .flat_map(|spec| dashboards::collect_data_view_refs(&Value::Object(spec.data.clone())))
        .collect();
    let requires_server =
        overwrite || skip_existing || transport.is_some() || !references.is_empty();
    let transport = if requires_server { transport } else { None };
    if (overwrite || skip_existing || !references.is_empty()) && transport.is_none() {
        return Err(Error::new(
            ErrorKind::Error,
            "dashboard import preflight needs a transport",
        ));
    }

    let total = specs.len();
    let mut before = BTreeMap::new();
    let mut conflicts = Vec::new();
    if let Some(transport) = transport {
        for spec in &specs {
            match read_spec(transport, &spec.id).await {
                Ok(current) => {
                    if !overwrite && !skip_existing {
                        conflicts.push(spec.id.clone());
                    }
                    before.insert(spec.id.clone(), Some(current));
                }
                Err(error) if error.kind == ErrorKind::NotFound => {
                    before.insert(spec.id.clone(), None);
                }
                Err(error) => return Err(error),
            }
        }

        let mut missing = Vec::new();
        for id in references {
            match data_views::get(transport, &id).await {
                Ok(data_view) => match data_view.data_view.get("id").and_then(Value::as_str) {
                    Some(actual) if actual == id => {}
                    Some(actual) => {
                        return Err(Error::new(
                            ErrorKind::Http,
                            format!("decoding data view: expected id '{id}', got '{actual}'"),
                        ));
                    }
                    None => {
                        return Err(Error::new(
                            ErrorKind::Http,
                            format!(
                                "decoding data view: expected id '{id}', got missing or non-string id"
                            ),
                        ));
                    }
                },
                Err(error) if error.kind == ErrorKind::NotFound => missing.push(id),
                Err(error) => return Err(error),
            }
        }
        if !missing.is_empty() {
            return Err(Error::new(
                ErrorKind::NotFound,
                format!("referenced data views do not exist: {}", missing.join(", ")),
            ));
        }
    } else {
        before.extend(specs.iter().map(|spec| (spec.id.clone(), None)));
    }

    if !conflicts.is_empty() {
        return Err(Error::new(
            ErrorKind::Conflict,
            format!("dashboards already exist: {}", conflicts.join(", ")),
        ));
    }

    let mut skipped = Vec::new();
    if skip_existing {
        specs.retain(|spec| match before.get(&spec.id) {
            Some(Some(_)) => {
                skipped.push(serde_json::json!({"id": spec.id, "reason": "exists"}));
                false
            }
            _ => true,
        });
        before.retain(|id, _| specs.iter().any(|spec| spec.id == *id));
    }

    let preview = crate::ops::MutationPlan {
        preview_action: format!("Import {} dashboard(s)", specs.len()),
        preview_details: import_preview_details(&specs, &before),
        targets: specs.iter().map(|spec| spec.id.clone()).collect(),
    };
    Ok(DashboardImportPlan {
        preview,
        specs,
        before,
        skipped,
        total,
        overwrite,
    })
}

/// Apply a guard-approved dashboard import without rereading its source file.
///
/// The final dashboard GET immediately precedes each possible PUT. Kibana has
/// no conditional-write token, so the interval after that read is the smallest
/// unavoidable race window. Independent objects continue after failures, and
/// successful earlier writes are never rolled back.
pub async fn apply_import(
    transport: &Transport,
    plan: &DashboardImportPlan,
) -> Result<DashboardImportReport> {
    validate_import_plan(plan)?;
    let mut succeeded = Vec::new();
    let mut failed = Vec::new();
    let mut lossy = Vec::new();

    for desired in &plan.specs {
        let Some(before) = plan.before.get(&desired.id) else {
            failed.push(failed_row(&desired.id, false, "missing preflight snapshot"));
            continue;
        };
        let current = match read_spec(transport, &desired.id).await {
            Ok(current) => Some(current),
            Err(error) if error.kind == ErrorKind::NotFound => None,
            Err(error) => {
                failed.push(failed_row(&desired.id, false, error.message));
                continue;
            }
        };

        match (before, current) {
            (None, Some(_)) => {
                failed.push(failed_row(
                    &desired.id,
                    false,
                    "dashboard appeared since preview",
                ));
            }
            (Some(_), None) => {
                failed.push(failed_row(
                    &desired.id,
                    false,
                    "dashboard disappeared since preview",
                ));
            }
            (Some(before), Some(current)) if before != &current => {
                failed.push(failed_row(
                    &desired.id,
                    false,
                    "dashboard changed since preview",
                ));
            }
            (Some(_), Some(current)) if current == *desired => {
                succeeded.push(serde_json::json!({"id": desired.id, "action": "unchanged"}));
            }
            (None, None) => {
                apply_put(
                    transport,
                    desired,
                    "created",
                    &mut succeeded,
                    &mut failed,
                    &mut lossy,
                )
                .await;
            }
            (Some(_), Some(_)) => {
                apply_put(
                    transport,
                    desired,
                    "replaced",
                    &mut succeeded,
                    &mut failed,
                    &mut lossy,
                )
                .await;
            }
        }
    }

    Ok(DashboardImportReport {
        applied: true,
        succeeded,
        skipped: plan.skipped.clone(),
        failed,
        lossy,
        total: plan.total,
    })
}
async fn apply_put(
    transport: &Transport,
    desired: &DashboardSpec,
    action: &str,
    succeeded: &mut Vec<Value>,
    failed: &mut Vec<Value>,
    lossy: &mut Vec<Value>,
) {
    let response = match dashboards::put(transport, desired).await {
        Ok(response) => response,
        Err(error) => {
            failed.push(failed_row(&desired.id, false, error.message));
            return;
        }
    };
    if response.id != desired.id {
        failed.push(failed_row(
            &desired.id,
            true,
            format!(
                "dashboard PUT returned id '{}' instead of '{}'",
                response.id, desired.id
            ),
        ));
        return;
    }

    let mut paths: Vec<_> = dashboards::subset_losses(
        &Value::Object(desired.data.clone()),
        &Value::Object(response.data),
    )
    .into_iter()
    .map(|loss| loss.path)
    .collect();
    if paths.is_empty() {
        succeeded.push(serde_json::json!({"id": desired.id, "action": action}));
        return;
    }
    paths.sort();
    let warnings = match dashboards::get(transport, &desired.id).await {
        Ok(dashboard) if dashboard.id == desired.id => dashboard
            .warnings
            .into_iter()
            .map(|warning| warning.message)
            .collect(),
        Ok(dashboard) => {
            failed.push(failed_row(
                &desired.id,
                true,
                format!(
                    "dashboard loss audit returned id '{}' instead of '{}'",
                    dashboard.id, desired.id
                ),
            ));
            Vec::new()
        }
        Err(error) => {
            failed.push(failed_row(
                &desired.id,
                true,
                format!("dashboard loss audit failed: {}", error.message),
            ));
            Vec::new()
        }
    };
    lossy.push(serde_json::json!({
        "id": desired.id,
        "applied": true,
        "paths": paths,
        "warnings": warnings,
    }));
}

fn validate_import_plan(plan: &DashboardImportPlan) -> Result<()> {
    if plan.total == 0 {
        return invalid_plan("total must be greater than zero");
    }
    if plan.total != plan.specs.len() + plan.skipped.len() {
        return invalid_plan("total does not equal pending and skipped dashboards");
    }
    if !plan.skipped.is_empty() && plan.overwrite {
        return invalid_plan("skipped dashboards require skip-existing mode");
    }

    let mut ids = Vec::with_capacity(plan.specs.len());
    for spec in &plan.specs {
        dashboards::validate_spec(spec)?;
        if ids
            .last()
            .is_some_and(|previous: &String| previous >= &spec.id)
        {
            return invalid_plan("pending dashboards must be unique and sorted by id");
        }
        ids.push(spec.id.clone());
    }
    let pending: BTreeSet<_> = ids.iter().cloned().collect();
    if plan.preview.targets != ids {
        return invalid_plan("preview targets do not match pending dashboards");
    }
    if plan.preview.preview_action != format!("Import {} dashboard(s)", plan.specs.len()) {
        return invalid_plan("preview action does not match pending dashboards");
    }
    if plan.preview.preview_details != import_preview_details(&plan.specs, &plan.before) {
        return invalid_plan("preview details do not match pending dashboards");
    }

    if plan.before.keys().cloned().collect::<BTreeSet<_>>() != pending {
        return invalid_plan("preflight snapshots do not match pending dashboards");
    }
    for spec in &plan.specs {
        match plan.before.get(&spec.id).expect("checked key set") {
            None => {}
            Some(snapshot) => {
                dashboards::validate_spec(snapshot)?;
                if snapshot.id != spec.id {
                    return invalid_plan("preflight snapshot id does not match its target");
                }
                if !plan.overwrite {
                    return invalid_plan("replacement plan requires overwrite");
                }
            }
        }
    }

    let mut skipped_ids = BTreeSet::new();
    let mut previous = None;
    for row in &plan.skipped {
        let object = row
            .as_object()
            .filter(|object| object.len() == 2)
            .ok_or_else(|| Error::new(ErrorKind::Error, "invalid dashboard import skipped row"))?;
        if !object.keys().map(String::as_str).eq(["id", "reason"]) {
            return invalid_plan("invalid dashboard import skipped row order");
        }
        let id = object
            .get("id")
            .and_then(Value::as_str)
            .filter(|id| !id.trim().is_empty())
            .ok_or_else(|| Error::new(ErrorKind::Error, "invalid dashboard import skipped row"))?;
        if object.get("reason").and_then(Value::as_str) != Some("exists")
            || previous.is_some_and(|previous: &str| previous >= id)
            || !skipped_ids.insert(id.to_owned())
            || pending.contains(id)
        {
            return invalid_plan("invalid dashboard import skipped rows");
        }
        previous = Some(id);
    }
    Ok(())
}

fn failed_row(id: &str, applied: bool, error: impl Into<String>) -> Value {
    serde_json::json!({"id": id, "applied": applied, "error": error.into()})
}
/// Read one live dashboard and rebuild the portable spec used for snapshot
/// comparisons. The response id is checked separately from its request path.
async fn read_spec(transport: &Transport, id: &str) -> Result<DashboardSpec> {
    let dashboard = dashboards::get(transport, id).await?;
    if dashboard.id != id {
        return Err(Error::new(
            ErrorKind::Http,
            format!(
                "decoding dashboard: expected id '{id}', got '{}'",
                dashboard.id
            ),
        ));
    }
    let spec = DashboardSpec {
        id: dashboard.id,
        data: dashboard.data,
    };
    dashboards::validate_spec(&spec)?;
    Ok(spec)
}

fn import_preview_details(
    specs: &[DashboardSpec],
    before: &BTreeMap<String, Option<DashboardSpec>>,
) -> Vec<String> {
    specs
        .iter()
        .filter_map(|spec| match before.get(&spec.id) {
            Some(None) => Some(format!("{}  create  {}", spec.id, dashboard_title(spec))),
            Some(Some(current)) if current == spec => {
                Some(format!("{}  no-op  {}", spec.id, dashboard_title(spec)))
            }
            Some(Some(current)) => Some(format!(
                "{}  replace  {} -> {}",
                spec.id,
                dashboard_title(current),
                dashboard_title(spec)
            )),
            None => None,
        })
        .collect()
}

fn dashboard_title(spec: &DashboardSpec) -> &str {
    spec.data
        .get("title")
        .and_then(Value::as_str)
        .expect("validated dashboard specs have a title")
}