nautilus_bitmex/common/
credential.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 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//! API credential utilities for signing BitMEX requests.
17
18#![allow(unused_assignments)] // Fields are accessed externally, false positive from nightly
19
20use std::fmt::Debug;
21
22use aws_lc_rs::hmac;
23use ustr::Ustr;
24use zeroize::ZeroizeOnDrop;
25
26/// BitMEX API credentials for signing requests.
27///
28/// Uses HMAC SHA256 for request signing as per BitMEX API specifications.
29/// Secrets are automatically zeroized on drop for security.
30#[derive(Clone, ZeroizeOnDrop)]
31pub struct Credential {
32    #[zeroize(skip)]
33    pub api_key: Ustr,
34    api_secret: Box<[u8]>,
35}
36
37impl Debug for Credential {
38    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
39        f.debug_struct(stringify!(Credential))
40            .field("api_key", &self.api_key)
41            .field("api_secret", &"<redacted>")
42            .finish()
43    }
44}
45
46impl Credential {
47    /// Creates a new [`Credential`] instance.
48    #[must_use]
49    pub fn new(api_key: String, api_secret: String) -> Self {
50        let boxed: Box<[u8]> = api_secret.into_bytes().into_boxed_slice();
51
52        Self {
53            api_key: api_key.into(),
54            api_secret: boxed,
55        }
56    }
57
58    /// Signs a request message according to the BitMEX authentication scheme.
59    #[must_use]
60    pub fn sign(&self, verb: &str, endpoint: &str, expires: i64, data: &str) -> String {
61        let sign_message = format!("{verb}{endpoint}{expires}{data}");
62        let key = hmac::Key::new(hmac::HMAC_SHA256, &self.api_secret[..]);
63        let signature = hmac::sign(&key, sign_message.as_bytes());
64        hex::encode(signature.as_ref())
65    }
66
67    /// Returns a masked version of the API key for logging purposes.
68    ///
69    /// Shows first 4 and last 4 characters with ellipsis in between.
70    /// For keys shorter than 8 characters, shows asterisks only.
71    #[must_use]
72    pub fn api_key_masked(&self) -> String {
73        nautilus_core::string::mask_api_key(self.api_key.as_str())
74    }
75}
76
77////////////////////////////////////////////////////////////////////////////////
78// Tests
79////////////////////////////////////////////////////////////////////////////////
80
81/// Tests use examples from <https://www.bitmex.com/app/apiKeysUsage>.
82#[cfg(test)]
83mod tests {
84    use rstest::rstest;
85
86    use super::*;
87    use crate::common::testing::load_test_json;
88
89    const API_KEY: &str = "LAqUlngMIQkIUjXMUreyu3qn";
90    const API_SECRET: &str = "chNOOS4KvNXR_Xq4k4c9qsfoKWvnDecLATCRlcBwyKDYnWgO";
91
92    #[rstest]
93    fn test_simple_get() {
94        let credential = Credential::new(API_KEY.to_string(), API_SECRET.to_string());
95
96        let signature = credential.sign("GET", "/api/v1/instrument", 1518064236, "");
97
98        assert_eq!(
99            signature,
100            "c7682d435d0cfe87c16098df34ef2eb5a549d4c5a3c2b1f0f77b8af73423bf00"
101        );
102    }
103
104    #[rstest]
105    fn test_get_with_query() {
106        let credential = Credential::new(API_KEY.to_string(), API_SECRET.to_string());
107
108        let signature = credential.sign(
109            "GET",
110            "/api/v1/instrument?filter=%7B%22symbol%22%3A+%22XBTM15%22%7D",
111            1518064237,
112            "",
113        );
114
115        assert_eq!(
116            signature,
117            "e2f422547eecb5b3cb29ade2127e21b858b235b386bfa45e1c1756eb3383919f"
118        );
119    }
120
121    #[rstest]
122    fn test_post_with_data() {
123        let credential = Credential::new(API_KEY.to_string(), API_SECRET.to_string());
124
125        let data = load_test_json("credential_post_order.json");
126
127        let signature = credential.sign("POST", "/api/v1/order", 1518064238, data.trim_end());
128
129        assert_eq!(
130            signature,
131            "1749cd2ccae4aa49048ae09f0b95110cee706e0944e6a14ad0b3a8cb45bd336b"
132        );
133    }
134
135    #[rstest]
136    fn test_debug_redacts_secret() {
137        let credential = Credential::new(API_KEY.to_string(), API_SECRET.to_string());
138        let dbg_out = format!("{credential:?}");
139        assert!(dbg_out.contains("api_secret: \"<redacted>\""));
140        assert!(!dbg_out.contains("chNOO"));
141        let secret_bytes_dbg = format!("{:?}", API_SECRET.as_bytes());
142        assert!(
143            !dbg_out.contains(&secret_bytes_dbg),
144            "Debug output must not contain raw secret bytes"
145        );
146    }
147}