livewire-rust 0.1.3

Livewire for Rust: server-rendered reactive components for Laravel for Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
//! The errors the Livewire protocol reports, with the status and message upstream Livewire 4.x
//! answers with.
//!
//! The status split is the browser runtime's contract: a `404` hides the endpoint from scanners, a
//! `419` asks the client to reload the page, a `429` stops a client that keeps sending corrupt
//! snapshots, and a `500` is a bug in the component or the application.

use laravel::http::{Response, StatusCode};
use serde_json::{Map, Value};

/// Something a Livewire request can go wrong with.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum LivewireError {
    /// The update request has no `X-Livewire` header, so it did not come from the client.
    #[error("the request has no `X-Livewire` header")]
    MissingHeader,
    /// The update request's content type is not JSON.
    #[error("the request's content type is `{}`, not JSON", content_type.as_deref().unwrap_or("none"))]
    NotJson {
        /// The content type the request sent, or `None` when it sent none.
        content_type: Option<String>,
    },
    /// The request body is not the JSON object the protocol defines.
    #[error("the request payload is malformed: {0}")]
    MalformedPayload(String),
    /// A component's snapshot is not the structure the protocol defines.
    #[error("Invalid Livewire snapshot structure: expected [data], [memo], [checksum], [memo.id], and [memo.name].")]
    InvalidSnapshot,
    /// A model reference names a row that no longer exists.
    #[error("Unable to find the [{class}] model for the reference [{key}].")]
    ModelNotFound {
        /// The model's class name, as the wire names it.
        class: String,
        /// The key the reference carried.
        key: String,
    },
    /// A database query the framework ran for a component failed.
    #[error("A database query failed: {message}")]
    Database {
        /// What the framework reported.
        message: String,
    },
    /// A validation rule rejected the component's state. The browser reads the messages from the
    /// snapshot, so this error is not an HTTP failure of its own: the response still renders.
    #[error("The given data was invalid.")]
    ValidationFailed {
        /// The messages, keyed by field.
        errors: Map<String, Value>,
    },
    /// An action's policy failed, which is a server fault rather than a refusal: a policy that
    /// refuses returns `Ok(false)`.
    #[error("The policy guarding [{method}] failed: {message}")]
    PolicyFailed {
        /// The method whose policy failed.
        method: String,
        /// What the policy reported.
        message: String,
    },
    /// A call's parameters mix positional and named parameters.
    #[error("a call's parameters mix positional and named parameters")]
    MixedParameters,
    /// The snapshot's path, method, or route does not match the request that arrived.
    #[error("the snapshot's route context does not match the request: {0}")]
    InvalidRouteContext(String),
    /// A custom update URI is configured, so the default route answers nothing.
    #[error("a custom update URI is configured, so the default update route answers nothing")]
    DefaultUpdateUriOverridden,
    /// The snapshot's checksum does not match its contents.
    #[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,
    /// The snapshot was made by another deployment.
    #[error(
        "Livewire detected a release token mismatch. \nThis happens when a user's browser session has been invalidated by a new deployment."
    )]
    ReleaseTokenMismatch,
    /// A call names a method the component does not publish.
    #[error("Unable to call component method. Public method [{method}] not found on component")]
    MethodNotFound {
        /// The method the call named.
        method: String,
    },
    /// An update sets a property the component locked.
    #[error("Unable to update locked property [{property}] of component [{component}]")]
    LockedProperty {
        /// The property the update named.
        property: String,
        /// The component the update named.
        component: String,
    },
    /// A value cannot be hydrated into the field it belongs to.
    #[error("Unable to hydrate [{property}] into component [{component}]: {message}")]
    HydrationFailed {
        /// The property being hydrated.
        property: String,
        /// The component being hydrated.
        component: String,
        /// What the value could not be read as.
        message: String,
    },
    /// The client sent too many corrupt snapshots.
    #[error("Too many invalid Livewire requests. Please try again later.")]
    TooManyChecksumFailures {
        /// How many seconds until the client may send another request.
        retry_after: u64,
    },
    /// The snapshot names a component the registry does not hold.
    #[error("Unable to find component: [{name}]")]
    ComponentNotFound {
        /// The component name the snapshot holds.
        name: String,
    },
    /// A snapshot or update names a synthesizer the registry does not hold.
    #[error("Unable to find synthesizer with key: [{key}]")]
    SynthNotFound {
        /// The synthesizer key that could not be resolved.
        key: String,
    },
    /// An update sets a property that is not public on the wire.
    #[error("Unable to set component data. Public property [${property}] not found on component: [{component}]")]
    UnknownProperty {
        /// The property the update named.
        property: String,
        /// The component the update named.
        component: String,
    },
    /// The request body is larger than the configured limit.
    #[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 {
        /// The size of the request body, in bytes.
        size: usize,
        /// The configured limit, in bytes.
        max: usize,
    },
    /// The request updates more components than the configured limit.
    #[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 {
        /// How many components the request updated.
        count: usize,
        /// The configured limit.
        max: usize,
    },
    /// The request makes more calls than the configured limit.
    #[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 {
        /// How many calls the request made.
        count: usize,
        /// The configured limit.
        max: usize,
    },
    /// An update sets a property path deeper than the configured limit.
    #[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 {
        /// The property path the update set.
        path: String,
        /// The configured limit.
        max: usize,
    },
    /// A component's view rendered no HTML element.
    #[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,
    /// A component's view rendered more than one HTML element.
    #[error(
        "Livewire only supports one HTML element per component. Multiple root elements detected for component: [{name}]"
    )]
    MultipleRootElements {
        /// The component that rendered several elements.
        name: String,
    },
    /// The browser dispatched an event the component does not listen for.
    #[error("Handler for event [{event}] does not exist")]
    EventListenerMissing {
        /// The event the browser dispatched.
        event: String,
    },
    /// The component's policy denied the action.
    #[error("This action is unauthorized.")]
    Unauthorized {
        /// The action that was denied.
        method: String,
    },
    /// The upload endpoint's URL signature is invalid or expired.
    #[error("The upload endpoint's signature is invalid or expired")]
    InvalidUploadSignature,
    /// A temporary file reference is invalid or expired.
    #[error("The temporary file reference is invalid or expired")]
    InvalidSignedReference,
    /// A temporary upload failed its validation.
    #[error("the uploaded file is invalid: {0}")]
    UploadValidation(String),
    /// A component resolved to a view that does not exist.
    #[error("Unable to find component's view: [{view}]")]
    ViewNotFound {
        /// The view the component named.
        view: String,
    },
}

impl LivewireError {
    /// The status the browser receives.
    ///
    /// # Panics
    ///
    /// Panics when `419` stops being a status code, which a Rust update would only do by breaking
    /// the protocol's own contract.
    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,
        }
    }

    /// Whether upstream Livewire lets the framework render its debug page for this error instead of
    /// answering with the bare status. In production the status alone is the answer, so that a
    /// probing client learns nothing about the failure.
    #[must_use]
    pub const fn renders_framework_error(&self) -> bool {
        matches!(
            self,
            Self::CorruptPayload
                | Self::ReleaseTokenMismatch
                | Self::MethodNotFound { .. }
                | Self::EventListenerMissing { .. }
        )
    }

    /// The message the browser receives in debug mode, and that the server logs otherwise.
    #[must_use]
    pub fn message(&self) -> String {
        self.to_string()
    }

    /// The response for this error. In debug mode, errors upstream renders as a page answer with
    /// the framework's detailed error page; every other error answers with its status and, for a
    /// `429`, the retry information.
    pub fn into_response(self, debug: bool) -> Response {
        // A refused request is a normal answer; logging it at debug keeps a diagnosis possible
        // without making the log a report of expected 419s and 404s.
        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
    }
}

/// Rounds a byte count to the kilobytes upstream's message reports.
fn kb(bytes: usize) -> f64 {
    format!("{:.0}", bytes as f64 / 1024.0).parse().unwrap_or_default()
}

/// A message with the characters an HTTP header cannot carry removed.
fn sanitize_header(message: &str) -> String {
    message
        .chars()
        .map(|character| if character.is_control() { ' ' } else { character })
        .collect()
}

/// The framework's own error page, for a `500` in debug mode.
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);

    // The framework's page carries a `content-length` that does not match the body it finally
    // sends, and hyper aborts the connection when it disagrees. The header is hyper's to compute.
    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");
    }
}