use laravel::http::{Response, StatusCode};
use serde_json::{Map, Value};
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum LivewireError {
#[error("the request has no `X-Livewire` header")]
MissingHeader,
#[error("the request's content type is `{}`, not JSON", content_type.as_deref().unwrap_or("none"))]
NotJson {
content_type: Option<String>,
},
#[error("the request payload is malformed: {0}")]
MalformedPayload(String),
#[error("Invalid Livewire snapshot structure: expected [data], [memo], [checksum], [memo.id], and [memo.name].")]
InvalidSnapshot,
#[error("Unable to find the [{class}] model for the reference [{key}].")]
ModelNotFound {
class: String,
key: String,
},
#[error("A database query failed: {message}")]
Database {
message: String,
},
#[error("The given data was invalid.")]
ValidationFailed {
errors: Map<String, Value>,
},
#[error("The policy guarding [{method}] failed: {message}")]
PolicyFailed {
method: String,
message: String,
},
#[error("a call's parameters mix positional and named parameters")]
MixedParameters,
#[error("the snapshot's route context does not match the request: {0}")]
InvalidRouteContext(String),
#[error("a custom update URI is configured, so the default update route answers nothing")]
DefaultUpdateUriOverridden,
#[error(
"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."
)]
CorruptPayload,
#[error(
"Livewire detected a release token mismatch. \nThis happens when a user's browser session has been invalidated by a new deployment."
)]
ReleaseTokenMismatch,
#[error("Unable to call component method. Public method [{method}] not found on component")]
MethodNotFound {
method: String,
},
#[error("Unable to update locked property [{property}] of component [{component}]")]
LockedProperty {
property: String,
component: String,
},
#[error("Unable to hydrate [{property}] into component [{component}]: {message}")]
HydrationFailed {
property: String,
component: String,
message: String,
},
#[error("Too many invalid Livewire requests. Please try again later.")]
TooManyChecksumFailures {
retry_after: u64,
},
#[error("Unable to find component: [{name}]")]
ComponentNotFound {
name: String,
},
#[error("Unable to find synthesizer with key: [{key}]")]
SynthNotFound {
key: String,
},
#[error("Unable to set component data. Public property [${property}] not found on component: [{component}]")]
UnknownProperty {
property: String,
component: String,
},
#[error(
"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}.",
kb(*size),
kb(*max)
)]
PayloadTooLarge {
size: usize,
max: usize,
},
#[error(
"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}."
)]
TooManyComponents {
count: usize,
max: usize,
},
#[error(
"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}."
)]
TooManyCalls {
count: usize,
max: usize,
},
#[error(
"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}."
)]
NestingDepthExceeded {
path: String,
max: usize,
},
#[error(
"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."
)]
RootTagMissing,
#[error(
"Livewire only supports one HTML element per component. Multiple root elements detected for component: [{name}]"
)]
MultipleRootElements {
name: String,
},
#[error("Handler for event [{event}] does not exist")]
EventListenerMissing {
event: String,
},
#[error("This action is unauthorized.")]
Unauthorized {
method: String,
},
#[error("The upload endpoint's signature is invalid or expired")]
InvalidUploadSignature,
#[error("The temporary file reference is invalid or expired")]
InvalidSignedReference,
#[error("the uploaded file is invalid: {0}")]
UploadValidation(String),
#[error("Unable to find component's view: [{view}]")]
ViewNotFound {
view: String,
},
}
impl LivewireError {
pub fn status(&self) -> StatusCode {
match self {
Self::MissingHeader
| Self::NotJson { .. }
| Self::MalformedPayload(_)
| Self::InvalidSnapshot
| Self::MixedParameters
| Self::InvalidRouteContext(_)
| Self::DefaultUpdateUriOverridden => StatusCode::NOT_FOUND,
Self::CorruptPayload
| Self::ReleaseTokenMismatch
| Self::MethodNotFound { .. }
| Self::LockedProperty { .. }
| Self::HydrationFailed { .. } => StatusCode::from_u16(419).expect("419 is a status code"),
Self::TooManyChecksumFailures { .. } => StatusCode::TOO_MANY_REQUESTS,
Self::Unauthorized { .. } => StatusCode::FORBIDDEN,
Self::ModelNotFound { .. } => StatusCode::NOT_FOUND,
Self::InvalidUploadSignature => StatusCode::UNAUTHORIZED,
Self::InvalidSignedReference => StatusCode::FORBIDDEN,
Self::UploadValidation(_) | Self::ValidationFailed { .. } => StatusCode::UNPROCESSABLE_ENTITY,
Self::PolicyFailed { .. }
| Self::Database { .. }
| Self::ComponentNotFound { .. }
| Self::SynthNotFound { .. }
| Self::UnknownProperty { .. }
| Self::PayloadTooLarge { .. }
| Self::TooManyComponents { .. }
| Self::TooManyCalls { .. }
| Self::NestingDepthExceeded { .. }
| Self::EventListenerMissing { .. }
| Self::RootTagMissing
| Self::MultipleRootElements { .. }
| Self::ViewNotFound { .. } => StatusCode::INTERNAL_SERVER_ERROR,
}
}
#[must_use]
pub const fn renders_framework_error(&self) -> bool {
matches!(
self,
Self::CorruptPayload
| Self::ReleaseTokenMismatch
| Self::MethodNotFound { .. }
| Self::EventListenerMissing { .. }
)
}
#[must_use]
pub fn message(&self) -> String {
self.to_string()
}
pub fn into_response(self, debug: bool) -> Response {
tracing::debug!(error = ?self, "livewire answered with an error");
if debug && self.renders_framework_error() {
return framework_error_page(self);
}
let status = self.status();
let mut response = Response::new("").with_status(status);
if let Self::TooManyChecksumFailures { retry_after } = self
&& let Ok(value) = retry_after.to_string().parse()
{
response.headers_mut().insert("retry-after", value);
}
if debug {
response.headers_mut().insert(
"x-livewire-error",
laravel::http::HeaderValue::from_str(&sanitize_header(&self.message()))
.unwrap_or_else(|_| laravel::http::HeaderValue::from_static("invalid")),
);
}
response
}
}
fn kb(bytes: usize) -> f64 {
format!("{:.0}", bytes as f64 / 1024.0).parse().unwrap_or_default()
}
fn sanitize_header(message: &str) -> String {
message
.chars()
.map(|character| if character.is_control() { ' ' } else { character })
.collect()
}
fn framework_error_page(error: LivewireError) -> Response {
let error = laravel::Error::new(StatusCode::INTERNAL_SERVER_ERROR, error);
let mut response = laravel::http::IntoResponse::into_response(error);
response.headers_mut().remove("content-length");
response
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn keeps_upstream_statuses() {
assert_eq!(LivewireError::MissingHeader.status(), StatusCode::NOT_FOUND);
assert_eq!(LivewireError::CorruptPayload.status().as_u16(), 419);
assert_eq!(LivewireError::ReleaseTokenMismatch.status().as_u16(), 419);
assert_eq!(
LivewireError::TooManyChecksumFailures { retry_after: 60 }.status(),
StatusCode::TOO_MANY_REQUESTS
);
assert_eq!(
LivewireError::PayloadTooLarge { size: 10, max: 1 }.status(),
StatusCode::INTERNAL_SERVER_ERROR
);
assert_eq!(LivewireError::InvalidUploadSignature.status(), StatusCode::UNAUTHORIZED);
assert_eq!(LivewireError::InvalidSignedReference.status(), StatusCode::FORBIDDEN);
assert_eq!(
LivewireError::UploadValidation("too large".to_owned()).status(),
StatusCode::UNPROCESSABLE_ENTITY
);
}
#[test]
fn repeats_the_upstream_guard_messages() {
assert_eq!(
LivewireError::PayloadTooLarge {
size: 2_097_152,
max: 1_048_576
}
.to_string(),
"Livewire request payload is too large (2048KB). Maximum allowed size is 1024KB. \
You can configure this limit in config/livewire.php under \u{27}payload.max_size\u{27}."
);
assert_eq!(
LivewireError::TooManyCalls { count: 51, max: 50 }.to_string(),
"Too many method calls in a single request (51). Maximum allowed is 50. \
You can configure this limit in config/livewire.php under \u{27}payload.max_calls\u{27}."
);
assert_eq!(
LivewireError::TooManyComponents { count: 201, max: 200 }.to_string(),
"Too many components in a single request (201). Maximum allowed is 200. \
You can configure this limit in config/livewire.php under \u{27}payload.max_components\u{27}."
);
assert_eq!(
LivewireError::NestingDepthExceeded {
path: "a.b.c".to_owned(),
max: 2
}
.to_string(),
"Property path [a.b.c] exceeds the maximum nesting depth of 2 levels. \
You can configure this limit in config/livewire.php under \u{27}payload.max_nesting_depth\u{27}."
);
assert_eq!(
LivewireError::UnknownProperty {
property: "title".to_owned(),
component: "post-editor".to_owned()
}
.to_string(),
"Unable to set component data. Public property [$title] not found on component: [post-editor]"
);
}
#[test]
fn a_checksum_failure_is_a_framework_page_only_in_debug() {
let debug = LivewireError::CorruptPayload.into_response(true);
assert_eq!(debug.status(), StatusCode::INTERNAL_SERVER_ERROR);
let production = LivewireError::CorruptPayload.into_response(false);
assert_eq!(production.status().as_u16(), 419);
}
#[test]
fn a_rate_limited_client_is_told_when_to_retry() {
let response = LivewireError::TooManyChecksumFailures { retry_after: 42 }.into_response(false);
assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
assert_eq!(response.headers()["retry-after"], "42");
}
}