1use crate::auth::Credential;
5use crate::capabilities::{Capabilities, Feature};
6use crate::config::Profile;
7use crate::error::{Error, ErrorKind, Result};
8use reqwest::{Client, Method, Response, StatusCode};
9use serde_json::Value;
10use std::collections::BTreeMap;
11use std::io::Write;
12use std::time::Duration;
13use tokio::sync::OnceCell;
14
15const API_VERSION: &str = "2023-10-31";
17const MAX_ATTEMPTS: u32 = 3;
18
19const CAPTURED_HEADERS: [&str; 3] = [
28 "x-found-handling-cluster",
29 "x-found-handling-instance",
30 "x-elastic-product",
31];
32
33fn parse_response_json(text: &str) -> Result<Value> {
36 validate_json_integer_ranges(text)?;
37 serde_json::from_str(text)
38 .map_err(|e| Error::new(ErrorKind::Http, format!("parsing response JSON: {e}")))
39}
40
41fn validate_json_integer_ranges(text: &str) -> Result<()> {
46 let bytes = text.as_bytes();
47 let mut index = 0;
48
49 while index < bytes.len() {
50 if bytes[index] == b'"' {
51 index += 1;
52 while index < bytes.len() {
53 match bytes[index] {
54 b'\\' => index += 2,
55 b'"' => {
56 index += 1;
57 break;
58 }
59 _ => index += 1,
60 }
61 }
62 continue;
63 }
64
65 if bytes[index] != b'-' && !bytes[index].is_ascii_digit() {
66 index += 1;
67 continue;
68 }
69
70 let start = index;
71 if bytes[index] == b'-' {
72 index += 1;
73 }
74 if index == bytes.len() || !bytes[index].is_ascii_digit() {
75 index = start + 1;
76 continue;
77 }
78
79 if bytes[index] == b'0' {
80 index += 1;
81 } else {
82 while index < bytes.len() && bytes[index].is_ascii_digit() {
83 index += 1;
84 }
85 }
86
87 let mut is_integer = true;
88 if bytes.get(index) == Some(&b'.') {
89 is_integer = false;
90 index += 1;
91 while index < bytes.len() && bytes[index].is_ascii_digit() {
92 index += 1;
93 }
94 }
95 if matches!(bytes.get(index), Some(b'e' | b'E')) {
96 is_integer = false;
97 index += 1;
98 if matches!(bytes.get(index), Some(b'+' | b'-')) {
99 index += 1;
100 }
101 while index < bytes.len() && bytes[index].is_ascii_digit() {
102 index += 1;
103 }
104 }
105
106 if is_integer {
107 let number = &text[start..index];
108 let in_range = if bytes[start] == b'-' {
109 number.parse::<i64>().is_ok()
110 } else {
111 number.parse::<u64>().is_ok()
112 };
113 if !in_range {
114 return Err(Error::new(
115 ErrorKind::Http,
116 format!(
117 "parsing response JSON: integer {number} is outside supported integer range"
118 ),
119 ));
120 }
121 }
122 }
123
124 Ok(())
125}
126
127#[derive(Debug, Clone)]
132pub struct Responded {
133 pub body: Value,
134 pub headers: BTreeMap<String, String>,
135}
136
137impl Responded {
138 pub fn header(&self, name: &str) -> Option<&str> {
143 self.headers.get(&name.to_ascii_lowercase()).map(|s| &**s)
144 }
145}
146
147pub fn urlencode(s: &str) -> String {
152 let mut out = String::with_capacity(s.len());
153 for b in s.bytes() {
154 match b {
155 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
156 out.push(b as char)
157 }
158 _ => out.push_str(&format!("%{b:02X}")),
159 }
160 }
161 out
162}
163
164pub struct Transport {
165 client: Client,
166 base: String,
167 kibana_url: String,
171 es_base: String,
174 has_es_url: bool,
179 space: String,
180 auth_header: String,
181 debug: bool,
182 capabilities: OnceCell<Capabilities>,
183}
184
185impl Transport {
186 pub fn new(profile: &Profile) -> Result<Transport> {
187 Self::with_debug(profile, false)
188 }
189
190 pub fn with_debug(profile: &Profile, debug: bool) -> Result<Transport> {
194 let mut profile = profile.clone();
197 profile.strip_userinfo();
198 let credential = Credential::from_profile(&profile)?;
199 let client = Client::builder()
200 .timeout(Duration::from_secs(profile.timeout_secs))
201 .danger_accept_invalid_certs(!profile.verify)
202 .build()
203 .map_err(|e| Error::new(ErrorKind::Connection, format!("building HTTP client: {e}")))?;
204
205 let base = profile.kibana_url.trim_end_matches('/').to_string();
206 let kibana_url = profile.kibana_url.clone();
207 let has_es_url = profile.es_url.is_some();
208 let es_base = profile
209 .es_url
210 .as_deref()
211 .unwrap_or(&profile.kibana_url)
212 .trim_end_matches('/')
213 .to_string();
214
215 Ok(Transport {
216 client,
217 base,
218 kibana_url,
219 es_base,
220 has_es_url,
221 space: profile.space.clone(),
222 auth_header: credential.header_value(),
223 debug,
224 capabilities: OnceCell::new(),
225 })
226 }
227
228 fn debug_log(&self, method: &Method, url: &str, status: u16, attempt: u32) {
234 if !self.debug {
235 return;
236 }
237 if attempt > 1 {
238 eprintln!(
239 "[debug] {} {url} -> {status} (attempt {attempt})",
240 method.as_str()
241 );
242 } else {
243 eprintln!("[debug] {} {url} -> {status}", method.as_str());
244 }
245 }
246
247 fn debug_request(&self, method: &Method, url: &str, attempt: u32) {
249 if !self.debug {
250 return;
251 }
252 if attempt > 1 {
253 eprintln!("[debug] -> {} {url} (attempt {attempt})", method.as_str());
254 } else {
255 eprintln!("[debug] -> {} {url}", method.as_str());
256 }
257 }
258
259 fn debug_failure(&self, method: &Method, url: &str, what: &str) {
261 if !self.debug {
262 return;
263 }
264 let _ = writeln!(
265 std::io::stderr(),
266 "[debug] {} {url} -> {what}",
267 method.as_str()
268 );
269 }
270
271 pub fn space_path(space: &str, path: &str) -> String {
275 if space.is_empty() || space == "default" {
276 path.to_string()
277 } else {
278 format!("/s/{space}{path}")
279 }
280 }
281
282 pub fn kibana_url(&self) -> &str {
284 &self.kibana_url
285 }
286
287 pub fn has_es_url(&self) -> bool {
292 self.has_es_url
293 }
294
295 pub async fn capabilities(&self) -> Result<&Capabilities> {
297 self.capabilities
298 .get_or_try_init(|| Capabilities::probe(self, self.kibana_url()))
299 .await
300 }
301
302 pub async fn require_feature(&self, feature: Feature) -> Result<()> {
304 self.capabilities().await?.require_feature(feature)
305 }
306
307 fn url(&self, path: &str) -> String {
308 format!("{}{}", self.base, Self::space_path(&self.space, path))
309 }
310
311 async fn response_text(
314 &self,
315 method: &Method,
316 url: &str,
317 response: Response,
318 ) -> Result<String> {
319 match response.text().await {
320 Ok(text) => Ok(text),
321 Err(e) if e.is_timeout() => {
322 self.debug_failure(method, url, "timeout");
323 Err(Error::new(
324 ErrorKind::Timeout,
325 format!("request timed out while reading response body: {e}"),
326 ))
327 }
328 Err(e) => {
329 self.debug_failure(method, url, "connection error");
330 Err(Error::new(
331 ErrorKind::Connection,
332 format!("request failed while reading response body: {e}"),
333 ))
334 }
335 }
336 }
337
338 async fn send_retrying<F>(&self, method: Method, url: &str, mut build: F) -> Result<Response>
339 where
340 F: FnMut() -> Result<reqwest::RequestBuilder>,
341 {
342 let mut attempt = 0;
343
344 loop {
345 attempt += 1;
346 let req = build()?;
347
348 self.debug_request(&method, url, attempt);
349 let result = req.send().await;
350
351 let response = match result {
352 Ok(r) => r,
353 Err(e) if e.is_timeout() => {
354 self.debug_failure(&method, url, "timeout");
355 return Err(Error::new(
356 ErrorKind::Timeout,
357 format!("request timed out: {e}"),
358 ));
359 }
360 Err(e) => {
361 self.debug_failure(&method, url, "connection error");
362 return Err(Error::new(
363 ErrorKind::Connection,
364 format!("request failed: {e}"),
365 ));
366 }
367 };
368
369 let status = response.status();
370 self.debug_log(&method, url, status.as_u16(), attempt);
371 if status.is_success() {
372 return Ok(response);
373 }
374
375 let transient = status == StatusCode::TOO_MANY_REQUESTS || status.is_server_error();
378 if transient && attempt < MAX_ATTEMPTS {
379 let backoff = Duration::from_millis(200 * 2u64.pow(attempt - 1));
380 tokio::time::sleep(backoff).await;
381 continue;
382 }
383
384 let code = status.as_u16();
385 let text = self.response_text(&method, url, response).await?;
386 return Err(Error::from_response_body(code, &text));
387 }
388 }
389
390 async fn send(&self, method: Method, path: &str, body: Option<&Value>) -> Result<Response> {
391 let url = self.url(path);
392 let request_method = method.clone();
393 self.send_retrying(method, &url, || {
394 let mut req = self
395 .client
396 .request(request_method.clone(), &url)
397 .header("Authorization", &self.auth_header)
398 .header("elastic-api-version", API_VERSION);
399
400 if request_method != Method::GET {
402 req = req.header("kbn-xsrf", "true");
403 }
404 if let Some(b) = body {
405 req = req.json(b);
406 }
407
408 Ok(req)
409 })
410 .await
411 }
412
413 async fn send_json(&self, method: Method, path: &str, body: Option<&Value>) -> Result<Value> {
414 let url = self.url(path);
415 let response = self.send(method.clone(), path, body).await?;
416 let text = self.response_text(&method, &url, response).await?;
417 if text.trim().is_empty() {
418 return Ok(Value::Null);
419 }
420 parse_response_json(&text)
421 }
422
423 pub async fn get(&self, path: &str) -> Result<Value> {
424 self.send_json(Method::GET, path, None).await
425 }
426
427 pub async fn get_internal(&self, path: &str) -> Result<Value> {
433 let method = Method::GET;
434 let url = self.url(path);
435 let response = self
436 .send_retrying(method.clone(), &url, || {
437 Ok(self
438 .client
439 .request(Method::GET, &url)
440 .header("Authorization", &self.auth_header)
441 .header("x-elastic-internal-origin", "Kibana"))
442 })
443 .await?;
444
445 let text = self.response_text(&method, &url, response).await?;
450 if text.trim().is_empty() {
451 return Ok(Value::Null);
452 }
453 parse_response_json(&text)
454 }
455
456 pub async fn post_internal(&self, path: &str, body: &Value) -> Result<Value> {
466 let method = Method::POST;
467 let url = self.url(path);
468 let response = self
469 .send_retrying(method.clone(), &url, || {
470 Ok(self
471 .client
472 .request(Method::POST, &url)
473 .header("Authorization", &self.auth_header)
474 .header("kbn-xsrf", "true")
475 .header("x-elastic-internal-origin", "Kibana")
476 .json(body))
477 })
478 .await?;
479
480 let text = self.response_text(&method, &url, response).await?;
481 if text.trim().is_empty() {
482 return Ok(Value::Null);
483 }
484 parse_response_json(&text)
485 }
486
487 pub async fn get_with_headers(&self, path: &str) -> Result<Responded> {
492 let method = Method::GET;
493 let url = self.url(path);
494 let response = self.send(method.clone(), path, None).await?;
495
496 let mut headers = BTreeMap::new();
497 for name in CAPTURED_HEADERS {
498 if let Some(value) = response.headers().get(name)
499 && let Ok(text) = value.to_str()
500 {
501 headers.insert(name.to_string(), text.to_string());
502 }
503 }
504
505 let text = self.response_text(&method, &url, response).await?;
506 let body = if text.trim().is_empty() {
507 Value::Null
508 } else {
509 parse_response_json(&text)?
510 };
511
512 Ok(Responded { body, headers })
513 }
514
515 pub async fn post(&self, path: &str, body: Option<&Value>) -> Result<Value> {
516 self.send_json(Method::POST, path, body).await
517 }
518
519 pub async fn put(&self, path: &str, body: &Value) -> Result<Value> {
520 self.send_json(Method::PUT, path, Some(body)).await
521 }
522
523 pub async fn patch(&self, path: &str, body: &Value) -> Result<Value> {
524 self.send_json(Method::PATCH, path, Some(body)).await
525 }
526
527 pub async fn delete(&self, path: &str) -> Result<Value> {
528 self.send_json(Method::DELETE, path, None).await
529 }
530
531 pub async fn get_absolute_es(&self, path: &str) -> Result<Value> {
535 self.send_absolute_es(Method::GET, path, None).await
536 }
537
538 pub async fn post_absolute_es(&self, path: &str, body: &Value) -> Result<Value> {
541 self.send_absolute_es(Method::POST, path, Some(body)).await
542 }
543
544 pub async fn delete_absolute_es(&self, path: &str) -> Result<Value> {
548 self.send_absolute_es(Method::DELETE, path, None).await
549 }
550
551 pub async fn delete_absolute_es_json(&self, path: &str, body: &Value) -> Result<Value> {
554 self.send_absolute_es(Method::DELETE, path, Some(body))
555 .await
556 }
557
558 async fn send_absolute_es(
559 &self,
560 method: Method,
561 path: &str,
562 body: Option<&Value>,
563 ) -> Result<Value> {
564 let url = format!("{}{}", self.es_base, path);
565 let request_method = method.clone();
566 let response = self
567 .send_retrying(method.clone(), &url, || {
568 let mut req = self
569 .client
570 .request(request_method.clone(), &url)
571 .header("Authorization", &self.auth_header);
572 if let Some(b) = body {
573 req = req.json(b);
574 }
575 Ok(req)
576 })
577 .await?;
578
579 let text = self.response_text(&method, &url, response).await?;
580 if text.trim().is_empty() {
581 return Ok(Value::Null);
582 }
583 parse_response_json(&text)
584 }
585
586 pub async fn post_text(&self, path: &str, body: Option<&Value>) -> Result<String> {
588 let method = Method::POST;
589 let url = self.url(path);
590 let response = self.send(method.clone(), path, body).await?;
591 self.response_text(&method, &url, response).await
592 }
593
594 pub async fn post_multipart_ndjson(&self, path: &str, ndjson: &str) -> Result<Value> {
596 let method = Method::POST;
597 let url = self.url(path);
598 let response = self
599 .send_retrying(method.clone(), &url, || {
600 let part = reqwest::multipart::Part::text(ndjson.to_string())
603 .file_name("rules.ndjson")
604 .mime_str("application/octet-stream")
605 .map_err(|e| Error::new(ErrorKind::Error, format!("building upload: {e}")))?;
606 let form = reqwest::multipart::Form::new().part("file", part);
607
608 Ok(self
609 .client
610 .post(&url)
611 .header("Authorization", &self.auth_header)
612 .header("elastic-api-version", API_VERSION)
613 .header("kbn-xsrf", "true")
614 .multipart(form))
615 })
616 .await?;
617
618 let text = self.response_text(&method, &url, response).await?;
619 parse_response_json(&text)
620 }
621}