Skip to main content

elasticctl_core/
transport.rs

1//! HTTP transport, including URL construction, headers, retries, and error
2//! classification.
3
4use 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
15/// Version of the public API this client targets.
16const API_VERSION: &str = "2023-10-31";
17const MAX_ATTEMPTS: u32 = 3;
18
19/// Response headers retained past the transport boundary.
20///
21/// These headers are allowlisted because recorded fixtures are public.
22/// Capturing all headers could record cookies, rate-limit counters, or future
23/// proxy headers that do not belong in the repository.
24///
25/// The capability probe reads `x-found-handling-cluster`. The other two show
26/// which Cloud headers the recorded response contained.
27const CAPTURED_HEADERS: [&str; 3] = [
28    "x-found-handling-cluster",
29    "x-found-handling-instance",
30    "x-elastic-product",
31];
32
33/// Parse a JSON response without letting serde_json coerce an out-of-range
34/// integer literal into an imprecise floating-point number.
35fn 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
41/// Reject positive integer lexemes above `u64::MAX` and negative integer
42/// lexemes below `i64::MIN`. Numbers with a decimal point or exponent remain
43/// floating-point JSON values, even when their magnitude is greater than
44/// `u64::MAX`.
45fn 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/// A response body and its captured headers.
128///
129/// Hosted and self-managed stacks return the same `/api/status` body. An
130/// edge-proxy header distinguishes them.
131#[derive(Debug, Clone)]
132pub struct Responded {
133    pub body: Value,
134    pub headers: BTreeMap<String, String>,
135}
136
137impl Responded {
138    /// Look up a header case-insensitively.
139    ///
140    /// The Elastic proxy varies the casing of `x-found-handling-cluster` by
141    /// endpoint.
142    pub fn header(&self, name: &str) -> Option<&str> {
143        self.headers.get(&name.to_ascii_lowercase()).map(|s| &**s)
144    }
145}
146
147/// Percent-encode a query value while leaving URL-safe characters unchanged.
148///
149/// The API client and fixture recorder share this encoder so they produce the
150/// same scoped-filter URL.
151pub 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    /// The Kibana URL exactly as configured, before trailing-slash
168    /// normalization. `doctor` reports it as the connectivity target and the
169    /// capability probe uses it for hostname-based flavor detection.
170    kibana_url: String,
171    /// Elasticsearch host. Cloud deployments use a different host from
172    /// Kibana; otherwise this uses the Kibana host.
173    es_base: String,
174    /// Whether the profile configured an explicit `es_url`. `es_base` falls
175    /// back to the Kibana host either way, so a caller that needs to know
176    /// whether that fallback happened (e.g. to name a likely cause in an
177    /// error message) reads this instead of comparing hosts.
178    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    /// Build a transport with HTTP request logging enabled or disabled.
191    ///
192    /// Keeping `debug` as a `bool` prevents CLI `clap` types entering `-core`.
193    pub fn with_debug(profile: &Profile, debug: bool) -> Result<Transport> {
194        // Scrub URL userinfo before deriving any base URL or logging, so a
195        // credential embedded in a URL never reaches a request or debug line.
196        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    /// Log one request or response line to stderr.
229    ///
230    /// Logs include the method, complete URL, and status. They exclude
231    /// authorization headers and bodies. Callers must not put credentials in
232    /// query strings.
233    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    /// Log the request before sending it so timeouts produce debug output.
248    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    /// Log a timeout or connection failure in the response-line format.
260    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    /// Prefix non-default spaces with `/s/<name>`.
272    ///
273    /// Kibana serves the default space at the bare path.
274    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    /// The Kibana URL this transport targets, exactly as configured.
283    pub fn kibana_url(&self) -> &str {
284        &self.kibana_url
285    }
286
287    /// Whether the profile configured an explicit `es_url`. When it did not,
288    /// every `*_absolute_es` call silently falls back to the Kibana host —
289    /// callers that need to distinguish "no Elasticsearch host configured"
290    /// from "the real Elasticsearch host answered" read this.
291    pub fn has_es_url(&self) -> bool {
292        self.has_es_url
293    }
294
295    /// Probe deployment capabilities once for this transport.
296    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    /// Refuse an unverified feature before its public route is called.
303    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    /// Read a response body without retrying an operation that may have
312    /// completed after its headers were received.
313    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            // Retry transient failures only. Retrying a 4xx repeats the same
376            // caller error.
377            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            // Kibana rejects any state-changing request without this header.
401            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    /// GET a Kibana *internal* route. Internal routes sit outside the public
428    /// API's versioning contract: Kibana requires `x-elastic-internal-origin`
429    /// on them (without it the route family answers 400 "exists but is not
430    /// available"), and `elastic-api-version: 2023-10-31` names a public-API
431    /// version internal routes do not serve, so it is omitted.
432    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        // Convert the response exactly as `get` does: the same
446        // response_text/parse_response_json path `send_json` uses after its
447        // send, with the same `Error::from_response_body` classification
448        // already applied inside `send_retrying`.
449        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    /// POST a Kibana *internal* route with a JSON body. Mirrors
457    /// `get_internal`'s reasoning (same `x-elastic-internal-origin`
458    /// requirement, `elastic-api-version` still omitted), plus `kbn-xsrf`:
459    /// Kibana rejects any state-changing request without it, same as every
460    /// other non-GET call `send` makes.
461    ///
462    /// Its only caller today is xtask's profile-activation login
463    /// (`POST /internal/security/login`) — not reachable from
464    /// `elasticctl-api` or `elasticctl-cli`.
465    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    /// GET a body with its captured headers.
488    ///
489    /// This is separate from `get` because only the capability probe needs
490    /// headers.
491    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    /// GET Elasticsearch without a Kibana space prefix.
532    ///
533    /// Cloud deployments use a different Elasticsearch host.
534    pub async fn get_absolute_es(&self, path: &str) -> Result<Value> {
535        self.send_absolute_es(Method::GET, path, None).await
536    }
537
538    /// POST JSON to Elasticsearch without a Kibana space prefix or `kbn-xsrf`
539    /// header.
540    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    /// DELETE from Elasticsearch.
545    ///
546    /// The fixture recorder uses this to remove its scratch index.
547    pub async fn delete_absolute_es(&self, path: &str) -> Result<Value> {
548        self.send_absolute_es(Method::DELETE, path, None).await
549    }
550
551    /// DELETE from Elasticsearch with a JSON body. The PIT close needs one;
552    /// the plain `delete_absolute_es` sends no body.
553    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    /// POST and return the raw body for NDJSON endpoints.
587    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    /// Upload a multipart NDJSON file for Kibana rule import.
595    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                // Retryable HTTP responses deliberately replay this POST. Part and Form are
601                // recreated here because reqwest consumes multipart bodies while sending.
602                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}