1use laravel::http::{Response, StatusCode};
9use serde_json::{Map, Value};
10
11#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
13pub enum LivewireError {
14 #[error("the request has no `X-Livewire` header")]
16 MissingHeader,
17 #[error("the request's content type is `{}`, not JSON", content_type.as_deref().unwrap_or("none"))]
19 NotJson {
20 content_type: Option<String>,
22 },
23 #[error("the request payload is malformed: {0}")]
25 MalformedPayload(String),
26 #[error("Invalid Livewire snapshot structure: expected [data], [memo], [checksum], [memo.id], and [memo.name].")]
28 InvalidSnapshot,
29 #[error("Unable to find the [{class}] model for the reference [{key}].")]
31 ModelNotFound {
32 class: String,
34 key: String,
36 },
37 #[error("A database query failed: {message}")]
39 Database {
40 message: String,
42 },
43 #[error("The given data was invalid.")]
46 ValidationFailed {
47 errors: Map<String, Value>,
49 },
50 #[error("The policy guarding [{method}] failed: {message}")]
53 PolicyFailed {
54 method: String,
56 message: String,
58 },
59 #[error("a call's parameters mix positional and named parameters")]
61 MixedParameters,
62 #[error("the snapshot's route context does not match the request: {0}")]
64 InvalidRouteContext(String),
65 #[error("a custom update URI is configured, so the default update route answers nothing")]
67 DefaultUpdateUriOverridden,
68 #[error(
70 "Livewire encountered corrupt data when trying to hydrate a component. \nEnsure that the [name, id, data] of the Livewire component wasn't tampered with between requests."
71 )]
72 CorruptPayload,
73 #[error(
75 "Livewire detected a release token mismatch. \nThis happens when a user's browser session has been invalidated by a new deployment."
76 )]
77 ReleaseTokenMismatch,
78 #[error("Unable to call component method. Public method [{method}] not found on component")]
80 MethodNotFound {
81 method: String,
83 },
84 #[error("Unable to update locked property [{property}] of component [{component}]")]
86 LockedProperty {
87 property: String,
89 component: String,
91 },
92 #[error("Unable to hydrate [{property}] into component [{component}]: {message}")]
94 HydrationFailed {
95 property: String,
97 component: String,
99 message: String,
101 },
102 #[error("Too many invalid Livewire requests. Please try again later.")]
104 TooManyChecksumFailures {
105 retry_after: u64,
107 },
108 #[error("Unable to find component: [{name}]")]
110 ComponentNotFound {
111 name: String,
113 },
114 #[error("Unable to find synthesizer with key: [{key}]")]
116 SynthNotFound {
117 key: String,
119 },
120 #[error("Unable to set component data. Public property [${property}] not found on component: [{component}]")]
122 UnknownProperty {
123 property: String,
125 component: String,
127 },
128 #[error(
130 "Livewire request payload is too large ({}KB). Maximum allowed size is {}KB. You can configure this limit in config/livewire.php under \u{27}payload.max_size\u{27}.",
131 kb(*size),
132 kb(*max)
133 )]
134 PayloadTooLarge {
135 size: usize,
137 max: usize,
139 },
140 #[error(
142 "Too many components in a single request ({count}). Maximum allowed is {max}. You can configure this limit in config/livewire.php under \u{27}payload.max_components\u{27}."
143 )]
144 TooManyComponents {
145 count: usize,
147 max: usize,
149 },
150 #[error(
152 "Too many method calls in a single request ({count}). Maximum allowed is {max}. You can configure this limit in config/livewire.php under \u{27}payload.max_calls\u{27}."
153 )]
154 TooManyCalls {
155 count: usize,
157 max: usize,
159 },
160 #[error(
162 "Property path [{path}] exceeds the maximum nesting depth of {max} levels. You can configure this limit in config/livewire.php under \u{27}payload.max_nesting_depth\u{27}."
163 )]
164 NestingDepthExceeded {
165 path: String,
167 max: usize,
169 },
170 #[error(
172 "Livewire encountered a missing root tag when trying to render a component. \n When rendering a Blade view, make sure it contains a root HTML tag."
173 )]
174 RootTagMissing,
175 #[error(
177 "Livewire only supports one HTML element per component. Multiple root elements detected for component: [{name}]"
178 )]
179 MultipleRootElements {
180 name: String,
182 },
183 #[error("Handler for event [{event}] does not exist")]
185 EventListenerMissing {
186 event: String,
188 },
189 #[error("This action is unauthorized.")]
191 Unauthorized {
192 method: String,
194 },
195 #[error("The upload endpoint's signature is invalid or expired")]
197 InvalidUploadSignature,
198 #[error("The temporary file reference is invalid or expired")]
200 InvalidSignedReference,
201 #[error("the uploaded file is invalid: {0}")]
203 UploadValidation(String),
204 #[error("Unable to find component's view: [{view}]")]
206 ViewNotFound {
207 view: String,
209 },
210}
211
212impl LivewireError {
213 pub fn status(&self) -> StatusCode {
220 match self {
221 Self::MissingHeader
222 | Self::NotJson { .. }
223 | Self::MalformedPayload(_)
224 | Self::InvalidSnapshot
225 | Self::MixedParameters
226 | Self::InvalidRouteContext(_)
227 | Self::DefaultUpdateUriOverridden => StatusCode::NOT_FOUND,
228
229 Self::CorruptPayload
230 | Self::ReleaseTokenMismatch
231 | Self::MethodNotFound { .. }
232 | Self::LockedProperty { .. }
233 | Self::HydrationFailed { .. } => StatusCode::from_u16(419).expect("419 is a status code"),
234
235 Self::TooManyChecksumFailures { .. } => StatusCode::TOO_MANY_REQUESTS,
236 Self::Unauthorized { .. } => StatusCode::FORBIDDEN,
237 Self::ModelNotFound { .. } => StatusCode::NOT_FOUND,
238 Self::InvalidUploadSignature => StatusCode::UNAUTHORIZED,
239 Self::InvalidSignedReference => StatusCode::FORBIDDEN,
240 Self::UploadValidation(_) | Self::ValidationFailed { .. } => StatusCode::UNPROCESSABLE_ENTITY,
241
242 Self::PolicyFailed { .. }
243 | Self::Database { .. }
244 | Self::ComponentNotFound { .. }
245 | Self::SynthNotFound { .. }
246 | Self::UnknownProperty { .. }
247 | Self::PayloadTooLarge { .. }
248 | Self::TooManyComponents { .. }
249 | Self::TooManyCalls { .. }
250 | Self::NestingDepthExceeded { .. }
251 | Self::EventListenerMissing { .. }
252 | Self::RootTagMissing
253 | Self::MultipleRootElements { .. }
254 | Self::ViewNotFound { .. } => StatusCode::INTERNAL_SERVER_ERROR,
255 }
256 }
257
258 #[must_use]
262 pub const fn renders_framework_error(&self) -> bool {
263 matches!(
264 self,
265 Self::CorruptPayload
266 | Self::ReleaseTokenMismatch
267 | Self::MethodNotFound { .. }
268 | Self::EventListenerMissing { .. }
269 )
270 }
271
272 #[must_use]
274 pub fn message(&self) -> String {
275 self.to_string()
276 }
277
278 pub fn into_response(self, debug: bool) -> Response {
282 tracing::debug!(error = ?self, "livewire answered with an error");
285
286 if debug && self.renders_framework_error() {
287 return framework_error_page(self);
288 }
289
290 let status = self.status();
291 let mut response = Response::new("").with_status(status);
292
293 if let Self::TooManyChecksumFailures { retry_after } = self
294 && let Ok(value) = retry_after.to_string().parse()
295 {
296 response.headers_mut().insert("retry-after", value);
297 }
298
299 if debug {
300 response.headers_mut().insert(
301 "x-livewire-error",
302 laravel::http::HeaderValue::from_str(&sanitize_header(&self.message()))
303 .unwrap_or_else(|_| laravel::http::HeaderValue::from_static("invalid")),
304 );
305 }
306
307 response
308 }
309}
310
311fn kb(bytes: usize) -> f64 {
313 format!("{:.0}", bytes as f64 / 1024.0).parse().unwrap_or_default()
314}
315
316fn sanitize_header(message: &str) -> String {
318 message
319 .chars()
320 .map(|character| if character.is_control() { ' ' } else { character })
321 .collect()
322}
323
324fn framework_error_page(error: LivewireError) -> Response {
326 let error = laravel::Error::new(StatusCode::INTERNAL_SERVER_ERROR, error);
327 let mut response = laravel::http::IntoResponse::into_response(error);
328
329 response.headers_mut().remove("content-length");
332
333 response
334}
335
336#[cfg(test)]
337mod tests {
338 use super::*;
339
340 #[test]
341 fn keeps_upstream_statuses() {
342 assert_eq!(LivewireError::MissingHeader.status(), StatusCode::NOT_FOUND);
343 assert_eq!(LivewireError::CorruptPayload.status().as_u16(), 419);
344 assert_eq!(LivewireError::ReleaseTokenMismatch.status().as_u16(), 419);
345 assert_eq!(
346 LivewireError::TooManyChecksumFailures { retry_after: 60 }.status(),
347 StatusCode::TOO_MANY_REQUESTS
348 );
349 assert_eq!(
350 LivewireError::PayloadTooLarge { size: 10, max: 1 }.status(),
351 StatusCode::INTERNAL_SERVER_ERROR
352 );
353 assert_eq!(LivewireError::InvalidUploadSignature.status(), StatusCode::UNAUTHORIZED);
354 assert_eq!(LivewireError::InvalidSignedReference.status(), StatusCode::FORBIDDEN);
355 assert_eq!(
356 LivewireError::UploadValidation("too large".to_owned()).status(),
357 StatusCode::UNPROCESSABLE_ENTITY
358 );
359 }
360
361 #[test]
362 fn repeats_the_upstream_guard_messages() {
363 assert_eq!(
364 LivewireError::PayloadTooLarge {
365 size: 2_097_152,
366 max: 1_048_576
367 }
368 .to_string(),
369 "Livewire request payload is too large (2048KB). Maximum allowed size is 1024KB. \
370 You can configure this limit in config/livewire.php under \u{27}payload.max_size\u{27}."
371 );
372 assert_eq!(
373 LivewireError::TooManyCalls { count: 51, max: 50 }.to_string(),
374 "Too many method calls in a single request (51). Maximum allowed is 50. \
375 You can configure this limit in config/livewire.php under \u{27}payload.max_calls\u{27}."
376 );
377 assert_eq!(
378 LivewireError::TooManyComponents { count: 201, max: 200 }.to_string(),
379 "Too many components in a single request (201). Maximum allowed is 200. \
380 You can configure this limit in config/livewire.php under \u{27}payload.max_components\u{27}."
381 );
382 assert_eq!(
383 LivewireError::NestingDepthExceeded {
384 path: "a.b.c".to_owned(),
385 max: 2
386 }
387 .to_string(),
388 "Property path [a.b.c] exceeds the maximum nesting depth of 2 levels. \
389 You can configure this limit in config/livewire.php under \u{27}payload.max_nesting_depth\u{27}."
390 );
391 assert_eq!(
392 LivewireError::UnknownProperty {
393 property: "title".to_owned(),
394 component: "post-editor".to_owned()
395 }
396 .to_string(),
397 "Unable to set component data. Public property [$title] not found on component: [post-editor]"
398 );
399 }
400
401 #[test]
402 fn a_checksum_failure_is_a_framework_page_only_in_debug() {
403 let debug = LivewireError::CorruptPayload.into_response(true);
404 assert_eq!(debug.status(), StatusCode::INTERNAL_SERVER_ERROR);
405
406 let production = LivewireError::CorruptPayload.into_response(false);
407 assert_eq!(production.status().as_u16(), 419);
408 }
409
410 #[test]
411 fn a_rate_limited_client_is_told_when_to_retry() {
412 let response = LivewireError::TooManyChecksumFailures { retry_after: 42 }.into_response(false);
413
414 assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
415 assert_eq!(response.headers()["retry-after"], "42");
416 }
417}