use laravel::rate_limit::{self, Limit};
use laravel::time::ToSpan;
use crate::error::LivewireError;
use crate::snapshot::Snapshot;
pub const MAX_FAILURES: u32 = 10;
#[must_use]
pub fn limit() -> Limit {
Limit::per(MAX_FAILURES, 10.minutes())
}
#[must_use]
pub fn rate_limit_key(ip: &str) -> String {
format!("livewire-checksum-failures:{ip}")
}
#[must_use]
pub fn sign(snapshot: &Snapshot, key: &[u8]) -> String {
laravel_core::crypt::hmac::sign(key, [snapshot.signed_bytes()])
}
#[must_use]
pub fn verify(snapshot: &Snapshot, key: &[u8]) -> bool {
laravel_core::crypt::hmac::verify(key, [snapshot.signed_bytes()], &snapshot.checksum)
}
pub fn verify_or_error(snapshot: &Snapshot, key: &[u8]) -> Result<(), LivewireError> {
if verify(snapshot, key) {
Ok(())
} else {
Err(LivewireError::CorruptPayload)
}
}
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(()),
}
}
pub async fn record_failure(ip: &str) -> Result<(), laravel::Error> {
rate_limit::hit(&rate_limit_key(ip), limit()).await
}
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");
}
}