static-web-server 2.44.0

A cross-platform, high-performance and asynchronous web server for static files-serving.
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
// SPDX-License-Identifier: MIT OR Apache-2.0
// This file is part of Static Web Server.
// See https://static-web-server.net/ for more information
// Copyright (C) 2019-present Jose Quintana <joseluisq.net>

//! Redirection module to handle config redirect URLs with pattern matching support.
//!
//! # Security: ReDoS / pattern complexity
//!
//! Redirect/rewrite source patterns are admin-supplied at startup. SWS
//! uses [`regex_lite`], which has **no backtracking** (linear-time NFA
//! engine), so the classic catastrophic-backtracking ReDoS class does
//! not apply. However:
//!
//! - Per-request work is still proportional to `pattern_size * uri_len`.
//!   To bound it, requests with URI paths longer than the internal matching cap
//!   are skipped (no regex evaluation, no redirect).
//! - Operators should treat redirect patterns as trusted configuration
//!   and avoid loading them from untrusted sources.

use headers::HeaderValue;
use hyper::{Body, Request, Response, StatusCode};
use regex_lite::Regex;

use crate::{Error, error_page, handler::RequestHandlerOpts, settings::Redirects};

/// Maximum URI length (bytes) that will be fed to the redirect regex
/// engine. Requests above this size skip redirect matching entirely.
///
/// 8 KiB matches the common HTTP-server URI cap and is more than the
/// largest realistic redirect source while still bounding per-request
/// regex work to a small constant.
pub(crate) const MAX_URI_LEN_FOR_REGEX: usize = 8 * 1024;

/// Applies redirect rules to a request if necessary.
pub(crate) fn pre_process<T>(
    opts: &RequestHandlerOpts,
    req: &Request<T>,
) -> Option<Result<Response<Body>, Error>> {
    let redirects = opts.advanced_opts.as_ref()?.redirects.as_deref()?;

    let uri = req.uri();
    let uri_path = uri.path();
    // Refuse to run any regex against unreasonably long URIs.
    // See module-level docs.
    if uri_path.len() > MAX_URI_LEN_FOR_REGEX {
        tracing::debug!(
            "redirects: skipping match, uri path length {} exceeds cap {}",
            uri_path.len(),
            MAX_URI_LEN_FOR_REGEX
        );
        return None;
    }
    let host = req
        .headers()
        .get(http::header::HOST)
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");
    let mut uri_host = uri.host().unwrap_or(host).to_owned();
    if let Some(uri_port) = uri.port_u16() {
        uri_host.push_str(&format!(":{uri_port}"));
    }
    let matched = get_redirection(&uri_host, uri_path, Some(redirects))?;
    let mut dest = match replace_placeholders(
        uri_path,
        &matched.source,
        &matched.destination,
        &matched.replacer,
    ) {
        Ok(dest) => dest,
        Err(err) => return handle_error(err, opts, req),
    };
    if let Some(query) = uri.query() {
        if !dest.ends_with('?') && !dest.ends_with('&') {
            dest.push(if dest.contains('?') { '&' } else { '?' });
        }
        dest.push_str(query);
    }

    match HeaderValue::from_str(&dest) {
        Ok(loc) => {
            let mut resp = Response::new(Body::empty());
            resp.headers_mut().insert(hyper::header::LOCATION, loc);
            *resp.status_mut() = matched.kind;
            tracing::trace!(
                "uri matches redirects glob pattern, redirecting with status '{}'",
                matched.kind
            );
            Some(Ok(resp))
        }
        Err(err) => handle_error(
            Error::new(err).context("invalid header value from current uri"),
            opts,
            req,
        ),
    }
}

/// Replaces placeholders in the destination URI by matching capture groups from the original URI.
pub(crate) fn replace_placeholders(
    orig_uri: &str,
    regex: &Regex,
    dest_uri: &str,
    ac: &aho_corasick::AhoCorasick,
) -> Result<String, Error> {
    let regex_caps = if let Some(regex_caps) = regex.captures(orig_uri) {
        regex_caps
    } else {
        return Err(Error::msg("regex didn't match, extracting captures failed"));
    };

    let caps: Vec<&str> = (0..regex_caps.len())
        .map(|i| regex_caps.get(i).map(|s| s.as_str()).unwrap_or(""))
        .collect();

    tracing::debug!("url redirects/rewrites regex equivalent: {regex}");
    tracing::debug!("url redirects/rewrites glob pattern captures: {caps:?}");
    tracing::debug!("url redirects/rewrites glob pattern destination: {dest_uri:?}");

    match ac.try_replace_all(dest_uri, &caps) {
        Ok(dest) => {
            tracing::debug!("url redirects/rewrites glob pattern destination replaced: {dest:?}");
            Ok(dest)
        }
        Err(err) => Err(Error::new(err).context("failed replacing captures")),
    }
}

/// Logs error and produces an Internal Server Error response.
pub(crate) fn handle_error<T>(
    err: Error,
    opts: &RequestHandlerOpts,
    req: &Request<T>,
) -> Option<Result<Response<Body>, Error>> {
    tracing::error!("{err:?}");
    Some(error_page::error_response(
        req.uri(),
        req.method(),
        &StatusCode::INTERNAL_SERVER_ERROR,
        &opts.page404,
        &opts.page50x,
    ))
}

/// It returns a redirect's destination path and status code if the current request uri
/// matches against the provided redirect's array.
pub fn get_redirection<'a>(
    uri_host: &'a str,
    uri_path: &'a str,
    redirects_opts: Option<&'a [Redirects]>,
) -> Option<&'a Redirects> {
    if let Some(redirects_vec) = redirects_opts {
        for redirect_entry in redirects_vec {
            // Match `host` redirect against `uri_host` if specified
            if let Some(host) = &redirect_entry.host {
                tracing::debug!(
                    "checking host '{host}' redirect entry against uri host '{uri_host}'"
                );
                if !host.eq(uri_host) {
                    continue;
                }
            }

            // Match source glob pattern against the request uri path
            if redirect_entry.source.is_match(uri_path) {
                return Some(redirect_entry);
            }
        }
    }

    None
}

#[cfg(test)]
mod tests {
    use super::pre_process;
    use crate::{
        Error,
        handler::RequestHandlerOpts,
        settings::{Advanced, Redirects, build_placeholder_replacer},
    };
    use hyper::{Body, Request, Response, StatusCode};
    use regex_lite::Regex;

    fn make_request(host: &str, uri: &str) -> Request<Body> {
        let mut builder = Request::builder();
        if !host.is_empty() {
            builder = builder.header("Host", host);
        }
        builder.method("GET").uri(uri).body(Body::empty()).unwrap()
    }

    fn get_redirects() -> Vec<Redirects> {
        let s1 = Regex::new(r"/source1$").unwrap();
        let r1 = build_placeholder_replacer(&s1);
        let s2 = Regex::new(r"/source2$").unwrap();
        let r2 = build_placeholder_replacer(&s2);
        let s3 = Regex::new(r"/(prefix/)?(source3)/(.*)").unwrap();
        let r3 = build_placeholder_replacer(&s3);
        let s4 = Regex::new(r"/source4/(.*)").unwrap();
        let r4 = build_placeholder_replacer(&s4);
        vec![
            Redirects {
                host: None,
                source: s1,
                destination: "/destination1".into(),
                kind: StatusCode::FOUND,
                replacer: r1,
            },
            Redirects {
                host: Some("example.com".into()),
                source: s2,
                destination: "/destination2".into(),
                kind: StatusCode::MOVED_PERMANENTLY,
                replacer: r2,
            },
            Redirects {
                host: Some("example.info".into()),
                source: s3,
                destination: "/destination3/$2/$3".into(),
                kind: StatusCode::MOVED_PERMANENTLY,
                replacer: r3,
            },
            Redirects {
                host: None,
                source: s4,
                destination: "/destination4?p=$1".into(),
                kind: StatusCode::FOUND,
                replacer: r4,
            },
        ]
    }

    fn is_redirect(result: Option<Result<Response<Body>, Error>>) -> Option<(StatusCode, String)> {
        if let Some(Ok(response)) = result {
            let location = response.headers().get("Location")?.to_str().unwrap().into();
            Some((response.status(), location))
        } else {
            None
        }
    }

    #[test]
    fn test_no_redirects() {
        assert!(
            pre_process(
                &RequestHandlerOpts {
                    advanced_opts: None,
                    ..Default::default()
                },
                &make_request("", "/")
            )
            .is_none()
        );

        assert!(
            pre_process(
                &RequestHandlerOpts {
                    advanced_opts: Some(Advanced {
                        redirects: None,
                        ..Default::default()
                    }),
                    ..Default::default()
                },
                &make_request("", "/")
            )
            .is_none()
        );
    }

    #[test]
    fn test_no_match() {
        assert!(
            pre_process(
                &RequestHandlerOpts {
                    advanced_opts: Some(Advanced {
                        redirects: Some(get_redirects()),
                        ..Default::default()
                    }),
                    ..Default::default()
                },
                &make_request("example.com", "/source2/whatever")
            )
            .is_none()
        );

        assert!(
            pre_process(
                &RequestHandlerOpts {
                    advanced_opts: Some(Advanced {
                        redirects: Some(get_redirects()),
                        ..Default::default()
                    }),
                    ..Default::default()
                },
                &make_request("", "/source2")
            )
            .is_none()
        );
    }

    #[test]
    fn test_match() {
        assert_eq!(
            is_redirect(pre_process(
                &RequestHandlerOpts {
                    advanced_opts: Some(Advanced {
                        redirects: Some(get_redirects()),
                        ..Default::default()
                    }),
                    ..Default::default()
                },
                &make_request("", "/source1")
            )),
            Some((StatusCode::FOUND, "/destination1".into()))
        );

        assert_eq!(
            is_redirect(pre_process(
                &RequestHandlerOpts {
                    advanced_opts: Some(Advanced {
                        redirects: Some(get_redirects()),
                        ..Default::default()
                    }),
                    ..Default::default()
                },
                &make_request("example.com", "/source2")
            )),
            Some((StatusCode::MOVED_PERMANENTLY, "/destination2".into()))
        );

        assert_eq!(
            is_redirect(pre_process(
                &RequestHandlerOpts {
                    advanced_opts: Some(Advanced {
                        redirects: Some(get_redirects()),
                        ..Default::default()
                    }),
                    ..Default::default()
                },
                &make_request("example.info", "/source3/whatever")
            )),
            Some((
                StatusCode::MOVED_PERMANENTLY,
                "/destination3/source3/whatever".into()
            ))
        );

        assert_eq!(
            is_redirect(pre_process(
                &RequestHandlerOpts {
                    advanced_opts: Some(Advanced {
                        redirects: Some(get_redirects()),
                        ..Default::default()
                    }),
                    ..Default::default()
                },
                &make_request("", "/source4/whatever")
            )),
            Some((StatusCode::FOUND, "/destination4?p=whatever".into()))
        );
    }

    #[test]
    fn test_query() {
        assert_eq!(
            is_redirect(pre_process(
                &RequestHandlerOpts {
                    advanced_opts: Some(Advanced {
                        redirects: Some(get_redirects()),
                        ..Default::default()
                    }),
                    ..Default::default()
                },
                &make_request("", "/source1?q=query-string")
            )),
            Some((StatusCode::FOUND, "/destination1?q=query-string".into()))
        );

        assert_eq!(
            is_redirect(pre_process(
                &RequestHandlerOpts {
                    advanced_opts: Some(Advanced {
                        redirects: Some(get_redirects()),
                        ..Default::default()
                    }),
                    ..Default::default()
                },
                &make_request("example.com", "/source2?q=query-string")
            )),
            Some((
                StatusCode::MOVED_PERMANENTLY,
                "/destination2?q=query-string".into()
            ))
        );

        assert_eq!(
            is_redirect(pre_process(
                &RequestHandlerOpts {
                    advanced_opts: Some(Advanced {
                        redirects: Some(get_redirects()),
                        ..Default::default()
                    }),
                    ..Default::default()
                },
                &make_request("example.info", "/source3/whatever?q=query-string")
            )),
            Some((
                StatusCode::MOVED_PERMANENTLY,
                "/destination3/source3/whatever?q=query-string".into()
            ))
        );

        assert_eq!(
            is_redirect(pre_process(
                &RequestHandlerOpts {
                    advanced_opts: Some(Advanced {
                        redirects: Some(get_redirects()),
                        ..Default::default()
                    }),
                    ..Default::default()
                },
                &make_request("", "/source4/whatever?q=query-string")
            )),
            Some((
                StatusCode::FOUND,
                "/destination4?p=whatever&q=query-string".into()
            ))
        );
    }
}