1#![allow(unused_assignments)] use 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#[derive(Debug, Error)]
37pub enum CredentialError {
38 #[error("API key provided but secret is missing")]
40 MissingSecret,
41 #[error("API secret provided but key is missing")]
43 MissingKey,
44}
45
46#[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#[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 #[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 #[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 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 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 #[must_use]
141 pub fn api_key(&self) -> &str {
142 &self.api_key
143 }
144
145 #[must_use]
150 pub fn api_key_masked(&self) -> String {
151 nautilus_core::string::secret::mask_api_key(&self.api_key)
152 }
153
154 #[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 #[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 pub fn sign_auth_headers(
200 &self,
201 method: &str,
202 uri: &str,
203 body: &[u8],
204 ) -> Result<HashMap<String, String>, DeribitHttpError> {
205 let timestamp = get_atomic_clock_realtime().get_time_ms() as i64;
207
208 let nonce_uuid = UUID4::new();
210 let nonce = nonce_uuid.as_str();
211
212 let request_data = format!(
214 "{}\n{}\n{}\n",
215 method.to_uppercase(),
216 uri,
217 String::from_utf8_lossy(body)
218 );
219
220 let signature = self.sign_message(timestamp, nonce, &request_data);
222
223 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 assert!(
269 signature.chars().all(|c| c.is_ascii_hexdigit()),
270 "Signature should be hex-encoded"
271 );
272
273 assert_eq!(
275 signature.len(),
276 64,
277 "HMAC-SHA256 should produce 64 hex characters"
278 );
279
280 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 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 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 assert!(
393 headers.contains_key("Authorization"),
394 "Should contain Authorization header"
395 );
396
397 let auth_header = headers.get("Authorization").unwrap();
398
399 assert!(
401 auth_header.starts_with("deri-hmac-sha256 "),
402 "Authorization header should start with 'deri-hmac-sha256 '"
403 );
404
405 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 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 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}