capsule_sdk/client.rs
1//! The session-composed typed REST client.
2//!
3//! [`AuthenticatedClient`] revives the shape the parked wrapper in the crate root promised —
4//! a thin skin over the `spargen`-generated [`rest::Client`] that owns
5//! the base URL, swaps base URL/credentials without callers rebuilding anything, and
6//! `Deref`s to the typed client so every generated operation is called directly. What the
7//! parked sketch could not express, this composition does: instead of a static bearer string,
8//! the client is wired to the SDK's [`Session`] through spargen's async
9//! token-provider seam, so **every** typed call transparently gets a valid access token, with
10//! the session's proactive pre-flight refresh and single-flight coalescing — callers never
11//! touch a raw token. The refresh/expiry/single-flight logic is reused wholesale from
12//! [`crate::auth`]; nothing is duplicated here.
13//!
14//! # Both halves of the refresh contract
15//!
16//! The token provider is the **proactive** half: it refreshes when the stored token is within
17//! its skew of expiry, before the request leaves. That cannot cover a token the server stops
18//! honouring early — a revocation mid-flight, or a clock the two ends disagree about — so
19//! `RefreshOn401` is the **reactive** half: an [`rest::HttpBackend`] wrapping
20//! [`rest::ReqwestBackend`] that, on a `401` whose problem code says the access token was
21//! refused (`error.request.unauthenticated`), refreshes once through the session and replays
22//! the request exactly once. A `401` carrying any other code is a refused *credential* — a
23//! wrong password or second-factor code — and is surfaced untouched. The two are
24//! complementary and neither duplicates the other; the refresh itself is still `auth`'s
25//! single-flight gate.
26//!
27//! It sits at the transport seam rather than in each caller, so **every** generated operation
28//! is covered by one layer that survives regeneration — no generated code is touched, and
29//! there is no per-call retry loop to keep in step.
30//!
31//! Scope: this covers the plain request/response REST surfaces the OpenAPI schema declares
32//! (auth/session, quota, storage-verify, receipts, devices, escrow, …). The stateful upload
33//! protocol ([`crate::upload`]) stays hand-written. The sync feed ([`crate::sync`]) *is* a
34//! generated operation (`GET /v1/sync`), but [`crate::sync::SyncConsumer`] drives it under its
35//! own cursor/anti-rewind state machine and builds its own client, because it also serves a
36//! static-token mode that has no session to refresh.
37
38use std::ops::Deref;
39use std::sync::Arc;
40
41use http_body_util::BodyExt;
42use reqwest::header::{AUTHORIZATION, HeaderValue};
43use secrecy::ExposeSecret;
44
45use crate::auth::Session;
46use crate::net::negotiation;
47use crate::rest::{self, Client};
48
49/// The credential a generated client presents under the contract's `bearer` security scheme,
50/// attached through the typed setter spargen generates for that scheme.
51pub(crate) enum Bearer {
52 /// A fixed token: a static access token, or a federation capability.
53 Token(String),
54 /// A source asked for a fresh token each time a call attaches the scheme.
55 Provider(rest::TokenProvider),
56}
57
58/// An optional, nullable field of a generated request: the value, or absent (omitted from the
59/// body) when there is none, as spargen before 0.8 sent an `Option`'s `None`. Never `null`:
60/// nothing the SDK sends distinguishes the two.
61pub(crate) fn absent_unless<T>(value: Option<T>) -> rest::Nullable<T> {
62 value.map_or(rest::Nullable::Absent, rest::Nullable::Value)
63}
64
65impl Bearer {
66 /// `client`, presenting this credential on every operation whose `security` names the
67 /// bearer scheme.
68 pub(crate) fn attach(self, client: Client) -> Client {
69 match self {
70 Self::Token(token) => client.with_bearer(token.into()),
71 Self::Provider(provider) => client.with_bearer_provider(provider),
72 }
73 }
74}
75
76/// Failure constructing an [`AuthenticatedClient`] — today only a malformed base URL. Wire
77/// failures surface later, per operation, through the generated client's own typed error.
78#[derive(Debug, thiserror::Error)]
79pub enum ClientError {
80 /// The configured base URL could not be parsed.
81 #[error("invalid base URL {url:?}: {reason}")]
82 InvalidBaseUrl {
83 /// The offending URL.
84 url: String,
85 /// Why the generated client rejected it.
86 reason: String,
87 },
88}
89
90/// A typed REST client that authenticates itself from an SDK [`Session`].
91///
92/// Cheap to build; holds one [`rest::Client`] whose bearer credential is
93/// an async provider backed by the session. Because the provider is consulted per request,
94/// token rotation (refresh) is picked up with no rebuild. Deref-transparent: call any
95/// generated operation directly, e.g.
96/// `client.get_quota(GetQuotaParamsRequired { x_capsule_protocol: PROTOCOL_VERSION.into() })` —
97/// every gated operation's `…ParamsRequired` carries the protocol date, because the document
98/// declares `X-Capsule-Protocol` required there (issue #404); the transport sends the same value
99/// as a default header regardless.
100pub struct AuthenticatedClient {
101 base_url: String,
102 session: Session,
103 client: Client,
104}
105
106impl AuthenticatedClient {
107 /// Build a client for `base_url` (the API root the generated operation paths hang off,
108 /// e.g. `https://api.example.com`), authenticated by `session`.
109 pub fn new(base_url: &str, session: Session) -> Result<Self, ClientError> {
110 let client = build_client(base_url, session.clone())?;
111 Ok(Self {
112 base_url: base_url.to_string(),
113 session,
114 client,
115 })
116 }
117
118 /// The API root this client is currently pointed at.
119 #[must_use]
120 pub fn base_url(&self) -> &str {
121 &self.base_url
122 }
123
124 /// Whether this build is outside the window this client's server last advertised — the
125 /// read-side signal: reads keep being served, writes are refused with a `426`, and this is
126 /// what a UI asks to tell the user to update. `None` before any response, and inside it.
127 #[must_use]
128 pub fn upgrade_required(&self) -> Option<negotiation::UpgradeRequired> {
129 let url = reqwest::Url::parse(&self.base_url).ok()?;
130 negotiation::upgrade_required_for(&url)
131 }
132
133 /// The session backing this client's bearer credential.
134 #[must_use]
135 pub fn session(&self) -> &Session {
136 &self.session
137 }
138
139 /// Repoint the client at a new API root, keeping the same session. Rebuilds the inner
140 /// generated client (base URL is fixed at its construction).
141 pub fn with_base_url(&mut self, base_url: &str) -> Result<&mut Self, ClientError> {
142 self.client = build_client(base_url, self.session.clone())?;
143 self.base_url = base_url.to_string();
144 Ok(self)
145 }
146
147 /// Swap the backing session (e.g. after re-authentication), rebuilding the credential.
148 pub fn with_session(&mut self, session: Session) -> Result<&mut Self, ClientError> {
149 self.client = build_client(&self.base_url, session.clone())?;
150 self.session = session;
151 Ok(self)
152 }
153}
154
155impl Deref for AuthenticatedClient {
156 type Target = Client;
157
158 fn deref(&self) -> &Self::Target {
159 &self.client
160 }
161}
162
163/// The bearer prefix the `Authorization` header carries, and the only credential shape
164/// [`RefreshOn401`] recognises as a token it can refresh.
165const BEARER_PREFIX: &str = "Bearer ";
166
167/// The reactive half of the refresh contract: an [`rest::HttpBackend`] that,
168/// on a `401` coded [`EXPIRED_TOKEN_CODE`], refreshes the session once and replays the request
169/// exactly once. Any other `401` is returned as the server sent it.
170///
171/// # Why the transport seam and not [`rest::Middleware`]
172///
173/// A middleware receives a `Next`, and `Next::run` takes `self` by value while `Next` is
174/// neither `Clone` nor constructible outside the generated runtime. A middleware therefore
175/// *cannot* send a second time, which is the one thing this layer must do. The backend seam
176/// has no such constraint, and spargen's own `RetryBackend` is the precedent — including the
177/// `try_clone`-returns-`None` rule for one-shot bodies.
178///
179/// # Exactly once, by construction
180///
181/// The replay is straight-line code, not a loop with a counter: one send, one refresh, one
182/// replay, and whatever the replay answers is returned as-is. A second `401` is surfaced.
183struct RefreshOn401 {
184 inner: Arc<dyn rest::HttpBackend>,
185 session: Session,
186}
187
188// `Session` is not `Debug` (it holds token material), and `HttpBackend` requires `Debug` so the
189// generated `ClientCore` stays printable. The manual impl names the layer and the backend under
190// it, and shows nothing of the session.
191impl std::fmt::Debug for RefreshOn401 {
192 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
193 f.debug_struct("RefreshOn401")
194 .field("inner", &self.inner)
195 .finish_non_exhaustive()
196 }
197}
198
199impl rest::HttpBackend for RefreshOn401 {
200 fn execute(&self, request: http::Request<rest::HttpBody>) -> rest::ExecuteFuture<'_> {
201 // Own clones of the `Arc`/`Session` so the returned future is self-contained, matching
202 // the seam's expectations (and `RetryBackend`'s shape).
203 let inner = self.inner.clone();
204 let session = self.session.clone();
205 Box::pin(async move {
206 // A one-shot streaming body cannot be resent intact. Execute the original once and
207 // return: half a body on the wire twice is worse than a `401` the caller can see.
208 let Some(mut replay) = crate::net::try_clone_request(&request) else {
209 tracing::debug!("request body is not replayable; a 401 will not be retried");
210 return inner.execute(request).await;
211 };
212
213 let response = inner.execute(request).await?;
214 if response.status() != reqwest::StatusCode::UNAUTHORIZED {
215 return Ok(response);
216 }
217
218 // An operation carrying no bearer has nothing to refresh — that `401` is the
219 // server's answer about the request, not about a stale token.
220 let Some(stale) = bearer_of(&replay) else {
221 tracing::debug!("a 401 arrived on a request carrying no bearer; not retrying");
222 return Ok(response);
223 };
224
225 // Only the bearer scheme's own refusal is a stale token. A `401` an operation
226 // answers about its *payload* — a wrong password on `reauthenticate`, a wrong code
227 // on `totp_disable` — is a refused credential: replaying it charges the lockout
228 // twice and spends the refresh token for nothing (issue #511).
229 let (code, response) = problem_code_of(response).await?;
230 if code.as_deref() != Some(EXPIRED_TOKEN_CODE) {
231 tracing::debug!(
232 code = code.as_deref().unwrap_or("<none>"),
233 "a 401 that is not an expired token; not retrying"
234 );
235 return Ok(response);
236 }
237
238 let fresh = match session.refresh_rejected(&stale).await {
239 Ok(fresh) => fresh,
240 // Deliberately the *original* `401`, not a synthetic transport error: the
241 // generated operation then maps it to its typed `Status401` and the caller
242 // reads the server's own problem — the `error.request.unauthenticated` the
243 // operation answered, not whatever the failed refresh answered — instead of a
244 // transport error that carries no code at all.
245 Err(error) => {
246 tracing::warn!(%error, "a 401 could not be recovered; surfacing it");
247 return Ok(response);
248 }
249 };
250 let Ok(header) =
251 HeaderValue::from_str(&format!("{BEARER_PREFIX}{}", fresh.expose_secret()))
252 else {
253 tracing::warn!(
254 "the refreshed token is not a valid header value; surfacing the 401"
255 );
256 return Ok(response);
257 };
258 replay.headers_mut().insert(AUTHORIZATION, header);
259 tracing::info!("the typed client's 401 was refreshed; replaying once");
260 inner.execute(replay).await
261 })
262 }
263}
264
265/// The one `401` problem code [`RefreshOn401`] refreshes and replays: the code the server's
266/// coded-problem interceptor gives the bearer scheme's own refusal — a token that does not
267/// verify, has expired, or names a session the ledger no longer holds
268/// (`capsule_server::problem::code_for`). Every route-level `401` carries its own `error.*`
269/// code, and none of those is a stale token.
270const EXPIRED_TOKEN_CODE: &str = capsule_i18n::error_codes::REQUEST_UNAUTHENTICATED;
271
272/// The `code` member of an RFC 9457 problem body; every other member is the generated
273/// operation's to parse.
274#[derive(serde::Deserialize)]
275struct ProblemCode {
276 code: Option<String>,
277}
278
279/// Read `response`'s problem `code`, then rebuild the response from the bytes read so the
280/// generated operation still maps it to its typed error. A body that is not a problem yields
281/// `None`, which [`RefreshOn401`] treats as "not an expired token": it fails closed, never
282/// replaying a `401` it cannot classify.
283async fn problem_code_of(
284 response: http::Response<rest::HttpBody>,
285) -> Result<(Option<String>, http::Response<rest::HttpBody>), rest::TransportError> {
286 let (parts, body) = response.into_parts();
287 let body = BodyExt::collect(body).await?.to_bytes();
288 let code = serde_json::from_slice::<ProblemCode>(&body)
289 .ok()
290 .and_then(|problem| problem.code);
291 Ok((code, http::Response::from_parts(parts, body.into())))
292}
293
294/// The bearer token a prepared request carries, if any. `None` for an unauthenticated
295/// operation, and for any credential shape this layer cannot refresh.
296fn bearer_of(request: &http::Request<rest::HttpBody>) -> Option<String> {
297 request
298 .headers()
299 .get(AUTHORIZATION)?
300 .to_str()
301 .ok()?
302 .strip_prefix(BEARER_PREFIX)
303 .map(str::to_owned)
304}
305
306/// Wire a generated client to `base_url` with a bearer credential that pulls a fresh access
307/// token from `session` on demand (the proactive half), executing through [`RefreshOn401`]
308/// (the reactive half).
309fn build_client(base_url: &str, session: Session) -> Result<Client, ClientError> {
310 let provider_session = session.clone();
311 let provider: rest::TokenProvider = Arc::new(move || {
312 let session = provider_session.clone();
313 // The session yields a currently-valid bearer, refreshing pre-flight if the stored
314 // token is within its refresh skew of expiry; the failure is mapped into spargen's
315 // provider-error type so a dead session is a request-construction error, not a 401.
316 Box::pin(async move {
317 session
318 .bearer()
319 .await
320 .map_err(|e| rest::AuthError::new(e.to_string()))
321 })
322 });
323
324 // `with_backend` builds no HTTP client of its own: every request is executed through the
325 // backend, so the executing client — and with it the TLS stack, the redirect policy and the
326 // timeouts — is `reqwest_client()`, one layer down.
327 let backend: Arc<dyn rest::HttpBackend> = Arc::new(Negotiate::over(Arc::new(RefreshOn401 {
328 inner: crate::net::backend(reqwest_client()),
329 session,
330 })));
331 let client = crate::net::generated_client(backend, base_url)
332 .map_err(|reason| ClientError::InvalidBaseUrl {
333 url: base_url.to_string(),
334 reason,
335 })?
336 .with_bearer_provider(provider);
337 Ok(client)
338}
339
340/// The generated client's transport: the SDK's one HTTP client
341/// ([`crate::net::http_client`]) — rustls only, carrying the protocol handshake on every request
342/// it sends, the generated operations included.
343///
344/// **One per process, shared.** A `reqwest::Client` owns a connection pool, and cloning it
345/// shares that pool; building a new one throws the pool away. The FFI's escrow verbs construct
346/// a fresh [`AuthenticatedClient`] per call (the API root is a per-call argument), so a
347/// per-client transport would mean a fresh TLS handshake for every escrow read on a device
348/// that does several during one cadence prompt. Nothing here is configured per instance —
349/// `http_client` takes no arguments and its protocol headers are the same on every request —
350/// so there is nothing to vary: the same client serves them all. `Client::with_backend` builds
351/// no client of its own (spargen 0.8), so this is the only `reqwest::Client` an
352/// [`AuthenticatedClient`] touches.
353fn reqwest_client() -> reqwest::Client {
354 static SHARED: std::sync::OnceLock<reqwest::Client> = std::sync::OnceLock::new();
355 SHARED
356 .get_or_init(|| {
357 crate::net::http_client()
358 .expect("a default rustls reqwest client is always constructible")
359 })
360 .clone()
361}
362
363/// The protocol window on the generated client's transport (issue #674): every response's
364/// advertised window is latched ([`negotiation::observe`]), and a write the latched window
365/// already refuses is answered here, before it leaves, with a local `426`.
366///
367/// # Why a synthesized `426` and not an error
368///
369/// The backend seam's error type carries a failure *class* and a cause, so a typed refusal
370/// cannot cross it as one. A `426` can: the generated operation maps it exactly as it maps the
371/// server's own, and [`upgrade_required_of`] turns either into the one
372/// [`UpgradeRequired`](negotiation::UpgradeRequired). The synthesized response carries the
373/// latched window headers and a coded problem, so it is indistinguishable at the caller from
374/// the refusal the server would have sent — minus the request the server never sees.
375#[derive(Debug)]
376pub(crate) struct Negotiate {
377 inner: Arc<dyn rest::HttpBackend>,
378 /// Whether a write the latched window refuses is answered locally. Off for the auth
379 /// client's session-upkeep operations, which only the server's own `426` refuses
380 /// (see `auth::NegotiatedSend`).
381 preflight: bool,
382}
383
384impl Negotiate {
385 /// Put the window screen over `inner`: latch every window, refuse a write it refuses.
386 pub(crate) fn over(inner: Arc<dyn rest::HttpBackend>) -> Self {
387 Self {
388 inner,
389 preflight: true,
390 }
391 }
392
393 /// Latch every window `inner`'s responses advertise, and refuse nothing.
394 pub(crate) fn observing(inner: Arc<dyn rest::HttpBackend>) -> Self {
395 Self {
396 inner,
397 preflight: false,
398 }
399 }
400}
401
402impl rest::HttpBackend for Negotiate {
403 fn execute(&self, request: http::Request<rest::HttpBody>) -> rest::ExecuteFuture<'_> {
404 let inner = self.inner.clone();
405 let preflight = self.preflight;
406 Box::pin(async move {
407 // The seam carries an `http::Uri`, which the generated runtime guarantees absolute.
408 // One that is not a URL is the runtime's to refuse, so it passes through unscreened.
409 let url = reqwest::Url::parse(&request.uri().to_string()).ok();
410 let protocol = negotiation::protocol_of(request.headers());
411 if preflight
412 && let Some(url) = &url
413 && let Err(refusal) = negotiation::preflight(request.method(), url, &protocol)
414 {
415 return Ok(local_upgrade_required(&refusal));
416 }
417 let response = inner.execute(request).await?;
418 // The window is latched for the origin the request was sent to, because an
419 // `http::Response` carries no final URL (reqwest keeps it private). That assumes the
420 // API answers its operations where the document places them: the SDK's client still
421 // follows redirects, and a cross-origin one would latch the redirect target's window
422 // under this origin. A narrower window there refuses a write locally with a `426`; a
423 // wider one lets through a write this origin's server then refuses with its own. No
424 // write lands that the server would refuse either way.
425 if let Some(url) = &url {
426 negotiation::observe(url, response.headers());
427 }
428 if response.status() == reqwest::StatusCode::PAYLOAD_TOO_LARGE {
429 return coded_too_large(response).await;
430 }
431 Ok(response)
432 })
433 }
434}
435
436/// A `413` as the generated operations can read it, whoever answered it.
437///
438/// The contract declares every `413` a coded problem, and this server sends one. A server from
439/// before that (its body-size backstop answered with no body), or a reverse proxy refusing the
440/// body before it reached the server (nginx's `client_max_body_size` answers `413 text/html`),
441/// does not. The generated client then fails to decode the documented body and reports a
442/// wire failure instead of the typed refusal, which tells the caller to retry the same bytes.
443/// Native clients stay lenient towards older and intermediary peers, so a `413` whose body is
444/// not a coded problem is answered here with one coded `error.request.too_large`, keeping the
445/// status and headers. A `413` that already carries a code passes through unchanged.
446async fn coded_too_large(
447 response: http::Response<rest::HttpBody>,
448) -> Result<http::Response<rest::HttpBody>, rest::TransportError> {
449 let (mut parts, body) = response.into_parts();
450 let body = BodyExt::collect(body).await?.to_bytes();
451 let coded = serde_json::from_slice::<ProblemCode>(&body)
452 .ok()
453 .and_then(|problem| problem.code)
454 .is_some();
455 let body = if coded {
456 body
457 } else {
458 tracing::debug!(
459 bytes = body.len(),
460 "a 413 without a coded problem body was coded error.request.too_large"
461 );
462 parts.headers.insert(
463 reqwest::header::CONTENT_TYPE,
464 HeaderValue::from_static("application/problem+json"),
465 );
466 parts.headers.remove(reqwest::header::CONTENT_LENGTH);
467 serde_json::json!({
468 "type": "about:blank",
469 "title": "Payload Too Large",
470 "status": 413,
471 "detail": "the request body is larger than the server or a proxy in front of it accepts",
472 "code": capsule_i18n::error_codes::REQUEST_TOO_LARGE,
473 })
474 .to_string()
475 .into()
476 };
477 Ok(http::Response::from_parts(parts, body.into()))
478}
479
480/// A generated client for `base_url` that executes on `http` under the window screen — the
481/// one way this crate builds a generated client outside [`AuthenticatedClient`], so a write
482/// through any of them is pre-flighted and a read through any of them latches the window.
483///
484/// The error is the generated client's description of a `base_url` it cannot parse.
485pub(crate) fn negotiated_client(http: reqwest::Client, base_url: &str) -> Result<Client, String> {
486 crate::net::generated_client(
487 Arc::new(Negotiate::over(crate::net::backend(http))),
488 base_url,
489 )
490}
491
492/// The `426` [`Negotiate`] answers a refused write with: the window it was refused under, as
493/// headers, and an RFC 9457 problem coded `error.protocol.version_unsupported`.
494fn local_upgrade_required(
495 refusal: &negotiation::UpgradeRequired,
496) -> http::Response<rest::HttpBody> {
497 let problem = serde_json::json!({
498 "type": "about:blank",
499 "title": "Upgrade Required",
500 "status": 426,
501 "detail": refusal.message,
502 "code": refusal.error_code(),
503 });
504 let mut response = http::Response::new(rest::HttpBody::from(problem.to_string()));
505 *response.status_mut() = reqwest::StatusCode::UPGRADE_REQUIRED;
506 let headers = response.headers_mut();
507 headers.insert(
508 reqwest::header::CONTENT_TYPE,
509 HeaderValue::from_static("application/problem+json"),
510 );
511 for (name, value) in [
512 (
513 negotiation::PROTOCOL_MIN_HEADER,
514 &refusal.window.protocol_min,
515 ),
516 (
517 negotiation::PROTOCOL_MAX_HEADER,
518 &refusal.window.protocol_max,
519 ),
520 (
521 negotiation::MIN_CLIENT_BUILD_HEADER,
522 &refusal.window.min_client_build,
523 ),
524 ] {
525 if let Some(value) = value.as_deref().and_then(|v| HeaderValue::from_str(v).ok()) {
526 headers.insert(name, value);
527 }
528 }
529 response
530}
531
532/// The one typed [`UpgradeRequired`](negotiation::UpgradeRequired) a generated-client failure
533/// carries, if it is one: a `426` — the server's, or the typed transport's local refusal of a
534/// write the latched window refuses — documented or not. `None` for every other failure.
535pub fn upgrade_required_of<E>(error: &rest::Error<E>) -> Option<negotiation::UpgradeRequired>
536where
537 E: std::error::Error + 'static,
538{
539 let (headers, message) = match error {
540 rest::Error::Api(response)
541 if response.status() == reqwest::StatusCode::UPGRADE_REQUIRED =>
542 {
543 (response.headers(), error.to_string())
544 }
545 rest::Error::UnexpectedStatus {
546 status,
547 headers,
548 body,
549 } if *status == reqwest::StatusCode::UPGRADE_REQUIRED => (
550 headers,
551 negotiation::problem_detail(&String::from_utf8_lossy(body)),
552 ),
553 _ => return None,
554 };
555 Some(negotiation::UpgradeRequired::refused(
556 headers,
557 negotiation::PROTOCOL_VERSION,
558 message,
559 ))
560}
561
562/// Whether a generated-client failure is the session failing to produce a bearer.
563///
564/// `RequestConstruction` is **not** a token-only class: every request-kind cause lands there,
565/// a request the runtime could not assemble among them (connection-refused, DNS and TLS
566/// failures are the generated taxonomy's `Transport`). The *source* discriminates them: the
567/// token provider
568/// [`build_client`] registers boxes its failure as the generated runtime's own
569/// [`rest::AuthError`], and nothing else on this path is. A dead session must reach a caller
570/// as an auth failure rather than as a transport blip, because the two have opposite remedies.
571pub(crate) fn is_token_failure<E>(error: &rest::Error<E>) -> bool
572where
573 E: std::error::Error + 'static,
574{
575 matches!(error, rest::Error::RequestConstruction(inner)
576 if std::error::Error::source(inner)
577 .and_then(|source| source.downcast_ref::<rest::AuthError>())
578 .is_some())
579}
580
581/// Render a generated-client failure together with its source chain. The taxonomy's own
582/// `Display` names the class and, for the wire classes, little else (`"transport failed"`,
583/// `"request construction failed"`); the source chain is where the reqwest/hyper reason a log
584/// reader needs actually lives.
585pub(crate) fn describe_error<E>(error: &rest::Error<E>) -> String
586where
587 E: std::error::Error + 'static,
588{
589 let mut rendered = error.to_string();
590 let mut source = std::error::Error::source(error);
591 while let Some(cause) = source {
592 rendered.push_str(": ");
593 rendered.push_str(&cause.to_string());
594 source = cause.source();
595 }
596 rendered
597}
598
599#[cfg(test)]
600mod tests;