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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
use ;
/// Byte-buffer types re-exported for use as request body extractors and as
/// response bodies.
pub use ;
use Parts;
use ;
use crate::;
/// An incoming HTTP request, carrying a [`Body`] by default.
pub type Request<T = Body> = Request;
/// A type that can be built from an incoming request.
///
/// A page or route may accept one `FromRequest` body parameter alongside an
/// optional `cx: &Cx`. Use a built-in extractor or implement this trait for
/// custom parsing.
///
/// A handler accepts only one body parameter because the body can be consumed
/// only once.
///
/// An implementation that buffers the body should delegate the buffering to
/// [`Bytes`], which enforces the request's
/// [`body_limit`]; reading the body by hand bypasses that
/// limit.
///
/// # Examples
///
/// Implement it to parse a request in a way the built-ins don't cover. Here,
/// JSON whose body is verified against an `x-signature` header before it is
/// deserialized:
///
/// ```rust
/// # #[derive(serde::Deserialize)]
/// # struct CreateUser { name: String }
/// # fn verify_signature(_signature: &str, _bytes: &[u8]) -> topcoat::Result<()> { Ok(()) }
/// use serde::de::DeserializeOwned;
/// use topcoat::{
/// Result,
/// context::Cx,
/// router::{
/// Body,
/// error::bad_request,
/// request::{Bytes, FromRequest, headers},
/// route,
/// },
/// };
///
/// struct SignedJson<T>(T);
///
/// impl<T> FromRequest for SignedJson<T>
/// where
/// T: DeserializeOwned,
/// {
/// async fn from_request(cx: &Cx, body: Body) -> Result<Self> {
/// let signature = headers(cx)
/// .get("x-signature")
/// .and_then(|value| value.to_str().ok())
/// .ok_or_else(|| bad_request("missing x-signature header"))?;
///
/// let bytes = Bytes::from_request(cx, body).await?;
///
/// verify_signature(signature, &bytes)?;
///
/// Ok(Self(serde_json::from_slice(&bytes)?))
/// }
/// }
///
/// // Once implemented, use it like the built-in extractors:
/// #[route(POST "/api/signed")]
/// async fn signed(SignedJson(input): SignedJson<CreateUser>) -> Result<&'static str> {
/// let _ = input;
/// Ok("ok")
/// }
/// ```
/// Yields the request body unchanged, leaving it unbuffered for the handler to
/// read or forward itself.
/// Buffers the entire request body into memory, rejecting a body larger than
/// the request's [`body_limit`] with `413 Content Too Large`.
/// Buffers the entire request body into a mutable buffer.
/// Buffers the request body and decodes it as UTF-8, rejecting a non-UTF-8 body
/// with `400 Bad Request`.
/// Customizes the behavior of `Option<Self>` as a [`FromRequest`] extractor.
///
/// Implementing this trait lets `Option<Self>` be extracted from a request,
/// yielding `None` when the request carries no value for the extractor (for
/// example, a missing body) while still surfacing an error for values that are
/// present but malformed.
/// Makes any [`OptionalFromRequest`] extractor optional, yielding `None` when
/// the request carries no value of that kind while still surfacing an error for
/// a value that is present but malformed.
/// Returns the [`Parts`] of the current request.
///
/// Use this to read several request fields at once. For one field, use its
/// accessor, such as [`method`] or [`headers`].
///
/// # Examples
///
/// ```rust
/// use topcoat::{context::Cx, router::request::parts};
///
/// async fn log_request(cx: &Cx) {
/// let parts = parts(cx);
/// println!("{} {}", parts.method, parts.uri);
/// }
/// ```
/// Returns the HTTP [`Method`] of the current request.
///
/// [`Method`]: http::Method
///
/// # Examples
///
/// ```rust
/// use topcoat::{context::Cx, router::request::method};
///
/// async fn is_post(cx: &Cx) -> bool {
/// method(cx) == http::Method::POST
/// }
/// ```
/// Returns the [`Uri`] of the current request.
///
/// [`Uri`]: http::Uri
///
/// # Examples
///
/// ```rust
/// use topcoat::{context::Cx, router::request::uri};
///
/// async fn current_path(cx: &Cx) -> &str {
/// uri(cx).path()
/// }
/// ```
/// Returns the HTTP [`Version`] of the current request.
///
/// [`Version`]: http::Version
///
/// # Examples
///
/// ```rust
/// use topcoat::{context::Cx, router::request::version};
///
/// async fn is_http2(cx: &Cx) -> bool {
/// *version(cx) == http::Version::HTTP_2
/// }
/// ```
/// Returns the [`HeaderMap`] of the current request.
///
/// [`HeaderMap`]: http::HeaderMap
///
/// # Examples
///
/// ```rust
/// use topcoat::{context::Cx, router::request::headers};
///
/// async fn user_agent(cx: &Cx) -> Option<&str> {
/// headers(cx).get("user-agent")?.to_str().ok()
/// }
/// ```
/// Returns the `Content-Type` header of the current request as a string slice,
/// or [`None`] when it is absent or not valid UTF-8.
///
/// # Examples
///
/// ```rust
/// use topcoat::{context::Cx, router::request::content_type};
///
/// async fn is_json(cx: &Cx) -> bool {
/// content_type(cx).is_some_and(|value| value.starts_with("application/json"))
/// }
/// ```
/// Returns the [`Extensions`] of the current request.
///
/// Extensions carry typed values attached to the request, typically by
/// middleware running before the handler.
///
/// [`Extensions`]: http::Extensions
///
/// # Examples
///
/// ```rust
/// use topcoat::{context::Cx, router::request::extensions};
///
/// struct RequestId(String);
///
/// async fn request_id(cx: &Cx) -> Option<&str> {
/// extensions(cx).get::<RequestId>().map(|id| id.0.as_str())
/// }
/// ```
/// Returns the IP address and port of the direct connection for this request,
/// or `None` when they are unknown.
///
/// Behind a reverse proxy, this returns the proxy's address. Use
/// [`client_ip`] to read the client's IP address instead.
/// Returns `None` if the request has no [`RemoteAddr`] in its extensions,
/// as is normally the case for Unix socket connections, or if the context
/// was not created by a router.
///
/// # Examples
///
/// ```rust
/// use topcoat::{context::Cx, router::request::remote_addr};
///
/// fn peer_port(cx: &Cx) -> Option<u16> {
/// remote_addr(cx).map(|addr| addr.port())
/// }
/// ```
/// Returns the client's IP address for this request, or `None`
/// when it cannot be determined.
///
/// By default, this returns the IP address from [`remote_addr`]. Behind a
/// reverse proxy, that is the proxy's address. Configure
/// [`TrustedProxies`](crate::TrustedProxies) on the router to read the
/// client's address from the proxy's header.
///
/// For a header that lists multiple addresses, Topcoat starts with the direct
/// connection and reads the list from right to left. It skips trusted proxies
/// and returns the first address it does not trust. If every address is
/// trusted, it returns the leftmost address. If the list is empty or missing,
/// it uses the direct connection's address.
///
/// Returns `None` if the direct connection's address is unknown and it is not
/// trusted through [`TrustedProxies::nearest`](crate::TrustedProxies::nearest),
/// or if an address needed from the header cannot be parsed. Headers
/// containing a single address follow the rules in
/// [`ForwardedHeader::Single`](crate::ForwardedHeader::Single). IPv4-mapped
/// IPv6 addresses are returned as IPv4.
///
/// The router determines the address before running any layers. Later changes
/// to request headers do not change this result. Returns `None` if the context
/// was not created by a router.
///
/// # Examples
///
/// ```rust
/// use topcoat::{
/// Result,
/// context::Cx,
/// router::{error::forbidden, request::client_ip},
/// };
///
/// # fn is_banned(_ip: std::net::IpAddr) -> bool { false }
/// fn reject_banned(cx: &Cx) -> Result<()> {
/// match client_ip(cx) {
/// Some(ip) if is_banned(ip) => Err(forbidden().into()),
/// _ => Ok(()),
/// }
/// }
/// ```
/// The parts the request arrived with, shared by every dispatch.
pub );
/// Returns the [`Parts`] of the request as the client sent it, before any
/// rewrite or changes made by layers.
///
/// A handler reached through a [`rewrite`](crate::error::rewrite) sees the
/// rewritten request in [`parts`], which may differ in its URI and method;
/// this accessor returns the parts the request arrived with. Layers can
/// also change the current parts without a rewrite. For example,
/// [`StripPrefixLayer`](crate::StripPrefixLayer) changes the current URI
/// while leaving the original URI intact.
///
/// # Examples
///
/// ```rust
/// use topcoat::{context::Cx, router::request::original_parts};
///
/// async fn arrived_with_header(cx: &Cx, name: &str) -> bool {
/// original_parts(cx).headers.contains_key(name)
/// }
/// ```
/// Returns the HTTP [`Method`] the client actually requested with, before
/// any rewrite.
///
/// A rewrite may dispatch the request with another method; this accessor
/// returns the one the request arrived with. For a request that was never
/// rewritten it is the same as [`method`].
///
/// [`Method`]: http::Method
///
/// # Examples
///
/// ```rust
/// use topcoat::{context::Cx, router::request::original_method};
///
/// async fn arrived_as_post(cx: &Cx) -> bool {
/// original_method(cx) == http::Method::POST
/// }
/// ```
/// Returns the [`Uri`] the client actually requested, before any rewrite.
///
/// A handler reached through a [`rewrite`](crate::error::rewrite) sees the
/// rewritten URI in [`uri`]; this accessor returns the URI the request
/// arrived with, for example to render a form that posts back to the visible
/// URL. Layers such as [`StripPrefixLayer`](crate::StripPrefixLayer) can
/// also change the current URI without changing this original URI.
///
/// [`Uri`]: http::Uri
///
/// # Examples
///
/// ```rust
/// use topcoat::{context::Cx, router::request::original_uri};
///
/// async fn form_action(cx: &Cx) -> String {
/// original_uri(cx).path().to_owned()
/// }
/// ```
/// Returns the HTTP [`Version`] of the request as the client sent it, before
/// any rewrite.
///
/// See [`original_parts`] for how a rewritten request differs from the one
/// that arrived.
///
/// [`Version`]: http::Version
/// Returns the [`HeaderMap`] of the request as the client sent it, before
/// any rewrite.
///
/// See [`original_parts`] for how a rewritten request differs from the one
/// that arrived.
///
/// [`HeaderMap`]: http::HeaderMap
/// Returns the `Content-Type` header of the request as the client sent it,
/// before any rewrite, as a string slice, or [`None`] when it is absent or
/// not valid UTF-8.
///
/// See [`original_parts`] for how a rewritten request differs from the one
/// that arrived.
/// Returns the [`Extensions`] of the request as the client sent it, before
/// any rewrite.
///
/// See [`original_parts`] for how a rewritten request differs from the one
/// that arrived.
///
/// [`Extensions`]: http::Extensions
/// The header naming the identity the router installs on a request's context.
pub const IDENTITY_HEADER: &str = "x-topcoat-identity";
/// Returns the identity the current request's build starts at.
///
/// A client re-running part of a page names the identity of that part in
/// the [`IDENTITY_HEADER`], so the server derives the same identities inside
/// it as the render the client holds. A request without the header starts at
/// [`Identity::ROOT`], like a page request.
///
/// # Errors
///
/// Errors with a `400 Bad Request` if the header is present but not an
/// identity.
///
/// # Examples
///
/// ```rust
/// use topcoat::{
/// Result, context::Cx, core::identity::Identity, router::request::initial_identity,
/// };
///
/// async fn is_page_request(cx: &Cx) -> Result<bool> {
/// Ok(initial_identity(cx)? == Identity::ROOT)
/// }
/// ```