Skip to main content

beyondigital_auth_sdk/api/
transport.rs

1//! The one hand-written part of the generated API client: it turns an [`OperationDescriptor`] plus typed input into an
2//! HTTP request, and the response back into a result (WP-21 R-21.1).
3//!
4//! The generator (`sdk/auth/tools/generate_clients.py`) decides what exists and what it looks like; this module
5//! decides how it travels. It mirrors the TypeScript and Python transports rule for rule, and the recorded exchanges in
6//! `sdk/auth/tester/fixtures/recorded-responses.json` are replayed through all three:
7//!
8//! - path parameters are percent-encoded one segment at a time, and `.` or `..` is refused, because a URL parser would
9//!   otherwise collapse it and aim the request at a different route;
10//! - credentials only go to https, or to a loopback host for local development;
11//! - redirects are never followed, so a credential cannot be replayed to another origin;
12//! - input the descriptor does not declare is an error, not silently dropped or sent;
13//! - a credential goes only to an operation that lists that scheme;
14//! - errors carry the status, the server's error code and the request id, never the request, a header or a token.
15
16use std::sync::Arc;
17use std::time::Duration;
18
19use base64::Engine as _;
20use serde::de::DeserializeOwned;
21use serde::Serialize;
22use serde_json::{Map, Value};
23
24use super::runtime::NdjsonPage;
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum HttpMethod {
28    Get,
29    Post,
30    Put,
31    Patch,
32    Delete,
33}
34
35impl HttpMethod {
36    pub fn as_str(self) -> &'static str {
37        match self {
38            Self::Get => "GET",
39            Self::Post => "POST",
40            Self::Put => "PUT",
41            Self::Patch => "PATCH",
42            Self::Delete => "DELETE",
43        }
44    }
45}
46
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum Surface {
49    Public,
50    Management,
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub enum ResponseKind {
55    Json,
56    Ndjson,
57    Empty,
58}
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61pub enum BodyKind {
62    Json,
63    Form,
64}
65
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67pub struct BodySpec {
68    pub kind: BodyKind,
69    pub required: bool,
70}
71
72/// What the generator knows about one operation. The transport reads nothing else about the contract.
73#[derive(Debug, Clone, Copy)]
74pub struct OperationDescriptor {
75    pub operation_id: &'static str,
76    pub handler: &'static str,
77    pub surface: Surface,
78    pub method: HttpMethod,
79    /// Path template; `{name}` marks a path parameter.
80    pub path: &'static str,
81    pub path_params: &'static [&'static str],
82    /// Path parameters that may contain `/` (the route captures the rest of the path).
83    pub catch_all: &'static [&'static str],
84    pub query: &'static [&'static str],
85    pub headers: &'static [&'static str],
86    pub body: Option<BodySpec>,
87    pub response: ResponseKind,
88    pub success_statuses: &'static [u16],
89    /// Alternatives in the contract's order; an empty alternative means the call may be anonymous.
90    pub security: &'static [&'static [&'static str]],
91}
92
93/// A contract operation the client has no method for, with the coded reason.
94#[derive(Debug, Clone, Copy)]
95pub struct ExcludedOperation {
96    pub operation_id: &'static str,
97    pub method: HttpMethod,
98    pub path: &'static str,
99    pub handler: &'static str,
100    pub reason: &'static str,
101}
102
103/// A token, or a function that returns one on every call (so a refreshed token is picked up).
104#[derive(Clone)]
105pub enum TokenSource {
106    Static(String),
107    Provider(Arc<dyn Fn() -> String + Send + Sync>),
108}
109
110impl std::fmt::Debug for TokenSource {
111    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
112        f.write_str("TokenSource(<redacted>)")
113    }
114}
115
116impl From<&str> for TokenSource {
117    fn from(value: &str) -> Self {
118        Self::Static(value.to_string())
119    }
120}
121
122impl From<String> for TokenSource {
123    fn from(value: String) -> Self {
124        Self::Static(value)
125    }
126}
127
128#[derive(Clone)]
129pub struct ClientBasicCredential {
130    pub client_id: String,
131    pub client_secret: String,
132}
133
134impl std::fmt::Debug for ClientBasicCredential {
135    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
136        f.write_str("ClientBasicCredential(<redacted>)")
137    }
138}
139
140#[derive(Clone)]
141pub enum ClientBasicSource {
142    Static(ClientBasicCredential),
143    Provider(Arc<dyn Fn() -> ClientBasicCredential + Send + Sync>),
144}
145
146impl std::fmt::Debug for ClientBasicSource {
147    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
148        f.write_str("ClientBasicSource(<redacted>)")
149    }
150}
151
152/// One credential per security scheme named in the contract. The transport picks what an operation accepts.
153#[derive(Debug, Clone, Default)]
154pub struct ApiCredentials {
155    /// A user or service access token (`bearerAuth`).
156    pub bearer_auth: Option<TokenSource>,
157    /// An access token for the management MCP resource (`managementOAuth`).
158    pub management_oauth: Option<TokenSource>,
159    /// An application API key (`applicationApiKey`).
160    pub application_api_key: Option<TokenSource>,
161    /// A SCIM token (`scimToken`).
162    pub scim_token: Option<TokenSource>,
163    /// The registered client id and secret (`clientBasic`).
164    pub client_basic: Option<ClientBasicSource>,
165}
166
167impl ApiCredentials {
168    pub fn bearer(token: impl Into<TokenSource>) -> Self {
169        Self {
170            bearer_auth: Some(token.into()),
171            ..Self::default()
172        }
173    }
174}
175
176#[derive(Clone)]
177pub struct ApiClientOptions {
178    /// The issuer origin, for example `https://auth.example.com`. A path prefix is allowed.
179    pub base_url: String,
180    pub credentials: ApiCredentials,
181    /// The value of a `Cookie` header, sent only to operations that authenticate with the console or hosted-page
182    /// cookie, never to a public endpoint.
183    pub cookie: Option<String>,
184    /// Per-request timeout; zero disables it. Default 30 seconds.
185    pub timeout: Duration,
186    /// Headers added to every request (never `Authorization`, `Content-Type`, `Cookie`, `Host`).
187    pub headers: Vec<(String, String)>,
188    /// Allow `http://` to a non-loopback host. Credentials then cross the network in clear text. Default false.
189    pub allow_insecure_http: bool,
190}
191
192impl std::fmt::Debug for ApiClientOptions {
193    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
194        f.debug_struct("ApiClientOptions")
195            .field("base_url", &self.base_url)
196            .field("credentials", &self.credentials)
197            .field("cookie", &self.cookie.as_ref().map(|_| "<redacted>"))
198            .field("timeout", &self.timeout)
199            .field("allow_insecure_http", &self.allow_insecure_http)
200            .finish_non_exhaustive()
201    }
202}
203
204impl ApiClientOptions {
205    pub fn new(base_url: impl Into<String>) -> Self {
206        Self {
207            base_url: base_url.into(),
208            credentials: ApiCredentials::default(),
209            cookie: None,
210            timeout: Duration::from_secs(30),
211            headers: Vec::new(),
212            allow_insecure_http: false,
213        }
214    }
215
216    pub fn with_credentials(mut self, credentials: ApiCredentials) -> Self {
217        self.credentials = credentials;
218        self
219    }
220}
221
222/// Per-call settings. Build one and pass it with `AuthApiClient::with_options`.
223#[derive(Debug, Clone, Default)]
224pub struct CallOptions {
225    pub timeout: Option<Duration>,
226    /// Extra headers for this call (never `Authorization`, `Content-Type`, `Cookie`, `Host`).
227    pub headers: Vec<(String, String)>,
228    /// Replaces the client-level credential for each scheme given here.
229    pub credentials: Option<ApiCredentials>,
230}
231
232/// What a method hands the transport: each group as a JSON object (or absent). Every group is optional here; each
233/// descriptor declares which are required.
234#[derive(Debug, Clone, Default)]
235pub struct CallInput {
236    pub path: Option<Value>,
237    pub query: Option<Value>,
238    pub headers: Option<Value>,
239    pub body: Option<Value>,
240}
241
242#[derive(Debug, Clone, Copy, PartialEq, Eq)]
243pub enum ClientErrorCode {
244    InvalidInput,
245    InvalidBaseUrl,
246    MissingCredentials,
247    InvalidResponse,
248}
249
250impl ClientErrorCode {
251    pub fn as_str(self) -> &'static str {
252        match self {
253            Self::InvalidInput => "invalid_input",
254            Self::InvalidBaseUrl => "invalid_base_url",
255            Self::MissingCredentials => "missing_credentials",
256            Self::InvalidResponse => "invalid_response",
257        }
258    }
259}
260
261/// The service answered with a non-2xx status. It holds the status, the server's error code and the request id,
262/// never the request, a header or a credential.
263#[derive(Debug, Clone)]
264pub struct ApiResponseError {
265    pub operation_id: &'static str,
266    pub status: u16,
267    /// The `error` (OAuth-style) or `detail` (service envelope) field, when the body had one.
268    pub code: Option<String>,
269    pub description: Option<String>,
270    pub request_id: Option<String>,
271    pub retry_after_seconds: Option<u64>,
272    /// The parsed JSON error body when there was one (at most 64 KiB).
273    pub body: Option<Value>,
274    message: String,
275}
276
277impl std::fmt::Display for ApiResponseError {
278    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
279        f.write_str(&self.message)
280    }
281}
282
283impl std::error::Error for ApiResponseError {}
284
285#[derive(Debug, thiserror::Error)]
286pub enum ApiError {
287    /// Raised before a request is sent (bad input, missing credential, bad base URL) or when a success body is not
288    /// the shape the contract promises. The message never carries a token.
289    #[error("{message}")]
290    Client {
291        code: ClientErrorCode,
292        message: String,
293    },
294    #[error(transparent)]
295    Response(#[from] Box<ApiResponseError>),
296    /// The request did not complete. The message names the operation and nothing the transport carried.
297    #[error("{0}")]
298    Network(String),
299}
300
301impl ApiError {
302    fn client(code: ClientErrorCode, message: impl Into<String>) -> Self {
303        Self::Client {
304            code,
305            message: message.into(),
306        }
307    }
308
309    fn input(message: impl Into<String>) -> Self {
310        Self::client(ClientErrorCode::InvalidInput, message)
311    }
312
313    pub fn code(&self) -> Option<&str> {
314        match self {
315            Self::Client { code, .. } => Some(code.as_str()),
316            Self::Response(error) => error.code.as_deref(),
317            Self::Network(_) => None,
318        }
319    }
320}
321
322const MAX_ERROR_BODY: usize = 64 * 1024;
323const RESERVED_HEADERS: [&str; 5] = [
324    "authorization",
325    "content-type",
326    "host",
327    "content-length",
328    "cookie",
329];
330const COOKIE_SCHEMES: [&str; 2] = ["portalCookie", "hostedCookie"];
331const BEARER_SCHEMES: [&str; 4] = [
332    "bearerAuth",
333    "managementOAuth",
334    "applicationApiKey",
335    "scimToken",
336];
337
338/// Serialize one parameter group (or a body) for [`CallInput`].
339pub fn group<T: Serialize>(value: &T) -> Result<Value, ApiError> {
340    serde_json::to_value(value).map_err(|_| ApiError::input("the input cannot be written as JSON"))
341}
342
343fn is_loopback(host: &str) -> bool {
344    let host = host.trim_matches(|c| c == '[' || c == ']').to_lowercase();
345    if host == "localhost" || host.ends_with(".localhost") {
346        return true;
347    }
348    host.parse::<std::net::IpAddr>()
349        .map(|ip| ip.is_loopback())
350        .unwrap_or(false)
351}
352
353fn normalize_base(raw: &str, allow_insecure_http: bool) -> Result<String, ApiError> {
354    let invalid = |message: &str| ApiError::client(ClientErrorCode::InvalidBaseUrl, message);
355    let url = reqwest::Url::parse(raw)
356        .map_err(|_| invalid("base_url must be an absolute http(s) URL"))?;
357    if url.scheme() != "https" && url.scheme() != "http" {
358        return Err(invalid("base_url must use https"));
359    }
360    let Some(host) = url.host_str() else {
361        return Err(invalid("base_url must be an absolute http(s) URL"));
362    };
363    if !url.username().is_empty()
364        || url.password().is_some()
365        || url.query().is_some()
366        || url.fragment().is_some()
367    {
368        return Err(invalid(
369            "base_url must not carry credentials, a query or a fragment",
370        ));
371    }
372    if url.scheme() == "http" && !is_loopback(host) && !allow_insecure_http {
373        return Err(invalid(
374            "base_url must use https (plain http is only accepted for a loopback host)",
375        ));
376    }
377    let mut base = format!("{}://{}", url.scheme(), url.host_str().unwrap_or_default());
378    if let Some(port) = url.port() {
379        base.push_str(&format!(":{port}"));
380    }
381    base.push_str(url.path().trim_end_matches('/'));
382    Ok(base)
383}
384
385fn scalar(value: &Value, place: &str) -> Result<String, ApiError> {
386    match value {
387        Value::String(text) => Ok(text.clone()),
388        Value::Bool(flag) => Ok(flag.to_string()),
389        Value::Number(number) => {
390            if let Some(float) = number.as_f64().filter(|_| number.is_f64()) {
391                if float.fract() == 0.0 && float.abs() < 1e15 {
392                    return Ok(format!("{}", float as i64));
393                }
394            }
395            Ok(number.to_string())
396        }
397        _ => Err(ApiError::input(format!(
398            "{place} must be a string, number or boolean"
399        ))),
400    }
401}
402
403/// `application/x-www-form-urlencoded` for one component: a space is `+`, `*-._` and alphanumerics stay.
404pub fn form_quote(value: &str) -> String {
405    let mut out = String::new();
406    for byte in value.bytes() {
407        match byte {
408            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'*' | b'-' | b'.' | b'_' => {
409                out.push(byte as char)
410            }
411            b' ' => out.push('+'),
412            _ => out.push_str(&format!("%{byte:02X}")),
413        }
414    }
415    out
416}
417
418/// Percent-encoding for a path segment or a Basic credential: everything but the characters `encodeURIComponent`
419/// leaves alone, so the URL is the same in every language.
420fn component_quote(value: &str) -> String {
421    let mut out = String::new();
422    for byte in value.bytes() {
423        match byte {
424            b'A'..=b'Z'
425            | b'a'..=b'z'
426            | b'0'..=b'9'
427            | b'-'
428            | b'_'
429            | b'.'
430            | b'~'
431            | b'!'
432            | b'*'
433            | b'\''
434            | b'('
435            | b')' => out.push(byte as char),
436            _ => out.push_str(&format!("%{byte:02X}")),
437        }
438    }
439    out
440}
441
442/// Query and form encoding: arrays repeat the key, null is left out, nested objects are refused.
443fn encode_pairs(
444    values: &[(String, Value)],
445    place: &str,
446) -> Result<Vec<(String, String)>, ApiError> {
447    let mut pairs = Vec::new();
448    for (name, value) in values {
449        match value {
450            Value::Null => {}
451            Value::Array(items) => {
452                for item in items.iter().filter(|item| !item.is_null()) {
453                    pairs.push((name.clone(), scalar(item, &format!("{place}.{name}"))?));
454                }
455            }
456            other => pairs.push((name.clone(), scalar(other, &format!("{place}.{name}"))?)),
457        }
458    }
459    Ok(pairs)
460}
461
462fn join_pairs(pairs: &[(String, String)]) -> String {
463    pairs
464        .iter()
465        .map(|(name, value)| format!("{}={}", form_quote(name), form_quote(value)))
466        .collect::<Vec<_>>()
467        .join("&")
468}
469
470/// The members of a group the descriptor declares, in declared order. An undeclared member is an error.
471fn only_declared(
472    group: Option<&Value>,
473    declared: &[&'static str],
474    place: &str,
475    case_insensitive: bool,
476) -> Result<Vec<(String, Value)>, ApiError> {
477    let map: &Map<String, Value> = match group {
478        None | Some(Value::Null) => return Ok(Vec::new()),
479        Some(Value::Object(map)) => map,
480        Some(_) => return Err(ApiError::input(format!("{place} must be an object"))),
481    };
482    let mut given: Vec<Option<&Value>> = vec![None; declared.len()];
483    for (name, value) in map {
484        let hit = declared.iter().position(|candidate| {
485            if case_insensitive {
486                candidate.eq_ignore_ascii_case(name)
487            } else {
488                candidate == name
489            }
490        });
491        match hit {
492            Some(index) => given[index] = Some(value),
493            None => {
494                return Err(ApiError::input(format!(
495                    "{place}.{name} is not a parameter of this operation"
496                )))
497            }
498        }
499    }
500    Ok(declared
501        .iter()
502        .zip(given)
503        .filter_map(|(name, value)| value.map(|value| (name.to_string(), value.clone())))
504        .collect())
505}
506
507fn segment(value: &str, name: &str) -> Result<String, ApiError> {
508    if value.is_empty() || value == "." || value == ".." {
509        return Err(ApiError::input(format!(
510            "path parameter {name} is empty or a dot segment"
511        )));
512    }
513    Ok(component_quote(value))
514}
515
516/// The path of a call: the template with each parameter encoded. `.`, `..` and an empty value are refused.
517pub fn build_path(
518    descriptor: &OperationDescriptor,
519    path: Option<&Value>,
520) -> Result<String, ApiError> {
521    let given = only_declared(path, descriptor.path_params, "path", false)?;
522    let template = descriptor.path;
523    let mut out = String::new();
524    let mut rest = template;
525    while let Some(open) = rest.find('{') {
526        out.push_str(&rest[..open]);
527        let after = &rest[open + 1..];
528        let close = after
529            .find('}')
530            .ok_or_else(|| ApiError::input("the path template is malformed"))?;
531        let name = &after[..close];
532        let raw = given
533            .iter()
534            .find(|(candidate, _)| candidate == name)
535            .map(|(_, value)| value)
536            .filter(|value| !value.is_null())
537            .ok_or_else(|| ApiError::input(format!("path parameter {name} is required")))?;
538        let value = scalar(raw, &format!("path.{name}"))?;
539        if descriptor.catch_all.contains(&name) {
540            let parts = value
541                .split('/')
542                .map(|part| segment(part, name))
543                .collect::<Result<Vec<_>, _>>()?;
544            out.push_str(&parts.join("/"));
545        } else {
546            out.push_str(&segment(&value, name)?);
547        }
548        rest = &after[close + 1..];
549    }
550    out.push_str(rest);
551    Ok(out)
552}
553
554/// The `x-next-cursor` header is at most 15 digits, and so is a cursor taken from the last line.
555const MAX_CURSOR: u64 = 999_999_999_999_999;
556
557fn is_token(value: &str) -> bool {
558    !value.is_empty() && value.bytes().all(|b| (0x21..=0x7e).contains(&b))
559}
560
561fn resolve_token(source: &TokenSource, scheme: &str) -> Result<String, ApiError> {
562    let token = match source {
563        TokenSource::Static(token) => token.clone(),
564        TokenSource::Provider(provider) => provider(),
565    };
566    if !is_token(&token) {
567        return Err(ApiError::input(format!(
568            "the {scheme} credential is empty or has characters that cannot go in a header"
569        )));
570    }
571    Ok(token)
572}
573
574fn merge_credentials(base: &ApiCredentials, over: Option<&ApiCredentials>) -> ApiCredentials {
575    let mut merged = base.clone();
576    if let Some(over) = over {
577        macro_rules! take {
578            ($field:ident) => {
579                if over.$field.is_some() {
580                    merged.$field = over.$field.clone();
581                }
582            };
583        }
584        take!(bearer_auth);
585        take!(management_oauth);
586        take!(application_api_key);
587        take!(scim_token);
588        take!(client_basic);
589    }
590    merged
591}
592
593fn token_for<'a>(credentials: &'a ApiCredentials, scheme: &str) -> Option<&'a TokenSource> {
594    match scheme {
595        "bearerAuth" => credentials.bearer_auth.as_ref(),
596        "managementOAuth" => credentials.management_oauth.as_ref(),
597        "applicationApiKey" => credentials.application_api_key.as_ref(),
598        "scimToken" => credentials.scim_token.as_ref(),
599        _ => None,
600    }
601}
602
603fn check_extra_headers(headers: &[(String, String)], place: &str) -> Result<(), ApiError> {
604    for (name, _) in headers {
605        if RESERVED_HEADERS.contains(&name.to_ascii_lowercase().as_str()) {
606            return Err(ApiError::input(format!(
607                "{place} cannot set the {} header",
608                name.to_ascii_lowercase()
609            )));
610        }
611    }
612    Ok(())
613}
614
615/// Which Authorization header an operation gets, or none. Fails when it needs a credential that was not supplied.
616pub fn authorization(
617    descriptor: &OperationDescriptor,
618    credentials: &ApiCredentials,
619    has_cookie: bool,
620) -> Result<Option<String>, ApiError> {
621    let has = |scheme: &str| -> bool {
622        if COOKIE_SCHEMES.contains(&scheme) {
623            return has_cookie;
624        }
625        if scheme == "clientBasic" {
626            return credentials.client_basic.is_some();
627        }
628        token_for(credentials, scheme).is_some()
629    };
630    let satisfied: Vec<&&[&str]> = descriptor
631        .security
632        .iter()
633        .filter(|alternative| !alternative.is_empty() && alternative.iter().all(|s| has(s)))
634        .collect();
635    let with_header = satisfied
636        .iter()
637        .find(|alternative| alternative.iter().any(|s| !COOKIE_SCHEMES.contains(s)));
638    if let Some(alternative) = with_header {
639        let scheme = alternative
640            .iter()
641            .find(|s| !COOKIE_SCHEMES.contains(s))
642            .copied()
643            .unwrap_or_default();
644        if BEARER_SCHEMES.contains(&scheme) {
645            let source =
646                token_for(credentials, scheme).ok_or_else(|| ApiError::input("missing token"))?;
647            return Ok(Some(format!("Bearer {}", resolve_token(source, scheme)?)));
648        }
649        let basic = match credentials.client_basic.as_ref() {
650            Some(ClientBasicSource::Static(basic)) => basic.clone(),
651            Some(ClientBasicSource::Provider(provider)) => provider(),
652            None => return Err(ApiError::input("missing client credentials")),
653        };
654        if basic.client_id.is_empty() {
655            return Err(ApiError::input(
656                "the client_basic credential needs a client_id and a client_secret",
657            ));
658        }
659        // RFC 6749 section 2.3.1 form-encodes both before Base64. A space is %20, never +: the service's Basic decoder
660        // leaves a literal + alone, so a + for a space would authenticate as a different secret.
661        let pair = format!(
662            "{}:{}",
663            component_quote(&basic.client_id),
664            component_quote(&basic.client_secret)
665        );
666        return Ok(Some(format!(
667            "Basic {}",
668            base64::engine::general_purpose::STANDARD.encode(pair)
669        )));
670    }
671    if !satisfied.is_empty() {
672        return Ok(None); // authenticated by cookie alone
673    }
674    if descriptor
675        .security
676        .iter()
677        .any(|alternative| alternative.is_empty())
678    {
679        return Ok(None);
680    }
681    let needs = descriptor
682        .security
683        .iter()
684        .map(|alternative| alternative.join(" + "))
685        .collect::<Vec<_>>()
686        .join(" or ");
687    Err(ApiError::client(
688        ClientErrorCode::MissingCredentials,
689        format!(
690            "{} needs {needs}; none was supplied",
691            descriptor.operation_id
692        ),
693    ))
694}
695
696fn snippet(value: Option<&Value>) -> Option<String> {
697    let text = value?.as_str()?;
698    let clean: String = text
699        .chars()
700        .map(|c| if c.is_control() { ' ' } else { c })
701        .collect::<String>()
702        .split_whitespace()
703        .collect::<Vec<_>>()
704        .join(" ");
705    let clean = clean.trim().to_string();
706    if clean.is_empty() {
707        None
708    } else {
709        Some(clean.chars().take(200).collect())
710    }
711}
712
713fn response_error(
714    descriptor: &OperationDescriptor,
715    status: u16,
716    headers: &reqwest::header::HeaderMap,
717    text: &str,
718) -> ApiError {
719    let mut body = None;
720    let mut code = None;
721    let mut description = None;
722    let is_json = headers
723        .get("content-type")
724        .and_then(|v| v.to_str().ok())
725        .map(|v| v.to_ascii_lowercase().contains("json"))
726        .unwrap_or(false);
727    if !text.is_empty() && text.len() <= MAX_ERROR_BODY && is_json {
728        if let Ok(parsed) = serde_json::from_str::<Value>(text) {
729            if let Value::Object(map) = &parsed {
730                code = snippet(map.get("error")).or_else(|| snippet(map.get("detail")));
731                description = snippet(map.get("error_description"))
732                    .or_else(|| map.get("error").and_then(|_| snippet(map.get("detail"))));
733            }
734            body = Some(parsed);
735        }
736    }
737    let header_text = |name: &str| headers.get(name).and_then(|v| v.to_str().ok());
738    let retry = header_text("retry-after")
739        .filter(|v| !v.is_empty() && v.len() <= 9 && v.bytes().all(|b| b.is_ascii_digit()))
740        .and_then(|v| v.parse::<u64>().ok());
741    let request_id =
742        header_text("x-request-id").and_then(|v| snippet(Some(&Value::String(v.to_string()))));
743    let message = format!(
744        "{} {} failed with {status}{}",
745        descriptor.method.as_str(),
746        descriptor.path,
747        code.as_ref().map(|c| format!(": {c}")).unwrap_or_default()
748    );
749    ApiError::Response(Box::new(ApiResponseError {
750        operation_id: descriptor.operation_id,
751        status,
752        code,
753        description,
754        request_id,
755        retry_after_seconds: retry,
756        body,
757        message,
758    }))
759}
760
761/// Executes descriptors over one `reqwest::Client` that never follows a redirect.
762pub struct Transport {
763    client: reqwest::Client,
764    base: String,
765    credentials: ApiCredentials,
766    cookie: Option<String>,
767    timeout: Duration,
768    headers: Vec<(String, String)>,
769}
770
771impl std::fmt::Debug for Transport {
772    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
773        f.debug_struct("Transport")
774            .field("base", &self.base)
775            .finish_non_exhaustive()
776    }
777}
778
779impl Transport {
780    pub fn new(options: &ApiClientOptions) -> Result<Self, ApiError> {
781        let base = normalize_base(&options.base_url, options.allow_insecure_http)?;
782        check_extra_headers(&options.headers, "headers")?;
783        if let Some(cookie) = &options.cookie {
784            if cookie.is_empty() || !cookie.bytes().all(|b| (0x20..=0x7e).contains(&b)) {
785                return Err(ApiError::input(
786                    "the cookie value is empty or has characters that cannot go in a header",
787                ));
788            }
789        }
790        let client = reqwest::Client::builder()
791            .redirect(reqwest::redirect::Policy::none())
792            .build()
793            .map_err(|_| ApiError::Network("the HTTP client could not be created".to_string()))?;
794        Ok(Self {
795            client,
796            base,
797            credentials: options.credentials.clone(),
798            cookie: options.cookie.clone(),
799            timeout: options.timeout,
800            headers: options.headers.clone(),
801        })
802    }
803
804    /// The request a call would send, without sending it.
805    pub fn build_request(
806        &self,
807        descriptor: &OperationDescriptor,
808        input: CallInput,
809        options: &CallOptions,
810    ) -> Result<reqwest::Request, ApiError> {
811        match (&descriptor.body, &input.body) {
812            (None, Some(_)) => return Err(ApiError::input("this operation takes no body")),
813            (Some(spec), None) if spec.required => {
814                return Err(ApiError::input("this operation requires a body"))
815            }
816            _ => {}
817        }
818        let mut url = self.base.clone();
819        url.push_str(&build_path(descriptor, input.path.as_ref())?);
820        let query = encode_pairs(
821            &only_declared(input.query.as_ref(), descriptor.query, "query", false)?,
822            "query",
823        )?;
824        if !query.is_empty() {
825            url.push('?');
826            url.push_str(&join_pairs(&query));
827        }
828        let method = match descriptor.method {
829            HttpMethod::Get => reqwest::Method::GET,
830            HttpMethod::Post => reqwest::Method::POST,
831            HttpMethod::Put => reqwest::Method::PUT,
832            HttpMethod::Patch => reqwest::Method::PATCH,
833            HttpMethod::Delete => reqwest::Method::DELETE,
834        };
835        let parsed = reqwest::Url::parse(&url)
836            .map_err(|_| ApiError::input("the request URL could not be built"))?;
837        let mut request = reqwest::Request::new(method, parsed);
838
839        let mut headers: Vec<(String, String)> = vec![(
840            "accept".to_string(),
841            if descriptor.response == ResponseKind::Ndjson {
842                "application/x-ndjson"
843            } else {
844                "application/json"
845            }
846            .to_string(),
847        )];
848        let mut set = |name: &str, value: String| {
849            let lower = name.to_ascii_lowercase();
850            headers.retain(|(existing, _)| *existing != lower);
851            headers.push((lower, value));
852        };
853        for (name, value) in &self.headers {
854            set(name, value.clone());
855        }
856        check_extra_headers(&options.headers, "options.headers")?;
857        for (name, value) in &options.headers {
858            set(name, value.clone());
859        }
860        for (name, value) in
861            only_declared(input.headers.as_ref(), descriptor.headers, "headers", true)?
862        {
863            if !value.is_null() {
864                set(&name, scalar(&value, &format!("headers.{name}"))?);
865            }
866        }
867        let credentials = merge_credentials(&self.credentials, options.credentials.as_ref());
868        if let Some(auth) = authorization(descriptor, &credentials, self.cookie.is_some())? {
869            set("authorization", auth);
870        }
871        if let Some(cookie) = &self.cookie {
872            if descriptor
873                .security
874                .iter()
875                .any(|alternative| alternative.iter().any(|s| COOKIE_SCHEMES.contains(s)))
876            {
877                set("cookie", cookie.clone());
878            }
879        }
880
881        if let (Some(spec), Some(body)) = (&descriptor.body, &input.body) {
882            match spec.kind {
883                BodyKind::Json => {
884                    set("content-type", "application/json".to_string());
885                    let bytes = serde_json::to_vec(body)
886                        .map_err(|_| ApiError::input("the body cannot be written as JSON"))?;
887                    *request.body_mut() = Some(bytes.into());
888                }
889                BodyKind::Form => {
890                    let Value::Object(map) = body else {
891                        return Err(ApiError::input("a form body must be an object"));
892                    };
893                    let entries: Vec<(String, Value)> =
894                        map.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
895                    let pairs = encode_pairs(&entries, "body")?;
896                    set(
897                        "content-type",
898                        "application/x-www-form-urlencoded".to_string(),
899                    );
900                    *request.body_mut() = Some(join_pairs(&pairs).into_bytes().into());
901                }
902            }
903        }
904        for (name, value) in headers {
905            let name = reqwest::header::HeaderName::from_bytes(name.as_bytes())
906                .map_err(|_| ApiError::input(format!("{name} is not a valid header name")))?;
907            let value = reqwest::header::HeaderValue::from_str(&value).map_err(|_| {
908                ApiError::input("a header value has characters that cannot go in a header")
909            })?;
910            request.headers_mut().append(name, value);
911        }
912        let timeout = options.timeout.unwrap_or(self.timeout);
913        if !timeout.is_zero() {
914            *request.timeout_mut() = Some(timeout);
915        }
916        Ok(request)
917    }
918
919    async fn send(
920        &self,
921        descriptor: &OperationDescriptor,
922        input: CallInput,
923        options: &CallOptions,
924    ) -> Result<(reqwest::header::HeaderMap, String), ApiError> {
925        let request = self.build_request(descriptor, input, options)?;
926        let network = || {
927            ApiError::Network(format!(
928                "{} {} did not complete",
929                descriptor.method.as_str(),
930                descriptor.path
931            ))
932        };
933        let response = self.client.execute(request).await.map_err(|_| network())?;
934        let status = response.status().as_u16();
935        let headers = response.headers().clone();
936        let text = response.text().await.map_err(|_| network())?;
937        if !(200..300).contains(&status) {
938            return Err(response_error(descriptor, status, &headers, &text));
939        }
940        Ok((headers, text))
941    }
942
943    fn expect(descriptor: &OperationDescriptor, kind: ResponseKind) -> Result<(), ApiError> {
944        if descriptor.response == kind {
945            Ok(())
946        } else {
947            Err(ApiError::input(format!(
948                "{} does not answer with {kind:?}",
949                descriptor.operation_id
950            )))
951        }
952    }
953
954    /// An operation whose success carries no body.
955    pub async fn call_empty(
956        &self,
957        descriptor: &OperationDescriptor,
958        input: CallInput,
959        options: &CallOptions,
960    ) -> Result<(), ApiError> {
961        Self::expect(descriptor, ResponseKind::Empty)?;
962        self.send(descriptor, input, options).await.map(|_| ())
963    }
964
965    /// A JSON operation. An empty body reads as JSON `null`, which only an optional result type accepts.
966    pub async fn call_json<T: DeserializeOwned>(
967        &self,
968        descriptor: &OperationDescriptor,
969        input: CallInput,
970        options: &CallOptions,
971    ) -> Result<T, ApiError> {
972        Self::expect(descriptor, ResponseKind::Json)?;
973        let (_, text) = self.send(descriptor, input, options).await?;
974        let value = if text.trim().is_empty() {
975            Value::Null
976        } else {
977            serde_json::from_str::<Value>(&text).map_err(|_| {
978                ApiError::client(
979                    ClientErrorCode::InvalidResponse,
980                    format!(
981                        "{} returned a body that is not JSON",
982                        descriptor.operation_id
983                    ),
984                )
985            })?
986        };
987        serde_json::from_value::<T>(value).map_err(|_| {
988            ApiError::client(
989                ClientErrorCode::InvalidResponse,
990                format!(
991                    "{} returned a body that does not match the contract",
992                    descriptor.operation_id
993                ),
994            )
995        })
996    }
997
998    /// A JSON operation that may also answer with no body (or `null`), which is `None`.
999    pub async fn call_json_opt<T: DeserializeOwned>(
1000        &self,
1001        descriptor: &OperationDescriptor,
1002        input: CallInput,
1003        options: &CallOptions,
1004    ) -> Result<Option<T>, ApiError> {
1005        self.call_json::<Option<T>>(descriptor, input, options)
1006            .await
1007    }
1008
1009    /// An NDJSON export page.
1010    pub async fn call_ndjson(
1011        &self,
1012        descriptor: &OperationDescriptor,
1013        input: CallInput,
1014        options: &CallOptions,
1015    ) -> Result<NdjsonPage, ApiError> {
1016        Self::expect(descriptor, ResponseKind::Ndjson)?;
1017        let (headers, text) = self.send(descriptor, input, options).await?;
1018        let mut lines = Vec::new();
1019        for line in text.split('\n').filter(|line| !line.trim().is_empty()) {
1020            lines.push(serde_json::from_str::<Value>(line).map_err(|_| {
1021                ApiError::client(
1022                    ClientErrorCode::InvalidResponse,
1023                    format!(
1024                        "{} returned a line that is not JSON",
1025                        descriptor.operation_id
1026                    ),
1027                )
1028            })?);
1029        }
1030        let mut next_cursor = headers
1031            .get("x-next-cursor")
1032            .and_then(|v| v.to_str().ok())
1033            .filter(|v| !v.is_empty() && v.len() <= 15 && v.bytes().all(|b| b.is_ascii_digit()))
1034            .and_then(|v| v.parse::<u64>().ok());
1035        if next_cursor.is_none() {
1036            // A cross-origin caller cannot read the header unless it is exposed; the last line carries the same cursor.
1037            next_cursor = lines
1038                .last()
1039                .and_then(|line| line.get("cursor"))
1040                .and_then(Value::as_u64)
1041                .filter(|cursor| *cursor <= MAX_CURSOR);
1042        }
1043        Ok(NdjsonPage {
1044            text,
1045            lines,
1046            next_cursor,
1047        })
1048    }
1049}