use std::fmt;
use std::sync::Arc;
use std::sync::atomic::{AtomicI64, Ordering};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use ring::rand::SecureRandom;
use crate::auth::{ApiKeyAuthenticator, AuthRequest, Authenticator, REDACTED};
use crate::error::Result;
pub const SIGNING_SCHEME: &str = "CEXY-HMAC-SHA256-v1";
pub const MAX_CLOCK_OFFSET: Duration = Duration::from_secs(60 * 60);
fn is_unreserved(b: u8) -> bool {
b.is_ascii_alphanumeric() || b"-._~".contains(&b)
}
pub(crate) fn encode_bytes(bytes: &[u8]) -> String {
let mut out = String::with_capacity(bytes.len());
for &b in bytes {
if is_unreserved(b) {
out.push(b as char);
} else {
out.push_str(&format!("%{b:02X}"));
}
}
out
}
fn percent_decode(s: &str) -> Vec<u8> {
let raw = s.as_bytes();
let mut out = Vec::with_capacity(raw.len());
let mut i = 0;
while i < raw.len() {
if raw[i] == b'%'
&& i + 2 < raw.len()
&& raw[i + 1].is_ascii_hexdigit()
&& raw[i + 2].is_ascii_hexdigit()
{
let hex = std::str::from_utf8(&raw[i + 1..i + 3]).expect("ascii");
out.push(u8::from_str_radix(hex, 16).expect("hex"));
i += 3;
continue;
}
out.push(raw[i]);
i += 1;
}
out
}
pub(crate) fn canonical_path(path: &str) -> String {
path.split('/')
.map(|seg| encode_bytes(&percent_decode(seg)))
.collect::<Vec<_>>()
.join("/")
}
pub(crate) fn canonical_query(query: &str) -> String {
let mut pairs: Vec<(String, String)> = query
.split('&')
.filter(|part| !part.is_empty()) .map(|part| {
let (name, value) = part.split_once('=').unwrap_or((part, ""));
(
encode_bytes(&percent_decode(name)),
encode_bytes(&percent_decode(value)),
)
})
.collect();
pairs.sort();
pairs
.into_iter()
.map(|(n, v)| format!("{n}={v}"))
.collect::<Vec<_>>()
.join("&")
}
fn hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
pub(crate) fn sha256_hex(data: &[u8]) -> String {
hex(ring::digest::digest(&ring::digest::SHA256, data).as_ref())
}
pub(crate) fn hmac_hex(secret: &str, message: &str) -> String {
let key = ring::hmac::Key::new(ring::hmac::HMAC_SHA256, secret.as_bytes());
hex(ring::hmac::sign(&key, message.as_bytes()).as_ref())
}
pub(crate) fn canonical_request(
method: &str,
path: &str,
query: &str,
timestamp: &str,
nonce: &str,
body: &[u8],
) -> String {
[
SIGNING_SCHEME,
&method.to_uppercase(),
&canonical_path(path),
&canonical_query(query),
timestamp,
nonce,
&sha256_hex(body),
]
.join("\n")
}
pub(crate) fn encode_query(pairs: &[(&str, String)]) -> String {
pairs
.iter()
.map(|(k, v)| {
format!(
"{}={}",
encode_bytes(k.as_bytes()),
encode_bytes(v.as_bytes())
)
})
.collect::<Vec<_>>()
.join("&")
}
pub(crate) fn new_nonce() -> String {
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
let mut b = [0u8; 16];
ring::rand::SystemRandom::new()
.fill(&mut b)
.expect("the system random number generator failed");
let mut out = String::with_capacity(22);
for chunk in b.chunks(3) {
let n = chunk
.iter()
.enumerate()
.fold(0u32, |acc, (i, &x)| acc | (u32::from(x) << (16 - 8 * i)));
let chars = chunk.len() + 1;
for i in 0..chars {
out.push(ALPHABET[((n >> (18 - 6 * i)) & 63) as usize] as char);
}
}
out
}
type NowMs = Arc<dyn Fn() -> i64 + Send + Sync>;
type Nonce = Arc<dyn Fn() -> String + Send + Sync>;
fn system_now_ms() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_millis() as i64)
.unwrap_or(0)
}
#[derive(Clone)]
pub struct HmacAuthenticator {
key: String,
secret: String,
offset_ms: Arc<AtomicI64>,
now: NowMs,
nonce: Nonce,
}
impl HmacAuthenticator {
pub fn new(api_key: impl Into<String>, api_secret: impl Into<String>) -> Result<Self> {
let (key, secret) = (api_key.into(), api_secret.into());
ApiKeyAuthenticator::new(key.clone(), secret.clone())?;
Ok(HmacAuthenticator {
key,
secret,
offset_ms: Arc::new(AtomicI64::new(0)),
now: Arc::new(system_now_ms),
nonce: Arc::new(new_nonce),
})
}
#[cfg(test)]
pub(crate) fn with_sources(mut self, now: NowMs, nonce: Option<Nonce>) -> Self {
self.now = now;
if let Some(n) = nonce {
self.nonce = n;
}
self
}
pub fn clock_offset_ms(&self) -> i64 {
self.offset_ms.load(Ordering::SeqCst)
}
pub fn key_hint(&self) -> String {
let head: String = self.key.chars().take(6).collect();
format!("{head}…")
}
}
impl Authenticator for HmacAuthenticator {
fn kind(&self) -> &str {
"hmac"
}
fn authenticate(&self, request: &mut AuthRequest<'_>) -> Result<()> {
let ts = ((self.now)() + self.offset_ms.load(Ordering::SeqCst)).to_string();
let nonce = (self.nonce)();
let canonical = canonical_request(
request.method,
request.url.path(),
request.url.query().unwrap_or(""),
&ts,
&nonce,
request.body.unwrap_or(&[]),
);
request.set_header("X-API-Key", self.key.clone());
request.set_header("X-API-Timestamp", ts);
request.set_header("X-API-Nonce", nonce);
request.set_header("X-API-Signature", hmac_hex(&self.secret, &canonical));
Ok(())
}
fn redact(&self, text: &str) -> String {
let mut out = text.to_string();
for s in [&self.secret, &self.key] {
if !s.is_empty() {
out = out.replace(s.as_str(), REDACTED);
}
}
out
}
fn adjust_clock(&self, server_time_ms: i64) -> Option<bool> {
let offset = server_time_ms - (self.now)();
if offset.unsigned_abs() > MAX_CLOCK_OFFSET.as_millis() as u64 {
return Some(false);
}
self.offset_ms.store(offset, Ordering::SeqCst);
Some(true)
}
fn sign_websocket_challenge(
&self,
connection_id: &str,
challenge: &str,
) -> Option<(String, String)> {
Some((
self.key.clone(),
hmac_hex(
&self.secret,
&format!("CEXY-WS-AUTH-v1\n{connection_id}\n{challenge}"),
),
))
}
}
impl fmt::Display for HmacAuthenticator {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"HmacAuthenticator({}, secret={REDACTED})",
self.key_hint()
)
}
}
impl fmt::Debug for HmacAuthenticator {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}