Skip to main content

elasticctl_api/
health.rs

1//! Health orchestration: `doctor` and `info`.
2//!
3//! `doctor` reads the stack and reports every check it can, so a broken
4//! configuration surfaces as a failed check rather than an error envelope.
5//! The checks that read the operator's local configuration live in `-cli`,
6//! which has the `Context`; these functions take a `&Transport` and report
7//! only what the stack says.
8
9use crate::rules::{self, RuleFilter};
10use elasticctl_core::capabilities::{probe_license_tier, probe_spaces};
11use elasticctl_core::{Capabilities, Error, ErrorKind, Result, Transport};
12use serde::Serialize;
13use serde_json::Value;
14
15/// The outcome of one `doctor` check.
16///
17/// Serialized lowercase (`ok`, `warn`, `fail`). `warn` passes the report but
18/// carries a caution, so it is distinct from `ok` even though both leave
19/// [`DoctorReport::ok`] true.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
21#[serde(rename_all = "lowercase")]
22pub enum Status {
23    Ok,
24    Warn,
25    Fail,
26}
27
28/// One `doctor` check.
29///
30/// Field order is the serialized JSON key order and is contractual: the root
31/// `Cargo.toml` enables `serde_json`'s `preserve_order`, so reordering these
32/// fields would silently change rendered output.
33#[derive(Debug, Clone, PartialEq, Serialize)]
34pub struct DoctorCheck {
35    #[serde(rename = "check")]
36    pub name: String,
37    #[serde(rename = "status")]
38    pub status: Status,
39    #[serde(rename = "message")]
40    pub detail: String,
41}
42
43/// The report `doctor` renders.
44#[derive(Debug, Clone, PartialEq, Serialize)]
45pub struct DoctorReport {
46    pub checks: Vec<DoctorCheck>,
47    pub ok: bool,
48}
49
50impl DoctorReport {
51    /// Build a report from its checks, deriving `ok` from them.
52    ///
53    /// This is the single place `ok` is derived, so a check with a misspelled
54    /// status cannot silently report a broken stack as healthy.
55    pub fn from_checks(checks: Vec<DoctorCheck>) -> DoctorReport {
56        let ok = checks.iter().all(|c| c.status != Status::Fail);
57        DoctorReport { checks, ok }
58    }
59}
60
61/// The stack-derived half of `info`'s report. The caller prepends the
62/// profile fields (`elasticctl_version`, `profile`, `kibana_url`, `space`)
63/// it alone can supply.
64#[derive(Debug, Clone, PartialEq)]
65pub struct InfoReport {
66    pub version: String,
67    pub flavor: String,
68    pub license: Option<String>,
69    pub spaces: Option<Vec<String>>,
70}
71
72/// Construct a check. Public so `-cli` builds its configuration checks with
73/// the same shape as the stack checks.
74pub fn check(name: &str, status: Status, message: impl Into<String>) -> DoctorCheck {
75    DoctorCheck {
76        name: name.into(),
77        status,
78        detail: message.into(),
79    }
80}
81
82/// `_es_api_key` can mint a rule API key for the caller; `_cloud_api_key`
83/// cannot. Other realms are not API keys, so the result names the realm
84/// without claiming otherwise.
85fn key_scope_check(realm: &str) -> DoctorCheck {
86    match realm {
87        "_es_api_key" => check(
88            "key_scope",
89            Status::Ok,
90            "project-scoped Elasticsearch API key",
91        ),
92        "_cloud_api_key" => check(
93            "key_scope",
94            Status::Warn,
95            "Organization-level API key: reads and deletes work, but enabling a \
96             rule will fail. Create a project-scoped Elasticsearch API key in \
97             Kibana under Management > API keys.",
98        ),
99        other => check(
100            "key_scope",
101            Status::Ok,
102            format!("authenticated via the '{other}' realm, not an Elasticsearch API key"),
103        ),
104    }
105}
106
107/// Identities longer than this are truncated in output.
108///
109/// API keys authenticate as their key IDs. Truncate those IDs because
110/// `config show` redacts them, while short usernames remain readable.
111const MAX_IDENTITY_CHARS: usize = 12;
112
113fn short_identity(value: &str) -> String {
114    if value.chars().count() <= MAX_IDENTITY_CHARS {
115        return value.to_string();
116    }
117    // By characters, not bytes: a byte slice can split a multibyte character
118    // and panic.
119    let head: String = value.chars().take(6).collect();
120    format!("{head}...")
121}
122
123/// Reads the username and authentication realm from Elasticsearch.
124async fn identity(t: &Transport) -> Result<(String, String)> {
125    let body = t.get_absolute_es("/_security/_authenticate").await?;
126    decode_identity(&body)
127}
128
129/// Decode an `_authenticate` response, refusing a malformed success body.
130///
131/// A missing or mistyped `username` or `authentication_realm.type` must fail
132/// the auth check rather than read as an "unknown" realm.
133fn decode_identity(body: &Value) -> Result<(String, String)> {
134    let username = body
135        .get("username")
136        .and_then(Value::as_str)
137        .ok_or_else(|| identity_error("username", "must be a string"))?
138        .to_string();
139    let realm = body
140        .get("authentication_realm")
141        .and_then(|realm| realm.get("type"))
142        .and_then(Value::as_str)
143        .ok_or_else(|| identity_error("authentication_realm.type", "must be a string"))?
144        .to_string();
145    Ok((username, realm))
146}
147
148fn identity_error(field: &str, detail: impl std::fmt::Display) -> Error {
149    Error::new(
150        ErrorKind::Http,
151        format!("decoding identity response field {field}: {detail}"),
152    )
153}
154
155/// The value-list data streams (`/api/lists/index`) bootstrapping check.
156///
157/// A 404 is the absent case, not an error (spec 7.7): the route answering 404
158/// is how it says the data streams do not exist, and an exception entry of
159/// type `list` cannot work until they are created. Absence is a warning, not a
160/// failure — a stack with no value-list-backed exceptions never needs them.
161async fn value_list_index_check(t: &Transport) -> DoctorCheck {
162    match crate::exceptions::value_lists_bootstrapped(t).await {
163        Ok(true) => check(
164            "value_list_index",
165            Status::Ok,
166            "value-list data streams are bootstrapped",
167        ),
168        Ok(false) => check(
169            "value_list_index",
170            Status::Warn,
171            "value-list data streams are not bootstrapped; an exception entry of type \
172             'list' cannot work until POST /api/lists/index runs",
173        ),
174        Err(e) => check("value_list_index", Status::Fail, e.message),
175    }
176}
177
178/// Run the stack-reading checks.
179///
180/// The connectivity check gates the rest: without a capability probe there is
181/// no flavor, no realm, and no rule access to report. Spec 7.2: the realm is
182/// the signal for whether rule mutation will work — `_cloud_api_key` cannot
183/// enable a rule, and an operator must learn that here rather than from a 400
184/// in the middle of a push.
185pub async fn doctor(t: &Transport) -> Result<DoctorReport> {
186    let mut checks = Vec::new();
187
188    let caps = Capabilities::probe(t, t.kibana_url()).await;
189    match &caps {
190        Ok(_) => checks.push(check("connectivity", Status::Ok, t.kibana_url())),
191        Err(e) => checks.push(check("connectivity", Status::Fail, e.message.clone())),
192    }
193
194    if let Ok(c) = &caps {
195        checks.push(check(
196            "flavor",
197            Status::Ok,
198            format!("{} {}", c.flavor.as_str(), c.version),
199        ));
200
201        match identity(t).await {
202            Ok((username, realm)) => {
203                checks.push(check(
204                    "auth",
205                    Status::Ok,
206                    format!("{} via {realm}", short_identity(&username)),
207                ));
208                checks.push(key_scope_check(&realm));
209            }
210            Err(e) => checks.push(check("auth", Status::Fail, e.message)),
211        }
212
213        match rules::find_page(t, &RuleFilter::default(), 1, 1).await {
214            Ok((_, total)) => checks.push(check(
215                "rules_access",
216                Status::Ok,
217                format!("{total} rules visible"),
218            )),
219            Err(e) => checks.push(check("rules_access", Status::Fail, e.message)),
220        }
221
222        checks.push(value_list_index_check(t).await);
223    }
224
225    Ok(DoctorReport::from_checks(checks))
226}
227
228/// Probe the stack values only `info` reports.
229///
230/// Spaces and license tier each cost a request, so they are not part of the
231/// capability probe every command pays for. `None` means the value could not
232/// be determined; Serverless has no license tier.
233pub async fn info(t: &Transport) -> Result<InfoReport> {
234    let caps = Capabilities::probe(t, t.kibana_url()).await?;
235    let spaces = probe_spaces(t).await;
236    let license = probe_license_tier(t, caps.flavor).await;
237
238    Ok(InfoReport {
239        version: caps.version,
240        flavor: caps.flavor.as_str().to_string(),
241        license,
242        spaces,
243    })
244}
245
246#[cfg(test)]
247mod tests {
248    use super::*;
249
250    #[test]
251    fn status_serializes_to_the_rendered_lowercase_strings() {
252        assert_eq!(
253            serde_json::to_value(Status::Ok).unwrap(),
254            serde_json::json!("ok")
255        );
256        assert_eq!(
257            serde_json::to_value(Status::Warn).unwrap(),
258            serde_json::json!("warn")
259        );
260        assert_eq!(
261            serde_json::to_value(Status::Fail).unwrap(),
262            serde_json::json!("fail")
263        );
264    }
265
266    #[test]
267    fn key_scope_check_reports_ok_for_a_project_scoped_es_api_key() {
268        let c = key_scope_check("_es_api_key");
269        assert_eq!(c.status, Status::Ok);
270        assert!(c.detail.contains("project-scoped"));
271    }
272
273    #[test]
274    fn key_scope_check_warns_for_an_organization_cloud_api_key() {
275        let c = key_scope_check("_cloud_api_key");
276        assert_eq!(c.status, Status::Warn);
277        assert!(c.detail.contains("Organization-level"));
278    }
279
280    #[test]
281    fn key_scope_check_names_an_unrecognized_realm_rather_than_calling_it_an_api_key() {
282        let c = key_scope_check("native");
283        assert_eq!(c.status, Status::Ok);
284        assert!(
285            c.detail.contains("native"),
286            "message must name the realm: {}",
287            c.detail
288        );
289        assert!(
290            !c.detail.contains("project-scoped Elasticsearch API key"),
291            "must not claim a non-API-key realm is a project-scoped API key: {}",
292            c.detail
293        );
294    }
295
296    #[test]
297    fn key_scope_check_names_an_unclassifiable_realm() {
298        // A realm string that is neither API-key type is reported by name, not
299        // claimed as an API key.
300        let c = key_scope_check("unknown");
301        assert_eq!(c.status, Status::Ok);
302        assert!(c.detail.contains("unknown"));
303    }
304
305    #[test]
306    fn a_key_id_is_truncated_in_the_auth_check() {
307        // An API key authenticates as its key ID. `config show` redacts that
308        // identifier, so do not write it in full to stdout.
309        let full = "2XTe9p8BLjNicQlhfc9W";
310        let short = short_identity(full);
311        assert_eq!(short, "2XTe9p...");
312        assert!(
313            !full.starts_with(&short),
314            "sanity: the id must be shortened"
315        );
316    }
317
318    #[test]
319    fn a_human_username_is_left_readable() {
320        // Keep common usernames readable.
321        assert_eq!(short_identity("elastic"), "elastic");
322        assert_eq!(short_identity("admin"), "admin");
323        assert_eq!(short_identity("unknown"), "unknown");
324    }
325
326    #[test]
327    fn truncation_never_splits_a_multibyte_character() {
328        let s = short_identity("ααααααααααααααααα");
329        assert!(s.ends_with("..."));
330        assert_eq!(s.chars().count(), 9);
331    }
332
333    #[test]
334    fn doctor_check_serializes_to_the_rendered_key_names() {
335        let c = check("config", Status::Ok, "profile 'default'");
336        let v = serde_json::to_value(&c).unwrap();
337        assert_eq!(v["check"], "config");
338        assert_eq!(v["status"], "ok");
339        assert_eq!(v["message"], "profile 'default'");
340        assert_eq!(
341            v.as_object().map(|o| o.keys().cloned().collect::<Vec<_>>()),
342            Some(vec![
343                "check".to_string(),
344                "status".to_string(),
345                "message".to_string()
346            ]),
347            "key order is the rendered JSON order"
348        );
349    }
350
351    #[test]
352    fn from_checks_derives_ok_from_the_checks() {
353        assert!(
354            DoctorReport::from_checks(vec![
355                check("connectivity", Status::Ok, "ok"),
356                check("key_scope", Status::Warn, "caution"),
357            ])
358            .ok,
359            "a warning must not fail the report"
360        );
361        assert!(!DoctorReport::from_checks(vec![check("config", Status::Fail, "fail")]).ok);
362    }
363}