web-net 0.3.0

Web layer on serve-net: URL normalization, sites and base paths, a compiled router with 404 and 405, gate checkpoints for authentication and authorization, hooks, error pages, and a render trait that reads typed views.
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
//! The handler's context: the cleared request, its identity, its route
//! parameters, and the reply being written.

use std::borrow::Cow;
use std::fmt;
use std::str::FromStr;

use serve_net::{Method, Verdict};

use crate::app::Shared;
use crate::error::Error;
use crate::router::Captures;
use crate::{Output, Request, RequestId, Result, Stage, TemplateId, View, url};

/// The reply a handler writes. Held by web-net until the handler returns, so
/// an error or a panic replaces it whole: nothing a failed handler set (a
/// cookie, a header) leaves.
#[derive(Default)]
pub(crate) struct Out {
    pub(crate) status: u16,
    pub(crate) names: Vec<u8>,
    pub(crate) values: Vec<u8>,
    pub(crate) spans: Vec<(u32, u32, u32, u32)>,
    pub(crate) body: Vec<u8>,
    pub(crate) invalid: bool,
    pub(crate) has_type: bool,
}

/// Fields a handler may not set: framing is serve-net's.
const FRAMING: [&str; 5] = [
    "content-length",
    "transfer-encoding",
    "connection",
    "keep-alive",
    "upgrade",
];

impl Out {
    pub(crate) fn reset(&mut self) {
        self.status = 200;
        self.names.clear();
        self.values.clear();
        self.spans.clear();
        self.body.clear();
        self.invalid = false;
        self.has_type = false;
    }

    pub(crate) fn wipe(&mut self) {
        // black_box keeps the zeroing from being dropped as a dead store.
        for v in [&mut self.names, &mut self.values, &mut self.body] {
            v.iter_mut().for_each(|b| *b = 0);
            std::hint::black_box(&v);
        }
    }

    pub(crate) fn header(&mut self, name: &str, value: &[u8]) {
        let ok_name = !name.is_empty()
            && name.bytes().all(is_tchar)
            && !FRAMING.iter().any(|f| f.eq_ignore_ascii_case(name));
        let ok_value = value
            .iter()
            .all(|&b| b == b'\t' || (b >= 0x20 && b != 0x7f));
        if !ok_name || !ok_value || self.spans.len() >= 64 {
            self.invalid = true;
            return;
        }
        if name.eq_ignore_ascii_case("content-type") {
            self.has_type = true;
        }
        let (ns, vs) = (self.names.len() as u32, self.values.len() as u32);
        self.names
            .extend(name.bytes().map(|b| b.to_ascii_lowercase()));
        self.values.extend_from_slice(value);
        self.spans
            .push((ns, self.names.len() as u32, vs, self.values.len() as u32));
    }

    pub(crate) fn has(&self, name: &str) -> bool {
        self.spans
            .iter()
            .any(|&(s, e, _, _)| &self.names[s as usize..e as usize] == name.as_bytes())
    }
}

const fn is_tchar(b: u8) -> bool {
    matches!(b,
        b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9'
        | b'!' | b'#' | b'$' | b'%' | b'&' | b'\'' | b'*' | b'+' | b'-' | b'.'
        | b'^' | b'_' | b'`' | b'|' | b'~')
}

/// A site-relative path that is safe as a redirect target: it starts with
/// one `/` (never `//` or `/\`, which browsers read as another host) and
/// holds only visible ASCII.
pub(crate) fn is_local_target(p: &str) -> bool {
    let b = p.as_bytes();
    b.first() == Some(&b'/')
        && !matches!(b.get(1), Some(b'/' | b'\\'))
        && b.iter().all(|&c| (0x21..0x7f).contains(&c) && c != b'\\')
}

/// The context a handler receives: proof that the request passed its
/// route's access check, the identity it carries, and the reply.
///
/// There is no public way to make one: web-net builds it only after the
/// gate cleared the request.
pub struct Cx<'r, I> {
    pub(crate) req: Request<'r>,
    pub(crate) who: &'r I,
    pub(crate) caps: Captures,
    pub(crate) names: &'r [Box<str>],
    pub(crate) out: &'r mut Out,
    pub(crate) shared: &'r Shared,
    pub(crate) template: Option<TemplateId>,
}

impl<'r, I> Cx<'r, I> {
    // ---------------------------------------------------------------- request

    /// The request.
    #[must_use]
    pub fn request(&self) -> &Request<'r> {
        &self.req
    }

    /// The method.
    #[must_use]
    pub fn method(&self) -> Method {
        self.req.method()
    }

    /// The canonical path inside the site.
    #[must_use]
    pub fn path(&self) -> &'r str {
        self.req.path
    }

    /// The first value of a request field.
    #[must_use]
    pub fn header(&self, name: &str) -> Option<&'r [u8]> {
        self.req.header(name)
    }

    /// Who the request comes from: always present, possibly a guest.
    #[must_use]
    pub fn identity(&self) -> &'r I {
        self.who
    }

    /// The request's reference, as shown on error pages.
    #[must_use]
    pub fn id(&self) -> RequestId {
        self.req.id()
    }

    /// A route parameter (`:id` or `*rest`), percent-decoded.
    #[must_use]
    pub fn param(&self, name: &str) -> Option<Cow<'r, str>> {
        let i = self.names.iter().position(|n| n.as_ref() == name)?;
        let (s, e) = self.caps.get(i)?;
        Some(url::decode(&self.req.path[s..e]))
    }

    /// A route parameter parsed as `T`. A value that does not parse means
    /// the page does not exist (`/users/abc` for a numeric id): 404.
    ///
    /// # Errors
    ///
    /// 404 `route.param` when the parameter is missing or does not parse.
    pub fn param_as<T: FromStr>(&self, name: &str) -> Result<T> {
        self.param(name)
            .and_then(|v| v.parse().ok())
            .ok_or_else(|| Error::not_found("route.param"))
    }

    /// The first value of a query parameter, decoded (`+` is a space).
    ///
    /// # Errors
    ///
    /// 400 `query.duplicate` when the name appears twice (parameter
    /// pollution is refused, never resolved by picking one), 400
    /// `query.invalid` when the value does not decode to UTF-8.
    pub fn query(&self, name: &str) -> Result<Option<Cow<'r, str>>> {
        let Some(q) = self.req.query() else {
            return Ok(None);
        };
        let mut found = None;
        for pair in q.split('&') {
            let (k, v) = pair.split_once('=').unwrap_or((pair, ""));
            if decode_query(k).as_deref() != Some(name) {
                continue;
            }
            if found.is_some() {
                return Err(Error::bad_request("query.duplicate"));
            }
            found = Some(decode_query(v).ok_or_else(|| Error::bad_request("query.invalid"))?);
        }
        Ok(found)
    }

    /// The request body.
    ///
    /// # Errors
    ///
    /// None today; reading the body is fallible so CSRF and body inspection
    /// can refuse it in later versions without changing handlers.
    pub fn body(&self) -> Result<&'r [u8]> {
        Ok(self.req.http.body_bytes())
    }

    // ---------------------------------------------------------------- reply

    /// Sets the status (default 200).
    pub fn status(&mut self, status: u16) -> &mut Self {
        self.out.status = status;
        self
    }

    /// Adds a reply field. A name that is not a token, a value with a
    /// control character, or a framing field (`content-length`, ...) turns
    /// the reply into a 500 when the handler returns.
    pub fn set_header(&mut self, name: &str, value: impl AsRef<[u8]>) -> &mut Self {
        self.out.header(name, value.as_ref());
        self
    }

    /// Sets the body.
    pub fn body_bytes(&mut self, bytes: &[u8]) -> &mut Self {
        self.out.body.clear();
        self.out.body.extend_from_slice(bytes);
        self
    }

    /// Status, `content-type: text/html; charset=utf-8`, and the HTML.
    pub fn html(&mut self, status: u16, html: &str) -> &mut Self {
        self.content_type("text/html; charset=utf-8");
        self.status(status).body_bytes(html.as_bytes())
    }

    /// Status, `content-type: text/plain; charset=utf-8`, and the text.
    pub fn text(&mut self, status: u16, text: &str) -> &mut Self {
        self.content_type("text/plain; charset=utf-8");
        self.status(status).body_bytes(text.as_bytes())
    }

    /// Adds a `Set-Cookie` field built with cookie-net (re-exported as
    /// [`web_net::cookie_net`](crate::cookie_net)).
    ///
    /// ```
    /// use web_net::{App, get, cookie_net::SetCookie};
    ///
    /// let app = App::builder()
    ///     .route(get("/", |cx| {
    ///         cx.set_cookie(&SetCookie::new("theme", "dark").map_err(|_| web_net::Error::internal("cookie"))?);
    ///         cx.text(200, "ok");
    ///         Ok(())
    ///     }).public())
    ///     .build()?;
    /// let r = serve_net::testing::respond(&app, b"GET / HTTP/1.1\r\nHost: a\r\n\r\n");
    /// assert!(r.header("set-cookie").is_some());
    /// # Ok::<(), web_net::BuildError>(())
    /// ```
    pub fn set_cookie(&mut self, cookie: &cookie_net::SetCookie<'_>) -> &mut Self {
        let line = cookie.encode();
        self.out.header("set-cookie", line.as_bytes());
        self
    }

    /// The conditional fast path for a page: sets `ETag: "<tag>"` and, when
    /// the request's `If-None-Match` matches it (a `GET` or `HEAD`), turns the
    /// reply into `304 Not Modified` and returns `true`, so the handler
    /// returns before building the page.
    ///
    /// `tag` is the opaque part (letters, digits, and `-._~` are safe), for
    /// example a revision number. An unusable tag sets nothing and returns
    /// `false`.
    ///
    /// ```
    /// use web_net::{App, get};
    ///
    /// let app = App::builder()
    ///     .route(get("/", |cx| {
    ///         if cx.not_modified("rev-7") {
    ///             return Ok(());
    ///         }
    ///         cx.html(200, "<h1>page</h1>");
    ///         Ok(())
    ///     }).public())
    ///     .build()?;
    /// let r = serve_net::testing::respond(&app, b"GET / HTTP/1.1\r\nHost: a\r\nIf-None-Match: \"rev-7\"\r\n\r\n");
    /// assert_eq!(r.status, 304);
    /// # Ok::<(), web_net::BuildError>(())
    /// ```
    pub fn not_modified(&mut self, tag: &str) -> bool {
        let Ok(current) = parse_net::EntityTag::strong(tag.as_bytes()) else {
            return false;
        };
        let quoted = format!("\"{tag}\"");
        self.out.header("etag", quoted.as_bytes());
        if !matches!(self.method(), Method::Get | Method::Head) {
            return false;
        }
        let matched = self
            .req
            .header("if-none-match")
            .is_some_and(|v| parse_net::if_none_match(v, &current).unwrap_or(false));
        if matched {
            self.out.status = 304;
            self.out.body.clear();
        }
        matched
    }

    fn content_type(&mut self, value: &str) {
        if !self.out.has_type {
            self.out.header("content-type", value.as_bytes());
        }
    }

    /// The site-relative `path` as a URL path: the site's base path in
    /// front (`/blog` + `/posts/1`). Every link a page writes goes through
    /// this, so the site works installed in a folder.
    #[must_use]
    pub fn url(&self, path: &str) -> String {
        let base = self.shared.base.as_ref();
        if path == "/" && !base.is_empty() {
            format!("{base}/")
        } else {
            format!("{base}{path}")
        }
    }

    /// `303 See Other` to a site-relative path: the answer to a form that
    /// was accepted, so a reload does not post it again.
    ///
    /// # Errors
    ///
    /// 500 `redirect.not_local` when `path` is not a local path (it must
    /// start with one `/`): redirects to other hosts are never built from a
    /// string a handler passes along.
    pub fn see_other(&mut self, path: &str) -> Result {
        self.redirect(303, path)
    }

    /// A redirect with `status` (301, 302, 303, 307, 308) to a
    /// site-relative path.
    ///
    /// # Errors
    ///
    /// As [`see_other`](Self::see_other); 500 `redirect.status` for a
    /// status that is not a redirect.
    pub fn redirect(&mut self, status: u16, path: &str) -> Result {
        if !matches!(status, 301 | 302 | 303 | 307 | 308) {
            return Err(Error::internal("redirect.status"));
        }
        if !is_local_target(path) {
            return Err(Error::internal("redirect.not_local"));
        }
        let location = self.url(path);
        self.out.header("location", location.as_bytes());
        self.out.status = status;
        self.out.body.clear();
        Ok(())
    }

    /// Renders the route's template (declared with
    /// [`Route::template`](crate::Route::template)) against `view` into the
    /// body. The status stays as set (200 by default); `content-type` is
    /// HTML unless the handler set one.
    ///
    /// # Errors
    ///
    /// 500 `render.no_engine` or `render.no_template` when nothing can
    /// render; the engine's own [`RenderError`](crate::RenderError) as a 500;
    /// a checkpoint's denial.
    pub fn render(&mut self, view: &dyn View) -> Result {
        let t = self
            .template
            .ok_or_else(|| Error::internal("render.no_template"))?;
        self.render_id(t, view)
    }

    /// Renders the template `name` against `view`. The name is resolved by
    /// the engine on every call; prefer [`render`](Self::render) with a
    /// template declared on the route, resolved once at build.
    ///
    /// # Errors
    ///
    /// As [`render`](Self::render).
    pub fn render_named(&mut self, name: &str, view: &dyn View) -> Result {
        let engine = self
            .shared
            .render
            .as_deref()
            .ok_or_else(|| Error::internal("render.no_engine"))?;
        let t = engine
            .template(name)
            .ok_or_else(|| Error::internal("render.no_template"))?;
        self.render_id(t, view)
    }

    fn render_id(&mut self, t: TemplateId, view: &dyn View) -> Result {
        let engine = self
            .shared
            .render
            .as_deref()
            .ok_or_else(|| Error::internal("render.no_engine"))?;
        if let Some(cp) = &self.shared.checkpoint {
            match cp.check(self.req.env, Stage::BeforeRender) {
                Verdict::Pass => {}
                Verdict::Deny { status } => return Err(Error::new(status, "checkpoint.denied")),
                _ => return Err(Error::forbidden("checkpoint.killed")),
            }
        }
        self.out.body.clear();
        let mut output = Output::new(&mut self.out.body, self.shared.page_limit);
        let rendered = engine.render(t, view, &mut output);
        if let Err(e) = rendered {
            self.out.body.clear();
            return Err(e.into());
        }
        self.content_type("text/html; charset=utf-8");
        Ok(())
    }
}

impl<I> fmt::Debug for Cx<'_, I> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Cx")
            .field("request", &self.req)
            .field("status", &self.out.status)
            .finish_non_exhaustive()
    }
}

/// Decodes one query name or value: `+` is a space, escapes decoded once.
fn decode_query(s: &str) -> Option<Cow<'_, str>> {
    if !s.contains(['%', '+']) {
        return Some(Cow::Borrowed(s));
    }
    let b = s.as_bytes();
    let mut out = Vec::with_capacity(b.len());
    let mut i = 0;
    while i < b.len() {
        match b[i] {
            b'+' => {
                out.push(b' ');
                i += 1;
            }
            b'%' => {
                let h = b.get(i + 1).and_then(|&c| (c as char).to_digit(16))?;
                let l = b.get(i + 2).and_then(|&c| (c as char).to_digit(16))?;
                out.push(((h << 4) | l) as u8);
                i += 3;
            }
            c => {
                out.push(c);
                i += 1;
            }
        }
    }
    String::from_utf8(out).ok().map(Cow::Owned)
}

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

    #[test]
    fn test_local_targets() {
        for ok in ["/", "/a", "/a/b?c=d", "/a%20b"] {
            assert!(is_local_target(ok), "{ok}");
        }
        for bad in [
            "",
            "a",
            "//evil.example",
            "/\\evil.example",
            "https://x",
            "/a\r\nx",
            "/a b",
            "/a\\b",
        ] {
            assert!(!is_local_target(bad), "{bad:?}");
        }
    }

    #[test]
    fn test_decode_query() {
        assert_eq!(decode_query("a+b%21").as_deref(), Some("a b!"));
        assert_eq!(decode_query("plain").as_deref(), Some("plain"));
        assert_eq!(decode_query("%zz"), None);
        assert_eq!(decode_query("%ff"), None);
    }

    #[test]
    fn test_out_refuses_bad_fields() {
        let mut o = Out::default();
        o.header("x-ok", b"v");
        assert!(!o.invalid);
        o.header("content-length", b"1");
        assert!(o.invalid);
        let mut o = Out::default();
        o.header("x", b"a\r\nb");
        assert!(o.invalid);
        let mut o = Out::default();
        o.header("bad name", b"v");
        assert!(o.invalid);
        let mut o = Out::default();
        o.header("Content-Type", b"text/x");
        assert!(o.has_type && o.has("content-type"));
    }
}