Skip to main content

livewire/
error.rs

1//! The errors the Livewire protocol reports, with the status and message upstream Livewire 4.x
2//! answers with.
3//!
4//! The status split is the browser runtime's contract: a `404` hides the endpoint from scanners, a
5//! `419` asks the client to reload the page, a `429` stops a client that keeps sending corrupt
6//! snapshots, and a `500` is a bug in the component or the application.
7
8use laravel::http::{Response, StatusCode};
9use serde_json::{Map, Value};
10
11/// Something a Livewire request can go wrong with.
12#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
13pub enum LivewireError {
14    /// The update request has no `X-Livewire` header, so it did not come from the client.
15    #[error("the request has no `X-Livewire` header")]
16    MissingHeader,
17    /// The update request's content type is not JSON.
18    #[error("the request's content type is `{}`, not JSON", content_type.as_deref().unwrap_or("none"))]
19    NotJson {
20        /// The content type the request sent, or `None` when it sent none.
21        content_type: Option<String>,
22    },
23    /// The request body is not the JSON object the protocol defines.
24    #[error("the request payload is malformed: {0}")]
25    MalformedPayload(String),
26    /// A component's snapshot is not the structure the protocol defines.
27    #[error("Invalid Livewire snapshot structure: expected [data], [memo], [checksum], [memo.id], and [memo.name].")]
28    InvalidSnapshot,
29    /// A model reference names a row that no longer exists.
30    #[error("Unable to find the [{class}] model for the reference [{key}].")]
31    ModelNotFound {
32        /// The model's class name, as the wire names it.
33        class: String,
34        /// The key the reference carried.
35        key: String,
36    },
37    /// A database query the framework ran for a component failed.
38    #[error("A database query failed: {message}")]
39    Database {
40        /// What the framework reported.
41        message: String,
42    },
43    /// A validation rule rejected the component's state. The browser reads the messages from the
44    /// snapshot, so this error is not an HTTP failure of its own: the response still renders.
45    #[error("The given data was invalid.")]
46    ValidationFailed {
47        /// The messages, keyed by field.
48        errors: Map<String, Value>,
49    },
50    /// An action's policy failed, which is a server fault rather than a refusal: a policy that
51    /// refuses returns `Ok(false)`.
52    #[error("The policy guarding [{method}] failed: {message}")]
53    PolicyFailed {
54        /// The method whose policy failed.
55        method: String,
56        /// What the policy reported.
57        message: String,
58    },
59    /// A call's parameters mix positional and named parameters.
60    #[error("a call's parameters mix positional and named parameters")]
61    MixedParameters,
62    /// The snapshot's path, method, or route does not match the request that arrived.
63    #[error("the snapshot's route context does not match the request: {0}")]
64    InvalidRouteContext(String),
65    /// A custom update URI is configured, so the default route answers nothing.
66    #[error("a custom update URI is configured, so the default update route answers nothing")]
67    DefaultUpdateUriOverridden,
68    /// The snapshot's checksum does not match its contents.
69    #[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    /// The snapshot was made by another deployment.
74    #[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    /// A call names a method the component does not publish.
79    #[error("Unable to call component method. Public method [{method}] not found on component")]
80    MethodNotFound {
81        /// The method the call named.
82        method: String,
83    },
84    /// An update sets a property the component locked.
85    #[error("Unable to update locked property [{property}] of component [{component}]")]
86    LockedProperty {
87        /// The property the update named.
88        property: String,
89        /// The component the update named.
90        component: String,
91    },
92    /// A value cannot be hydrated into the field it belongs to.
93    #[error("Unable to hydrate [{property}] into component [{component}]: {message}")]
94    HydrationFailed {
95        /// The property being hydrated.
96        property: String,
97        /// The component being hydrated.
98        component: String,
99        /// What the value could not be read as.
100        message: String,
101    },
102    /// The client sent too many corrupt snapshots.
103    #[error("Too many invalid Livewire requests. Please try again later.")]
104    TooManyChecksumFailures {
105        /// How many seconds until the client may send another request.
106        retry_after: u64,
107    },
108    /// The snapshot names a component the registry does not hold.
109    #[error("Unable to find component: [{name}]")]
110    ComponentNotFound {
111        /// The component name the snapshot holds.
112        name: String,
113    },
114    /// A snapshot or update names a synthesizer the registry does not hold.
115    #[error("Unable to find synthesizer with key: [{key}]")]
116    SynthNotFound {
117        /// The synthesizer key that could not be resolved.
118        key: String,
119    },
120    /// An update sets a property that is not public on the wire.
121    #[error("Unable to set component data. Public property [${property}] not found on component: [{component}]")]
122    UnknownProperty {
123        /// The property the update named.
124        property: String,
125        /// The component the update named.
126        component: String,
127    },
128    /// The request body is larger than the configured limit.
129    #[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        /// The size of the request body, in bytes.
136        size: usize,
137        /// The configured limit, in bytes.
138        max: usize,
139    },
140    /// The request updates more components than the configured limit.
141    #[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        /// How many components the request updated.
146        count: usize,
147        /// The configured limit.
148        max: usize,
149    },
150    /// The request makes more calls than the configured limit.
151    #[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        /// How many calls the request made.
156        count: usize,
157        /// The configured limit.
158        max: usize,
159    },
160    /// An update sets a property path deeper than the configured limit.
161    #[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        /// The property path the update set.
166        path: String,
167        /// The configured limit.
168        max: usize,
169    },
170    /// A component's view rendered no HTML element.
171    #[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    /// A component's view rendered more than one HTML element.
176    #[error(
177        "Livewire only supports one HTML element per component. Multiple root elements detected for component: [{name}]"
178    )]
179    MultipleRootElements {
180        /// The component that rendered several elements.
181        name: String,
182    },
183    /// The browser dispatched an event the component does not listen for.
184    #[error("Handler for event [{event}] does not exist")]
185    EventListenerMissing {
186        /// The event the browser dispatched.
187        event: String,
188    },
189    /// The component's policy denied the action.
190    #[error("This action is unauthorized.")]
191    Unauthorized {
192        /// The action that was denied.
193        method: String,
194    },
195    /// The upload endpoint's URL signature is invalid or expired.
196    #[error("The upload endpoint's signature is invalid or expired")]
197    InvalidUploadSignature,
198    /// A temporary file reference is invalid or expired.
199    #[error("The temporary file reference is invalid or expired")]
200    InvalidSignedReference,
201    /// A temporary upload failed its validation.
202    #[error("the uploaded file is invalid: {0}")]
203    UploadValidation(String),
204    /// A component resolved to a view that does not exist.
205    #[error("Unable to find component's view: [{view}]")]
206    ViewNotFound {
207        /// The view the component named.
208        view: String,
209    },
210}
211
212impl LivewireError {
213    /// The status the browser receives.
214    ///
215    /// # Panics
216    ///
217    /// Panics when `419` stops being a status code, which a Rust update would only do by breaking
218    /// the protocol's own contract.
219    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    /// Whether upstream Livewire lets the framework render its debug page for this error instead of
259    /// answering with the bare status. In production the status alone is the answer, so that a
260    /// probing client learns nothing about the failure.
261    #[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    /// The message the browser receives in debug mode, and that the server logs otherwise.
273    #[must_use]
274    pub fn message(&self) -> String {
275        self.to_string()
276    }
277
278    /// The response for this error. In debug mode, errors upstream renders as a page answer with
279    /// the framework's detailed error page; every other error answers with its status and, for a
280    /// `429`, the retry information.
281    pub fn into_response(self, debug: bool) -> Response {
282        // A refused request is a normal answer; logging it at debug keeps a diagnosis possible
283        // without making the log a report of expected 419s and 404s.
284        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
311/// Rounds a byte count to the kilobytes upstream's message reports.
312fn kb(bytes: usize) -> f64 {
313    format!("{:.0}", bytes as f64 / 1024.0).parse().unwrap_or_default()
314}
315
316/// A message with the characters an HTTP header cannot carry removed.
317fn sanitize_header(message: &str) -> String {
318    message
319        .chars()
320        .map(|character| if character.is_control() { ' ' } else { character })
321        .collect()
322}
323
324/// The framework's own error page, for a `500` in debug mode.
325fn 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    // The framework's page carries a `content-length` that does not match the body it finally
330    // sends, and hyper aborts the connection when it disagrees. The header is hyper's to compute.
331    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}