footing 0.6.4

Feature-gated foundations for Rust backend services
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
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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
//! Request-scoped identity, locale, client, and correlation context.

use std::{convert::Infallible, fmt, net::IpAddr};

use axum::{
    extract::FromRequestParts,
    http::{HeaderMap, HeaderValue, request::Parts},
};
use serde::{Deserialize, Deserializer, Serialize};

#[cfg(feature = "http-locale")]
use crate::http::locale::ResolvedLocale;
use crate::{auth::Principal, http::trusted_proxy::ForwardedHeadersPolicy, net::ClientIp};

use super::{
    forwarding::{ClientIpSource, ForwardedHeadersStatus, client_ip_from_forwarded_headers},
    identifiers::{REQUEST_ID_HEADER_NAME, RequestId, TRACEPARENT_HEADER_NAME, TraceParent},
};

/// Locale header name.
pub const LOCALE_HEADER_NAME: &str = "x-locale";
/// Time zone header name.
pub const TIME_ZONE_HEADER_NAME: &str = "x-time-zone";
/// UTC offset header name.
pub const UTC_OFFSET_HEADER_NAME: &str = "x-utc-offset";
/// Client identifier header name.
pub const CLIENT_ID_HEADER_NAME: &str = "x-client-id";
/// Session identifier header name.
pub const SESSION_ID_HEADER_NAME: &str = "x-session-id";
/// Maximum supported request context value length.
pub const MAX_REQUEST_CONTEXT_VALUE_LENGTH: usize = 256;
/// Maximum supported user agent length.
pub const MAX_USER_AGENT_LENGTH: usize = 512;

#[derive(Clone, Serialize)]
/// Context associated with request.
pub struct RequestContext {
    request_id: RequestId,
    traceparent: Option<TraceParent>,
    client_ip: Option<ClientIp>,
    client_ip_source: Option<ClientIpSource>,
    forwarded_headers_status: Option<ForwardedHeadersStatus>,
    locale: Option<String>,
    #[cfg(feature = "http-locale")]
    #[serde(skip)]
    resolved_locale: Option<ResolvedLocale>,
    time_zone: Option<String>,
    utc_offset_minutes: Option<i16>,
    user_agent: Option<String>,
    client_id: Option<String>,
    session_id: Option<String>,
    principal: Option<Principal>,
}

impl fmt::Debug for RequestContext {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut debug = formatter.debug_struct("RequestContext");
        debug
            .field("request_id", &self.request_id)
            .field("traceparent", &self.traceparent)
            .field("client_ip", &self.client_ip.as_ref().map(|_| "[REDACTED]"))
            .field("client_ip_source", &self.client_ip_source)
            .field("forwarded_headers_status", &self.forwarded_headers_status)
            .field("locale", &self.locale.as_ref().map(|_| "[REDACTED]"))
            .field("time_zone", &self.time_zone.as_ref().map(|_| "[REDACTED]"))
            .field("utc_offset_minutes", &self.utc_offset_minutes)
            .field(
                "user_agent",
                &self.user_agent.as_ref().map(|_| "[REDACTED]"),
            )
            .field("client_id", &self.client_id.as_ref().map(|_| "[REDACTED]"))
            .field(
                "session_id",
                &self.session_id.as_ref().map(|_| "[REDACTED]"),
            )
            .field("principal", &self.principal);
        #[cfg(feature = "http-locale")]
        debug.field("resolved_locale", &self.resolved_locale);
        debug.finish()
    }
}

impl<'de> Deserialize<'de> for RequestContext {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct RequestContextWire {
            request_id: RequestId,
            #[serde(default)]
            traceparent: Option<TraceParent>,
            #[serde(default)]
            client_ip: Option<ClientIp>,
            #[serde(default)]
            client_ip_source: Option<ClientIpSource>,
            #[serde(default)]
            forwarded_headers_status: Option<ForwardedHeadersStatus>,
            #[serde(default)]
            locale: Option<String>,
            #[serde(default)]
            time_zone: Option<String>,
            #[serde(default)]
            utc_offset_minutes: Option<i16>,
            #[serde(default)]
            user_agent: Option<String>,
            #[serde(default)]
            client_id: Option<String>,
            #[serde(default)]
            session_id: Option<String>,
            #[serde(default)]
            principal: Option<Principal>,
        }

        let wire = RequestContextWire::deserialize(deserializer)?;
        let mut context = Self {
            request_id: wire.request_id,
            traceparent: wire.traceparent,
            client_ip: None,
            client_ip_source: None,
            forwarded_headers_status: wire.forwarded_headers_status,
            locale: wire.locale.as_deref().and_then(normalize_locale),
            #[cfg(feature = "http-locale")]
            resolved_locale: None,
            time_zone: wire.time_zone.as_deref().and_then(normalize_time_zone),
            utc_offset_minutes: wire
                .utc_offset_minutes
                .filter(|value| valid_utc_offset_minutes(*value)),
            user_agent: wire.user_agent.as_deref().and_then(normalize_user_agent),
            client_id: wire.client_id.as_deref().and_then(normalize_context_id),
            session_id: wire.session_id.as_deref().and_then(normalize_context_id),
            principal: wire.principal,
        };

        if let Some(client_ip) = wire.client_ip {
            context.client_ip = Some(client_ip);
            context.client_ip_source = wire.client_ip_source.or(Some(ClientIpSource::Explicit));
        }

        if let Some(status) = context.forwarded_headers_status {
            let consistent = match status {
                ForwardedHeadersStatus::Resolved => matches!(
                    context.client_ip_source,
                    Some(
                        ClientIpSource::Forwarded
                            | ClientIpSource::XForwardedFor
                            | ClientIpSource::XRealIp
                    )
                ),
                ForwardedHeadersStatus::MissingPeer => context.client_ip_source.is_none(),
                ForwardedHeadersStatus::UntrustedPeer | ForwardedHeadersStatus::NoUntrustedHop => {
                    context.client_ip_source == Some(ClientIpSource::Peer)
                }
                ForwardedHeadersStatus::Absent
                | ForwardedHeadersStatus::Disabled
                | ForwardedHeadersStatus::Malformed
                | ForwardedHeadersStatus::Conflicting => {
                    matches!(context.client_ip_source, None | Some(ClientIpSource::Peer))
                }
            };
            if !consistent {
                return Err(serde::de::Error::custom(
                    "forwarded-header status does not match the client IP source",
                ));
            }
        }

        Ok(context)
    }
}

impl RequestContext {
    pub(crate) fn from_parts(parts: &mut Parts) -> &mut Self {
        parts
            .extensions
            .get_or_insert_with(|| Self::from_headers(&parts.headers))
    }

    #[must_use]
    /// Creates a context with an explicit, validated request identifier.
    ///
    /// Add validated tracing and address information through
    /// [`Self::with_traceparent`] and [`Self::with_client_ip`]. These fields are
    /// never reparsed or silently discarded; parsing errors remain with the caller.
    /// Use [`Self::from_headers`] to apply the tolerant untrusted-header policy.
    ///
    /// ```
    /// use footing::{http::{RequestContext, RequestId, TraceParent}, net::ClientIp};
    ///
    /// let context = RequestContext::new(RequestId::new("request-123")?)
    ///     .with_traceparent(TraceParent::new(
    ///         "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
    ///     )?)
    ///     .with_client_ip(ClientIp::new("198.51.100.10")?);
    /// assert_eq!(context.client_ip(), Some("198.51.100.10"));
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn new(request_id: RequestId) -> Self {
        Self {
            request_id,
            traceparent: None,
            client_ip: None,
            client_ip_source: None,
            forwarded_headers_status: None,
            locale: None,
            #[cfg(feature = "http-locale")]
            resolved_locale: None,
            time_zone: None,
            utc_offset_minutes: None,
            user_agent: None,
            client_id: None,
            session_id: None,
            principal: None,
        }
    }

    #[must_use]
    /// Creates a context from untrusted request headers.
    ///
    /// Correlation headers are accepted only when exactly one field is present
    /// and its value is valid. A missing, invalid, or repeated `x-request-id`
    /// generates a new identifier; an invalid or repeated `traceparent` is
    /// ignored. Repeated fields are ambiguous even when their values are equal.
    pub fn from_headers(headers: &HeaderMap) -> Self {
        Self::from_headers_and_peer_ip(headers, None)
    }

    #[must_use]
    /// Creates a value from headers and peer IP.
    /// Uses the correlation-header rules of [`Self::from_headers`].
    pub fn from_headers_and_peer_ip(headers: &HeaderMap, peer_client_ip: Option<IpAddr>) -> Self {
        Self::from_headers_and_peer_ip_with_forwarded_policy(
            headers,
            peer_client_ip,
            &ForwardedHeadersPolicy::never(),
        )
    }

    #[must_use]
    /// Creates a value from headers and peer IP with forwarded policy.
    /// Uses the correlation-header rules of [`Self::from_headers`].
    pub fn from_headers_and_peer_ip_with_forwarded_policy(
        headers: &HeaderMap,
        peer_client_ip: Option<IpAddr>,
        forwarded_headers: &ForwardedHeadersPolicy,
    ) -> Self {
        let request_id = single_header_value(headers, REQUEST_ID_HEADER_NAME)
            .and_then(RequestId::parse)
            .unwrap_or_default();

        let traceparent =
            single_header_value(headers, TRACEPARENT_HEADER_NAME).and_then(TraceParent::parse);
        let (client_ip, client_ip_source, forwarded_headers_status) =
            resolve_client_ip(headers, peer_client_ip, forwarded_headers);
        let locale = locale_from_headers(headers);
        let time_zone = header_values(headers, TIME_ZONE_HEADER_NAME).find_map(normalize_time_zone);
        let utc_offset_minutes =
            header_values(headers, UTC_OFFSET_HEADER_NAME).find_map(parse_utc_offset_minutes);
        let user_agent = header_values(headers, "user-agent").find_map(normalize_user_agent);
        let client_id =
            header_values(headers, CLIENT_ID_HEADER_NAME).find_map(normalize_context_id);
        let session_id =
            header_values(headers, SESSION_ID_HEADER_NAME).find_map(normalize_context_id);

        Self {
            request_id,
            traceparent,
            client_ip,
            client_ip_source,
            forwarded_headers_status: Some(forwarded_headers_status),
            locale,
            #[cfg(feature = "http-locale")]
            resolved_locale: None,
            time_zone,
            utc_offset_minutes,
            user_agent,
            client_id,
            session_id,
            principal: None,
        }
    }

    pub(crate) fn refresh_client_ip(
        &mut self,
        headers: &HeaderMap,
        peer_client_ip: Option<IpAddr>,
        forwarded_headers: &ForwardedHeadersPolicy,
    ) {
        // Explicit addresses come from application code, not forwarded headers.
        // All other sources must respect the policy of the current middleware.
        if self.client_ip_source != Some(ClientIpSource::Explicit) {
            let (client_ip, source, status) =
                resolve_client_ip(headers, peer_client_ip, forwarded_headers);
            self.client_ip = client_ip;
            self.client_ip_source = source;
            self.forwarded_headers_status = Some(status);
        }
    }

    #[must_use]
    /// Returns the request identifier.
    pub const fn request_id(&self) -> &RequestId {
        &self.request_id
    }

    #[must_use]
    /// Returns the W3C `traceparent` header value as text.
    pub fn traceparent_str(&self) -> Option<&str> {
        self.traceparent.as_ref().map(TraceParent::as_str)
    }

    #[must_use]
    /// Returns the validated, structured W3C `traceparent` value.
    pub fn traceparent_value(&self) -> Option<&TraceParent> {
        self.traceparent.as_ref()
    }

    #[must_use]
    /// Returns the trace identifier.
    pub fn trace_id(&self) -> Option<&str> {
        self.traceparent.as_ref().map(TraceParent::trace_id)
    }

    #[must_use]
    /// Returns the span identifier.
    pub fn span_id(&self) -> Option<&str> {
        self.traceparent.as_ref().map(TraceParent::span_id)
    }

    #[must_use]
    /// Returns the client IP.
    pub fn client_ip(&self) -> Option<&str> {
        self.client_ip.as_ref().map(ClientIp::as_str)
    }

    #[must_use]
    /// Returns the client IP addr.
    pub fn client_ip_addr(&self) -> Option<IpAddr> {
        self.client_ip.as_ref().map(ClientIp::as_ip_addr)
    }

    #[must_use]
    /// Returns the client IP source.
    pub const fn client_ip_source(&self) -> Option<ClientIpSource> {
        self.client_ip_source
    }

    #[must_use]
    /// Returns how the current forwarding policy handled the request headers.
    ///
    /// Absence is checked first. Present headers are only parsed after the policy
    /// permits their use; ignored untrusted input is not classified as malformed.
    /// `X-Real-IP` is examined only when both chain headers are absent. A valid
    /// chain therefore takes precedence even if `X-Real-IP` is malformed or differs.
    /// `Forwarded` parameter syntax is checked even for unused parameters, and
    /// names cannot repeat within one element. IPv6 addresses and nodes with a
    /// port must be quoted; IPv6 addresses also require brackets.
    /// Numeric and obfuscated ports are accepted, but the node must identify an IP.
    ///
    /// `None` means no outcome is recorded: the context was constructed directly,
    /// deserialized without this field, or its client IP was explicitly set or
    /// cleared. Serialization preserves a recorded outcome; deserialization rejects
    /// outcomes inconsistent with the client-IP source. It cannot authenticate
    /// the provenance of serialized context supplied by an application.
    ///
    /// No request is rejected or logged automatically. Applications can use this
    /// diagnostic to decide their own strict proxy policy:
    ///
    /// ```
    /// use axum::http::HeaderMap;
    /// use footing::http::{ForwardedHeadersPolicy, ForwardedHeadersStatus, RequestContext};
    ///
    /// let mut headers = HeaderMap::new();
    /// headers.insert("x-forwarded-for", "invalid".parse()?);
    /// let context = RequestContext::from_headers_and_peer_ip_with_forwarded_policy(
    ///     &headers,
    ///     Some("127.0.0.1".parse()?),
    ///     &ForwardedHeadersPolicy::local_development(),
    /// );
    /// assert_eq!(context.forwarded_headers_status(), Some(ForwardedHeadersStatus::Malformed));
    /// assert_eq!(context.client_ip(), Some("127.0.0.1"));
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub const fn forwarded_headers_status(&self) -> Option<ForwardedHeadersStatus> {
        self.forwarded_headers_status
    }

    #[must_use]
    /// Returns the explicit `x-locale`, or the highest-weight concrete
    /// `Accept-Language` preference. Equal weights retain request order;
    /// excluded (`q=0`), wildcard and malformed language ranges are ignored.
    /// This is the client's preference, not a negotiated response language;
    /// the application still selects which of its supported locales to serve.
    #[cfg_attr(
        feature = "http-locale",
        doc = "Use [`Self::resolved_locale`] for the locale selected by the application's policy."
    )]
    pub fn locale(&self) -> Option<&str> {
        self.locale.as_deref()
    }

    /// Returns the locale selected by the application's locale policy.
    ///
    /// This request-runtime value is independent of [`Self::locale`]. New and
    /// deserialized contexts have no resolved locale until the application or
    /// locale middleware installs one; it is never serialized.
    #[cfg(feature = "http-locale")]
    #[must_use]
    pub const fn resolved_locale(&self) -> Option<&ResolvedLocale> {
        self.resolved_locale.as_ref()
    }

    /// Installs a policy-validated locale without changing the client's preference.
    #[cfg(feature = "http-locale")]
    pub fn set_resolved_locale(&mut self, locale: ResolvedLocale) {
        self.resolved_locale = Some(locale);
    }

    /// Clears the resolved locale without changing the client's preference.
    #[cfg(feature = "http-locale")]
    pub fn clear_resolved_locale(&mut self) {
        self.resolved_locale = None;
    }

    #[must_use]
    /// Returns the time zone.
    pub fn time_zone(&self) -> Option<&str> {
        self.time_zone.as_deref()
    }

    #[must_use]
    /// Returns the UTC offset minutes.
    pub const fn utc_offset_minutes(&self) -> Option<i16> {
        self.utc_offset_minutes
    }

    #[must_use]
    /// Returns the user agent.
    pub fn user_agent(&self) -> Option<&str> {
        self.user_agent.as_deref()
    }

    #[must_use]
    /// Returns the client identifier.
    pub fn client_id(&self) -> Option<&str> {
        self.client_id.as_deref()
    }

    #[must_use]
    /// Returns the session identifier.
    pub fn session_id(&self) -> Option<&str> {
        self.session_id.as_deref()
    }

    #[must_use]
    /// Returns the principal.
    pub const fn principal(&self) -> Option<&Principal> {
        self.principal.as_ref()
    }

    #[must_use]
    /// Configures principal and returns the updated value.
    pub fn with_principal(mut self, principal: Principal) -> Self {
        self.principal = Some(principal);
        self
    }

    #[must_use]
    /// Configures traceparent and returns the updated value.
    pub fn with_traceparent(mut self, traceparent: TraceParent) -> Self {
        self.traceparent = Some(traceparent);
        self
    }

    /// Sets traceparent.
    pub fn set_traceparent(&mut self, traceparent: TraceParent) {
        self.traceparent = Some(traceparent);
    }

    #[must_use]
    /// Sets an explicit address from a validated [`ClientIp`] or an [`IpAddr`].
    ///
    /// Parse text with [`ClientIp::new`] before calling this method. Explicit
    /// addresses take precedence over forwarding policies and clear the previous
    /// forwarding diagnostic. IPv4-mapped IPv6 addresses normalize to IPv4.
    pub fn with_client_ip(mut self, client_ip: impl Into<ClientIp>) -> Self {
        self.set_client_ip(client_ip);
        self
    }

    /// Sets an explicit address with the same rules as [`Self::with_client_ip`].
    pub fn set_client_ip(&mut self, client_ip: impl Into<ClientIp>) {
        self.set_explicit_client_ip(Some(client_ip.into()));
    }

    fn set_explicit_client_ip(&mut self, client_ip: Option<ClientIp>) {
        self.client_ip_source = client_ip.as_ref().map(|_| ClientIpSource::Explicit);
        self.client_ip = client_ip;
        self.forwarded_headers_status = None;
    }

    #[must_use]
    /// Configures locale and returns the updated value.
    pub fn with_locale(mut self, locale: impl AsRef<str>) -> Self {
        self.locale = normalize_locale(locale.as_ref());
        self
    }

    /// Sets locale.
    pub fn set_locale(&mut self, locale: impl AsRef<str>) {
        self.locale = normalize_locale(locale.as_ref());
    }

    #[must_use]
    /// Clears locale.
    pub fn clear_locale(mut self) -> Self {
        self.locale = None;
        self
    }

    #[must_use]
    /// Configures time zone and returns the updated value.
    pub fn with_time_zone(mut self, time_zone: impl AsRef<str>) -> Self {
        self.time_zone = normalize_time_zone(time_zone.as_ref());
        self
    }

    /// Sets time zone.
    pub fn set_time_zone(&mut self, time_zone: impl AsRef<str>) {
        self.time_zone = normalize_time_zone(time_zone.as_ref());
    }

    #[must_use]
    /// Clears time zone.
    pub fn clear_time_zone(mut self) -> Self {
        self.time_zone = None;
        self
    }

    #[must_use]
    /// Configures UTC offset minutes and returns the updated value.
    pub const fn with_utc_offset_minutes(mut self, utc_offset_minutes: i16) -> Self {
        self.utc_offset_minutes = if valid_utc_offset_minutes(utc_offset_minutes) {
            Some(utc_offset_minutes)
        } else {
            None
        };
        self
    }

    /// Sets UTC offset minutes.
    pub fn set_utc_offset_minutes(&mut self, utc_offset_minutes: i16) {
        self.utc_offset_minutes = if valid_utc_offset_minutes(utc_offset_minutes) {
            Some(utc_offset_minutes)
        } else {
            None
        };
    }

    #[must_use]
    /// Clears UTC offset minutes.
    pub const fn clear_utc_offset_minutes(mut self) -> Self {
        self.utc_offset_minutes = None;
        self
    }

    #[must_use]
    /// Configures user agent and returns the updated value.
    pub fn with_user_agent(mut self, user_agent: impl AsRef<str>) -> Self {
        self.user_agent = normalize_user_agent(user_agent.as_ref());
        self
    }

    /// Sets user agent.
    pub fn set_user_agent(&mut self, user_agent: impl AsRef<str>) {
        self.user_agent = normalize_user_agent(user_agent.as_ref());
    }

    #[must_use]
    /// Clears user agent.
    pub fn clear_user_agent(mut self) -> Self {
        self.user_agent = None;
        self
    }

    #[must_use]
    /// Configures client identifier and returns the updated value.
    pub fn with_client_id(mut self, client_id: impl AsRef<str>) -> Self {
        self.client_id = normalize_context_id(client_id.as_ref());
        self
    }

    /// Sets client identifier.
    pub fn set_client_id(&mut self, client_id: impl AsRef<str>) {
        self.client_id = normalize_context_id(client_id.as_ref());
    }

    #[must_use]
    /// Clears client identifier.
    pub fn clear_client_id(mut self) -> Self {
        self.client_id = None;
        self
    }

    #[must_use]
    /// Configures session identifier and returns the updated value.
    pub fn with_session_id(mut self, session_id: impl AsRef<str>) -> Self {
        self.session_id = normalize_context_id(session_id.as_ref());
        self
    }

    /// Sets session identifier.
    pub fn set_session_id(&mut self, session_id: impl AsRef<str>) {
        self.session_id = normalize_context_id(session_id.as_ref());
    }

    #[must_use]
    /// Clears session identifier.
    pub fn clear_session_id(mut self) -> Self {
        self.session_id = None;
        self
    }

    #[must_use]
    /// Clears client IP.
    pub fn clear_client_ip(mut self) -> Self {
        self.set_explicit_client_ip(None);
        self
    }

    #[must_use]
    /// Clears traceparent.
    pub fn clear_traceparent(mut self) -> Self {
        self.traceparent = None;
        self
    }

    /// Sets principal.
    pub fn set_principal(&mut self, principal: Principal) {
        self.principal = Some(principal);
    }

    /// Clears principal.
    pub fn clear_principal(&mut self) {
        self.principal = None;
    }

    /// Replaces the response's request identifier with this context's identifier.
    pub fn write_response_headers(&self, headers: &mut HeaderMap) {
        headers.insert(REQUEST_ID_HEADER_NAME, HeaderValue::from(self.request_id()));
    }
}

impl<S> FromRequestParts<S> for RequestContext
where
    S: Send + Sync,
{
    type Rejection = Infallible;

    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        Ok(Self::from_parts(parts).clone())
    }
}

fn resolve_client_ip(
    headers: &HeaderMap,
    peer_client_ip: Option<IpAddr>,
    forwarded_headers: &ForwardedHeadersPolicy,
) -> (
    Option<ClientIp>,
    Option<ClientIpSource>,
    ForwardedHeadersStatus,
) {
    match client_ip_from_forwarded_headers(headers, peer_client_ip, forwarded_headers) {
        Ok((client_ip, source)) => (
            Some(client_ip),
            Some(source),
            ForwardedHeadersStatus::Resolved,
        ),
        Err(status) => (
            peer_client_ip.map(ClientIp::from_ip_addr),
            peer_client_ip.map(|_| ClientIpSource::Peer),
            status,
        ),
    }
}

fn single_header_value<'a>(headers: &'a HeaderMap, name: &'static str) -> Option<&'a str> {
    let mut values = headers.get_all(name).iter();
    let value = values.next()?;
    if values.next().is_some() {
        return None;
    }
    value.to_str().ok()
}

fn header_values<'a>(headers: &'a HeaderMap, name: &'static str) -> impl Iterator<Item = &'a str> {
    headers
        .get_all(name)
        .iter()
        .filter_map(|value| value.to_str().ok())
        .map(str::trim)
        .filter(|value| !value.is_empty())
}

fn locale_from_headers(headers: &HeaderMap) -> Option<String> {
    header_values(headers, LOCALE_HEADER_NAME)
        .find_map(normalize_locale)
        .or_else(|| {
            header_values(headers, "accept-language")
                .flat_map(|value| value.split(','))
                .filter_map(parse_language_preference)
                .reduce(|best, candidate| {
                    if candidate.0 > best.0 {
                        candidate
                    } else {
                        best
                    }
                })
                .map(|(_, locale)| locale.to_owned())
        })
}

fn parse_language_preference(value: &str) -> Option<(u16, &str)> {
    let mut parts = value.split(';');
    let locale = parts.next()?.trim();
    // A wildcard expresses no concrete locale; retain only basic language ranges.
    if locale.len() > MAX_REQUEST_CONTEXT_VALUE_LENGTH
        || !locale.split('-').enumerate().all(|(index, subtag)| {
            (1..=8).contains(&subtag.len())
                && subtag.bytes().all(|byte| {
                    if index == 0 {
                        byte.is_ascii_alphabetic()
                    } else {
                        byte.is_ascii_alphanumeric()
                    }
                })
        })
    {
        return None;
    }
    let quality = match parts.next() {
        None => 1000,
        Some(parameter) => {
            let (name, value) = parameter.trim().split_once('=')?;
            if !name.trim().eq_ignore_ascii_case("q") || parts.next().is_some() {
                return None;
            }
            crate::http::parse_quality(value.trim())?
        }
    };
    (quality > 0).then_some((quality, locale))
}

fn normalize_locale(value: &str) -> Option<String> {
    normalize_context_token(value, MAX_REQUEST_CONTEXT_VALUE_LENGTH, |character| {
        character.is_ascii_alphanumeric() || matches!(character, '-' | '_')
    })
}

fn normalize_time_zone(value: &str) -> Option<String> {
    normalize_context_token(value, MAX_REQUEST_CONTEXT_VALUE_LENGTH, |character| {
        character.is_ascii_alphanumeric() || matches!(character, '/' | '_' | '-' | '+')
    })
}

fn normalize_user_agent(value: &str) -> Option<String> {
    normalize_context_token(value, MAX_USER_AGENT_LENGTH, |character| {
        !character.is_control()
    })
}

fn normalize_context_id(value: &str) -> Option<String> {
    normalize_context_token(value, MAX_REQUEST_CONTEXT_VALUE_LENGTH, |character| {
        character.is_ascii_alphanumeric() || matches!(character, '-' | '_' | '.' | ':' | '@')
    })
}

fn normalize_context_token(
    value: &str,
    max_bytes: usize,
    valid_character: impl Fn(char) -> bool,
) -> Option<String> {
    let value = value.trim();
    if value.is_empty() || value.len() > max_bytes || !value.chars().all(valid_character) {
        return None;
    }
    Some(value.to_owned())
}

fn parse_utc_offset_minutes(value: &str) -> Option<i16> {
    let value = value.trim();
    if value.is_empty() {
        return None;
    }
    if let Ok(minutes) = value.parse::<i16>() {
        return valid_utc_offset_minutes(minutes).then_some(minutes);
    }

    let sign = match value.as_bytes().first()? {
        b'+' => 1,
        b'-' => -1,
        _ => return None,
    };
    let value = value.strip_prefix(['+', '-']).unwrap_or_default();
    let (hours, minutes) = value.split_once(':')?;
    let hours = hours.parse::<i16>().ok()?;
    let minutes = minutes.parse::<i16>().ok()?;
    if !(0..=23).contains(&hours) || !(0..=59).contains(&minutes) {
        return None;
    }
    let total = sign * (hours * 60 + minutes);
    valid_utc_offset_minutes(total).then_some(total)
}

const fn valid_utc_offset_minutes(value: i16) -> bool {
    value >= -23 * 60 - 59 && value <= 23 * 60 + 59
}