1use laravel::rate_limit::{self, Limit};
9use laravel::time::ToSpan;
10
11use crate::error::LivewireError;
12use crate::snapshot::Snapshot;
13
14pub const MAX_FAILURES: u32 = 10;
16
17#[must_use]
23pub fn limit() -> Limit {
24 Limit::per(MAX_FAILURES, 10.minutes())
25}
26
27#[must_use]
29pub fn rate_limit_key(ip: &str) -> String {
30 format!("livewire-checksum-failures:{ip}")
31}
32
33#[must_use]
35pub fn sign(snapshot: &Snapshot, key: &[u8]) -> String {
36 laravel_core::crypt::hmac::sign(key, [snapshot.signed_bytes()])
37}
38
39#[must_use]
41pub fn verify(snapshot: &Snapshot, key: &[u8]) -> bool {
42 laravel_core::crypt::hmac::verify(key, [snapshot.signed_bytes()], &snapshot.checksum)
43}
44
45pub 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
58pub 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
77pub async fn record_failure(ip: &str) -> Result<(), laravel::Error> {
83 rate_limit::hit(&rate_limit_key(ip), limit()).await
84}
85
86pub 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}