livewire-rust 0.1.3

Livewire for Rust: server-rendered reactive components for Laravel for Rust.
Documentation
//! The checksum that proves a snapshot reached the server as the server sent it, and the rate limit
//! that stops a client which keeps sending corrupt ones.
//!
//! The signature is HMAC-SHA256, in lowercase hex, under the application's encryption key, over
//! [`Snapshot::signed_bytes`]. The child list is outside the signature because the browser rewrites
//! it while morphing the DOM; every other part of the envelope is covered.

use laravel::rate_limit::{self, Limit};
use laravel::time::ToSpan;

use crate::error::LivewireError;
use crate::snapshot::Snapshot;

/// How many corrupt snapshots one client may send before the rate limit stops it.
pub const MAX_FAILURES: u32 = 10;

/// Ten failures in ten minutes.
///
/// # Panics
///
/// Never: the count and the span are constants the limit accepts.
#[must_use]
pub fn limit() -> Limit {
    Limit::per(MAX_FAILURES, 10.minutes())
}

/// The cache key of one client, `livewire-checksum-failures:{ip}`.
#[must_use]
pub fn rate_limit_key(ip: &str) -> String {
    format!("livewire-checksum-failures:{ip}")
}

/// Signs the snapshot's `signed_bytes()` under the application's encryption key.
#[must_use]
pub fn sign(snapshot: &Snapshot, key: &[u8]) -> String {
    laravel_core::crypt::hmac::sign(key, [snapshot.signed_bytes()])
}

/// Whether the snapshot's checksum matches, compared in constant time.
#[must_use]
pub fn verify(snapshot: &Snapshot, key: &[u8]) -> bool {
    laravel_core::crypt::hmac::verify(key, [snapshot.signed_bytes()], &snapshot.checksum)
}

/// Verifies or fails with `LivewireError::CorruptPayload`.
///
/// # Errors
///
/// [`LivewireError::CorruptPayload`] when [`verify`] rejects the snapshot.
pub fn verify_or_error(snapshot: &Snapshot, key: &[u8]) -> Result<(), LivewireError> {
    if verify(snapshot, key) {
        Ok(())
    } else {
        Err(LivewireError::CorruptPayload)
    }
}

/// Fails with `TooManyChecksumFailures` when the client is over the limit.
///
/// The check reads the cache, so it needs a running application. A cache that cannot be read does
/// not block the request: the limit is a guard against abuse, and failing closed would turn a cache
/// outage into a broken update endpoint.
///
/// # Errors
///
/// [`LivewireError::TooManyChecksumFailures`] when the client has used up the limit.
pub async fn ensure_allowed(ip: &str) -> Result<(), LivewireError> {
    match rate_limit::check(&rate_limit_key(ip), limit()).await {
        Ok(Ok(_)) => Ok(()),
        Ok(Err(too_many)) => Err(LivewireError::TooManyChecksumFailures {
            retry_after: too_many.retry_after().as_secs().max(1),
        }),
        Err(_) => Ok(()),
    }
}

/// Counts one corrupt snapshot for the client.
///
/// # Errors
///
/// Fails when the cache store cannot be written.
pub async fn record_failure(ip: &str) -> Result<(), laravel::Error> {
    rate_limit::hit(&rate_limit_key(ip), limit()).await
}

/// Forgets a client's failures, which the tests use.
///
/// # Errors
///
/// Fails when the cache store cannot be written.
pub async fn reset(ip: &str) -> Result<(), laravel::Error> {
    rate_limit::clear(&rate_limit_key(ip)).await
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::{Map, Value, json};

    const KEY: &[u8] = b"the application encryption key";

    fn object(value: Value) -> Map<String, Value> {
        match value {
            Value::Object(map) => map,
            other => panic!("expected a JSON object, got {other}"),
        }
    }

    fn snapshot() -> Snapshot {
        Snapshot {
            data: object(json!({"count": 0})),
            memo: object(json!({"id": "abc", "name": "counter", "children": {}})),
            checksum: String::new(),
        }
    }

    fn signed() -> Snapshot {
        let mut snapshot = snapshot();
        snapshot.checksum = sign(&snapshot, KEY);

        snapshot
    }

    #[test]
    fn signs_and_verifies_a_snapshot() {
        let snapshot = signed();

        assert_eq!(snapshot.checksum, sign(&snapshot, KEY));
        assert!(verify(&snapshot, KEY));
        assert_eq!(verify_or_error(&snapshot, KEY), Ok(()));
    }

    #[test]
    fn signs_lowercase_hex() {
        let checksum = sign(&snapshot(), KEY);

        assert_eq!(checksum.len(), 64);
        assert!(
            checksum
                .chars()
                .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase())
        );
    }

    #[test]
    fn tampering_with_data_fails_verification() {
        let mut snapshot = signed();
        snapshot.data.insert("count".into(), json!(1));

        assert!(!verify(&snapshot, KEY));
        assert_eq!(verify_or_error(&snapshot, KEY), Err(LivewireError::CorruptPayload));
    }

    #[test]
    fn tampering_with_the_children_still_verifies() {
        let mut snapshot = signed();
        snapshot.set_children(object(json!({
            "nested": ["div", "another-id"]
        })));

        assert!(verify(&snapshot, KEY));
    }

    #[test]
    fn a_wrong_key_fails_verification() {
        assert!(!verify(&signed(), b"another key"));
    }

    #[test]
    fn the_limit_is_ten_failures_in_ten_minutes() {
        assert_eq!(limit().max(), MAX_FAILURES);
        assert_eq!(limit().millis(), 600_000);
    }

    #[test]
    fn the_key_names_the_client() {
        assert_eq!(rate_limit_key("203.0.113.7"), "livewire-checksum-failures:203.0.113.7");
    }
}