use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use hmac::{Hmac, KeyInit, Mac};
use serde::{Serialize, de::DeserializeOwned};
use sha2::Sha256;
use zeroize::Zeroizing;
use super::{
CursorError, MIN_CURSOR_SECRET_BYTES,
cursor::{
decode_cursor_with_kind, encode_cursor_with_kind, validate_cursor_kind,
validate_cursor_length,
},
};
type HmacSha256 = Hmac<Sha256>;
#[derive(Clone)]
pub struct SignedCursorCodec {
active_key: Zeroizing<Vec<u8>>,
previous_keys: Vec<Zeroizing<Vec<u8>>>,
}
impl SignedCursorCodec {
pub fn with_previous_secret(self, key: impl AsRef<[u8]>) -> Result<Self, CursorError> {
self.with_previous_key(key)
}
pub fn with_previous_secrets<I, K>(self, keys: I) -> Result<Self, CursorError>
where
I: IntoIterator<Item = K>,
K: AsRef<[u8]>,
{
self.with_previous_keys(keys)
}
pub fn new(key: impl AsRef<[u8]>) -> Result<Self, CursorError> {
Ok(Self {
active_key: validate_cursor_key(key)?,
previous_keys: Vec::new(),
})
}
pub fn with_previous_key(mut self, key: impl AsRef<[u8]>) -> Result<Self, CursorError> {
self.previous_keys.push(validate_cursor_key(key)?);
Ok(self)
}
pub fn with_previous_keys<I, S>(mut self, keys: I) -> Result<Self, CursorError>
where
I: IntoIterator<Item = S>,
S: AsRef<[u8]>,
{
for key in keys {
self.previous_keys.push(validate_cursor_key(key)?);
}
Ok(self)
}
pub fn encode<T>(&self, value: &T) -> Result<String, CursorError>
where
T: Serialize,
{
self.encode_with_kind(None, value)
}
pub fn decode<T>(&self, cursor: &str) -> Result<T, CursorError>
where
T: DeserializeOwned,
{
self.decode_with_kind(None, cursor)
}
pub fn encode_typed<T>(&self, kind: impl Into<String>, value: &T) -> Result<String, CursorError>
where
T: Serialize,
{
self.encode_with_kind(Some(validate_cursor_kind(kind)?), value)
}
pub fn decode_typed<T>(&self, kind: &str, cursor: &str) -> Result<T, CursorError>
where
T: DeserializeOwned,
{
validate_cursor_kind(kind)?;
self.decode_with_kind(Some(kind), cursor)
}
fn encode_with_kind<T>(&self, kind: Option<String>, value: &T) -> Result<String, CursorError>
where
T: Serialize,
{
let payload = encode_cursor_with_kind(kind, value)?;
let signature = sign(self.active_key.as_slice(), payload.as_bytes())?;
let cursor = format!("{payload}.{signature}");
validate_cursor_length(&cursor)?;
Ok(cursor)
}
fn decode_with_kind<T>(
&self,
expected_kind: Option<&str>,
cursor: &str,
) -> Result<T, CursorError>
where
T: DeserializeOwned,
{
validate_cursor_length(cursor)?;
let (payload, signature) = cursor
.split_once('.')
.ok_or(CursorError::InvalidSignature)?;
self.verify(payload.as_bytes(), signature)?;
decode_cursor_with_kind(expected_kind, payload)
}
fn verify(&self, payload: &[u8], signature: &str) -> Result<(), CursorError> {
if verify_signature(self.active_key.as_slice(), payload, signature).is_ok() {
return Ok(());
}
if self
.previous_keys
.iter()
.any(|key| verify_signature(key.as_slice(), payload, signature).is_ok())
{
return Ok(());
}
Err(CursorError::InvalidSignature)
}
}
impl std::fmt::Debug for SignedCursorCodec {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("SignedCursorCodec")
.field("active_key", &RedactedBytes(self.active_key.len()))
.field("previous_secret_count", &self.previous_keys.len())
.finish()
}
}
struct RedactedBytes(usize);
impl std::fmt::Debug for RedactedBytes {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(formatter, "<redacted:{} bytes>", self.0)
}
}
fn validate_cursor_key(key: impl AsRef<[u8]>) -> Result<Zeroizing<Vec<u8>>, CursorError> {
let key = key.as_ref();
if key.len() < MIN_CURSOR_SECRET_BYTES {
return Err(CursorError::InvalidSecret {
min_bytes: MIN_CURSOR_SECRET_BYTES,
});
}
Ok(Zeroizing::new(key.to_vec()))
}
fn sign(key: &[u8], payload: &[u8]) -> Result<String, CursorError> {
let mut mac = HmacSha256::new_from_slice(key).map_err(|_| CursorError::InvalidSignature)?;
mac.update(payload);
Ok(URL_SAFE_NO_PAD.encode(mac.finalize().into_bytes()))
}
fn verify_signature(key: &[u8], payload: &[u8], signature: &str) -> Result<(), CursorError> {
let expected = URL_SAFE_NO_PAD
.decode(signature)
.map_err(|_| CursorError::InvalidSignature)?;
let mut mac = HmacSha256::new_from_slice(key).map_err(|_| CursorError::InvalidSignature)?;
mac.update(payload);
mac.verify_slice(&expected)
.map_err(|_| CursorError::InvalidSignature)
}