1use crate::http::{HttpClientConfig, HttpError};
35use crate::RetryableError;
36use reqwest::Client;
37use std::fmt;
38use std::time::Duration;
39use thiserror::Error;
40
41#[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
57const MAX_ERROR_BODY_LENGTH: usize = 500;
59
60#[must_use]
69pub fn join_url(base: &str, path: &str) -> String {
70 if let Ok(base_url) = url::Url::parse(base) {
72 let path_to_join = path.trim_start_matches('/');
75
76 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 let base_str = base.trim_end_matches('/');
85 return format!("{base_str}/{path_to_join}");
86 }
87 }
88
89 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
98fn 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#[must_use]
133pub fn sanitize_error_body(body: &str) -> String {
134 let truncated = if body.len() > MAX_ERROR_BODY_LENGTH {
136 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 let mut result = truncated;
150
151 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 let mut search_from = 0;
171 while let Some(start) = find_ascii_ci(&result, search_from, pattern) {
173 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 let value = &result[value_start..value_end];
181 if value_end > value_start && value != "[REDACTED]" {
182 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 search_from = start + pattern.len() + "[REDACTED]".len();
192 } else {
193 search_from = value_start;
195 }
196 }
197 }
198
199 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 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 let trimmed_start = result[value_start..]
232 .find(|c: char| !c.is_whitespace())
233 .map_or(value_start, |i| value_start + i);
234 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 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 let mut search_from = 0;
281 while let Some(key_start) = find_ascii_ci(&result, search_from, json_key) {
283 let after_key = key_start + json_key.len();
285 let remaining = &result[after_key..];
286
287 if let Some(colon_offset) = remaining.find(':') {
289 let after_colon = &remaining[colon_offset + 1..];
290 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 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 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 result = format!(
313 "{}[REDACTED]{}",
314 &result[..value_start_abs],
315 &result[value_end_abs..]
316 );
317 search_from = value_start_abs + "[REDACTED]".len();
319 } else {
320 search_from = after_key;
322 }
323 } else {
324 search_from = after_key;
326 }
327 } else {
328 search_from = after_key;
330 }
331 }
332 }
333
334 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 if let Some(potential_key) = result.get(after_0x..after_0x + 64) {
349 if potential_key.chars().all(|c| c.is_ascii_hexdigit()) {
350 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
374const KEY_CONTEXT_WINDOW: usize = 32;
376
377fn 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#[derive(Error, Debug)]
403#[non_exhaustive]
404pub enum ApiError<E: std::error::Error = NoDomainError> {
405 #[error("HTTP error: {0}")]
407 Http(#[from] reqwest::Error),
408
409 #[error("HTTP client error: {0}")]
411 HttpBuild(#[source] HttpError),
412
413 #[error("JSON error: {0}")]
415 Json(#[from] serde_json::Error),
416
417 #[error("API error: {status} - {message}")]
419 Api {
420 status: u16,
422 message: String,
424 },
425
426 #[error("Rate limited{}", .retry_after.map(|s| format!(" (retry after {s}s)")).unwrap_or_default())]
428 RateLimited {
429 retry_after: Option<u64>,
431 },
432
433 #[error("Server error ({status}): {message}")]
435 ServerError {
436 status: u16,
438 message: String,
440 },
441
442 #[error("URL error: {0}")]
444 Url(#[from] url::ParseError),
445
446 #[error(transparent)]
448 Domain(E),
449}
450
451impl<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 pub fn api(status: u16, message: impl Into<String>) -> Self {
461 Self::Api {
462 status,
463 message: message.into(),
464 }
465 }
466
467 #[must_use]
469 pub fn rate_limited(retry_after: Option<u64>) -> Self {
470 Self::RateLimited { retry_after }
471 }
472
473 pub fn server_error(status: u16, message: impl Into<String>) -> Self {
475 Self::ServerError {
476 status,
477 message: message.into(),
478 }
479 }
480
481 pub fn domain(error: E) -> Self {
483 Self::Domain(error)
484 }
485
486 #[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 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 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 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
565pub type ApiResult<T, E = NoDomainError> = std::result::Result<T, ApiError<E>>;
567
568#[derive(Clone)]
588pub struct SecretApiKey(String);
589
590impl SecretApiKey {
591 pub fn new(key: impl Into<String>) -> Self {
593 Self(key.into())
594 }
595
596 #[must_use]
600 pub fn expose(&self) -> &str {
601 &self.0
602 }
603
604 #[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#[derive(Clone)]
645pub struct ApiConfig {
646 pub base_url: String,
648 pub api_key: Option<SecretApiKey>,
650 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 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 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 #[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 #[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 #[must_use]
699 pub fn timeout(mut self, timeout: Duration) -> Self {
700 self.http.timeout = timeout;
701 self
702 }
703
704 #[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 #[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 #[must_use]
720 pub fn optional_proxy(mut self, proxy: Option<String>) -> Self {
721 self.http.proxy = proxy;
722 self
723 }
724
725 pub fn build_client(&self) -> Result<Client, HttpError> {
727 crate::http::build_client(&self.http)
728 }
729
730 pub fn validate(&self) -> Result<(), ConfigValidationError> {
750 let url = url::Url::parse(&self.base_url)
752 .map_err(|e| ConfigValidationError::InvalidUrl(e.to_string()))?;
753
754 match url.scheme() {
756 "https" => Ok(()),
757 "http" => {
758 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 #[must_use]
774 pub fn is_https(&self) -> bool {
775 self.base_url.starts_with("https://")
776 }
777
778 #[must_use]
780 pub fn get_api_key(&self) -> Option<&str> {
781 self.api_key.as_ref().map(SecretApiKey::expose)
782 }
783}
784
785#[derive(Debug, Clone, PartialEq, Eq)]
787pub enum ConfigValidationError {
788 InsecureScheme,
790 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#[derive(Debug, Clone)]
834pub struct BaseClient {
835 http: Client,
836 config: ApiConfig,
837 normalized_base_url: String,
839}
840
841impl BaseClient {
842 pub fn new(config: ApiConfig) -> Result<Self, HttpError> {
853 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 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 #[must_use]
872 pub fn http(&self) -> &Client {
873 &self.http
874 }
875
876 #[must_use]
878 pub fn config(&self) -> &ApiConfig {
879 &self.config
880 }
881
882 #[must_use]
884 pub fn base_url(&self) -> &str {
885 &self.config.base_url
886 }
887
888 #[must_use]
893 pub fn url(&self, path: &str) -> String {
894 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 join_url(&self.normalized_base_url, path)
905 }
906 }
907
908 pub fn default_headers(&self) -> reqwest::header::HeaderMap {
912 let mut headers = reqwest::header::HeaderMap::new();
913
914 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 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 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 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 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 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 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#[must_use]
1101pub fn extract_retry_after(headers: &reqwest::header::HeaderMap) -> Option<u64> {
1102 const MAX_RETRY_AFTER_SECS: u64 = 3600; 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
1111pub 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 let config = ApiConfig::new("https://api.example.com");
1237 assert!(config.validate().is_ok());
1238 assert!(config.is_https());
1239
1240 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 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 #[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 #[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 assert_eq!(client.url("/quote"), "https://api.example.com/quote");
1296
1297 assert_eq!(client.url("quote"), "https://api.example.com/quote");
1299
1300 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 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 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 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); assert!(sanitized.ends_with("... (truncated)"));
1356 }
1357
1358 #[test]
1359 fn test_sanitize_error_body_truncation_multibyte_boundary() {
1360 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 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 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 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 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 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 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 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 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 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 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 let err = reqwest::get("http://127.0.0.1:1/").await.unwrap_err();
1561 assert!(ApiError::<NoDomainError>::from(err).is_retryable());
1562 }
1563}