Skip to main content

nautilus_binance/papi/http/
client.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  you may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Binance Portfolio Margin (PAPI) HTTP client providing the signed request boundary.
17//!
18//! This client owns routing, signing, admission, retry, and error decoding for the PAPI service;
19//! endpoint-specific request and response models sit at the boundaries that consume it.
20
21use std::{
22    collections::HashMap,
23    fmt::Debug,
24    num::NonZeroU32,
25    sync::{Arc, LazyLock, Weak},
26    time::Duration,
27};
28
29use ahash::AHashMap;
30use jiff::Timestamp;
31use nautilus_core::datetime::SECONDS_IN_DAY;
32use nautilus_network::{
33    http::{
34        HttpClient, HttpRedirectPolicy, HttpResponse, Method, create_standard_nautilus_headers,
35    },
36    ratelimiter::{RateLimiter, clock::MonotonicClock, quota::Quota},
37    retry::{RetryError, RetryManager},
38};
39use parking_lot::Mutex;
40use serde::{Serialize, de::DeserializeOwned};
41use ustr::Ustr;
42
43use super::error::{BinancePapiHttpError, BinancePapiHttpResult};
44use crate::common::{
45    consts::{
46        BINANCE_API_KEY_HEADER, BINANCE_PAPI_PATH, BINANCE_PAPI_RATE_LIMITS,
47        BINANCE_RETRY_AFTER_HEADER, BinanceRateLimitQuota,
48    },
49    credential::SigningCredential,
50    enums::{BinanceEnvironment, BinanceRateLimitInterval, BinanceRateLimitType},
51    http::{BinanceHttpBackoff, BinanceHttpEndpointScope, sha256},
52    http_weights::{papi_route, request_weight_papi},
53    models::BinanceErrorResponse,
54    urls::get_papi_base_url,
55};
56
57const BINANCE_GLOBAL_RATE_KEY: &str = "binance:global";
58const BINANCE_ORDERS_RATE_KEY: &str = "binance:orders";
59
60type BinancePapiLimiter = RateLimiter<Ustr, MonotonicClock>;
61type BinancePapiRateLimiter = Arc<BinancePapiLimiter>;
62
63#[derive(Clone, PartialEq, Eq, Hash)]
64struct BinancePapiRequestScope {
65    endpoint: BinanceHttpEndpointScope,
66    proxy_url_digest: Option<[u8; 32]>,
67}
68
69#[derive(Clone, Copy, PartialEq, Eq, Hash)]
70struct BinancePapiAccountScope([u8; 32]);
71
72#[derive(Clone, PartialEq, Eq, Hash)]
73struct BinancePapiOrderScope {
74    endpoint: BinanceHttpEndpointScope,
75    account: BinancePapiAccountScope,
76}
77
78static BINANCE_PAPI_REQUEST_LIMITERS: LazyLock<
79    Mutex<AHashMap<BinancePapiRequestScope, Weak<BinancePapiLimiter>>>,
80> = LazyLock::new(|| Mutex::new(AHashMap::new()));
81
82static BINANCE_PAPI_ORDER_LIMITERS: LazyLock<
83    Mutex<AHashMap<BinancePapiOrderScope, Weak<BinancePapiLimiter>>>,
84> = LazyLock::new(|| Mutex::new(AHashMap::new()));
85
86struct PapiRateLimitConfig {
87    request_quota: Quota,
88    order_quotas: Vec<(String, Quota)>,
89    order_keys: Vec<String>,
90}
91
92/// Raw HTTP client for the Binance Portfolio Margin REST API.
93#[derive(Clone)]
94pub struct BinanceRawPapiHttpClient {
95    retry_manager: Arc<RetryManager<BinancePapiHttpError>>,
96    client: HttpClient,
97    base_url: String,
98    credential: Option<SigningCredential>,
99    recv_window: Option<u64>,
100    order_rate_keys: Vec<String>,
101    backoff: BinanceHttpBackoff,
102}
103
104impl Debug for BinanceRawPapiHttpClient {
105    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
106        // The nested HTTP client carries the API key header and is elided; the signing
107        // credential redacts itself; the base URL prints its origin only.
108        f.debug_struct(stringify!(BinanceRawPapiHttpClient))
109            .field("base_url", &nautilus_network::url_origin(&self.base_url))
110            .field("credential", &self.credential)
111            .field("recv_window", &self.recv_window)
112            .finish_non_exhaustive()
113    }
114}
115
116impl BinanceRawPapiHttpClient {
117    /// Returns a reference to the underlying HTTP client.
118    #[must_use]
119    pub fn http_client(&self) -> &HttpClient {
120        &self.client
121    }
122
123    /// Returns whether this client has complete signing credentials.
124    #[must_use]
125    pub const fn has_credentials(&self) -> bool {
126        self.credential.is_some()
127    }
128
129    /// Creates a new raw Binance Portfolio Margin HTTP client.
130    ///
131    /// Binance documents only a production PAPI host and HMAC-SHA256 request signing, so
132    /// testnet and demo environments and Ed25519 credentials are rejected before any connection
133    /// is attempted.
134    ///
135    /// # Errors
136    ///
137    /// Returns an error if the environment has no PAPI host, the credentials use an unsupported
138    /// signature scheme, credentials are incomplete, or the HTTP client fails to build.
139    pub fn new(
140        environment: BinanceEnvironment,
141        api_key: Option<String>,
142        api_secret: Option<String>,
143        base_url_override: Option<String>,
144        recv_window: Option<u64>,
145        timeout_secs: Option<u64>,
146        proxy_url: Option<String>,
147    ) -> BinancePapiHttpResult<Self> {
148        let Some(base_url) = get_papi_base_url(environment) else {
149            return Err(BinancePapiHttpError::ValidationError(format!(
150                "Binance PAPI has no {environment:?} environment host"
151            )));
152        };
153
154        let base_url = match base_url_override {
155            Some(url) => url.trim_end_matches('/').to_string(),
156            None => base_url.to_string(),
157        };
158
159        let credential = match (api_key, api_secret) {
160            (Some(key), Some(secret)) => Some(SigningCredential::new(key, secret)),
161            (None, None) => None,
162            _ => return Err(BinancePapiHttpError::MissingCredentials),
163        };
164
165        if let Some(credential) = &credential
166            && credential.is_ed25519()
167        {
168            return Err(BinancePapiHttpError::UnsupportedSignatureScheme(
169                "Ed25519".to_string(),
170            ));
171        }
172
173        let PapiRateLimitConfig {
174            request_quota,
175            order_quotas,
176            order_keys,
177        } = Self::rate_limit_config();
178
179        let backoff = BinanceHttpBackoff::new_papi(
180            environment,
181            &base_url,
182            proxy_url.as_deref(),
183            credential.as_ref(),
184        );
185
186        let account_scope = credential.as_ref().map(Self::account_scope);
187        let rate_limiters = Self::shared_rate_limiters(
188            environment,
189            &base_url,
190            proxy_url.as_deref(),
191            account_scope,
192            request_quota,
193            order_quotas,
194        );
195
196        let headers = Self::default_headers(&credential);
197
198        let client = HttpClient::builder()
199            .redirect_policy(HttpRedirectPolicy::Reject)
200            .headers(headers)
201            .header_keys(vec![
202                BINANCE_API_KEY_HEADER.to_string(),
203                BINANCE_RETRY_AFTER_HEADER.to_string(),
204            ])
205            .maybe_timeout_secs(timeout_secs)
206            .maybe_proxy_url(proxy_url)
207            .rate_limiters(rate_limiters)
208            .build()?;
209
210        Ok(Self {
211            retry_manager: Arc::new(RetryManager::new(crate::common::http::retry_config())),
212            client,
213            base_url,
214            credential,
215            recv_window,
216            order_rate_keys: order_keys,
217            backoff,
218        })
219    }
220
221    fn shared_rate_limiters(
222        environment: BinanceEnvironment,
223        base_url: &str,
224        proxy_url: Option<&str>,
225        account_scope: Option<BinancePapiAccountScope>,
226        request_quota: Quota,
227        order_quotas: Vec<(String, Quota)>,
228    ) -> Vec<BinancePapiRateLimiter> {
229        let endpoint = BinanceHttpEndpointScope::Custom {
230            environment,
231            base_url: base_url.to_string(),
232        };
233
234        let request_scope = BinancePapiRequestScope {
235            endpoint: endpoint.clone(),
236            proxy_url_digest: proxy_url.map(sha256),
237        };
238
239        let request_limiter = Self::request_rate_limiter(request_scope, request_quota);
240        let mut limiters = vec![request_limiter];
241
242        if let Some(account) = account_scope {
243            let order_scope = BinancePapiOrderScope { endpoint, account };
244            limiters.push(Self::order_rate_limiter(order_scope, order_quotas));
245        }
246
247        limiters
248    }
249
250    fn account_scope(credential: &SigningCredential) -> BinancePapiAccountScope {
251        BinancePapiAccountScope(sha256(credential.api_key()))
252    }
253
254    fn request_rate_limiter(
255        scope: BinancePapiRequestScope,
256        quota: Quota,
257    ) -> BinancePapiRateLimiter {
258        let mut registry = BINANCE_PAPI_REQUEST_LIMITERS.lock();
259
260        if let Some(limiter) = registry.get(&scope).and_then(Weak::upgrade) {
261            return limiter;
262        }
263
264        let limiter = Arc::new(RateLimiter::new_with_quota(
265            None,
266            vec![(Ustr::from(BINANCE_GLOBAL_RATE_KEY), quota)],
267        ));
268        registry.insert(scope, Arc::downgrade(&limiter));
269        limiter
270    }
271
272    fn order_rate_limiter(
273        scope: BinancePapiOrderScope,
274        quotas: Vec<(String, Quota)>,
275    ) -> BinancePapiRateLimiter {
276        let mut registry = BINANCE_PAPI_ORDER_LIMITERS.lock();
277
278        if let Some(limiter) = registry.get(&scope).and_then(Weak::upgrade) {
279            return limiter;
280        }
281
282        let quotas = quotas
283            .into_iter()
284            .map(|(key, quota)| (Ustr::from(&key), quota))
285            .collect();
286        let limiter = Arc::new(RateLimiter::new_with_quota(None, quotas));
287        registry.insert(scope, Arc::downgrade(&limiter));
288        limiter
289    }
290
291    /// Performs a GET request and deserializes the response body.
292    ///
293    /// # Errors
294    ///
295    /// Returns an error if the request fails or response deserialization fails.
296    pub async fn get<P, T>(
297        &self,
298        path: &str,
299        params: Option<&P>,
300        signed: bool,
301        use_order_quota: bool,
302    ) -> BinancePapiHttpResult<T>
303    where
304        P: Serialize + ?Sized,
305        T: DeserializeOwned,
306    {
307        self.request(Method::GET, path, params, signed, use_order_quota)
308            .await
309    }
310
311    /// Performs a POST request, signing the query when `signed` is true.
312    ///
313    /// The request is sent exactly once: a timeout or ambiguous outcome must be resolved by the
314    /// caller's reconciliation rather than a local resubmission.
315    ///
316    /// Every documented PAPI route carries its parameters in the query string; a request body is
317    /// not part of the PAPI contract, and the signature covers the query only.
318    ///
319    /// # Errors
320    ///
321    /// Returns an error if the request fails or response deserialization fails.
322    pub async fn post<P, T>(
323        &self,
324        path: &str,
325        params: Option<&P>,
326        signed: bool,
327        use_order_quota: bool,
328    ) -> BinancePapiHttpResult<T>
329    where
330        P: Serialize + ?Sized,
331        T: DeserializeOwned,
332    {
333        self.request_once(Method::POST, path, params, signed, use_order_quota, None)
334            .await
335    }
336
337    /// Performs a PUT request, signing the query when `signed` is true.
338    ///
339    /// # Errors
340    ///
341    /// Returns an error if the request fails or response deserialization fails.
342    pub async fn request_put<P, T>(
343        &self,
344        path: &str,
345        params: Option<&P>,
346        signed: bool,
347        use_order_quota: bool,
348    ) -> BinancePapiHttpResult<T>
349    where
350        P: Serialize + ?Sized,
351        T: DeserializeOwned,
352    {
353        self.request(Method::PUT, path, params, signed, use_order_quota)
354            .await
355    }
356
357    /// Performs a DELETE request, signing the query when `signed` is true.
358    ///
359    /// The request is sent exactly once: a timeout or ambiguous outcome must be resolved by the
360    /// caller's reconciliation rather than a local resubmission.
361    ///
362    /// # Errors
363    ///
364    /// Returns an error if the request fails or response deserialization fails.
365    pub async fn request_delete<P, T>(
366        &self,
367        path: &str,
368        params: Option<&P>,
369        signed: bool,
370        use_order_quota: bool,
371    ) -> BinancePapiHttpResult<T>
372    where
373        P: Serialize + ?Sized,
374        T: DeserializeOwned,
375    {
376        self.request(Method::DELETE, path, params, signed, use_order_quota)
377            .await
378    }
379
380    async fn request<P, T>(
381        &self,
382        method: Method,
383        path: &str,
384        params: Option<&P>,
385        signed: bool,
386        use_order_quota: bool,
387    ) -> BinancePapiHttpResult<T>
388    where
389        P: Serialize + ?Sized,
390        T: DeserializeOwned,
391    {
392        let operation =
393            || self.request_once(method.clone(), path, params, signed, use_order_quota, None);
394
395        if method != Method::GET {
396            return operation().await;
397        }
398
399        self.retry_manager
400            .invocation(
401                path,
402                operation,
403                |e| e.is_retryable(),
404                |e| match e {
405                    RetryError::Canceled => {
406                        BinancePapiHttpError::Canceled("HTTP requests canceled".to_string())
407                    }
408                    RetryError::OperationTimeout { timeout_ms } => {
409                        BinancePapiHttpError::Timeout(format!("Request exceeded {timeout_ms}ms"))
410                    }
411                    RetryError::InvalidConfiguration { message } => {
412                        BinancePapiHttpError::ValidationError(message)
413                    }
414                    e @ RetryError::ElapsedBudgetExceeded { .. } => {
415                        BinancePapiHttpError::RetryBudgetExceeded(e.to_string())
416                    }
417                },
418            )
419            .retry_delay(&BinancePapiHttpError::retry_after)
420            .execute()
421            .await
422    }
423
424    async fn request_once<P, T>(
425        &self,
426        method: Method,
427        path: &str,
428        params: Option<&P>,
429        signed: bool,
430        use_order_quota: bool,
431        body: Option<Vec<u8>>,
432    ) -> BinancePapiHttpResult<T>
433    where
434        P: Serialize + ?Sized,
435        T: DeserializeOwned,
436    {
437        let mut query = params
438            .map(serde_urlencoded::to_string)
439            .transpose()
440            .map_err(|e| BinancePapiHttpError::ValidationError(e.to_string()))?
441            .unwrap_or_default();
442
443        let mut headers = HashMap::new();
444
445        let credential = if signed {
446            Some(
447                self.credential
448                    .as_ref()
449                    .ok_or(BinancePapiHttpError::MissingCredentials)?,
450            )
451        } else {
452            None
453        };
454
455        let keys = self.rate_limit_keys(&method, path, &query, use_order_quota);
456        self.backoff
457            .admit(&self.client, keys, use_order_quota, method == Method::GET)
458            .await
459            .map_err(|()| BinancePapiHttpError::RateLimitBlocked)?;
460
461        if let Some(cred) = credential {
462            if !query.is_empty() {
463                query.push('&');
464            }
465
466            let timestamp = Timestamp::now().as_millisecond();
467            query.push_str(&format!("timestamp={timestamp}"));
468            if let Some(recv_window) = self.recv_window {
469                query.push_str(&format!("&recvWindow={recv_window}"));
470            }
471
472            let signature = Self::percent_encode(&cred.sign(&query));
473            query.push_str(&format!("&signature={signature}"));
474            headers.insert(
475                BINANCE_API_KEY_HEADER.to_string(),
476                cred.api_key().to_string(),
477            );
478        }
479
480        let url = self.build_url(path, &query);
481
482        let response = self
483            .client
484            .request(
485                method,
486                url,
487                None::<&HashMap<String, Vec<String>>>,
488                Some(headers),
489                body,
490                None,
491                None,
492            )
493            .await?;
494
495        if !response.status.is_success() {
496            return self.parse_error_response(&response);
497        }
498
499        serde_json::from_slice::<T>(&response.body)
500            .map_err(|e| BinancePapiHttpError::JsonError(e.to_string()))
501    }
502
503    fn build_url(&self, path: &str, query: &str) -> String {
504        let url_path = if path.starts_with("/papi/") {
505            path.to_string()
506        } else if path.starts_with('/') {
507            format!("{BINANCE_PAPI_PATH}{path}")
508        } else {
509            format!("{BINANCE_PAPI_PATH}/{path}")
510        };
511
512        let mut url = format!("{}{}", self.base_url, url_path);
513        if !query.is_empty() {
514            url.push('?');
515            url.push_str(query);
516        }
517
518        url
519    }
520
521    fn rate_limit_keys(
522        &self,
523        method: &Method,
524        path: &str,
525        query: &str,
526        use_orders: bool,
527    ) -> Vec<Ustr> {
528        let weight = request_weight_papi(method, path, query);
529        let mut keys = vec![Ustr::from(BINANCE_GLOBAL_RATE_KEY); weight as usize];
530
531        if use_orders {
532            // The venue counts one OCO placement as two orders against the order rate limit.
533            // <https://developers.binance.com/docs/catalog/advanced-trading-derivatives-trading-portfolio-margin/api/rest-api/trade#margin-account-new-oco>
534            let order_cost = if *method == Method::POST && papi_route(path) == "margin/order/oco" {
535                2
536            } else {
537                1
538            };
539
540            keys.extend(
541                self.order_rate_keys
542                    .iter()
543                    .flat_map(|key| std::iter::repeat_n(Ustr::from(key), order_cost)),
544            );
545        }
546
547        keys
548    }
549
550    fn parse_error_response<T>(&self, response: &HttpResponse) -> BinancePapiHttpResult<T> {
551        let status = response.status.as_u16();
552        let body = String::from_utf8_lossy(&response.body).to_string();
553        let retry_after = crate::common::http::retry_after(&response.headers, Timestamp::now());
554        if let Ok(err) = serde_json::from_str::<BinanceErrorResponse>(&body) {
555            self.backoff.observe(status, Some(err.code), retry_after);
556            return Err(BinancePapiHttpError::BinanceError {
557                code: err.code,
558                message: err.msg,
559                status,
560                retry_after,
561            });
562        }
563
564        self.backoff.observe(status, None, retry_after);
565        Err(BinancePapiHttpError::UnexpectedStatus {
566            status,
567            body,
568            retry_after,
569        })
570    }
571
572    fn rate_limit_config() -> PapiRateLimitConfig {
573        let mut order_quotas = Vec::new();
574        let mut order_keys = Vec::new();
575        let mut request_quota = None;
576
577        for quota in BINANCE_PAPI_RATE_LIMITS {
578            let Some(q) = Self::quota_from(quota) else {
579                continue;
580            };
581
582            match quota.rate_limit_type {
583                BinanceRateLimitType::RequestWeight if request_quota.is_none() => {
584                    request_quota = Some(q);
585                }
586                BinanceRateLimitType::Orders => {
587                    let key = format!(
588                        "{}:{}:{:?}",
589                        BINANCE_ORDERS_RATE_KEY, quota.interval_num, quota.interval
590                    );
591                    order_keys.push(key.clone());
592                    order_quotas.push((key, q));
593                }
594                _ => {}
595            }
596        }
597
598        let request_quota = request_quota.unwrap_or_else(|| {
599            Quota::per_second(NonZeroU32::new(10).expect("non-zero")).expect("valid constant")
600        });
601
602        PapiRateLimitConfig {
603            request_quota,
604            order_quotas,
605            order_keys,
606        }
607    }
608
609    fn quota_from(quota: &BinanceRateLimitQuota) -> Option<Quota> {
610        let burst = NonZeroU32::new(quota.limit)?;
611        let period = Self::quota_period(quota)?;
612        let replenish_interval_ns = period.as_nanos() / u128::from(quota.limit);
613        let replenish_interval_ns = u64::try_from(replenish_interval_ns).ok()?;
614
615        Quota::with_period(Duration::from_nanos(replenish_interval_ns))
616            .map(|q| q.allow_burst(burst))
617    }
618
619    fn quota_period(quota: &BinanceRateLimitQuota) -> Option<Duration> {
620        match quota.interval {
621            BinanceRateLimitInterval::Second => {
622                Some(Duration::from_secs(u64::from(quota.interval_num)))
623            }
624            BinanceRateLimitInterval::Minute => {
625                Some(Duration::from_secs(60 * u64::from(quota.interval_num)))
626            }
627            BinanceRateLimitInterval::Day => Some(Duration::from_secs(
628                SECONDS_IN_DAY * u64::from(quota.interval_num),
629            )),
630            BinanceRateLimitInterval::Unknown => None,
631        }
632    }
633
634    fn default_headers(credential: &Option<SigningCredential>) -> HashMap<String, String> {
635        let mut headers: HashMap<String, String> =
636            create_standard_nautilus_headers().into_iter().collect();
637
638        if let Some(cred) = credential {
639            headers.insert(
640                BINANCE_API_KEY_HEADER.to_string(),
641                cred.api_key().to_string(),
642            );
643        }
644
645        headers
646    }
647
648    /// Percent-encodes a string for use in URL query parameters.
649    fn percent_encode(input: &str) -> String {
650        let mut result = String::with_capacity(input.len() * 3);
651        for byte in input.bytes() {
652            match byte {
653                b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
654                    result.push(byte as char);
655                }
656                _ => {
657                    result.push('%');
658                    result.push_str(&format!("{byte:02X}"));
659                }
660            }
661        }
662
663        result
664    }
665}
666#[cfg(test)]
667mod tests {
668    use std::{
669        num::NonZeroU32,
670        sync::{
671            Arc, Mutex,
672            atomic::{AtomicUsize, Ordering},
673        },
674        time::Instant,
675    };
676
677    use axum::{
678        Router,
679        http::{HeaderMap, Method as AxumMethod},
680        response::IntoResponse,
681        routing::any,
682    };
683    use base64::Engine;
684    use nautilus_network::ratelimiter::quota::Quota;
685    use rstest::rstest;
686    use serde_json::json;
687
688    use super::*;
689    use crate::common::enums::BinanceEnvironment;
690
691    /// PKCS#8 DER wrapping of RFC 8032 test vector 1 Ed25519 private key, matching the vector in
692    /// `common::credential` tests.
693    const ED25519_PKCS8_TEST_VECTOR: [u8; 48] = [
694        0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04,
695        0x20, 0x9d, 0x61, 0xb1, 0x9d, 0xef, 0xfd, 0x5a, 0x60, 0xba, 0x84, 0x4a, 0xf4, 0x92, 0xec,
696        0x2c, 0xc4, 0x44, 0x49, 0xc5, 0x69, 0x7b, 0x32, 0x69, 0x19, 0x70, 0x3b, 0xac, 0x03, 0x1c,
697        0xae, 0x7f, 0x60,
698    ];
699
700    #[derive(Clone, Debug, Default)]
701    struct CapturedRequest {
702        method: String,
703        path: String,
704        query: String,
705        api_key_header: Option<String>,
706    }
707
708    fn hmac_signature(query: &str) -> String {
709        let credential =
710            SigningCredential::new("papi-test-key".to_string(), "papi-test-secret".to_string());
711        credential.sign(query)
712    }
713
714    async fn new_client(base_url: &str, recv_window: Option<u64>) -> BinanceRawPapiHttpClient {
715        BinanceRawPapiHttpClient::new(
716            BinanceEnvironment::Live,
717            Some("papi-test-key".to_string()),
718            Some("papi-test-secret".to_string()),
719            Some(base_url.to_string()),
720            recv_window,
721            None,
722            None,
723        )
724        .unwrap()
725    }
726
727    #[rstest]
728    #[case(BinanceEnvironment::Testnet, "Testnet")]
729    #[case(BinanceEnvironment::Demo, "Demo")]
730    fn test_new_rejects_environments_without_papi_host(
731        #[case] environment: BinanceEnvironment,
732        #[case] name: &str,
733        #[values(None, Some("http://127.0.0.1:9"))] base_url_override: Option<&str>,
734    ) {
735        let result = BinanceRawPapiHttpClient::new(
736            environment,
737            Some("key".to_string()),
738            Some("secret".to_string()),
739            base_url_override.map(String::from),
740            None,
741            None,
742            None,
743        );
744
745        match result {
746            Err(BinancePapiHttpError::ValidationError(message)) => {
747                assert!(message.contains(&format!("no {name}")), "was {message}");
748            }
749            other => panic!("expected ValidationError, was {other:?}"),
750        }
751    }
752
753    #[rstest]
754    fn test_new_rejects_ed25519_credentials() {
755        let key_b64 = base64::engine::general_purpose::STANDARD.encode(ED25519_PKCS8_TEST_VECTOR);
756
757        let result = BinanceRawPapiHttpClient::new(
758            BinanceEnvironment::Live,
759            Some("key".to_string()),
760            Some(key_b64),
761            None,
762            None,
763            None,
764            None,
765        );
766
767        match result {
768            Err(BinancePapiHttpError::UnsupportedSignatureScheme(scheme)) => {
769                assert_eq!(scheme, "Ed25519");
770            }
771            other => panic!("expected UnsupportedSignatureScheme, was {other:?}"),
772        }
773    }
774
775    #[rstest]
776    fn test_new_rejects_incomplete_credentials() {
777        let result = BinanceRawPapiHttpClient::new(
778            BinanceEnvironment::Live,
779            Some("key".to_string()),
780            None,
781            None,
782            None,
783            None,
784            None,
785        );
786
787        assert!(matches!(
788            result,
789            Err(BinancePapiHttpError::MissingCredentials)
790        ));
791    }
792
793    #[tokio::test]
794    async fn test_signed_get_captures_exact_request() {
795        let requests: Arc<Mutex<Vec<CapturedRequest>>> = Arc::new(Mutex::new(Vec::new()));
796        let captured = requests.clone();
797        let app = Router::new().fallback(any(
798            move |method: AxumMethod, uri: axum::http::Uri, headers: HeaderMap| {
799                let captured = captured.clone();
800                async move {
801                    let (path, query) = match uri.path_and_query() {
802                        Some(pq) => match pq.query() {
803                            Some(q) => (pq.path().to_string(), q.to_string()),
804                            None => (pq.path().to_string(), String::new()),
805                        },
806                        None => (uri.path().to_string(), String::new()),
807                    };
808
809                    captured.lock().unwrap().push(CapturedRequest {
810                        method: method.to_string(),
811                        path,
812                        query,
813                        api_key_header: headers
814                            .get("X-MBX-APIKEY")
815                            .map(|value| value.to_str().unwrap().to_string()),
816                    });
817
818                    (axum::http::StatusCode::OK, "{}").into_response()
819                }
820            },
821        ));
822
823        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
824        let url = format!("http://{}", listener.local_addr().unwrap());
825
826        let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
827
828        let client = new_client(&url, Some(5_000)).await;
829        let params = json!({"asset": "BTC"});
830        let result: Result<serde_json::Value, _> = client
831            .get("/papi/v1/balance", Some(&params), true, false)
832            .await;
833
834        server.abort();
835
836        result.unwrap();
837        let requests = requests.lock().unwrap();
838        assert_eq!(requests.len(), 1);
839        let request = &requests[0];
840
841        assert_eq!(request.method, "GET");
842        assert_eq!(request.path, "/papi/v1/balance");
843        assert_eq!(request.api_key_header.as_deref(), Some("papi-test-key"));
844
845        // Signed query: params, timestamp, recvWindow, signature; the signature must sign
846        // everything before it.
847        let parts: Vec<&str> = request.query.split('&').collect();
848        assert_eq!(parts.len(), 4);
849        assert_eq!(parts[0], "asset=BTC");
850        assert!(parts[1].starts_with("timestamp="));
851        assert_eq!(parts[2], "recvWindow=5000");
852        assert!(parts[3].starts_with("signature="));
853
854        let signed = request
855            .query
856            .split("&signature=")
857            .next()
858            .unwrap()
859            .to_string();
860        assert_eq!(
861            parts[3].trim_start_matches("signature="),
862            hmac_signature(&signed)
863        );
864    }
865
866    #[tokio::test]
867    async fn test_signed_request_without_params_omits_leading_separator() {
868        let requests: Arc<Mutex<Vec<CapturedRequest>>> = Arc::new(Mutex::new(Vec::new()));
869        let captured = requests.clone();
870        let app = Router::new().fallback(any(
871            move |method: AxumMethod, uri: axum::http::Uri, headers: HeaderMap| {
872                let captured = captured.clone();
873                async move {
874                    let (path, query) = match uri.path_and_query() {
875                        Some(pq) => match pq.query() {
876                            Some(q) => (pq.path().to_string(), q.to_string()),
877                            None => (pq.path().to_string(), String::new()),
878                        },
879                        None => (uri.path().to_string(), String::new()),
880                    };
881
882                    captured.lock().unwrap().push(CapturedRequest {
883                        method: method.to_string(),
884                        path,
885                        query,
886                        api_key_header: headers
887                            .get("X-MBX-APIKEY")
888                            .map(|value| value.to_str().unwrap().to_string()),
889                    });
890
891                    (axum::http::StatusCode::OK, "{}").into_response()
892                }
893            },
894        ));
895
896        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
897        let url = format!("http://{}", listener.local_addr().unwrap());
898
899        let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
900
901        let client = new_client(&url, None).await;
902        let result: Result<serde_json::Value, _> = client
903            .get::<serde_json::Value, _>(
904                "/papi/v1/balance",
905                None::<&serde_json::Value>,
906                true,
907                false,
908            )
909            .await;
910
911        server.abort();
912
913        result.unwrap();
914        let requests = requests.lock().unwrap();
915        let query = &requests[0].query;
916
917        // Without caller params the signed query starts directly at `timestamp`, with no
918        // leading separator that would invalidate the signature.
919        let parts: Vec<&str> = query.split('&').collect();
920        assert_eq!(parts.len(), 2);
921        assert!(parts[0].starts_with("timestamp="));
922        assert!(parts[1].starts_with("signature="));
923    }
924
925    #[tokio::test]
926    async fn test_redirect_is_rejected_without_following() {
927        let requests = Arc::new(AtomicUsize::new(0));
928        let captured = requests.clone();
929        let app = Router::new().fallback(any(move |method: AxumMethod| {
930            let captured = captured.clone();
931            async move {
932                captured.fetch_add(1, Ordering::Relaxed);
933
934                if method.as_str() == "GET" {
935                    let mut response = axum::http::StatusCode::FOUND.into_response();
936                    response.headers_mut().insert(
937                        "Location",
938                        axum::http::HeaderValue::from_static("/papi/v1/elsewhere"),
939                    );
940                    response
941                } else {
942                    (axum::http::StatusCode::OK, "{}").into_response()
943                }
944            }
945        }));
946
947        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
948        let url = format!("http://{}", listener.local_addr().unwrap());
949
950        let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
951
952        let client = new_client(&url, None).await;
953        let result: Result<serde_json::Value, _> = client
954            .get::<serde_json::Value, _>(
955                "/papi/v1/balance",
956                None::<&serde_json::Value>,
957                true,
958                false,
959            )
960            .await;
961
962        server.abort();
963
964        // A redirect carrying the signed query must not be followed.
965        assert!(result.is_err());
966        assert_eq!(requests.load(Ordering::Relaxed), 1);
967    }
968
969    #[tokio::test]
970    async fn test_signed_request_without_credentials_fails_before_dispatch() {
971        let requests = Arc::new(AtomicUsize::new(0));
972        let captured = requests.clone();
973        let app = Router::new().fallback(any(move || {
974            let captured = captured.clone();
975            async move {
976                captured.fetch_add(1, Ordering::Relaxed);
977                (axum::http::StatusCode::OK, "{}").into_response()
978            }
979        }));
980
981        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
982        let url = format!("http://{}", listener.local_addr().unwrap());
983
984        let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
985
986        let client = BinanceRawPapiHttpClient::new(
987            BinanceEnvironment::Live,
988            None,
989            None,
990            Some(url),
991            None,
992            None,
993            None,
994        )
995        .unwrap();
996        let result: Result<serde_json::Value, _> = client
997            .get::<serde_json::Value, _>(
998                "/papi/v1/balance",
999                None::<&serde_json::Value>,
1000                true,
1001                false,
1002            )
1003            .await;
1004
1005        server.abort();
1006
1007        match result {
1008            Err(BinancePapiHttpError::MissingCredentials) => {}
1009            other => panic!("expected MissingCredentials, was {other:?}"),
1010        }
1011
1012        assert_eq!(requests.load(Ordering::Relaxed), 0);
1013    }
1014
1015    #[tokio::test]
1016    async fn test_relative_path_routes_under_papi_prefix() {
1017        let requests: Arc<Mutex<Vec<CapturedRequest>>> = Arc::new(Mutex::new(Vec::new()));
1018        let captured = requests.clone();
1019        let app = Router::new().fallback(any(move |method: AxumMethod, uri: axum::http::Uri| {
1020            let captured = captured.clone();
1021            async move {
1022                captured.lock().unwrap().push(CapturedRequest {
1023                    method: method.to_string(),
1024                    path: uri.path().to_string(),
1025                    query: String::new(),
1026                    api_key_header: None,
1027                });
1028
1029                (axum::http::StatusCode::OK, "{}").into_response()
1030            }
1031        }));
1032
1033        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1034        let url = format!("http://{}", listener.local_addr().unwrap());
1035
1036        let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
1037
1038        let client = new_client(&url, None).await;
1039        let result: Result<serde_json::Value, _> = client
1040            .get::<serde_json::Value, _>("um/order", None::<&serde_json::Value>, false, false)
1041            .await;
1042
1043        server.abort();
1044
1045        result.unwrap();
1046        let requests = requests.lock().unwrap();
1047        assert_eq!(requests[0].path, "/papi/v1/um/order");
1048    }
1049
1050    #[rstest]
1051    #[case::permissions(
1052        -2015,
1053        400,
1054        "Invalid API-key, IP, or permissions for the action.",
1055        Some("17")
1056    )]
1057    #[case::clock_window(
1058        -1021,
1059        400,
1060        "Timestamp for this request is outside of the recvWindow.",
1061        None
1062    )]
1063    #[case::status_unknown(
1064        -1007,
1065        500,
1066        "Timeout waiting for response from backend server.",
1067        None
1068    )]
1069    #[tokio::test]
1070    async fn test_venue_error_decodes_code_and_message(
1071        #[case] code: i64,
1072        #[case] status: u16,
1073        #[case] message: &str,
1074        #[case] retry_after_header: Option<&str>,
1075    ) {
1076        let body = json!({"code": code, "msg": message}).to_string();
1077        let retry_after_header = retry_after_header.map(String::from);
1078        let expected_retry_after = retry_after_header
1079            .as_deref()
1080            .map(|secs| Duration::from_secs(secs.parse().unwrap()));
1081
1082        let app = Router::new().fallback(any(move || {
1083            let body = body.clone();
1084            let retry_after_header = retry_after_header.clone();
1085            async move {
1086                let mut response = (
1087                    axum::http::StatusCode::from_u16(status).unwrap(),
1088                    body.clone(),
1089                )
1090                    .into_response();
1091
1092                if let Some(value) = &retry_after_header {
1093                    response.headers_mut().insert(
1094                        "Retry-After",
1095                        axum::http::HeaderValue::from_str(value).unwrap(),
1096                    );
1097                }
1098
1099                response
1100            }
1101        }));
1102
1103        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1104        let url = format!("http://{}", listener.local_addr().unwrap());
1105
1106        let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
1107
1108        let client = new_client(&url, None).await;
1109        let result: Result<serde_json::Value, _> = client
1110            .get::<serde_json::Value, _>(
1111                "/papi/v1/balance",
1112                None::<&serde_json::Value>,
1113                true,
1114                false,
1115            )
1116            .await;
1117
1118        server.abort();
1119
1120        match result {
1121            Err(BinancePapiHttpError::BinanceError {
1122                code: venue_code,
1123                message: venue_message,
1124                status: venue_status,
1125                retry_after,
1126            }) => {
1127                assert_eq!(venue_code, code);
1128                assert_eq!(venue_status, status);
1129                assert_eq!(venue_message, message);
1130                assert_eq!(retry_after, expected_retry_after);
1131
1132                // Clock/window and permission failures are permanent venue rejections;
1133                // only the backend timeout is retryable.
1134                let error = BinancePapiHttpError::BinanceError {
1135                    code: venue_code,
1136                    message: venue_message,
1137                    status: venue_status,
1138                    retry_after,
1139                };
1140
1141                assert_eq!(error.is_retryable(), status >= 500);
1142            }
1143            other => panic!("expected BinanceError, was {other:?}"),
1144        }
1145    }
1146
1147    #[tokio::test]
1148    async fn test_timeout_surfaces_unknown_outcome_error() {
1149        let app = Router::new().fallback(any(|| async {
1150            tokio::time::sleep(Duration::from_secs(30)).await;
1151            (axum::http::StatusCode::OK, "{}").into_response()
1152        }));
1153
1154        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1155        let url = format!("http://{}", listener.local_addr().unwrap());
1156
1157        let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
1158
1159        let client = BinanceRawPapiHttpClient::new(
1160            BinanceEnvironment::Live,
1161            Some("papi-test-key".to_string()),
1162            Some("papi-test-secret".to_string()),
1163            Some(url),
1164            None,
1165            Some(1),
1166            None,
1167        )
1168        .unwrap();
1169        let result: Result<serde_json::Value, _> = client
1170            .post::<serde_json::Value, _>(
1171                "/papi/v1/um/order",
1172                None::<&serde_json::Value>,
1173                true,
1174                true,
1175            )
1176            .await;
1177
1178        server.abort();
1179
1180        // A timed-out write leaves the outcome unknown: the error must surface rather than
1181        // retry, and the caller reconciles the order state.
1182        match result {
1183            Err(BinancePapiHttpError::Timeout(message)) => {
1184                assert_eq!(message, "request deadline elapsed");
1185            }
1186            other => panic!("expected Timeout, was {other:?}"),
1187        }
1188    }
1189
1190    #[tokio::test]
1191    async fn test_unexpected_status_without_venue_payload() {
1192        let app = Router::new().fallback(any(|| async {
1193            (axum::http::StatusCode::BAD_GATEWAY, "upstream error").into_response()
1194        }));
1195
1196        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1197        let url = format!("http://{}", listener.local_addr().unwrap());
1198
1199        let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
1200
1201        let client = new_client(&url, None).await;
1202        let result: Result<serde_json::Value, _> = client
1203            .get::<serde_json::Value, _>(
1204                "/papi/v1/balance",
1205                None::<&serde_json::Value>,
1206                true,
1207                false,
1208            )
1209            .await;
1210
1211        server.abort();
1212
1213        match result {
1214            Err(BinancePapiHttpError::UnexpectedStatus { status, body, .. }) => {
1215                assert_eq!(status, 502);
1216                assert_eq!(body, "upstream error");
1217            }
1218            other => panic!("expected UnexpectedStatus, was {other:?}"),
1219        }
1220    }
1221
1222    #[tokio::test]
1223    async fn test_get_retries_after_venue_throttle() {
1224        let requests = Arc::new(AtomicUsize::new(0));
1225        let captured = requests.clone();
1226        let app = Router::new().fallback(any(move || {
1227            let captured = captured.clone();
1228            async move {
1229                if captured.fetch_add(1, Ordering::Relaxed) == 0 {
1230                    let mut response = (
1231                        axum::http::StatusCode::TOO_MANY_REQUESTS,
1232                        r#"{"code":-1003,"msg":"Requests rate too high."}"#,
1233                    )
1234                        .into_response();
1235                    response
1236                        .headers_mut()
1237                        .insert("Retry-After", axum::http::HeaderValue::from_static("0"));
1238                    response
1239                } else {
1240                    (axum::http::StatusCode::OK, "{}").into_response()
1241                }
1242            }
1243        }));
1244
1245        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1246        let url = format!("http://{}", listener.local_addr().unwrap());
1247
1248        let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
1249
1250        let client = new_client(&url, None).await;
1251        let result: Result<serde_json::Value, _> = client
1252            .get::<serde_json::Value, _>(
1253                "/papi/v1/balance",
1254                None::<&serde_json::Value>,
1255                true,
1256                false,
1257            )
1258            .await;
1259
1260        server.abort();
1261
1262        result.unwrap();
1263        assert_eq!(requests.load(Ordering::Relaxed), 2);
1264    }
1265
1266    #[rstest]
1267    #[case::post(Method::POST)]
1268    #[case::put(Method::PUT)]
1269    #[case::delete(Method::DELETE)]
1270    #[tokio::test]
1271    async fn test_write_is_sent_exactly_once_on_throttle(#[case] method: Method) {
1272        let requests = Arc::new(AtomicUsize::new(0));
1273        let bodies: Arc<Mutex<Vec<Option<Vec<u8>>>>> = Arc::new(Mutex::new(Vec::new()));
1274        let captured = requests.clone();
1275        let captured_bodies = bodies.clone();
1276
1277        let app = Router::new().fallback(any(move |body: axum::body::Bytes| {
1278            let captured = captured.clone();
1279            let captured_bodies = captured_bodies.clone();
1280            async move {
1281                captured_bodies
1282                    .lock()
1283                    .unwrap()
1284                    .push((!body.is_empty()).then(|| body.to_vec()));
1285
1286                if captured.fetch_add(1, Ordering::Relaxed) == 0 {
1287                    let mut response = (
1288                        axum::http::StatusCode::TOO_MANY_REQUESTS,
1289                        r#"{"code":-1003,"msg":"Requests rate too high."}"#,
1290                    )
1291                        .into_response();
1292                    response
1293                        .headers_mut()
1294                        .insert("Retry-After", axum::http::HeaderValue::from_static("0"));
1295                    response
1296                } else {
1297                    (axum::http::StatusCode::OK, "{}").into_response()
1298                }
1299            }
1300        }));
1301
1302        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1303        let url = format!("http://{}", listener.local_addr().unwrap());
1304
1305        let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
1306
1307        let client = new_client(&url, None).await;
1308        let params =
1309            json!({"symbol": "BTCUSDT", "side": "BUY", "type": "MARKET", "quantity": "0.01"});
1310
1311        let result: Result<serde_json::Value, _> = match method {
1312            Method::POST => {
1313                client
1314                    .post("/papi/v1/um/order", Some(&params), true, true)
1315                    .await
1316            }
1317            Method::PUT => {
1318                client
1319                    .request_put("/papi/v1/um/order", Some(&params), true, true)
1320                    .await
1321            }
1322            _ => {
1323                client
1324                    .request_delete("/papi/v1/um/order", Some(&params), true, true)
1325                    .await
1326            }
1327        };
1328
1329        server.abort();
1330
1331        // A throttled mutating request surfaces the venue error rather than resubmitting;
1332        // the ambiguous outcome belongs to the caller's reconciliation.
1333        match result {
1334            Err(BinancePapiHttpError::BinanceError { code, status, .. }) => {
1335                assert_eq!(code, -1003);
1336                assert_eq!(status, 429);
1337            }
1338            other => panic!("expected BinanceError, was {other:?}"),
1339        }
1340
1341        assert_eq!(requests.load(Ordering::Relaxed), 1);
1342        assert_eq!(bodies.lock().unwrap().as_slice(), [None].as_slice());
1343    }
1344
1345    #[tokio::test(start_paused = false)]
1346    async fn test_ip_throttle_backoff_blocks_next_request_until_expiry() {
1347        let requests = Arc::new(AtomicUsize::new(0));
1348        let captured = requests.clone();
1349        let app = Router::new().fallback(any(move || {
1350            let captured = captured.clone();
1351            async move {
1352                if captured.fetch_add(1, Ordering::Relaxed) == 0 {
1353                    let mut response = (
1354                        axum::http::StatusCode::TOO_MANY_REQUESTS,
1355                        r#"{"code":-1003,"msg":"Requests rate too high."}"#,
1356                    )
1357                        .into_response();
1358                    response
1359                        .headers_mut()
1360                        .insert("Retry-After", axum::http::HeaderValue::from_static("1"));
1361                    response
1362                } else {
1363                    (axum::http::StatusCode::OK, "{}").into_response()
1364                }
1365            }
1366        }));
1367
1368        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1369        let url = format!("http://{}", listener.local_addr().unwrap());
1370
1371        let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
1372
1373        let client = new_client(&url, None).await;
1374        let first: Result<serde_json::Value, _> = client
1375            .post::<serde_json::Value, _>(
1376                "/papi/v1/um/order",
1377                None::<&serde_json::Value>,
1378                true,
1379                false,
1380            )
1381            .await;
1382        assert!(first.is_err());
1383
1384        let start = Instant::now();
1385        let second: Result<serde_json::Value, _> = client
1386            .get::<serde_json::Value, _>(
1387                "/papi/v1/balance",
1388                None::<&serde_json::Value>,
1389                true,
1390                false,
1391            )
1392            .await;
1393
1394        server.abort();
1395
1396        // The shared IP backoff admits the next request no earlier than the venue delay.
1397        second.unwrap();
1398        assert!(start.elapsed() >= Duration::from_millis(900));
1399        assert_eq!(requests.load(Ordering::Relaxed), 2);
1400    }
1401
1402    #[rstest]
1403    fn test_default_base_url_is_official_papi_host() {
1404        let client = BinanceRawPapiHttpClient::new(
1405            BinanceEnvironment::Live,
1406            Some("key".to_string()),
1407            Some("secret".to_string()),
1408            None,
1409            None,
1410            None,
1411            None,
1412        )
1413        .unwrap();
1414
1415        let url = client.build_url("/papi/v1/ping", "");
1416        assert_eq!(url, "https://papi.binance.com/papi/v1/ping");
1417    }
1418
1419    #[rstest]
1420    fn test_override_base_url_trailing_slash_normalizes() {
1421        let client = BinanceRawPapiHttpClient::new(
1422            BinanceEnvironment::Live,
1423            Some("key".to_string()),
1424            Some("secret".to_string()),
1425            Some("http://127.0.0.1:9999/".to_string()),
1426            None,
1427            None,
1428            None,
1429        )
1430        .unwrap();
1431
1432        let url = client.build_url("/papi/v1/ping", "");
1433        assert_eq!(url, "http://127.0.0.1:9999/papi/v1/ping");
1434    }
1435
1436    #[rstest]
1437    fn test_rate_limit_keys_carry_weight_and_order_quota() {
1438        let client = BinanceRawPapiHttpClient::new(
1439            BinanceEnvironment::Live,
1440            Some("key".to_string()),
1441            Some("secret".to_string()),
1442            None,
1443            None,
1444            None,
1445            None,
1446        )
1447        .unwrap();
1448
1449        let read = client.rate_limit_keys(&Method::GET, "/papi/v1/um/income/asyn", "", false);
1450        assert_eq!(read.len(), 1_500);
1451
1452        let order = client.rate_limit_keys(&Method::POST, "/papi/v1/um/order", "", true);
1453        assert_eq!(order.len(), 2);
1454        assert!(order[1].as_str().starts_with("binance:orders"));
1455    }
1456
1457    #[rstest]
1458    fn test_debug_output_redacts_api_key() {
1459        let client = BinanceRawPapiHttpClient::new(
1460            BinanceEnvironment::Live,
1461            Some("papi-test-key".to_string()),
1462            Some("papi-test-secret".to_string()),
1463            None,
1464            None,
1465            None,
1466            None,
1467        )
1468        .unwrap();
1469
1470        let formatted = format!("{client:?}");
1471
1472        assert!(!formatted.contains("papi-test-key"));
1473        assert!(!formatted.contains("papi-test-secret"));
1474        assert!(formatted.contains("BinanceRawPapiHttpClient"));
1475    }
1476
1477    #[rstest]
1478    #[case("https://user:url-secret@papi-mirror.example/base#token")]
1479    fn test_debug_output_redacts_credential_bearing_url_override(#[case] url: &str) {
1480        let client = BinanceRawPapiHttpClient::new(
1481            BinanceEnvironment::Live,
1482            Some("papi-test-key".to_string()),
1483            Some("papi-test-secret".to_string()),
1484            Some(url.to_string()),
1485            None,
1486            None,
1487            None,
1488        )
1489        .unwrap();
1490
1491        let formatted = format!("{client:?}");
1492
1493        assert!(!formatted.contains("url-secret"));
1494        assert!(!formatted.contains("token"));
1495        assert!(formatted.contains("https://papi-mirror.example"));
1496    }
1497
1498    #[rstest]
1499    fn test_debug_output_redacts_url_override_without_scheme() {
1500        // A scheme-less override is not a valid HTTP(S) URL and prints fully redacted.
1501        let client = BinanceRawPapiHttpClient::new(
1502            BinanceEnvironment::Live,
1503            Some("papi-test-key".to_string()),
1504            Some("papi-test-secret".to_string()),
1505            Some("user:url-secret@papi-mirror.example".to_string()),
1506            None,
1507            None,
1508            None,
1509        )
1510        .unwrap();
1511
1512        let formatted = format!("{client:?}");
1513
1514        assert!(!formatted.contains("url-secret"));
1515        assert!(formatted.contains("<redacted>"));
1516    }
1517
1518    #[rstest]
1519    fn test_rate_limit_keys_charge_two_order_units_for_margin_oco() {
1520        let client = BinanceRawPapiHttpClient::new(
1521            BinanceEnvironment::Live,
1522            Some("key".to_string()),
1523            Some("secret".to_string()),
1524            None,
1525            None,
1526            None,
1527            None,
1528        )
1529        .unwrap();
1530
1531        let order = client.rate_limit_keys(&Method::POST, "/papi/v1/um/order", "", true);
1532        let oco = client.rate_limit_keys(&Method::POST, "/papi/v1/margin/order/oco", "", true);
1533
1534        // One OCO placement consumes two order-count units against the venue limit.
1535        assert_eq!(order.len(), 2);
1536        assert_eq!(oco.len(), 3);
1537    }
1538
1539    #[rstest]
1540    fn test_concurrent_clients_share_request_limiter_scope() {
1541        let quota = Quota::per_minute(NonZeroU32::new(6_000).unwrap());
1542
1543        let first = BinanceRawPapiHttpClient::request_rate_limiter(
1544            BinancePapiRequestScope {
1545                endpoint: BinanceHttpEndpointScope::Custom {
1546                    environment: BinanceEnvironment::Live,
1547                    base_url: "https://papi.example".to_string(),
1548                },
1549                proxy_url_digest: None,
1550            },
1551            quota,
1552        );
1553
1554        let second = BinanceRawPapiHttpClient::request_rate_limiter(
1555            BinancePapiRequestScope {
1556                endpoint: BinanceHttpEndpointScope::Custom {
1557                    environment: BinanceEnvironment::Live,
1558                    base_url: "https://papi.example".to_string(),
1559                },
1560                proxy_url_digest: None,
1561            },
1562            quota,
1563        );
1564
1565        assert!(Arc::ptr_eq(&first, &second));
1566
1567        let other = BinanceRawPapiHttpClient::request_rate_limiter(
1568            BinancePapiRequestScope {
1569                endpoint: BinanceHttpEndpointScope::Custom {
1570                    environment: BinanceEnvironment::Live,
1571                    base_url: "https://papi-other.example".to_string(),
1572                },
1573                proxy_url_digest: None,
1574            },
1575            quota,
1576        );
1577
1578        assert!(!Arc::ptr_eq(&first, &other));
1579    }
1580}