Skip to main content

encore_reqauth/
meta.rs

1use std::str::{self, FromStr};
2
3use http::HeaderValue;
4
5pub trait HeaderValueExt {
6    fn to_utf8_str(&self) -> Result<&str, std::str::Utf8Error>;
7}
8
9impl HeaderValueExt for HeaderValue {
10    // Some header values may contain utf8 characters (e.g authdata) so we use `str::from_utf8`
11    // rather than using `HeaderValues::to_str` which errors on non-visible ASCII characters.
12    fn to_utf8_str(&self) -> Result<&str, std::str::Utf8Error> {
13        std::str::from_utf8(self.as_bytes())
14    }
15}
16
17#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)]
18pub enum MetaKey {
19    TraceParent,
20    TraceState,
21    XCorrelationId,
22    Version,
23    UserId,
24    UserData,
25    Caller,
26    Callee,
27    SvcAuthMethod,
28    SvcAuthEncoreAuthHash,
29    SvcAuthEncoreAuthDate,
30    /// The service a call between containers is for, which the receiving
31    /// gateway routes on. Only a gateway sends it.
32    Service,
33    /// The gateway a public request another container's gateway relayed is
34    /// for, which the receiving gateway serves it through. Only a gateway
35    /// sends it.
36    Gateway,
37    /// The frontend a public request another container's gateway relayed is
38    /// for: one a service there hosts, which the receiving gateway passes it
39    /// to. Only a gateway sends it.
40    Frontend,
41    /// The address of the client a relayed public request came from, which
42    /// the receiving gateway serves it as. Covered by a relay's signature
43    /// alone.
44    ClientIp,
45    /// The host a relayed public request was first sent to, which the
46    /// receiving gateway serves it for. Covered by a relay's signature alone.
47    ForwardedHost,
48    /// What tells one relay from every other, so the receiving gateway serves
49    /// each once. Covered by a relay's signature alone.
50    RelayId,
51}
52
53impl MetaKey {
54    pub fn header_key(&self) -> &'static str {
55        use MetaKey::*;
56        match self {
57            TraceParent => "traceparent",
58            TraceState => "tracestate",
59            XCorrelationId => "x-correlation-id",
60            Version => "x-encore-meta-version",
61            UserId => "x-encore-meta-userid",
62            UserData => "x-encore-meta-authdata",
63            Caller => "x-encore-meta-caller",
64            Callee => "x-encore-meta-callee",
65            SvcAuthMethod => "x-encore-meta-svc-auth-method",
66            SvcAuthEncoreAuthHash => "x-encore-meta-svc-auth",
67            SvcAuthEncoreAuthDate => "x-encore-meta-date",
68            Service => "x-encore-service",
69            Gateway => "x-encore-gateway",
70            Frontend => "x-encore-frontend",
71            ClientIp => "x-encore-client-ip",
72            ForwardedHost => "x-forwarded-host",
73            RelayId => "x-encore-relay-id",
74        }
75    }
76}
77
78pub struct NotMetaKey;
79
80impl FromStr for MetaKey {
81    type Err = NotMetaKey;
82
83    fn from_str(value: &str) -> Result<Self, Self::Err> {
84        use MetaKey::*;
85        Ok(match value {
86            "traceparent" => TraceParent,
87            "tracestate" => TraceState,
88            "x-correlation-id" => XCorrelationId,
89            "x-encore-meta-version" => Version,
90            "x-encore-meta-userid" => UserId,
91            "x-encore-meta-authdata" => UserData,
92            "x-encore-meta-caller" => Caller,
93            "x-encore-meta-callee" => Callee,
94            "x-encore-meta-svc-auth-method" => SvcAuthMethod,
95            "x-encore-meta-svc-auth" => SvcAuthEncoreAuthHash,
96            "x-encore-meta-date" => SvcAuthEncoreAuthDate,
97            "x-encore-service" => Service,
98            "x-encore-gateway" => Gateway,
99            "x-encore-frontend" => Frontend,
100            "x-encore-client-ip" => ClientIp,
101            "x-forwarded-host" => ForwardedHost,
102            "x-encore-relay-id" => RelayId,
103            _ => return Err(NotMetaKey),
104        })
105    }
106}
107pub trait MetaMapMut: MetaMap {
108    fn set(&mut self, key: MetaKey, value: String) -> anyhow::Result<()>;
109}
110
111pub trait MetaMap {
112    fn get_meta(&self, key: MetaKey) -> Option<&str>;
113    fn meta_values<'a>(&'a self, key: MetaKey) -> Box<dyn Iterator<Item = &'a str> + 'a>;
114
115    /// Returns all meta keys, sorted alphabetically based on MetaKey::header_key.
116    fn sorted_meta_keys(&self) -> Vec<MetaKey>;
117
118    /// Every value of every Request Context header
119    /// ([`crate::reqctx::HEADER_PREFIX`]), with its header's name, in no
120    /// particular order. Values are bytes, so one that is not UTF-8 is still
121    /// covered by a call's signature.
122    fn ctx_fields(&self) -> Vec<(&str, &[u8])>;
123}
124
125/// The Request Context headers of `headers`, with each of their values.
126fn ctx_fields_of(headers: &http::HeaderMap) -> Vec<(&str, &[u8])> {
127    headers
128        .iter()
129        .filter(|(name, _)| crate::reqctx::is_field_header(name.as_str()))
130        .map(|(name, value)| (name.as_str(), value.as_bytes()))
131        .collect()
132}
133
134impl MetaMapMut for http::HeaderMap {
135    fn set(&mut self, key: MetaKey, value: String) -> anyhow::Result<()> {
136        self.insert(key.header_key(), value.parse()?);
137        Ok(())
138    }
139}
140
141impl MetaMap for http::HeaderMap {
142    fn get_meta(&self, key: MetaKey) -> Option<&str> {
143        self.get(key.header_key())
144            .and_then(|val| val.to_utf8_str().ok())
145    }
146
147    fn meta_values<'a>(&'a self, key: MetaKey) -> Box<dyn Iterator<Item = &'a str> + 'a> {
148        Box::new(
149            self.get_all(key.header_key())
150                .iter()
151                .filter_map(|v| v.to_utf8_str().ok()),
152        )
153    }
154
155    fn sorted_meta_keys(&self) -> Vec<MetaKey> {
156        let mut keys: Vec<_> = self
157            .keys()
158            .filter_map(|k| MetaKey::from_str(k.as_str()).ok())
159            .collect();
160        keys.sort_by_key(|k| k.header_key());
161        keys
162    }
163
164    fn ctx_fields(&self) -> Vec<(&str, &[u8])> {
165        ctx_fields_of(self)
166    }
167}
168
169#[cfg(feature = "pingora")]
170impl MetaMapMut for pingora_http::RequestHeader {
171    fn set(&mut self, key: MetaKey, value: String) -> anyhow::Result<()> {
172        self.insert_header(key.header_key(), value)?;
173        Ok(())
174    }
175}
176
177#[cfg(feature = "pingora")]
178impl MetaMap for pingora_http::RequestHeader {
179    fn get_meta(&self, key: MetaKey) -> Option<&str> {
180        self.headers
181            .get(key.header_key())
182            .and_then(|v| v.to_utf8_str().ok())
183    }
184
185    fn meta_values<'a>(&'a self, key: MetaKey) -> Box<dyn Iterator<Item = &'a str> + 'a> {
186        Box::new(
187            self.headers
188                .get_all(key.header_key())
189                .iter()
190                .filter_map(|v| v.to_utf8_str().ok()),
191        )
192    }
193
194    fn sorted_meta_keys(&self) -> Vec<MetaKey> {
195        let mut keys: Vec<_> = self
196            .headers
197            .keys()
198            .filter_map(|k| MetaKey::from_str(k.as_str()).ok())
199            .collect();
200        keys.sort_by_key(|k| k.header_key());
201        keys
202    }
203
204    fn ctx_fields(&self) -> Vec<(&str, &[u8])> {
205        ctx_fields_of(&self.headers)
206    }
207}