use crate::dao::GarrisonDao;
use crate::error::{GarrisonError, GarrisonResult};
use base64::{engine::general_purpose::STANDARD, Engine};
use hkdf::Hkdf;
use hmac::{KeyInit, Mac};
use sha2::Sha256;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
use super::{HmacSha256, SignHandler, DEFAULT_TIMESTAMP_WINDOW, HKDF_INFO, MIN_APP_SECRET_LEN};
impl SignHandler {
pub fn new(
app_key: impl Into<String>,
app_secret: impl Into<String>,
dao: Arc<dyn GarrisonDao>,
) -> GarrisonResult<Self> {
let app_key = app_key.into();
let app_secret = app_secret.into();
if app_key.is_empty() {
return Err(GarrisonError::Config("sign-app-key-empty::".to_string()));
}
if app_secret.len() < MIN_APP_SECRET_LEN {
return Err(GarrisonError::Config(format!(
"sign-app-secret-too-short::{}::{}",
app_secret.len(),
MIN_APP_SECRET_LEN
)));
}
let hkdf = Hkdf::<Sha256>::new(Some(app_key.as_bytes()), app_secret.as_bytes());
let mut derived_key = [0u8; 32];
hkdf.expand(HKDF_INFO, &mut derived_key)
.expect("HKDF expand 32 bytes must not fail");
Ok(Self {
app_key,
app_secret,
dao,
timestamp_window: DEFAULT_TIMESTAMP_WINDOW,
derived_key,
})
}
pub fn with_timestamp_window(mut self, seconds: i64) -> Self {
self.timestamp_window = seconds;
self
}
pub fn app_key(&self) -> &str {
&self.app_key
}
pub fn timestamp_window(&self) -> i64 {
self.timestamp_window
}
pub fn sign(
&self,
method: &str,
path: &str,
timestamp: i64,
nonce: &str,
body_sha256: &str,
) -> String {
let payload = format!(
"{}\n{}\n{}\n{}\n{}",
method, path, timestamp, nonce, body_sha256
);
let mut mac =
HmacSha256::new_from_slice(&self.derived_key).expect("HMAC accepts 32-byte key");
mac.update(payload.as_bytes());
STANDARD.encode(mac.finalize().into_bytes())
}
pub async fn validate(
&self,
method: &str,
path: &str,
timestamp: i64,
nonce: &str,
body_sha256: &str,
signature: &str,
) -> GarrisonResult<()> {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.map_err(|e| GarrisonError::Internal(format!("sign-clock::{}", e)))?;
let diff = now
.checked_sub(timestamp)
.ok_or_else(|| GarrisonError::ExpiredToken("sign-timestamp-window".to_string()))?;
if diff.abs() > self.timestamp_window {
return Err(GarrisonError::ExpiredToken(
"sign-timestamp-window".to_string(),
));
}
let nonce_key = format!("garrison:sign:nonce:{}:{}", self.app_key, nonce);
let count = self
.dao
.incr(&nonce_key, self.timestamp_window as u64)
.await?;
if count > 1 {
return Err(GarrisonError::InvalidToken("sign-nonce-replay".to_string()));
}
let payload = format!(
"{}\n{}\n{}\n{}\n{}",
method, path, timestamp, nonce, body_sha256
);
let mut mac =
HmacSha256::new_from_slice(&self.derived_key).expect("HMAC accepts 32-byte key");
mac.update(payload.as_bytes());
let signature_bytes = STANDARD
.decode(signature)
.map_err(|e| GarrisonError::InvalidToken(format!("sign-base64-decode::{}", e)))?;
match mac.verify_slice(&signature_bytes) {
Ok(_) => {},
Err(_) => {
return Err(GarrisonError::InvalidToken("sign-mismatch".to_string()));
},
}
Ok(())
}
}
#[cfg(feature = "protocol-zeroize")]
impl Drop for SignHandler {
fn drop(&mut self) {
use zeroize::Zeroize;
self.app_secret.zeroize();
self.derived_key.zeroize();
}
}