1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
21#[serde(rename_all = "lowercase")]
22pub enum Status {
23 Ok,
24 Warn,
25 Fail,
26}
27
28#[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#[derive(Debug, Clone, PartialEq, Serialize)]
45pub struct DoctorReport {
46 pub checks: Vec<DoctorCheck>,
47 pub ok: bool,
48}
49
50impl DoctorReport {
51 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#[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
72pub 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
82fn 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
107const 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 let head: String = value.chars().take(6).collect();
120 format!("{head}...")
121}
122
123async fn identity(t: &Transport) -> Result<(String, String)> {
125 let body = t.get_absolute_es("/_security/_authenticate").await?;
126 decode_identity(&body)
127}
128
129fn 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
155async 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
178pub 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
228pub 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 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 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 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}