Skip to main content

yldfi_common/
api.rs

1//! Generic API client infrastructure
2//!
3//! This module provides shared types for API clients, reducing boilerplate
4//! across the DEX aggregator crates.
5//!
6//! # Error Types
7//!
8//! ```
9//! use yldfi_common::api::{ApiError, ApiResult};
10//!
11//! // Use with no domain-specific errors
12//! type MyResult<T> = ApiResult<T>;
13//!
14//! // Or with domain-specific errors
15//! #[derive(Debug, thiserror::Error)]
16//! enum MyDomainError {
17//!     #[error("No route found")]
18//!     NoRouteFound,
19//! }
20//!
21//! type MyError = ApiError<MyDomainError>;
22//! ```
23//!
24//! # Config Types
25//!
26//! ```no_run
27//! use yldfi_common::api::ApiConfig;
28//!
29//! let config = ApiConfig::new("https://api.example.com")
30//!     .api_key("your-key")
31//!     .with_timeout_secs(30);
32//! ```
33
34use crate::http::{HttpClientConfig, HttpError};
35use crate::RetryableError;
36use reqwest::Client;
37use std::fmt;
38use std::time::Duration;
39use thiserror::Error;
40
41/// Marker type for API errors with no domain-specific variants
42///
43/// This type is used as the default for `ApiError<E>` when no domain-specific
44/// errors are needed. It can never be constructed, so the `Domain` variant
45/// is effectively unused.
46#[derive(Debug, Clone, Copy)]
47pub enum NoDomainError {}
48
49impl fmt::Display for NoDomainError {
50    fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
51        match *self {}
52    }
53}
54
55impl std::error::Error for NoDomainError {}
56
57/// Maximum length for error message bodies (SEC-005 fix)
58const MAX_ERROR_BODY_LENGTH: usize = 500;
59
60/// Join a base URL with a path, handling edge cases properly (LOW-003 fix).
61///
62/// This is more robust than simple string concatenation:
63/// - Handles trailing slashes in base URL
64/// - Handles leading slashes in path
65/// - Handles query strings properly
66///
67/// Falls back to simple concatenation if URL parsing fails.
68#[must_use]
69pub fn join_url(base: &str, path: &str) -> String {
70    // Try to use url::Url::parse for validation and proper handling
71    if let Ok(base_url) = url::Url::parse(base) {
72        // url::Url::join treats paths starting with / as absolute, which would
73        // replace the entire path. We want to append instead.
74        let path_to_join = path.trim_start_matches('/');
75
76        // For proper joining, the base needs a trailing slash
77        let base_path = base_url.path();
78        if base_path.ends_with('/') {
79            if let Ok(joined) = base_url.join(path_to_join) {
80                return joined.to_string();
81            }
82        } else {
83            // Manually append path with proper separator
84            let base_str = base.trim_end_matches('/');
85            return format!("{base_str}/{path_to_join}");
86        }
87    }
88
89    // Fallback to simple concatenation
90    let base_str = base.trim_end_matches('/');
91    if path.starts_with('/') {
92        format!("{base_str}{path}")
93    } else {
94        format!("{base_str}/{path}")
95    }
96}
97
98/// Find `needle` in `haystack[from..]` ignoring ASCII case, returning the
99/// absolute byte offset.
100///
101/// Searching the original string (rather than a lowercased copy) lets
102/// mixed-case needles such as `"accessToken"` match. Every needle is ASCII,
103/// so a matching window consists only of ASCII bytes and always starts on a
104/// char boundary.
105fn find_ascii_ci(haystack: &str, from: usize, needle: &str) -> Option<usize> {
106    let needle = needle.as_bytes();
107    haystack
108        .as_bytes()
109        .get(from..)?
110        .windows(needle.len())
111        .position(|w| w.eq_ignore_ascii_case(needle))
112        .map(|i| from + i)
113}
114
115/// Sanitize an API error body to remove potential secrets and truncate if too long.
116///
117/// This function:
118/// 1. Truncates bodies longer than 500 characters
119/// 2. Redacts common API key patterns (query params, bearer tokens, headers)
120/// 3. Redacts JSON key-value pairs with sensitive keys (MED-001 fix)
121///
122/// This is a security measure to prevent accidental exposure of sensitive data
123/// in error messages and logs.
124/// Sanitize an API error body to remove potential secrets.
125///
126/// This function:
127/// 1. Truncates long error messages
128/// 2. Redacts common API key patterns (query params, bearer tokens, headers, JSON)
129/// 3. Redacts hex-encoded private keys (when preceded by a key-like name)
130///
131/// Use this to sanitize error messages before logging or displaying them.
132#[must_use]
133pub fn sanitize_error_body(body: &str) -> String {
134    // Truncate if too long
135    let truncated = if body.len() > MAX_ERROR_BODY_LENGTH {
136        // Back up to a char boundary so a multi-byte character straddling the
137        // limit doesn't make the slice panic.
138        let mut end = MAX_ERROR_BODY_LENGTH;
139        while !body.is_char_boundary(end) {
140            end -= 1;
141        }
142        format!("{}... (truncated)", &body[..end])
143    } else {
144        body.to_string()
145    };
146
147    // Simple regex-free sanitization for common patterns
148    // Redact query params that look like keys/tokens
149    let mut result = truncated;
150
151    // API-002 fix: Extended list of sensitive query parameter patterns
152    // Includes private_key, client_secret, client_id variants
153    for pattern in [
154        "key=",
155        "apikey=",
156        "api_key=",
157        "token=",
158        "secret=",
159        "auth=",
160        "password=",
161        "private_key=",
162        "privatekey=",
163        "pk=",
164        "client_secret=",
165        "client_id=",
166        "access_key=",
167        "secret_key=",
168    ] {
169        // Track search position to avoid infinite loop
170        let mut search_from = 0;
171        // Search only from current position forward
172        while let Some(start) = find_ascii_ci(&result, search_from, pattern) {
173            // Find the end of the value (next & or end of string/whitespace)
174            let value_start = start + pattern.len();
175            let value_end = result[value_start..]
176                .find(|c: char| c == '&' || c.is_whitespace())
177                .map_or(result.len(), |i| value_start + i);
178
179            // Only redact if there's actual content and it's not already [REDACTED]
180            let value = &result[value_start..value_end];
181            if value_end > value_start && value != "[REDACTED]" {
182                // Preserve original case of the pattern key
183                let original_pattern = &result[start..start + pattern.len()];
184                result = format!(
185                    "{}{}[REDACTED]{}",
186                    &result[..start],
187                    original_pattern,
188                    &result[value_end..]
189                );
190                // Move search position past redaction
191                search_from = start + pattern.len() + "[REDACTED]".len();
192            } else {
193                // Move past this occurrence
194                search_from = value_start;
195            }
196        }
197    }
198
199    // Redact ALL Bearer tokens (LOW-002 fix: loop for multiple occurrences)
200    let mut search_from = 0;
201    while let Some(start) = find_ascii_ci(&result, search_from, "bearer ") {
202        let token_start = start + 7;
203        let token_end = result[token_start..]
204            .find(|c: char| c.is_whitespace())
205            .map_or(result.len(), |i| token_start + i);
206        let token = &result[token_start..token_end];
207        if token_end > token_start && token != "[REDACTED]" {
208            result = format!(
209                "{}Bearer [REDACTED]{}",
210                &result[..start],
211                &result[token_end..]
212            );
213            search_from = start + "Bearer [REDACTED]".len();
214        } else {
215            search_from = token_start;
216        }
217    }
218
219    // LOW-004 fix: Redact HTTP header patterns (e.g., "X-API-Key: value")
220    for header_pattern in [
221        "x-api-key:",
222        "x-auth-token:",
223        "authorization:",
224        "x-secret:",
225        "api-key:",
226    ] {
227        let mut search_from = 0;
228        while let Some(start) = find_ascii_ci(&result, search_from, header_pattern) {
229            let value_start = start + header_pattern.len();
230            // Skip whitespace after colon
231            let trimmed_start = result[value_start..]
232                .find(|c: char| !c.is_whitespace())
233                .map_or(value_start, |i| value_start + i);
234            // Find end of header value (newline or end of string)
235            let value_end = result[trimmed_start..]
236                .find(['\n', '\r'])
237                .map_or(result.len(), |i| trimmed_start + i);
238            let value = &result[trimmed_start..value_end];
239            if value_end > trimmed_start && value != "[REDACTED]" {
240                let original_header = &result[start..start + header_pattern.len()];
241                result = format!(
242                    "{}{} [REDACTED]{}",
243                    &result[..start],
244                    original_header,
245                    &result[value_end..]
246                );
247                search_from = start + header_pattern.len() + " [REDACTED]".len();
248            } else {
249                search_from = value_start;
250            }
251        }
252    }
253
254    // MED-001/API-002 fix: Redact JSON key-value pairs with sensitive keys
255    // Patterns like: "key": "value" or "api_key": "secret123"
256    // Extended list includes private_key, client_secret variants
257    for json_key in [
258        "\"key\"",
259        "\"apikey\"",
260        "\"api_key\"",
261        "\"token\"",
262        "\"secret\"",
263        "\"password\"",
264        "\"auth\"",
265        "\"access_token\"",
266        "\"accessToken\"",
267        "\"refresh_token\"",
268        "\"refreshToken\"",
269        "\"api-key\"",
270        "\"private_key\"",
271        "\"privateKey\"",
272        "\"client_secret\"",
273        "\"clientSecret\"",
274        "\"client_id\"",
275        "\"clientId\"",
276        "\"secret_key\"",
277        "\"secretKey\"",
278    ] {
279        // Track search position to avoid infinite loop
280        let mut search_from = 0;
281        // Search only from the current position forward
282        while let Some(key_start) = find_ascii_ci(&result, search_from, json_key) {
283            // Look for ": followed by a string value
284            let after_key = key_start + json_key.len();
285            let remaining = &result[after_key..];
286
287            // Find the colon and opening quote
288            if let Some(colon_offset) = remaining.find(':') {
289                let after_colon = &remaining[colon_offset + 1..];
290                // Skip whitespace
291                let quote_offset = after_colon.find('"');
292                if let Some(qo) = quote_offset {
293                    let value_start_abs = after_key + colon_offset + 1 + qo + 1;
294                    // Find closing quote (handle escaped quotes)
295                    let value_content = &result[value_start_abs..];
296                    let mut end_quote = 0;
297                    let mut chars = value_content.chars().peekable();
298                    while let Some(c) = chars.next() {
299                        if c == '\\' {
300                            // Skip escaped char
301                            chars.next();
302                            end_quote += 2;
303                        } else if c == '"' {
304                            break;
305                        } else {
306                            end_quote += c.len_utf8();
307                        }
308                    }
309                    if end_quote > 0 {
310                        let value_end_abs = value_start_abs + end_quote;
311                        // Preserve the key and structure, just redact the value
312                        result = format!(
313                            "{}[REDACTED]{}",
314                            &result[..value_start_abs],
315                            &result[value_end_abs..]
316                        );
317                        // Move search position past this redaction
318                        search_from = value_start_abs + "[REDACTED]".len();
319                    } else {
320                        // Move past this key to avoid infinite loop on malformed JSON
321                        search_from = after_key;
322                    }
323                } else {
324                    // No opening quote found, move past this key
325                    search_from = after_key;
326                }
327            } else {
328                // No colon found, move past this key
329                search_from = after_key;
330            }
331        }
332    }
333
334    // API-002 fix: Redact hex-encoded private keys (0x followed by 64 hex chars)
335    // These are Ethereum private keys and should never appear in logs.
336    //
337    // Private keys and tx/block hashes have the same shape, and error bodies
338    // routinely quote hashes ("transaction 0x... not found"). A key only ends
339    // up in an error body when a key parameter is echoed back, which comes
340    // with its name, so only redact when a key-like word precedes the value.
341    let mut search_from = 0;
342    while let Some(pos) = result[search_from..].find("0x") {
343        let abs_pos = search_from + pos;
344        let after_0x = abs_pos + 2;
345
346        // Check if followed by exactly 64 hex characters
347        // `get` returns None if the window ends inside a multi-byte char
348        if let Some(potential_key) = result.get(after_0x..after_0x + 64) {
349            if potential_key.chars().all(|c| c.is_ascii_hexdigit()) {
350                // Check it's not followed by more hex (could be longer hash)
351                let is_exact_64 = after_0x + 64 >= result.len()
352                    || !result[after_0x + 64..]
353                        .chars()
354                        .next()
355                        .is_some_and(|c| c.is_ascii_hexdigit());
356
357                if is_exact_64 && follows_key_like_name(&result, abs_pos) {
358                    result = format!(
359                        "{}0x[REDACTED_KEY]{}",
360                        &result[..abs_pos],
361                        &result[after_0x + 64..]
362                    );
363                    search_from = abs_pos + "0x[REDACTED_KEY]".len();
364                    continue;
365                }
366            }
367        }
368        search_from = after_0x;
369    }
370
371    result
372}
373
374/// How far back [`follows_key_like_name`] looks for a key-like word.
375const KEY_CONTEXT_WINDOW: usize = 32;
376
377/// Whether the text just before `pos` names a secret (`key`, `secret`, `pk`,
378/// `priv...`), e.g. `private_key=0x...` or `"Invalid key 0x..."`.
379fn follows_key_like_name(s: &str, pos: usize) -> bool {
380    let mut start = pos.saturating_sub(KEY_CONTEXT_WINDOW);
381    while !s.is_char_boundary(start) {
382        start += 1;
383    }
384    let context = s[start..pos].to_ascii_lowercase();
385    ["key", "secret", "priv", "pk"]
386        .iter()
387        .any(|word| context.contains(word))
388}
389
390/// Generic API error type with support for domain-specific errors
391///
392/// This error type covers the common error cases across all API clients:
393/// - HTTP transport errors
394/// - JSON parsing errors
395/// - API response errors (4xx)
396/// - Rate limiting (429)
397/// - Server errors (5xx)
398///
399/// Domain-specific errors can be added via the generic parameter `E`.
400/// Use `ApiError` (without a type parameter) when no domain-specific errors
401/// are needed.
402#[derive(Error, Debug)]
403#[non_exhaustive]
404pub enum ApiError<E: std::error::Error = NoDomainError> {
405    /// HTTP request error
406    #[error("HTTP error: {0}")]
407    Http(#[from] reqwest::Error),
408
409    /// HTTP client build error
410    #[error("HTTP client error: {0}")]
411    HttpBuild(#[source] HttpError),
412
413    /// JSON parsing error
414    #[error("JSON error: {0}")]
415    Json(#[from] serde_json::Error),
416
417    /// API returned an error response (4xx, excluding 429)
418    #[error("API error: {status} - {message}")]
419    Api {
420        /// HTTP status code
421        status: u16,
422        /// Error message from API
423        message: String,
424    },
425
426    /// Rate limit exceeded (429)
427    #[error("Rate limited{}", .retry_after.map(|s| format!(" (retry after {s}s)")).unwrap_or_default())]
428    RateLimited {
429        /// Seconds to wait before retrying
430        retry_after: Option<u64>,
431    },
432
433    /// Server error (5xx)
434    #[error("Server error ({status}): {message}")]
435    ServerError {
436        /// HTTP status code
437        status: u16,
438        /// Error message
439        message: String,
440    },
441
442    /// URL parsing error
443    #[error("URL error: {0}")]
444    Url(#[from] url::ParseError),
445
446    /// Domain-specific error
447    #[error(transparent)]
448    Domain(E),
449}
450
451// Manual From impl for HttpError since we can't use #[from] with the generic
452impl<E: std::error::Error> From<HttpError> for ApiError<E> {
453    fn from(e: HttpError) -> Self {
454        ApiError::HttpBuild(e)
455    }
456}
457
458impl<E: std::error::Error> ApiError<E> {
459    /// Create an API error
460    pub fn api(status: u16, message: impl Into<String>) -> Self {
461        Self::Api {
462            status,
463            message: message.into(),
464        }
465    }
466
467    /// Create a rate limited error
468    #[must_use]
469    pub fn rate_limited(retry_after: Option<u64>) -> Self {
470        Self::RateLimited { retry_after }
471    }
472
473    /// Create a server error
474    pub fn server_error(status: u16, message: impl Into<String>) -> Self {
475        Self::ServerError {
476            status,
477            message: message.into(),
478        }
479    }
480
481    /// Create a domain-specific error
482    pub fn domain(error: E) -> Self {
483        Self::Domain(error)
484    }
485
486    /// Create from HTTP response status and body
487    ///
488    /// Automatically categorizes the error based on status code:
489    /// - 429 -> `RateLimited`
490    /// - 500-599 -> `ServerError`
491    /// - Other -> Api
492    ///
493    /// Note: The body is sanitized to remove potential secrets and truncated
494    /// if too long (SEC-005 fix).
495    #[must_use]
496    pub fn from_response(status: u16, body: &str, retry_after: Option<u64>) -> Self {
497        let sanitized = sanitize_error_body(body);
498        match status {
499            429 => Self::RateLimited { retry_after },
500            500..=599 => Self::ServerError {
501                status,
502                message: sanitized,
503            },
504            _ => Self::Api {
505                status,
506                message: sanitized,
507            },
508        }
509    }
510
511    /// Check if this error is retryable
512    ///
513    /// Returns true for:
514    /// - Rate limited errors
515    /// - Server errors (5xx)
516    /// - HTTP transport errors (connection, timeout, ...)
517    ///
518    /// Not for a response that arrived but couldn't be decoded, or a request
519    /// that couldn't be built: those fail the same way every time.
520    ///
521    /// A transport error after the request was sent (e.g. a timeout) may still
522    /// have taken effect upstream, so only retry calls that are safe to
523    /// repeat (see [`crate::with_retry`]).
524    pub fn is_retryable(&self) -> bool {
525        match self {
526            Self::RateLimited { .. } | Self::ServerError { .. } => true,
527            Self::Http(e) => !e.is_decode() && !e.is_builder(),
528            _ => false,
529        }
530    }
531
532    /// Get retry-after duration if available
533    pub fn retry_after(&self) -> Option<Duration> {
534        if let Self::RateLimited {
535            retry_after: Some(secs),
536        } = self
537        {
538            Some(Duration::from_secs(*secs))
539        } else {
540            None
541        }
542    }
543
544    /// Get the HTTP status code if this is an API or server error
545    pub fn status_code(&self) -> Option<u16> {
546        match self {
547            Self::Api { status, .. } => Some(*status),
548            Self::ServerError { status, .. } => Some(*status),
549            Self::RateLimited { .. } => Some(429),
550            _ => None,
551        }
552    }
553}
554
555impl<E: std::error::Error> RetryableError for ApiError<E> {
556    fn is_retryable(&self) -> bool {
557        ApiError::is_retryable(self)
558    }
559
560    fn retry_after(&self) -> Option<Duration> {
561        ApiError::retry_after(self)
562    }
563}
564
565/// Result type alias for API operations
566pub type ApiResult<T, E = NoDomainError> = std::result::Result<T, ApiError<E>>;
567
568// ============================================================================
569// Secret API Key Wrapper
570// ============================================================================
571
572/// A wrapper for API keys that redacts the value in Debug output.
573///
574/// This prevents accidental logging of API keys in debug output.
575///
576/// # Example
577///
578/// ```
579/// use yldfi_common::api::SecretApiKey;
580///
581/// let key = SecretApiKey::new("sk-secret-key-12345");
582/// let debug_str = format!("{:?}", key);
583/// assert!(debug_str.contains("REDACTED"));
584/// assert!(!debug_str.contains("sk-secret"));
585/// assert_eq!(key.expose(), "sk-secret-key-12345");
586/// ```
587#[derive(Clone)]
588pub struct SecretApiKey(String);
589
590impl SecretApiKey {
591    /// Create a new secret API key.
592    pub fn new(key: impl Into<String>) -> Self {
593        Self(key.into())
594    }
595
596    /// Expose the secret value.
597    ///
598    /// Use this when you need to include the key in an HTTP header.
599    #[must_use]
600    pub fn expose(&self) -> &str {
601        &self.0
602    }
603
604    /// Check if the key is empty.
605    #[must_use]
606    pub fn is_empty(&self) -> bool {
607        self.0.is_empty()
608    }
609}
610
611impl fmt::Debug for SecretApiKey {
612    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
613        f.debug_tuple("SecretApiKey").field(&"[REDACTED]").finish()
614    }
615}
616
617impl From<String> for SecretApiKey {
618    fn from(s: String) -> Self {
619        Self::new(s)
620    }
621}
622
623impl From<&str> for SecretApiKey {
624    fn from(s: &str) -> Self {
625        Self::new(s)
626    }
627}
628
629// ============================================================================
630// API Configuration
631// ============================================================================
632
633/// Generic API configuration
634///
635/// Provides common configuration options for all API clients:
636/// - Base URL (validated to be HTTPS in production)
637/// - API key (optional, redacted in Debug)
638/// - HTTP client settings (timeout, proxy, user-agent)
639///
640/// # Security
641///
642/// - API keys are wrapped in `SecretApiKey` to prevent accidental logging
643/// - Use `validate()` to check that the base URL uses HTTPS
644#[derive(Clone)]
645pub struct ApiConfig {
646    /// Base URL for the API
647    pub base_url: String,
648    /// API key for authentication (optional, redacted in Debug)
649    pub api_key: Option<SecretApiKey>,
650    /// HTTP client configuration
651    pub http: HttpClientConfig,
652}
653
654impl fmt::Debug for ApiConfig {
655    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
656        f.debug_struct("ApiConfig")
657            .field("base_url", &self.base_url)
658            .field("api_key", &self.api_key)
659            .field("http", &self.http)
660            .finish()
661    }
662}
663
664impl ApiConfig {
665    /// Create a new config with a base URL
666    pub fn new(base_url: impl Into<String>) -> Self {
667        Self {
668            base_url: base_url.into(),
669            api_key: None,
670            http: HttpClientConfig::default(),
671        }
672    }
673
674    /// Create a new config with base URL and API key
675    pub fn with_api_key(base_url: impl Into<String>, api_key: impl Into<String>) -> Self {
676        Self {
677            base_url: base_url.into(),
678            api_key: Some(SecretApiKey::new(api_key)),
679            http: HttpClientConfig::default(),
680        }
681    }
682
683    /// Set the API key
684    #[must_use]
685    pub fn api_key(mut self, key: impl Into<String>) -> Self {
686        self.api_key = Some(SecretApiKey::new(key));
687        self
688    }
689
690    /// Set optional API key
691    #[must_use]
692    pub fn optional_api_key(mut self, key: Option<String>) -> Self {
693        self.api_key = key.map(SecretApiKey::new);
694        self
695    }
696
697    /// Set request timeout
698    #[must_use]
699    pub fn timeout(mut self, timeout: Duration) -> Self {
700        self.http.timeout = timeout;
701        self
702    }
703
704    /// Set request timeout in seconds
705    #[must_use]
706    pub fn with_timeout_secs(mut self, secs: u64) -> Self {
707        self.http.timeout = Duration::from_secs(secs);
708        self
709    }
710
711    /// Set proxy URL
712    #[must_use]
713    pub fn proxy(mut self, proxy: impl Into<String>) -> Self {
714        self.http.proxy = Some(proxy.into());
715        self
716    }
717
718    /// Set optional proxy URL
719    #[must_use]
720    pub fn optional_proxy(mut self, proxy: Option<String>) -> Self {
721        self.http.proxy = proxy;
722        self
723    }
724
725    /// Build an HTTP client from this configuration
726    pub fn build_client(&self) -> Result<Client, HttpError> {
727        crate::http::build_client(&self.http)
728    }
729
730    /// Validate the configuration for security.
731    ///
732    /// Returns an error if:
733    /// - The base URL uses HTTP instead of HTTPS (security risk)
734    /// - The base URL is malformed
735    ///
736    /// # Example
737    ///
738    /// ```
739    /// use yldfi_common::api::ApiConfig;
740    ///
741    /// // HTTPS URLs are valid
742    /// let config = ApiConfig::new("https://api.example.com");
743    /// assert!(config.validate().is_ok());
744    ///
745    /// // HTTP URLs are rejected
746    /// let config = ApiConfig::new("http://api.example.com");
747    /// assert!(config.validate().is_err());
748    /// ```
749    pub fn validate(&self) -> Result<(), ConfigValidationError> {
750        // Parse the URL
751        let url = url::Url::parse(&self.base_url)
752            .map_err(|e| ConfigValidationError::InvalidUrl(e.to_string()))?;
753
754        // Check scheme
755        match url.scheme() {
756            "https" => Ok(()),
757            "http" => {
758                // Allow localhost for development
759                if let Some(host) = url.host_str() {
760                    if host == "localhost" || host == "127.0.0.1" || host == "::1" {
761                        return Ok(());
762                    }
763                }
764                Err(ConfigValidationError::InsecureScheme)
765            }
766            scheme => Err(ConfigValidationError::InvalidUrl(format!(
767                "Unsupported URL scheme: {scheme}"
768            ))),
769        }
770    }
771
772    /// Check if the base URL uses HTTPS.
773    #[must_use]
774    pub fn is_https(&self) -> bool {
775        self.base_url.starts_with("https://")
776    }
777
778    /// Get the exposed API key, if set.
779    #[must_use]
780    pub fn get_api_key(&self) -> Option<&str> {
781        self.api_key.as_ref().map(SecretApiKey::expose)
782    }
783}
784
785/// Configuration validation errors
786#[derive(Debug, Clone, PartialEq, Eq)]
787pub enum ConfigValidationError {
788    /// The URL scheme is HTTP instead of HTTPS
789    InsecureScheme,
790    /// The URL is malformed
791    InvalidUrl(String),
792}
793
794impl fmt::Display for ConfigValidationError {
795    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
796        match self {
797            Self::InsecureScheme => write!(
798                f,
799                "Insecure URL scheme: use HTTPS instead of HTTP to protect API keys"
800            ),
801            Self::InvalidUrl(msg) => write!(f, "Invalid URL: {msg}"),
802        }
803    }
804}
805
806impl std::error::Error for ConfigValidationError {}
807
808// ============================================================================
809// Base Client
810// ============================================================================
811
812/// A base HTTP client that handles common request/response patterns.
813///
814/// This client provides reusable methods for making GET and POST requests
815/// with proper error handling, reducing boilerplate across API crates.
816///
817/// # Example
818///
819/// ```
820/// use yldfi_common::api::{ApiConfig, BaseClient};
821///
822/// // Create a client with configuration
823/// let config = ApiConfig::new("https://api.example.com")
824///     .api_key("your-api-key");
825/// let client = BaseClient::new(config).unwrap();
826///
827/// // Build URLs
828/// assert_eq!(client.url("/quote"), "https://api.example.com/quote");
829///
830/// // Access config
831/// assert_eq!(client.config().get_api_key(), Some("your-api-key"));
832/// ```
833#[derive(Debug, Clone)]
834pub struct BaseClient {
835    http: Client,
836    config: ApiConfig,
837    /// Cached normalized base URL (trailing slash removed) to avoid allocation in `url()`
838    normalized_base_url: String,
839}
840
841impl BaseClient {
842    /// Create a new base client from configuration.
843    ///
844    /// This constructor validates the configuration, enforcing HTTPS for security
845    /// (SEC-003 fix). HTTP is only allowed for localhost development URLs.
846    ///
847    /// # Errors
848    ///
849    /// Returns an error if:
850    /// - The URL uses HTTP (except localhost)
851    /// - The HTTP client cannot be built
852    pub fn new(config: ApiConfig) -> Result<Self, HttpError> {
853        // Validate HTTPS requirement (SEC-003 fix)
854        if let Err(e) = config.validate() {
855            return Err(HttpError::BuildError(format!(
856                "Configuration validation failed: {e}. Use HTTPS URLs to protect API keys."
857            )));
858        }
859
860        let http = config.build_client()?;
861        // Cache normalized base URL to avoid repeated allocation in url()
862        let normalized_base_url = config.base_url.trim_end_matches('/').to_string();
863        Ok(Self {
864            http,
865            config,
866            normalized_base_url,
867        })
868    }
869
870    /// Get the underlying HTTP client.
871    #[must_use]
872    pub fn http(&self) -> &Client {
873        &self.http
874    }
875
876    /// Get the configuration.
877    #[must_use]
878    pub fn config(&self) -> &ApiConfig {
879        &self.config
880    }
881
882    /// Get the base URL.
883    #[must_use]
884    pub fn base_url(&self) -> &str {
885        &self.config.base_url
886    }
887
888    /// Build the full URL for a path.
889    ///
890    /// Uses cached normalized base URL to avoid repeated string allocation.
891    /// LOW-003 fix: Uses proper URL joining for robustness.
892    #[must_use]
893    pub fn url(&self, path: &str) -> String {
894        // For simple relative paths, use the optimized string format
895        // This covers the common case where base_url is just a host + fixed path
896        if !path.contains('?') && !self.normalized_base_url.contains('?') {
897            if path.starts_with('/') {
898                format!("{}{}", self.normalized_base_url, path)
899            } else {
900                format!("{}/{}", self.normalized_base_url, path)
901            }
902        } else {
903            // For complex cases (query strings), use proper URL parsing
904            join_url(&self.normalized_base_url, path)
905        }
906    }
907
908    /// Build default headers with API key (if present).
909    ///
910    /// Override this in your client to add custom headers.
911    pub fn default_headers(&self) -> reqwest::header::HeaderMap {
912        let mut headers = reqwest::header::HeaderMap::new();
913
914        // Add Authorization header if API key is set
915        if let Some(key) = self.config.get_api_key() {
916            if let Ok(value) = reqwest::header::HeaderValue::from_str(&format!("Bearer {key}")) {
917                headers.insert(reqwest::header::AUTHORIZATION, value);
918            }
919        }
920
921        headers
922    }
923
924    /// Make a GET request with query parameters.
925    ///
926    /// # Type Parameters
927    ///
928    /// * `T` - The response type (must implement `DeserializeOwned`)
929    /// * `E` - Domain-specific error type (default: `NoDomainError`)
930    ///
931    /// # Arguments
932    ///
933    /// * `path` - The API path (will be joined with `base_url`)
934    /// * `params` - Query parameters as key-value pairs
935    ///
936    /// # Errors
937    ///
938    /// Returns an error if:
939    /// - Network request fails
940    /// - Response status indicates an error (4xx/5xx)
941    /// - Response body cannot be deserialized to type `T`
942    pub async fn get<T, E>(
943        &self,
944        path: &str,
945        params: &[(&str, impl AsRef<str>)],
946    ) -> Result<T, ApiError<E>>
947    where
948        T: serde::de::DeserializeOwned,
949        E: std::error::Error,
950    {
951        self.get_with_headers(path, params, self.default_headers())
952            .await
953    }
954
955    /// Make a GET request with custom headers.
956    ///
957    /// Use this when you need to add API-specific headers beyond the default
958    /// Authorization header.
959    pub async fn get_with_headers<T, E>(
960        &self,
961        path: &str,
962        params: &[(&str, impl AsRef<str>)],
963        headers: reqwest::header::HeaderMap,
964    ) -> Result<T, ApiError<E>>
965    where
966        T: serde::de::DeserializeOwned,
967        E: std::error::Error,
968    {
969        let url = self.url(path);
970        let query: Vec<(&str, &str)> = params.iter().map(|(k, v)| (*k, v.as_ref())).collect();
971
972        let response = self
973            .http
974            .get(&url)
975            .headers(headers)
976            .query(&query)
977            .send()
978            .await?;
979
980        self.handle_response(response).await
981    }
982
983    /// Make a POST request with JSON body.
984    ///
985    /// # Type Parameters
986    ///
987    /// * `T` - The response type
988    /// * `B` - The request body type (must implement `Serialize`)
989    /// * `E` - Domain-specific error type
990    ///
991    /// # Errors
992    ///
993    /// Returns an error if:
994    /// - Network request fails
995    /// - Response status indicates an error (4xx/5xx)
996    /// - Response body cannot be deserialized to type `T`
997    pub async fn post_json<T, B, E>(&self, path: &str, body: &B) -> Result<T, ApiError<E>>
998    where
999        T: serde::de::DeserializeOwned,
1000        B: serde::Serialize,
1001        E: std::error::Error,
1002    {
1003        self.post_json_with_headers(path, body, self.default_headers())
1004            .await
1005    }
1006
1007    /// Make a POST request with JSON body and custom headers.
1008    pub async fn post_json_with_headers<T, B, E>(
1009        &self,
1010        path: &str,
1011        body: &B,
1012        headers: reqwest::header::HeaderMap,
1013    ) -> Result<T, ApiError<E>>
1014    where
1015        T: serde::de::DeserializeOwned,
1016        B: serde::Serialize,
1017        E: std::error::Error,
1018    {
1019        let url = self.url(path);
1020
1021        let response = self
1022            .http
1023            .post(&url)
1024            .headers(headers)
1025            .json(body)
1026            .send()
1027            .await?;
1028
1029        self.handle_response(response).await
1030    }
1031
1032    /// Make a POST request with form data.
1033    pub async fn post_form<T, E>(
1034        &self,
1035        path: &str,
1036        form: &[(&str, impl AsRef<str>)],
1037    ) -> Result<T, ApiError<E>>
1038    where
1039        T: serde::de::DeserializeOwned,
1040        E: std::error::Error,
1041    {
1042        let url = self.url(path);
1043        let form_data: Vec<(&str, &str)> = form.iter().map(|(k, v)| (*k, v.as_ref())).collect();
1044
1045        let response = self
1046            .http
1047            .post(&url)
1048            .headers(self.default_headers())
1049            .form(&form_data)
1050            .send()
1051            .await?;
1052
1053        self.handle_response(response).await
1054    }
1055
1056    /// Handle a response, extracting the body or converting to error.
1057    async fn handle_response<T, E>(&self, response: reqwest::Response) -> Result<T, ApiError<E>>
1058    where
1059        T: serde::de::DeserializeOwned,
1060        E: std::error::Error,
1061    {
1062        if response.status().is_success() {
1063            Ok(response.json().await?)
1064        } else {
1065            Err(handle_error_response(response).await)
1066        }
1067    }
1068}
1069
1070// ============================================================================
1071// Response Handling Helper
1072// ============================================================================
1073
1074/// Extract retry-after header value from a response.
1075///
1076/// Parses the `Retry-After` header as seconds (delay-seconds format).
1077/// HTTP-date format (e.g., "Wed, 21 Oct 2015 07:28:00 GMT") is not supported
1078/// and will return `None`.
1079///
1080/// # Bounds
1081///
1082/// - Returns `None` for values that can't be parsed as a positive integer
1083/// - Caps the result at 3600 seconds (1 hour) to prevent unreasonably long waits
1084///   from malformed or malicious servers
1085///
1086/// # Example
1087///
1088/// ```
1089/// use reqwest::header::{HeaderMap, HeaderValue};
1090/// use yldfi_common::api::extract_retry_after;
1091///
1092/// let mut headers = HeaderMap::new();
1093/// headers.insert("retry-after", HeaderValue::from_static("30"));
1094/// assert_eq!(extract_retry_after(&headers), Some(30));
1095///
1096/// // Values over 3600 are capped
1097/// headers.insert("retry-after", HeaderValue::from_static("9999"));
1098/// assert_eq!(extract_retry_after(&headers), Some(3600));
1099/// ```
1100#[must_use]
1101pub fn extract_retry_after(headers: &reqwest::header::HeaderMap) -> Option<u64> {
1102    const MAX_RETRY_AFTER_SECS: u64 = 3600; // 1 hour max
1103
1104    headers
1105        .get("retry-after")
1106        .and_then(|v| v.to_str().ok())
1107        .and_then(|v| v.trim().parse::<u64>().ok())
1108        .map(|secs| secs.min(MAX_RETRY_AFTER_SECS))
1109}
1110
1111/// Handle an HTTP response, converting errors appropriately
1112///
1113/// This helper extracts the retry-after header and creates the appropriate
1114/// error type based on the response status code.
1115pub async fn handle_error_response<E: std::error::Error>(
1116    response: reqwest::Response,
1117) -> ApiError<E> {
1118    let status = response.status().as_u16();
1119    let retry_after = extract_retry_after(response.headers());
1120    let body = response.text().await.unwrap_or_default();
1121    ApiError::from_response(status, &body, retry_after)
1122}
1123
1124#[cfg(test)]
1125mod tests {
1126    use super::*;
1127
1128    #[test]
1129    fn test_api_error_display() {
1130        let err: ApiError = ApiError::api(400, "Bad request");
1131        assert!(err.to_string().contains("400"));
1132        assert!(err.to_string().contains("Bad request"));
1133    }
1134
1135    #[test]
1136    fn test_rate_limited_display() {
1137        let err: ApiError = ApiError::rate_limited(Some(60));
1138        assert!(err.to_string().contains("60"));
1139    }
1140
1141    #[test]
1142    fn test_rate_limited_no_retry() {
1143        let err: ApiError = ApiError::rate_limited(None);
1144        assert!(err.to_string().contains("Rate limited"));
1145        assert!(!err.to_string().contains("retry"));
1146    }
1147
1148    #[test]
1149    fn test_is_retryable() {
1150        let err: ApiError = ApiError::rate_limited(Some(10));
1151        assert!(err.is_retryable());
1152        let err: ApiError = ApiError::server_error(500, "error");
1153        assert!(err.is_retryable());
1154        let err: ApiError = ApiError::api(400, "bad request");
1155        assert!(!err.is_retryable());
1156    }
1157
1158    #[test]
1159    fn test_from_response() {
1160        let err: ApiError = ApiError::from_response(429, "rate limited", Some(30));
1161        assert!(matches!(
1162            err,
1163            ApiError::RateLimited {
1164                retry_after: Some(30)
1165            }
1166        ));
1167
1168        let err: ApiError = ApiError::from_response(503, "service unavailable", None);
1169        assert!(matches!(err, ApiError::ServerError { status: 503, .. }));
1170
1171        let err: ApiError = ApiError::from_response(400, "bad request", None);
1172        assert!(matches!(err, ApiError::Api { status: 400, .. }));
1173    }
1174
1175    #[test]
1176    fn test_retry_after() {
1177        let err: ApiError = ApiError::rate_limited(Some(30));
1178        assert_eq!(err.retry_after(), Some(Duration::from_secs(30)));
1179
1180        let err: ApiError = ApiError::api(400, "bad");
1181        assert_eq!(err.retry_after(), None);
1182    }
1183
1184    #[test]
1185    fn test_status_code() {
1186        let err: ApiError = ApiError::api(400, "bad");
1187        assert_eq!(err.status_code(), Some(400));
1188        let err: ApiError = ApiError::server_error(503, "down");
1189        assert_eq!(err.status_code(), Some(503));
1190        let err: ApiError = ApiError::rate_limited(None);
1191        assert_eq!(err.status_code(), Some(429));
1192        let err: ApiError = ApiError::Json(serde_json::from_str::<()>("invalid").unwrap_err());
1193        assert_eq!(err.status_code(), None);
1194    }
1195
1196    #[test]
1197    fn test_api_config() {
1198        let config = ApiConfig::new("https://api.example.com")
1199            .api_key("test-key")
1200            .with_timeout_secs(60)
1201            .proxy("http://proxy:8080");
1202
1203        assert_eq!(config.base_url, "https://api.example.com");
1204        assert_eq!(config.get_api_key(), Some("test-key"));
1205        assert_eq!(config.http.timeout, Duration::from_secs(60));
1206        assert_eq!(config.http.proxy, Some("http://proxy:8080".to_string()));
1207    }
1208
1209    #[test]
1210    fn test_api_config_build_client() {
1211        let config = ApiConfig::new("https://api.example.com");
1212        let client = config.build_client();
1213        assert!(client.is_ok());
1214    }
1215
1216    #[test]
1217    fn test_secret_api_key_redacted() {
1218        let key = SecretApiKey::new("sk-secret-key-12345");
1219        let debug_output = format!("{:?}", key);
1220        assert!(debug_output.contains("REDACTED"));
1221        assert!(!debug_output.contains("sk-secret"));
1222        assert_eq!(key.expose(), "sk-secret-key-12345");
1223    }
1224
1225    #[test]
1226    fn test_api_config_debug_redacts_key() {
1227        let config = ApiConfig::with_api_key("https://api.example.com", "super-secret-key");
1228        let debug_output = format!("{:?}", config);
1229        assert!(debug_output.contains("REDACTED"));
1230        assert!(!debug_output.contains("super-secret-key"));
1231    }
1232
1233    #[test]
1234    fn test_config_validation_https() {
1235        // HTTPS is valid
1236        let config = ApiConfig::new("https://api.example.com");
1237        assert!(config.validate().is_ok());
1238        assert!(config.is_https());
1239
1240        // HTTP is rejected
1241        let config = ApiConfig::new("http://api.example.com");
1242        assert!(config.validate().is_err());
1243        assert!(!config.is_https());
1244        assert_eq!(
1245            config.validate().unwrap_err(),
1246            ConfigValidationError::InsecureScheme
1247        );
1248    }
1249
1250    #[test]
1251    fn test_config_validation_localhost() {
1252        // HTTP to localhost is allowed for development
1253        let config = ApiConfig::new("http://localhost:8080");
1254        assert!(config.validate().is_ok());
1255
1256        let config = ApiConfig::new("http://127.0.0.1:8080");
1257        assert!(config.validate().is_ok());
1258    }
1259
1260    #[test]
1261    fn test_config_validation_invalid_url() {
1262        let config = ApiConfig::new("not a url");
1263        let result = config.validate();
1264        assert!(matches!(result, Err(ConfigValidationError::InvalidUrl(_))));
1265    }
1266
1267    // Test with domain-specific errors
1268    #[derive(Debug, thiserror::Error)]
1269    enum TestDomainError {
1270        #[error("No route found")]
1271        NoRouteFound,
1272    }
1273
1274    #[test]
1275    fn test_domain_error() {
1276        let err: ApiError<TestDomainError> = ApiError::domain(TestDomainError::NoRouteFound);
1277        assert!(err.to_string().contains("No route found"));
1278        assert!(!err.is_retryable());
1279    }
1280
1281    // BaseClient tests
1282    #[test]
1283    fn test_base_client_creation() {
1284        let config = ApiConfig::new("https://api.example.com");
1285        let client = BaseClient::new(config);
1286        assert!(client.is_ok());
1287    }
1288
1289    #[test]
1290    fn test_base_client_url_building() {
1291        let config = ApiConfig::new("https://api.example.com");
1292        let client = BaseClient::new(config).unwrap();
1293
1294        // With leading slash
1295        assert_eq!(client.url("/quote"), "https://api.example.com/quote");
1296
1297        // Without leading slash
1298        assert_eq!(client.url("quote"), "https://api.example.com/quote");
1299
1300        // With path
1301        assert_eq!(
1302            client.url("/v1/swap/quote"),
1303            "https://api.example.com/v1/swap/quote"
1304        );
1305    }
1306
1307    #[test]
1308    fn test_base_client_url_building_trailing_slash() {
1309        // Base URL with trailing slash
1310        let config = ApiConfig::new("https://api.example.com/");
1311        let client = BaseClient::new(config).unwrap();
1312
1313        assert_eq!(client.url("/quote"), "https://api.example.com/quote");
1314        assert_eq!(client.url("quote"), "https://api.example.com/quote");
1315    }
1316
1317    #[test]
1318    fn test_base_client_default_headers_no_key() {
1319        let config = ApiConfig::new("https://api.example.com");
1320        let client = BaseClient::new(config).unwrap();
1321        let headers = client.default_headers();
1322
1323        // No Authorization header without API key
1324        assert!(!headers.contains_key(reqwest::header::AUTHORIZATION));
1325    }
1326
1327    #[test]
1328    fn test_base_client_default_headers_with_key() {
1329        let config = ApiConfig::new("https://api.example.com").api_key("test-key");
1330        let client = BaseClient::new(config).unwrap();
1331        let headers = client.default_headers();
1332
1333        // Authorization header present with Bearer token
1334        assert!(headers.contains_key(reqwest::header::AUTHORIZATION));
1335        assert_eq!(
1336            headers.get(reqwest::header::AUTHORIZATION).unwrap(),
1337            "Bearer test-key"
1338        );
1339    }
1340
1341    #[test]
1342    fn test_base_client_accessors() {
1343        let config = ApiConfig::new("https://api.example.com").api_key("my-key");
1344        let client = BaseClient::new(config).unwrap();
1345
1346        assert_eq!(client.base_url(), "https://api.example.com");
1347        assert_eq!(client.config().get_api_key(), Some("my-key"));
1348    }
1349
1350    #[test]
1351    fn test_sanitize_error_body_truncation() {
1352        let long_body = "a".repeat(1000);
1353        let sanitized = super::sanitize_error_body(&long_body);
1354        assert!(sanitized.len() < 600); // Should be truncated with "... (truncated)"
1355        assert!(sanitized.ends_with("... (truncated)"));
1356    }
1357
1358    #[test]
1359    fn test_sanitize_error_body_truncation_multibyte_boundary() {
1360        // '€' is 3 bytes; the one starting at byte 499 straddles the 500-byte limit
1361        let body = format!("{}{}", "a".repeat(499), "€".repeat(5));
1362        let sanitized = super::sanitize_error_body(&body);
1363        assert_eq!(sanitized, format!("{}... (truncated)", "a".repeat(499)));
1364    }
1365
1366    #[test]
1367    fn test_sanitize_error_body_unicode_lowercase_length_change() {
1368        // 'İ' (2 bytes) lowercases to 3 bytes, which used to misalign the
1369        // offsets found in the lowercased copy
1370        let body = format!("{}token=secret123", "İ".repeat(10));
1371        let sanitized = super::sanitize_error_body(&body);
1372        assert!(!sanitized.contains("secret123"), "{sanitized}");
1373    }
1374
1375    #[test]
1376    fn test_sanitize_error_body_hex_window_ends_mid_char() {
1377        let body = format!("0x{}é", "a".repeat(63));
1378        assert_eq!(super::sanitize_error_body(&body), body);
1379    }
1380
1381    #[test]
1382    fn test_sanitize_error_body_key_redaction() {
1383        let body = "Error: ?api_key=secret123&foo=bar";
1384        let sanitized = super::sanitize_error_body(body);
1385        assert!(sanitized.contains("[REDACTED]"));
1386        assert!(!sanitized.contains("secret123"));
1387    }
1388
1389    #[test]
1390    fn test_sanitize_error_body_bearer_redaction() {
1391        let body = "Authorization: Bearer mysecrettoken123";
1392        let sanitized = super::sanitize_error_body(body);
1393        assert!(sanitized.contains("[REDACTED]"));
1394        assert!(!sanitized.contains("mysecrettoken123"));
1395    }
1396
1397    #[test]
1398    fn test_sanitize_error_body_no_redaction_needed() {
1399        let body = "Simple error message";
1400        let sanitized = super::sanitize_error_body(body);
1401        assert_eq!(sanitized, body);
1402    }
1403
1404    #[test]
1405    fn test_sanitize_error_body_json_key_redaction() {
1406        // MED-001 fix: Test JSON key-value redaction
1407        let body = r#"{"error": "Invalid API Key", "key": "sk_live_secret123", "status": 401}"#;
1408        let sanitized = super::sanitize_error_body(body);
1409        assert!(sanitized.contains("[REDACTED]"));
1410        assert!(!sanitized.contains("sk_live_secret123"));
1411        // Should preserve structure
1412        assert!(sanitized.contains("\"error\""));
1413        assert!(sanitized.contains("\"status\""));
1414    }
1415
1416    #[test]
1417    fn test_sanitize_error_body_json_api_key_redaction() {
1418        let body = r#"{"api_key": "test_api_key_12345", "message": "unauthorized"}"#;
1419        let sanitized = super::sanitize_error_body(body);
1420        assert!(sanitized.contains("[REDACTED]"));
1421        assert!(!sanitized.contains("test_api_key_12345"));
1422    }
1423
1424    #[test]
1425    fn test_sanitize_error_body_header_redaction() {
1426        // LOW-004 fix: Test HTTP header pattern redaction
1427        let body = "Request failed\nX-API-Key: my_secret_key_here\nContent-Type: application/json";
1428        let sanitized = super::sanitize_error_body(body);
1429        assert!(sanitized.contains("[REDACTED]"));
1430        assert!(!sanitized.contains("my_secret_key_here"));
1431        // Should preserve non-sensitive headers
1432        assert!(sanitized.contains("Content-Type"));
1433    }
1434
1435    #[test]
1436    fn test_sanitize_error_body_authorization_header() {
1437        let body = "Error: Authorization: Basic dXNlcjpwYXNz";
1438        let sanitized = super::sanitize_error_body(body);
1439        assert!(sanitized.contains("[REDACTED]"));
1440        assert!(!sanitized.contains("dXNlcjpwYXNz"));
1441    }
1442
1443    #[test]
1444    fn test_sanitize_error_body_multiple_json_keys() {
1445        // Test multiple sensitive JSON keys in same body
1446        let body = r#"{"key": "key1", "token": "token1", "api_key": "api1"}"#;
1447        let sanitized = super::sanitize_error_body(body);
1448        assert!(!sanitized.contains("key1"));
1449        assert!(!sanitized.contains("token1"));
1450        assert!(!sanitized.contains("api1"));
1451    }
1452
1453    #[test]
1454    fn test_sanitize_error_body_hex_private_key() {
1455        // API-002 fix: Test hex-encoded private key redaction (64 hex chars)
1456        let body = "Error: Invalid key 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef in request";
1457        let sanitized = super::sanitize_error_body(body);
1458        assert!(sanitized.contains("0x[REDACTED_KEY]"));
1459        assert!(!sanitized.contains("1234567890abcdef"));
1460    }
1461
1462    #[test]
1463    fn test_sanitize_error_body_keeps_tx_hash() {
1464        let hash = format!("0x{}", "ab".repeat(32));
1465        for body in [
1466            format!("transaction {hash} not found"),
1467            format!(r#"{{"error":"execution reverted","txHash":"{hash}"}}"#),
1468        ] {
1469            assert_eq!(super::sanitize_error_body(&body), body);
1470        }
1471    }
1472
1473    #[test]
1474    fn test_sanitize_error_body_hex_key_after_name() {
1475        let key = format!("0x{}", "cd".repeat(32));
1476        let sanitized = super::sanitize_error_body(&format!("bad privateKey: {key}"));
1477        assert!(!sanitized.contains(&key), "{sanitized}");
1478        assert!(sanitized.contains("0x[REDACTED_KEY]"), "{sanitized}");
1479    }
1480
1481    #[test]
1482    fn test_sanitize_error_body_camel_case_json_keys() {
1483        let body = r#"{"accessToken": "tok-a", "clientSecret": "cs-b", "privateKey": "pk-c", "refreshToken": "rt-d", "secretKey": "sk-e", "clientId": "ci-f", "apiKey": "ak-g"}"#;
1484        let sanitized = super::sanitize_error_body(body);
1485        for secret in ["tok-a", "cs-b", "pk-c", "rt-d", "sk-e", "ci-f", "ak-g"] {
1486            assert!(!sanitized.contains(secret), "{secret} leaked: {sanitized}");
1487        }
1488        assert!(sanitized.contains("\"accessToken\""), "{sanitized}");
1489    }
1490
1491    #[test]
1492    fn test_sanitize_error_body_upper_case_patterns() {
1493        let body = "X-API-KEY: hdr-secret\nurl?API_KEY=qs-secret&x=1\nBEARER bear-secret";
1494        let sanitized = super::sanitize_error_body(body);
1495        for secret in ["hdr-secret", "qs-secret", "bear-secret"] {
1496            assert!(!sanitized.contains(secret), "{secret} leaked: {sanitized}");
1497        }
1498        assert!(sanitized.contains("X-API-KEY:"), "{sanitized}");
1499    }
1500
1501    #[test]
1502    fn test_sanitize_error_body_private_key_param() {
1503        // API-002 fix: Test private_key query param redaction
1504        let body = "Error: ?private_key=secretkey123&foo=bar";
1505        let sanitized = super::sanitize_error_body(body);
1506        assert!(sanitized.contains("[REDACTED]"));
1507        assert!(!sanitized.contains("secretkey123"));
1508    }
1509
1510    #[test]
1511    fn test_sanitize_error_body_client_secret() {
1512        // API-002 fix: Test client_secret JSON key redaction
1513        let body = r#"{"client_secret": "my_secret_value", "client_id": "my_client_id"}"#;
1514        let sanitized = super::sanitize_error_body(body);
1515        assert!(!sanitized.contains("my_secret_value"));
1516        assert!(!sanitized.contains("my_client_id"));
1517    }
1518}
1519
1520#[cfg(test)]
1521mod retryable_tests {
1522    use super::*;
1523
1524    /// A one-shot HTTP server on localhost that answers 200 with `body`
1525    fn serve_once(body: &'static str) -> String {
1526        use std::io::{Read, Write};
1527        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1528        let addr = listener.local_addr().unwrap();
1529        std::thread::spawn(move || {
1530            if let Ok((mut stream, _)) = listener.accept() {
1531                let mut buf = [0u8; 1024];
1532                let _ = stream.read(&mut buf);
1533                let _ = write!(
1534                    stream,
1535                    "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
1536                    body.len(),
1537                    body
1538                );
1539            }
1540        });
1541        format!("http://{addr}/")
1542    }
1543
1544    #[tokio::test]
1545    async fn a_response_that_does_not_parse_is_not_retried() {
1546        let url = serve_once("not json");
1547        let err = reqwest::get(&url)
1548            .await
1549            .unwrap()
1550            .json::<serde_json::Value>()
1551            .await
1552            .unwrap_err();
1553        assert!(err.is_decode());
1554        assert!(!ApiError::<NoDomainError>::from(err).is_retryable());
1555    }
1556
1557    #[tokio::test]
1558    async fn a_refused_connection_is_retried() {
1559        // Nothing listens on port 1
1560        let err = reqwest::get("http://127.0.0.1:1/").await.unwrap_err();
1561        assert!(ApiError::<NoDomainError>::from(err).is_retryable());
1562    }
1563}