footing 0.6.5

Feature-gated foundations for Rust backend services
Documentation
use serde::{Serialize, de::DeserializeOwned};

use super::{
    CursorError, MIN_CURSOR_SECRET_BYTES,
    cursor::{
        decode_cursor_with_kind, encode_cursor_with_kind, validate_cursor_kind,
        validate_cursor_length,
    },
};

use crate::signing::SigningKeys;

const SIGNING_DOMAIN: &[u8] = b"footing:signed-cursor:v1\0";

#[derive(Debug, Clone)]
/// Codec for signed cursors, cryptographically separated from signed tokens.
///
/// Cursors signed without the purpose prefix are rejected and must be reissued.
pub struct SignedCursorCodec {
    keys: SigningKeys,
}

impl SignedCursorCodec {
    /// Creates a new instance.
    pub fn new(key: impl AsRef<[u8]>) -> Result<Self, CursorError> {
        Ok(Self {
            keys: SigningKeys::new(key).map_err(|_| CursorError::InvalidSecret {
                min_bytes: MIN_CURSOR_SECRET_BYTES,
            })?,
        })
    }

    /// Configures previous key and returns the updated value.
    pub fn with_previous_key(mut self, key: impl AsRef<[u8]>) -> Result<Self, CursorError> {
        self.keys
            .add_previous(key)
            .map_err(|_| CursorError::InvalidSecret {
                min_bytes: MIN_CURSOR_SECRET_BYTES,
            })?;
        Ok(self)
    }

    /// Configures previous keys and returns the updated value.
    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 = self.with_previous_key(key)?;
        }

        Ok(self)
    }

    /// Encodes the value.
    pub fn encode<T>(&self, value: &T) -> Result<String, CursorError>
    where
        T: Serialize + ?Sized,
    {
        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 + ?Sized,
    {
        let kind = kind.into();
        validate_cursor_kind(&kind)?;
        self.encode_with_kind(Some(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 + ?Sized,
    {
        let payload = encode_cursor_with_kind(kind, value)?;
        let signature = self
            .keys
            .sign(&[SIGNING_DOMAIN, payload.as_bytes()])
            .map_err(|_| CursorError::InvalidSignature)?;
        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.keys
            .verify(&[SIGNING_DOMAIN, payload.as_bytes()], signature)
            .map_err(|_| CursorError::InvalidSignature)?;
        decode_cursor_with_kind(expected_kind, payload)
    }
}