Skip to main content

livewire/
checksum.rs

1//! The checksum that proves a snapshot reached the server as the server sent it, and the rate limit
2//! that stops a client which keeps sending corrupt ones.
3//!
4//! The signature is HMAC-SHA256, in lowercase hex, under the application's encryption key, over
5//! [`Snapshot::signed_bytes`]. The child list is outside the signature because the browser rewrites
6//! it while morphing the DOM; every other part of the envelope is covered.
7
8use laravel::rate_limit::{self, Limit};
9use laravel::time::ToSpan;
10
11use crate::error::LivewireError;
12use crate::snapshot::Snapshot;
13
14/// How many corrupt snapshots one client may send before the rate limit stops it.
15pub const MAX_FAILURES: u32 = 10;
16
17/// Ten failures in ten minutes.
18///
19/// # Panics
20///
21/// Never: the count and the span are constants the limit accepts.
22#[must_use]
23pub fn limit() -> Limit {
24    Limit::per(MAX_FAILURES, 10.minutes())
25}
26
27/// The cache key of one client, `livewire-checksum-failures:{ip}`.
28#[must_use]
29pub fn rate_limit_key(ip: &str) -> String {
30    format!("livewire-checksum-failures:{ip}")
31}
32
33/// Signs the snapshot's `signed_bytes()` under the application's encryption key.
34#[must_use]
35pub fn sign(snapshot: &Snapshot, key: &[u8]) -> String {
36    laravel_core::crypt::hmac::sign(key, [snapshot.signed_bytes()])
37}
38
39/// Whether the snapshot's checksum matches, compared in constant time.
40#[must_use]
41pub fn verify(snapshot: &Snapshot, key: &[u8]) -> bool {
42    laravel_core::crypt::hmac::verify(key, [snapshot.signed_bytes()], &snapshot.checksum)
43}
44
45/// Verifies or fails with `LivewireError::CorruptPayload`.
46///
47/// # Errors
48///
49/// [`LivewireError::CorruptPayload`] when [`verify`] rejects the snapshot.
50pub fn verify_or_error(snapshot: &Snapshot, key: &[u8]) -> Result<(), LivewireError> {
51    if verify(snapshot, key) {
52        Ok(())
53    } else {
54        Err(LivewireError::CorruptPayload)
55    }
56}
57
58/// Fails with `TooManyChecksumFailures` when the client is over the limit.
59///
60/// The check reads the cache, so it needs a running application. A cache that cannot be read does
61/// not block the request: the limit is a guard against abuse, and failing closed would turn a cache
62/// outage into a broken update endpoint.
63///
64/// # Errors
65///
66/// [`LivewireError::TooManyChecksumFailures`] when the client has used up the limit.
67pub async fn ensure_allowed(ip: &str) -> Result<(), LivewireError> {
68    match rate_limit::check(&rate_limit_key(ip), limit()).await {
69        Ok(Ok(_)) => Ok(()),
70        Ok(Err(too_many)) => Err(LivewireError::TooManyChecksumFailures {
71            retry_after: too_many.retry_after().as_secs().max(1),
72        }),
73        Err(_) => Ok(()),
74    }
75}
76
77/// Counts one corrupt snapshot for the client.
78///
79/// # Errors
80///
81/// Fails when the cache store cannot be written.
82pub async fn record_failure(ip: &str) -> Result<(), laravel::Error> {
83    rate_limit::hit(&rate_limit_key(ip), limit()).await
84}
85
86/// Forgets a client's failures, which the tests use.
87///
88/// # Errors
89///
90/// Fails when the cache store cannot be written.
91pub async fn reset(ip: &str) -> Result<(), laravel::Error> {
92    rate_limit::clear(&rate_limit_key(ip)).await
93}
94
95#[cfg(test)]
96mod tests {
97    use super::*;
98    use serde_json::{Map, Value, json};
99
100    const KEY: &[u8] = b"the application encryption key";
101
102    fn object(value: Value) -> Map<String, Value> {
103        match value {
104            Value::Object(map) => map,
105            other => panic!("expected a JSON object, got {other}"),
106        }
107    }
108
109    fn snapshot() -> Snapshot {
110        Snapshot {
111            data: object(json!({"count": 0})),
112            memo: object(json!({"id": "abc", "name": "counter", "children": {}})),
113            checksum: String::new(),
114        }
115    }
116
117    fn signed() -> Snapshot {
118        let mut snapshot = snapshot();
119        snapshot.checksum = sign(&snapshot, KEY);
120
121        snapshot
122    }
123
124    #[test]
125    fn signs_and_verifies_a_snapshot() {
126        let snapshot = signed();
127
128        assert_eq!(snapshot.checksum, sign(&snapshot, KEY));
129        assert!(verify(&snapshot, KEY));
130        assert_eq!(verify_or_error(&snapshot, KEY), Ok(()));
131    }
132
133    #[test]
134    fn signs_lowercase_hex() {
135        let checksum = sign(&snapshot(), KEY);
136
137        assert_eq!(checksum.len(), 64);
138        assert!(
139            checksum
140                .chars()
141                .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase())
142        );
143    }
144
145    #[test]
146    fn tampering_with_data_fails_verification() {
147        let mut snapshot = signed();
148        snapshot.data.insert("count".into(), json!(1));
149
150        assert!(!verify(&snapshot, KEY));
151        assert_eq!(verify_or_error(&snapshot, KEY), Err(LivewireError::CorruptPayload));
152    }
153
154    #[test]
155    fn tampering_with_the_children_still_verifies() {
156        let mut snapshot = signed();
157        snapshot.set_children(object(json!({
158            "nested": ["div", "another-id"]
159        })));
160
161        assert!(verify(&snapshot, KEY));
162    }
163
164    #[test]
165    fn a_wrong_key_fails_verification() {
166        assert!(!verify(&signed(), b"another key"));
167    }
168
169    #[test]
170    fn the_limit_is_ten_failures_in_ten_minutes() {
171        assert_eq!(limit().max(), MAX_FAILURES);
172        assert_eq!(limit().millis(), 600_000);
173    }
174
175    #[test]
176    fn the_key_names_the_client() {
177        assert_eq!(rate_limit_key("203.0.113.7"), "livewire-checksum-failures:203.0.113.7");
178    }
179}