Skip to main content

nautilus_deribit/common/
credential.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//! Deribit API credential resolution, storage, and request signing.
17
18#![allow(unused_assignments)] // Fields are accessed externally, false positive from nightly
19
20use std::{
21    collections::HashMap,
22    fmt::{Debug, Display},
23};
24
25use aws_lc_rs::hmac;
26use nautilus_core::{
27    UUID4, env::resolve_env_var_pair, hex, string::secret::REDACTED,
28    time::get_atomic_clock_realtime,
29};
30use thiserror::Error;
31use zeroize::ZeroizeOnDrop;
32
33use crate::{common::enums::DeribitEnvironment, http::error::DeribitHttpError};
34
35/// Errors that can occur when resolving credentials.
36#[derive(Debug, Error)]
37pub enum CredentialError {
38    /// API key was provided but secret is missing.
39    #[error("API key provided but secret is missing")]
40    MissingSecret,
41    /// API secret was provided but key is missing.
42    #[error("API secret provided but key is missing")]
43    MissingKey,
44}
45
46/// Returns the environment variable names for API credentials,
47/// based on the network.
48#[must_use]
49pub fn credential_env_vars(environment: DeribitEnvironment) -> (&'static str, &'static str) {
50    match environment {
51        DeribitEnvironment::Testnet => ("DERIBIT_TESTNET_API_KEY", "DERIBIT_TESTNET_API_SECRET"),
52        DeribitEnvironment::Mainnet => ("DERIBIT_API_KEY", "DERIBIT_API_SECRET"),
53    }
54}
55
56/// Deribit API credentials for signing requests.
57///
58/// Uses HMAC SHA256 for request signing as per Deribit API specifications.
59/// Secrets are automatically zeroized on drop for security.
60#[derive(Clone, ZeroizeOnDrop)]
61pub struct Credential {
62    api_key: Box<str>,
63    api_secret: Box<[u8]>,
64}
65
66impl Debug for Credential {
67    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
68        f.debug_struct(stringify!(Credential))
69            .field("api_key", &REDACTED)
70            .field("api_secret", &REDACTED)
71            .finish()
72    }
73}
74
75impl Credential {
76    /// Creates a new [`Credential`] instance.
77    #[must_use]
78    pub fn new(api_key: String, api_secret: String) -> Self {
79        Self {
80            api_key: api_key.into_boxed_str(),
81            api_secret: api_secret.into_bytes().into_boxed_slice(),
82        }
83    }
84
85    /// Load credentials from environment variables.
86    ///
87    /// For mainnet: Looks for `DERIBIT_API_KEY` and `DERIBIT_API_SECRET`.
88    /// For testnet: Looks for `DERIBIT_TESTNET_API_KEY` and `DERIBIT_TESTNET_API_SECRET`.
89    ///
90    /// Returns `None` if either key or secret is not set.
91    #[must_use]
92    pub fn from_env(environment: DeribitEnvironment) -> Option<Self> {
93        let (key_var, secret_var) = credential_env_vars(environment);
94        let (k, s) = resolve_env_var_pair(None, None, key_var, secret_var)?;
95        Some(Self::new(k, s))
96    }
97
98    /// Resolves credentials from provided values or environment.
99    ///
100    /// If both `api_key` and `api_secret` are provided, uses those.
101    /// Otherwise falls back to loading from environment variables.
102    ///
103    /// # Errors
104    ///
105    /// Returns an error if only one of `api_key` or `api_secret` is provided.
106    pub fn resolve(
107        api_key: Option<String>,
108        api_secret: Option<String>,
109        environment: DeribitEnvironment,
110    ) -> Result<Option<Self>, CredentialError> {
111        Self::resolve_with_env_fallback(api_key, api_secret, environment, true)
112    }
113
114    /// Resolves credentials with optional environment fallback.
115    ///
116    /// If both `api_key` and `api_secret` are provided, uses those.
117    /// If `env_fallback` is true and neither credential is provided, loads from environment.
118    /// If `env_fallback` is false and neither credential is provided, returns `Ok(None)`.
119    ///
120    /// # Errors
121    ///
122    /// Returns an error if only one of `api_key` or `api_secret` is provided (partial credentials).
123    /// This prevents silent fallback to environment variables when user intent is unclear.
124    pub fn resolve_with_env_fallback(
125        api_key: Option<String>,
126        api_secret: Option<String>,
127        environment: DeribitEnvironment,
128        env_fallback: bool,
129    ) -> Result<Option<Self>, CredentialError> {
130        match (api_key, api_secret) {
131            (Some(k), Some(s)) => Ok(Some(Self::new(k, s))),
132            (None, None) if env_fallback => Ok(Self::from_env(environment)),
133            (None, None) => Ok(None),
134            (Some(_), None) => Err(CredentialError::MissingSecret),
135            (None, Some(_)) => Err(CredentialError::MissingKey),
136        }
137    }
138
139    /// Returns the API key associated with this credential.
140    #[must_use]
141    pub fn api_key(&self) -> &str {
142        &self.api_key
143    }
144
145    /// Returns a masked version of the API key for logging purposes.
146    ///
147    /// Shows first 4 and last 4 characters with ellipsis in between.
148    /// For keys shorter than 8 characters, shows asterisks only.
149    #[must_use]
150    pub fn api_key_masked(&self) -> String {
151        nautilus_core::string::secret::mask_api_key(&self.api_key)
152    }
153
154    /// Signs a WebSocket authentication request according to Deribit specification.
155    ///
156    /// # Deribit WebSocket Signature Formula
157    ///
158    /// ```text
159    /// StringToSign = Timestamp + "\n" + Nonce + "\n" + Data
160    /// Signature = HEX_STRING(HMAC-SHA256(ClientSecret, StringToSign))
161    /// ```
162    ///
163    /// # Returns
164    ///
165    /// Hex-encoded HMAC-SHA256 signature
166    #[must_use]
167    pub fn sign_ws_auth(&self, timestamp: u64, nonce: &str, data: &str) -> String {
168        self.sign_message(timestamp, nonce, data)
169    }
170
171    /// Signs a timestamp, nonce, and data payload according to the Deribit authentication scheme.
172    ///
173    /// ```text
174    /// StringToSign = Timestamp + "\n" + Nonce + "\n" + Data
175    /// Signature = HEX_STRING(HMAC-SHA256(ClientSecret, StringToSign))
176    /// ```
177    #[must_use]
178    fn sign_message(&self, timestamp: impl Display, nonce: &str, data: &str) -> String {
179        let string_to_sign = format!("{timestamp}\n{nonce}\n{data}");
180        let key = hmac::Key::new(hmac::HMAC_SHA256, &self.api_secret[..]);
181        let tag = hmac::sign(&key, string_to_sign.as_bytes());
182        hex::encode(tag.as_ref())
183    }
184
185    /// Signs a request and generates authentication headers.
186    ///
187    /// # Deribit Authentication Scheme
188    ///
189    /// ```text
190    /// RequestData = UPPERCASE(HTTP_METHOD) + "\n" + URI + "\n" + RequestBody + "\n"
191    /// StringToSign = Timestamp + "\n" + Nonce + "\n" + RequestData
192    /// Signature = HEX_STRING(HMAC-SHA256(ClientSecret, StringToSign))
193    /// Authorization: deri-hmac-sha256 id={ClientId},ts={Timestamp},nonce={Nonce},sig={Signature}
194    /// ```
195    ///
196    /// # Errors
197    ///
198    /// Returns an error if credentials are not configured.
199    pub fn sign_auth_headers(
200        &self,
201        method: &str,
202        uri: &str,
203        body: &[u8],
204    ) -> Result<HashMap<String, String>, DeribitHttpError> {
205        // Generate timestamp (milliseconds since UNIX epoch)
206        let timestamp = get_atomic_clock_realtime().get_time_ms() as i64;
207
208        // Generate random nonce (UUID v4)
209        let nonce_uuid = UUID4::new();
210        let nonce = nonce_uuid.as_str();
211
212        // Build RequestData per Deribit specification
213        let request_data = format!(
214            "{}\n{}\n{}\n",
215            method.to_uppercase(),
216            uri,
217            String::from_utf8_lossy(body)
218        );
219
220        // Sign the request
221        let signature = self.sign_message(timestamp, nonce, &request_data);
222
223        // Build Authorization header
224        let auth_header = format!(
225            "deri-hmac-sha256 id={},ts={},nonce={},sig={}",
226            self.api_key(),
227            timestamp,
228            nonce,
229            signature
230        );
231
232        let mut headers = HashMap::new();
233        headers.insert("Authorization".to_string(), auth_header);
234
235        Ok(headers)
236    }
237}
238
239#[cfg(test)]
240mod tests {
241    use rstest::rstest;
242
243    use super::*;
244
245    #[rstest]
246    #[case("test_api_key", "test_api_secret")]
247    #[case("my_key", "my_secret")]
248    fn test_credential_creation(#[case] api_key: &str, #[case] api_secret: &str) {
249        let credential = Credential::new(api_key.to_string(), api_secret.to_string());
250
251        assert_eq!(credential.api_key(), api_key);
252    }
253
254    #[rstest]
255    fn test_signature_generation() {
256        let credential = Credential::new(
257            "test_client_id".to_string(),
258            "test_client_secret".to_string(),
259        );
260
261        let timestamp = 1609459200000i64;
262        let nonce = "550e8400-e29b-41d4-a716-446655440000";
263        let request_data = "POST\n/api/v2\n{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"private/get_account_summaries\",\"params\":{}}\n";
264
265        let signature = credential.sign_message(timestamp, nonce, request_data);
266
267        // Verify it's a valid hex string
268        assert!(
269            signature.chars().all(|c| c.is_ascii_hexdigit()),
270            "Signature should be hex-encoded"
271        );
272
273        // SHA256 produces 32 bytes = 64 hex characters
274        assert_eq!(
275            signature.len(),
276            64,
277            "HMAC-SHA256 should produce 64 hex characters"
278        );
279
280        // Verify signature is deterministic
281        let signature2 = credential.sign_message(timestamp, nonce, request_data);
282        assert_eq!(signature, signature2, "Signature should be deterministic");
283    }
284
285    #[rstest]
286    #[case(1000, 2000)]
287    #[case(1000, 5000)]
288    fn test_signature_changes_with_timestamp(#[case] ts1: i64, #[case] ts2: i64) {
289        let credential = Credential::new("key".to_string(), "secret".to_string());
290        let nonce = "nonce";
291        let request_data = "POST\n/api/v2\n{}\n";
292
293        let sig1 = credential.sign_message(ts1, nonce, request_data);
294        let sig2 = credential.sign_message(ts2, nonce, request_data);
295
296        assert_ne!(sig1, sig2, "Signature should change with timestamp");
297    }
298
299    #[rstest]
300    #[case("nonce1", "nonce2")]
301    #[case("abc", "xyz")]
302    fn test_signature_changes_with_nonce(#[case] nonce1: &str, #[case] nonce2: &str) {
303        let credential = Credential::new("key".to_string(), "secret".to_string());
304        let timestamp = 1000;
305        let request_data = "POST\n/api/v2\n{}\n";
306
307        let sig1 = credential.sign_message(timestamp, nonce1, request_data);
308        let sig2 = credential.sign_message(timestamp, nonce2, request_data);
309
310        assert_ne!(sig1, sig2, "Signature should change with nonce");
311    }
312
313    #[rstest]
314    #[case("POST\n/api/v2\n{\"a\":1}\n", "POST\n/api/v2\n{\"b\":2}\n")]
315    #[case("GET\n/test\n\n", "POST\n/test\n\n")]
316    fn test_signature_changes_with_request_data(#[case] data1: &str, #[case] data2: &str) {
317        let credential = Credential::new("key".to_string(), "secret".to_string());
318        let timestamp = 1000;
319        let nonce = "nonce";
320
321        let sig1 = credential.sign_message(timestamp, nonce, data1);
322        let sig2 = credential.sign_message(timestamp, nonce, data2);
323
324        assert_ne!(sig1, sig2, "Signature should change with request data");
325    }
326
327    #[rstest]
328    fn test_debug_redacts_secret() {
329        let credential = Credential::new("my_api_key".to_string(), "super_secret".to_string());
330
331        let debug_output = format!("{credential:?}");
332
333        assert_eq!(debug_output.matches(REDACTED).count(), 2);
334        assert!(
335            !debug_output.contains("super_secret"),
336            "Debug output should not contain raw secret"
337        );
338        assert!(!debug_output.contains("my_api_key"));
339    }
340
341    #[rstest]
342    #[case("short")]
343    #[case("xyz")]
344    fn test_api_key_masked_short_key(#[case] key: &str) {
345        let credential = Credential::new(key.to_string(), "secret".to_string());
346        let masked = credential.api_key_masked();
347
348        // Short keys should be masked differently (likely all asterisks)
349        assert_ne!(masked, key, "Short key should be masked");
350    }
351
352    #[rstest]
353    #[case("abcdefgh-1234-5678-ijkl", "abcd", "ijkl")]
354    #[case("very-long-api-key-12345", "very", "2345")]
355    fn test_api_key_masked_long_key(#[case] key: &str, #[case] start: &str, #[case] end: &str) {
356        let credential = Credential::new(key.to_string(), "secret".to_string());
357        let masked = credential.api_key_masked();
358
359        // Should show first 4 and last 4 characters
360        assert!(
361            masked.starts_with(start),
362            "Masked key should start with first 4 chars"
363        );
364        assert!(
365            masked.ends_with(end),
366            "Masked key should end with last 4 chars"
367        );
368        assert!(masked.contains("..."), "Masked key should contain ellipsis");
369    }
370
371    #[rstest]
372    #[case("POST", "/api/v2", b"{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"private/get_account_summaries\",\"params\":{}}")]
373    #[case("GET", "/api/v2/public/test", b"")]
374    #[case(
375        "POST",
376        "/api/v2/private/buy",
377        b"{\"instrument_name\":\"BTC-PERPETUAL\",\"amount\":100}"
378    )]
379    fn test_sign_auth_headers(#[case] method: &str, #[case] uri: &str, #[case] body: &[u8]) {
380        let credential = Credential::new(
381            "test_client_id".to_string(),
382            "test_client_secret".to_string(),
383        );
384
385        let result = credential.sign_auth_headers(method, uri, body);
386
387        assert!(result.is_ok(), "Should successfully sign auth headers");
388
389        let headers = result.unwrap();
390
391        // Verify Authorization header exists
392        assert!(
393            headers.contains_key("Authorization"),
394            "Should contain Authorization header"
395        );
396
397        let auth_header = headers.get("Authorization").unwrap();
398
399        // Verify header format: deri-hmac-sha256 id=...,ts=...,nonce=...,sig=...
400        assert!(
401            auth_header.starts_with("deri-hmac-sha256 "),
402            "Authorization header should start with 'deri-hmac-sha256 '"
403        );
404
405        // Verify it contains all required components
406        assert!(
407            auth_header.contains("id=test_client_id"),
408            "Should contain client ID"
409        );
410        assert!(auth_header.contains("ts="), "Should contain timestamp");
411        assert!(auth_header.contains("nonce="), "Should contain nonce");
412        assert!(auth_header.contains("sig="), "Should contain signature");
413
414        // Verify signature is hex-encoded (64 characters after sig=)
415        let sig_part = auth_header.split("sig=").nth(1).unwrap();
416        assert_eq!(
417            sig_part.len(),
418            64,
419            "Signature should be 64 hex characters (HMAC-SHA256)"
420        );
421        assert!(
422            sig_part.chars().all(|c| c.is_ascii_hexdigit()),
423            "Signature should be hex-encoded"
424        );
425    }
426
427    #[rstest]
428    fn test_sign_auth_headers_changes_each_call() {
429        let credential = Credential::new("key".to_string(), "secret".to_string());
430
431        let method = "POST";
432        let uri = "/api/v2";
433        let body = b"{}";
434
435        let headers1 = credential.sign_auth_headers(method, uri, body).unwrap();
436        let headers2 = credential.sign_auth_headers(method, uri, body).unwrap();
437
438        let auth1 = headers1.get("Authorization").unwrap();
439        let auth2 = headers2.get("Authorization").unwrap();
440
441        let [nonce1, nonce2] = [auth1, auth2].map(|auth| {
442            auth.split(',')
443                .find(|part| part.starts_with("nonce="))
444                .unwrap()
445        });
446
447        assert_ne!(
448            nonce1, nonce2,
449            "Authorization nonces should differ between calls"
450        );
451    }
452
453    #[rstest]
454    fn test_sign_ws_auth_basic() {
455        let credential = Credential::new(
456            "test_client_id".to_string(),
457            "test_client_secret".to_string(),
458        );
459
460        let timestamp = 1576074319000u64;
461        let nonce = "1iqt2wls";
462        let data = "";
463
464        let signature = credential.sign_ws_auth(timestamp, nonce, data);
465
466        assert!(
467            signature.chars().all(|c| c.is_ascii_hexdigit()),
468            "Signature should be hex-encoded"
469        );
470        assert_eq!(
471            signature.len(),
472            64,
473            "HMAC-SHA256 should produce 64 hex characters"
474        );
475        let signature2 = credential.sign_ws_auth(timestamp, nonce, data);
476        assert_eq!(signature, signature2, "Signature should be deterministic");
477    }
478
479    #[rstest]
480    fn test_sign_ws_auth_with_known_values() {
481        // Test with known values from Deribit documentation example
482        // ClientSecret = "AMANDASECRECT", Timestamp = 1576074319000, Nonce = "1iqt2wls", Data = ""
483        // Expected signature from docs: 56590594f97921b09b18f166befe0d1319b198bbcdad7ca73382de2f88fe9aa1
484        let credential = Credential::new("AMANDA".to_string(), "AMANDASECRECT".to_string());
485
486        let timestamp = 1576074319000u64;
487        let nonce = "1iqt2wls";
488        let data = "";
489
490        let signature = credential.sign_ws_auth(timestamp, nonce, data);
491
492        assert_eq!(
493            signature, "56590594f97921b09b18f166befe0d1319b198bbcdad7ca73382de2f88fe9aa1",
494            "Signature should match Deribit documentation example"
495        );
496    }
497
498    #[rstest]
499    #[case(1000, 2000)]
500    #[case(1576074319000, 1576074320000)]
501    fn test_sign_ws_auth_changes_with_timestamp(#[case] ts1: u64, #[case] ts2: u64) {
502        let credential = Credential::new("key".to_string(), "secret".to_string());
503        let nonce = "nonce";
504        let data = "";
505
506        let sig1 = credential.sign_ws_auth(ts1, nonce, data);
507        let sig2 = credential.sign_ws_auth(ts2, nonce, data);
508
509        assert_ne!(sig1, sig2, "Signature should change with timestamp");
510    }
511
512    #[rstest]
513    #[case("nonce1", "nonce2")]
514    #[case("abc123", "xyz789")]
515    fn test_sign_ws_auth_changes_with_nonce(#[case] nonce1: &str, #[case] nonce2: &str) {
516        let credential = Credential::new("key".to_string(), "secret".to_string());
517        let timestamp = 1576074319000u64;
518        let data = "";
519
520        let sig1 = credential.sign_ws_auth(timestamp, nonce1, data);
521        let sig2 = credential.sign_ws_auth(timestamp, nonce2, data);
522
523        assert_ne!(sig1, sig2, "Signature should change with nonce");
524    }
525
526    #[rstest]
527    fn test_resolve_with_both_credentials() {
528        let result = Credential::resolve_with_env_fallback(
529            Some("key".to_string()),
530            Some("secret".to_string()),
531            DeribitEnvironment::Mainnet,
532            false,
533        );
534
535        assert!(result.is_ok());
536        let credential = result.unwrap();
537        assert!(credential.is_some());
538        assert_eq!(credential.unwrap().api_key(), "key");
539    }
540
541    #[rstest]
542    fn test_resolve_with_no_credentials_no_fallback() {
543        let result =
544            Credential::resolve_with_env_fallback(None, None, DeribitEnvironment::Mainnet, false);
545
546        assert!(result.is_ok());
547        assert!(result.unwrap().is_none());
548    }
549
550    #[rstest]
551    fn test_resolve_partial_key_only_returns_error() {
552        let result = Credential::resolve_with_env_fallback(
553            Some("key".to_string()),
554            None,
555            DeribitEnvironment::Mainnet,
556            false,
557        );
558
559        assert!(result.is_err());
560        assert!(matches!(
561            result.unwrap_err(),
562            CredentialError::MissingSecret
563        ));
564    }
565
566    #[rstest]
567    fn test_resolve_partial_secret_only_returns_error() {
568        let result = Credential::resolve_with_env_fallback(
569            None,
570            Some("secret".to_string()),
571            DeribitEnvironment::Mainnet,
572            false,
573        );
574
575        assert!(result.is_err());
576        assert!(matches!(result.unwrap_err(), CredentialError::MissingKey));
577    }
578}