footing 0.1.5

Feature-gated foundations for Rust backend services
Documentation
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)]
/// Codec for signed cursor.
pub struct SignedCursorCodec {
    active_secret: Zeroizing<Vec<u8>>,
    previous_secrets: Vec<Zeroizing<Vec<u8>>>,
}

impl SignedCursorCodec {
    /// Creates a new instance.
    pub fn new(secret: impl AsRef<[u8]>) -> Result<Self, CursorError> {
        Ok(Self {
            active_secret: validate_cursor_secret(secret)?,
            previous_secrets: Vec::new(),
        })
    }

    /// Configures previous secret and returns the updated value.
    pub fn with_previous_secret(mut self, secret: impl AsRef<[u8]>) -> Result<Self, CursorError> {
        self.previous_secrets.push(validate_cursor_secret(secret)?);
        Ok(self)
    }

    /// Configures previous secrets and returns the updated value.
    pub fn with_previous_secrets<I, S>(mut self, secrets: I) -> Result<Self, CursorError>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<[u8]>,
    {
        for secret in secrets {
            self.previous_secrets.push(validate_cursor_secret(secret)?);
        }

        Ok(self)
    }

    /// Encodes the value.
    pub fn encode<T>(&self, value: &T) -> Result<String, CursorError>
    where
        T: Serialize,
    {
        self.encode_with_kind(None, value)
    }

    /// Decodes the value.
    pub fn decode<T>(&self, cursor: &str) -> Result<T, CursorError>
    where
        T: DeserializeOwned,
    {
        self.decode_with_kind(None, cursor)
    }

    /// Encodes typed.
    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)
    }

    /// Decodes typed.
    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_secret.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_secret.as_slice(), payload, signature).is_ok() {
            return Ok(());
        }

        if self
            .previous_secrets
            .iter()
            .any(|secret| verify_signature(secret.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_secret", &RedactedBytes(self.active_secret.len()))
            .field("previous_secret_count", &self.previous_secrets.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_secret(secret: impl AsRef<[u8]>) -> Result<Zeroizing<Vec<u8>>, CursorError> {
    let secret = secret.as_ref();
    if secret.len() < MIN_CURSOR_SECRET_BYTES {
        return Err(CursorError::InvalidSecret {
            min_bytes: MIN_CURSOR_SECRET_BYTES,
        });
    }

    Ok(Zeroizing::new(secret.to_vec()))
}

fn sign(secret: &[u8], payload: &[u8]) -> Result<String, CursorError> {
    let mut mac = HmacSha256::new_from_slice(secret).map_err(|_| CursorError::InvalidSignature)?;
    mac.update(payload);
    Ok(URL_SAFE_NO_PAD.encode(mac.finalize().into_bytes()))
}

fn verify_signature(secret: &[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(secret).map_err(|_| CursorError::InvalidSignature)?;
    mac.update(payload);
    mac.verify_slice(&expected)
        .map_err(|_| CursorError::InvalidSignature)
}