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
129#[derive(Debug, Clone, PartialEq, Eq)]
131pub struct CredentialIdentity {
132 pub username: String,
134 pub realm_type: String,
136 pub api_key_id: Option<String>,
138}
139
140pub async fn credential_identity(t: &Transport) -> Result<CredentialIdentity> {
142 let body = t.get_absolute_es("/_security/_authenticate").await?;
143 let (username, realm_type) = decode_identity(&body)?;
144 let api_key_id = match body.get("api_key") {
145 None | Some(Value::Null) => None,
146 Some(Value::Object(key)) => match key.get("id") {
147 None => None,
148 Some(id) => Some(
149 id.as_str()
150 .filter(|s| !s.is_empty())
151 .ok_or_else(|| identity_error("api_key.id", "must be a non-empty string"))?
152 .to_string(),
153 ),
154 },
155 Some(_) => return Err(identity_error("api_key", "must be an object")),
156 };
157 Ok(CredentialIdentity {
158 username,
159 realm_type,
160 api_key_id,
161 })
162}
163
164fn decode_identity(body: &Value) -> Result<(String, String)> {
169 let username = body
170 .get("username")
171 .and_then(Value::as_str)
172 .filter(|value| !value.is_empty())
173 .ok_or_else(|| identity_error("username", "must be a non-empty string"))?
174 .to_string();
175 let realm = body
176 .get("authentication_realm")
177 .and_then(|realm| realm.get("type"))
178 .and_then(Value::as_str)
179 .filter(|value| !value.is_empty())
180 .ok_or_else(|| identity_error("authentication_realm.type", "must be a non-empty string"))?
181 .to_string();
182 Ok((username, realm))
183}
184
185fn identity_error(field: &str, detail: impl std::fmt::Display) -> Error {
186 Error::new(
187 ErrorKind::Http,
188 format!("decoding identity response field {field}: {detail}"),
189 )
190}
191
192async fn value_list_index_check(t: &Transport) -> DoctorCheck {
199 match crate::exceptions::value_lists_bootstrapped(t).await {
200 Ok(true) => check(
201 "value_list_index",
202 Status::Ok,
203 "value-list data streams are bootstrapped",
204 ),
205 Ok(false) => check(
206 "value_list_index",
207 Status::Warn,
208 "value-list data streams are not bootstrapped; an exception entry of type \
209 'list' cannot work until POST /api/lists/index runs",
210 ),
211 Err(e) => check("value_list_index", Status::Fail, e.message),
212 }
213}
214
215pub async fn doctor(t: &Transport) -> Result<DoctorReport> {
223 let mut checks = Vec::new();
224
225 let caps = Capabilities::probe(t, t.kibana_url()).await;
226 match &caps {
227 Ok(_) => checks.push(check("connectivity", Status::Ok, t.kibana_url())),
228 Err(e) => checks.push(check("connectivity", Status::Fail, e.message.clone())),
229 }
230
231 if let Ok(c) = &caps {
232 checks.push(check(
233 "flavor",
234 Status::Ok,
235 format!("{} {}", c.flavor.as_str(), c.version),
236 ));
237
238 match identity(t).await {
239 Ok((username, realm)) => {
240 checks.push(check(
241 "auth",
242 Status::Ok,
243 format!("{} via {realm}", short_identity(&username)),
244 ));
245 checks.push(key_scope_check(&realm));
246 }
247 Err(e) => checks.push(check("auth", Status::Fail, e.message)),
248 }
249
250 match rules::find_page(t, &RuleFilter::default(), 1, 1).await {
251 Ok((_, total)) => checks.push(check(
252 "rules_access",
253 Status::Ok,
254 format!("{total} rules visible"),
255 )),
256 Err(e) => checks.push(check("rules_access", Status::Fail, e.message)),
257 }
258
259 checks.push(value_list_index_check(t).await);
260 }
261
262 Ok(DoctorReport::from_checks(checks))
263}
264
265pub async fn info(t: &Transport) -> Result<InfoReport> {
271 let caps = Capabilities::probe(t, t.kibana_url()).await?;
272 let spaces = probe_spaces(t).await;
273 let license = probe_license_tier(t, caps.flavor).await;
274
275 Ok(InfoReport {
276 version: caps.version,
277 flavor: caps.flavor.as_str().to_string(),
278 license,
279 spaces,
280 })
281}
282
283#[cfg(test)]
284mod tests {
285 use super::*;
286
287 #[test]
288 fn status_serializes_to_the_rendered_lowercase_strings() {
289 assert_eq!(
290 serde_json::to_value(Status::Ok).unwrap(),
291 serde_json::json!("ok")
292 );
293 assert_eq!(
294 serde_json::to_value(Status::Warn).unwrap(),
295 serde_json::json!("warn")
296 );
297 assert_eq!(
298 serde_json::to_value(Status::Fail).unwrap(),
299 serde_json::json!("fail")
300 );
301 }
302
303 #[test]
304 fn key_scope_check_reports_ok_for_a_project_scoped_es_api_key() {
305 let c = key_scope_check("_es_api_key");
306 assert_eq!(c.status, Status::Ok);
307 assert!(c.detail.contains("project-scoped"));
308 }
309
310 #[test]
311 fn key_scope_check_warns_for_an_organization_cloud_api_key() {
312 let c = key_scope_check("_cloud_api_key");
313 assert_eq!(c.status, Status::Warn);
314 assert!(c.detail.contains("Organization-level"));
315 }
316
317 #[test]
318 fn key_scope_check_names_an_unrecognized_realm_rather_than_calling_it_an_api_key() {
319 let c = key_scope_check("native");
320 assert_eq!(c.status, Status::Ok);
321 assert!(
322 c.detail.contains("native"),
323 "message must name the realm: {}",
324 c.detail
325 );
326 assert!(
327 !c.detail.contains("project-scoped Elasticsearch API key"),
328 "must not claim a non-API-key realm is a project-scoped API key: {}",
329 c.detail
330 );
331 }
332
333 #[test]
334 fn key_scope_check_names_an_unclassifiable_realm() {
335 let c = key_scope_check("unknown");
338 assert_eq!(c.status, Status::Ok);
339 assert!(c.detail.contains("unknown"));
340 }
341
342 #[test]
343 fn a_key_id_is_truncated_in_the_auth_check() {
344 let full = "2XTe9p8BLjNicQlhfc9W";
347 let short = short_identity(full);
348 assert_eq!(short, "2XTe9p...");
349 assert!(
350 !full.starts_with(&short),
351 "sanity: the id must be shortened"
352 );
353 }
354
355 #[test]
356 fn a_human_username_is_left_readable() {
357 assert_eq!(short_identity("elastic"), "elastic");
359 assert_eq!(short_identity("admin"), "admin");
360 assert_eq!(short_identity("unknown"), "unknown");
361 }
362
363 #[test]
364 fn truncation_never_splits_a_multibyte_character() {
365 let s = short_identity("ααααααααααααααααα");
366 assert!(s.ends_with("..."));
367 assert_eq!(s.chars().count(), 9);
368 }
369
370 #[test]
371 fn doctor_check_serializes_to_the_rendered_key_names() {
372 let c = check("config", Status::Ok, "profile 'default'");
373 let v = serde_json::to_value(&c).unwrap();
374 assert_eq!(v["check"], "config");
375 assert_eq!(v["status"], "ok");
376 assert_eq!(v["message"], "profile 'default'");
377 assert_eq!(
378 v.as_object().map(|o| o.keys().cloned().collect::<Vec<_>>()),
379 Some(vec![
380 "check".to_string(),
381 "status".to_string(),
382 "message".to_string()
383 ]),
384 "key order is the rendered JSON order"
385 );
386 }
387
388 #[test]
389 fn from_checks_derives_ok_from_the_checks() {
390 assert!(
391 DoctorReport::from_checks(vec![
392 check("connectivity", Status::Ok, "ok"),
393 check("key_scope", Status::Warn, "caution"),
394 ])
395 .ok,
396 "a warning must not fail the report"
397 );
398 assert!(!DoctorReport::from_checks(vec![check("config", Status::Fail, "fail")]).ok);
399 }
400}