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
//! A warp filter for accepting form submissions using any HTTP method.

#![warn(missing_docs)]

use std::convert::TryFrom;

use futures::future;
use warp::http::Method;
use warp::{Buf, Filter};

/// Returns a [`Filter`] that matches a request with the following criteria:
/// - is a `POST` request
/// - has a `Content-Type: application/x-www-form-urlencoded` header and body
/// - the first field in the form has the name `_method` and a valid HTTP method
/// as the value
/// - the value of the `_method` field matches the specified HTTP method
///
/// Typically HTML forms can only be submitted as `GET` or `POST` requests, so
/// this filter allows for submitting forms using any HTTP method.
pub fn form_method(method: Method) -> impl Filter<Extract = (), Error = warp::Rejection> + Clone {
    warp::post()
        .and(is_form_content())
        .and(warp::body::aggregate())
        .map(parse_method_in_first_field)
        .and_then(move |form_method| match form_method {
            Some(form_method) if form_method == method => future::ok(()),
            _ => future::err(warp::reject()),
        })
        .untuple_one()
}

fn is_form_content() -> impl Filter<Extract = (), Error = warp::Rejection> + Copy {
    warp::header::exact_ignore_case("Content-Type", "application/x-www-form-urlencoded")
}

/// The minimum length of the `_method` field.
const MIN_LEN: usize = "_method=GET".len();

/// The maximum length of the `_method` field.
const MAX_LEN: usize = "_method=DELETE".len();

/// Attempts to parse a `_method` field containing an HTTP method as the
/// **first** field in an `application/x-www-form-urlencoded` body.
///
/// If the `_method` field is not present, not the first field, or contains a
/// value that can not be parsed as an HTTP method this will return [`None`].
fn parse_method_in_first_field(mut body: impl Buf) -> Option<Method> {
    if body.remaining() < MIN_LEN {
        return None;
    }

    let mut peek_buffer = vec![0; std::cmp::min(body.remaining(), MAX_LEN)];
    body.copy_to_slice(&mut peek_buffer);

    let mut parts = std::str::from_utf8(&peek_buffer)
        .ok()?
        .split(|c| c == '=' || c == '&')
        .take(2);

    let name = parts.next();
    let value = parts.next();
    match (name, value) {
        (Some("_method"), Some(value)) => Method::try_from(value).ok(),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn it_matches_with_post_method_form_content_and_matching_put_method_in_first_field() {
        let filter = form_method(Method::PUT);

        assert!(
            warp::test::request()
                .method("POST")
                .path("/")
                .header("Content-Type", "application/x-www-form-urlencoded")
                .body("_method=PUT&first_name=john")
                .matches(&filter)
                .await
        )
    }

    #[tokio::test]
    async fn it_matches_with_post_method_form_content_and_matching_delete_method_in_first_field() {
        let filter = form_method(Method::DELETE);

        assert!(
            warp::test::request()
                .method("POST")
                .path("/")
                .header("Content-Type", "application/x-www-form-urlencoded")
                .body("_method=DELETE&first_name=john")
                .matches(&filter)
                .await
        )
    }

    #[tokio::test]
    async fn it_matches_with_the_minimum_form_body_length() {
        let filter = form_method(Method::PUT);

        assert!(
            warp::test::request()
                .method("POST")
                .path("/")
                .header("Content-Type", "application/x-www-form-urlencoded")
                .body("_method=PUT")
                .matches(&filter)
                .await
        )
    }

    #[tokio::test]
    async fn it_matches_with_a_form_body_length_between_the_minimum_and_maximum() {
        let filter = form_method(Method::HEAD);

        assert!(
            warp::test::request()
                .method("POST")
                .path("/")
                .header("Content-Type", "application/x-www-form-urlencoded")
                .body("_method=HEAD")
                .matches(&filter)
                .await
        )
    }

    #[tokio::test]
    async fn it_matches_with_the_maximum_form_body_length() {
        let filter = form_method(Method::DELETE);

        assert!(
            warp::test::request()
                .method("POST")
                .path("/")
                .header("Content-Type", "application/x-www-form-urlencoded")
                .body("_method=DELETE")
                .matches(&filter)
                .await
        )
    }

    #[tokio::test]
    async fn it_rejects_with_post_method_form_content_and_matching_method_not_in_first_field() {
        let filter = form_method(Method::PUT);

        assert!(
            !warp::test::request()
                .method("POST")
                .path("/")
                .header("Content-Type", "application/x-www-form-urlencoded")
                .body("first_name=john&_method=PUT")
                .matches(&filter)
                .await
        )
    }

    #[tokio::test]
    async fn it_rejects_with_post_method_form_content_and_different_method_in_first_field() {
        let filter = form_method(Method::PUT);

        assert!(
            !warp::test::request()
                .method("POST")
                .path("/")
                .header("Content-Type", "application/x-www-form-urlencoded")
                .body("_method=DELETE&first_name=john")
                .matches(&filter)
                .await
        )
    }

    #[tokio::test]
    async fn it_rejects_with_post_method_form_content_and_no_content_type_header() {
        let filter = form_method(Method::PUT);

        assert!(
            !warp::test::request()
                .method("POST")
                .path("/")
                .body("_method=PUT&first_name=john")
                .matches(&filter)
                .await
        )
    }

    #[tokio::test]
    async fn it_rejects_with_post_method_and_no_content() {
        let filter = form_method(Method::PUT);

        assert!(
            !warp::test::request()
                .method("POST")
                .path("/")
                .matches(&filter)
                .await
        )
    }
}