logo
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
use std::collections::HashSet;

use http::{header::HeaderName, HeaderMap};

use crate::{Endpoint, IntoResponse, Middleware, Request, Response, Result};

#[derive(Debug, Copy, Clone, Eq, PartialEq)]
enum AppliedTo {
    RequestOnly,
    ResponseOnly,
    Both,
}

impl Default for AppliedTo {
    fn default() -> Self {
        AppliedTo::Both
    }
}

/// Middleware for mark headers value represents sensitive information.
///
/// Sensitive data could represent passwords or other data that should not be
/// stored on disk or in memory. By marking header values as sensitive,
/// components using this crate can be instructed to treat them with special
/// care for security reasons. For example, caches can avoid storing sensitive
/// values, and `HPACK` encoders used by `HTTP/2.0` implementations can choose
/// not to compress them.
///
/// Additionally, sensitive values will be masked by the `Debug` implementation
/// of HeaderValue.
///
/// # Reference
///
/// - <https://docs.rs/http/0.2.6/http/header/struct.HeaderValue.html#method.set_sensitive>
/// - <https://docs.rs/http/0.2.6/http/header/struct.HeaderValue.html#method.is_sensitive>
#[derive(Default)]
pub struct SensitiveHeader {
    headers: HashSet<HeaderName>,
    applied_to: AppliedTo,
}

impl SensitiveHeader {
    /// Create new `SensitiveHeader` middleware.
    #[must_use]
    pub fn new() -> Self {
        Default::default()
    }

    /// Applies to request headers only.
    #[must_use]
    pub fn request_only(self) -> Self {
        Self {
            applied_to: AppliedTo::RequestOnly,
            ..self
        }
    }

    /// Applies to responses headers only.
    #[must_use]
    pub fn response_only(self) -> Self {
        Self {
            applied_to: AppliedTo::ResponseOnly,
            ..self
        }
    }

    /// Append a header.
    #[must_use]
    pub fn header<K>(mut self, key: K) -> Self
    where
        K: TryInto<HeaderName>,
    {
        if let Ok(key) = key.try_into() {
            self.headers.insert(key);
        }
        self
    }
}

impl<E: Endpoint> Middleware<E> for SensitiveHeader {
    type Output = SensitiveHeaderEndpoint<E>;

    fn transform(&self, ep: E) -> Self::Output {
        SensitiveHeaderEndpoint {
            inner: ep,
            headers: self.headers.clone(),
            applied_to: self.applied_to,
        }
    }
}

/// Endpoint for SensitiveHeader middleware.
pub struct SensitiveHeaderEndpoint<E> {
    inner: E,
    headers: HashSet<HeaderName>,
    applied_to: AppliedTo,
}

#[async_trait::async_trait]
impl<E: Endpoint> Endpoint for SensitiveHeaderEndpoint<E> {
    type Output = Response;

    async fn call(&self, mut req: Request) -> Result<Self::Output> {
        if self.applied_to != AppliedTo::ResponseOnly {
            set_sensitive(req.headers_mut(), &self.headers);
        }

        let mut resp = self.inner.call(req).await?.into_response();

        if self.applied_to != AppliedTo::RequestOnly {
            set_sensitive(resp.headers_mut(), &self.headers);
        }

        Ok(resp)
    }
}

#[allow(clippy::mutable_key_type)]
fn set_sensitive(headers: &mut HeaderMap, names: &HashSet<HeaderName>) {
    for name in names {
        if let Some(value) = headers.get_mut(name) {
            value.set_sensitive(true);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{handler, EndpointExt};

    fn create_middleware() -> SensitiveHeader {
        SensitiveHeader::new()
            .header("x-api-key1")
            .header("x-api-key2")
            .header("x-api-key3")
            .header("x-api-key4")
    }

    fn create_request() -> Request {
        Request::builder()
            .header("x-api-key1", "a")
            .header("x-api-key2", "b")
            .finish()
    }

    #[tokio::test]
    async fn test_sensitive_header_request_only() {
        #[handler(internal)]
        fn index(headers: &HeaderMap) -> impl IntoResponse {
            assert!(headers.get("x-api-key1").unwrap().is_sensitive());
            assert!(headers.get("x-api-key2").unwrap().is_sensitive());

            ().with_header("x-api-key3", "c")
                .with_header("x-api-key4", "c")
        }

        let resp = index
            .with(create_middleware().request_only())
            .get_response(create_request())
            .await;

        assert!(!resp.headers().get("x-api-key3").unwrap().is_sensitive());
        assert!(!resp.headers().get("x-api-key4").unwrap().is_sensitive());
    }

    #[tokio::test]
    async fn test_sensitive_header_response_only() {
        #[handler(internal)]
        fn index(headers: &HeaderMap) -> impl IntoResponse {
            assert!(!headers.get("x-api-key1").unwrap().is_sensitive());
            assert!(!headers.get("x-api-key2").unwrap().is_sensitive());

            ().with_header("x-api-key3", "c")
                .with_header("x-api-key4", "c")
        }

        let resp = index
            .with(create_middleware().response_only())
            .get_response(create_request())
            .await;

        assert!(resp.headers().get("x-api-key3").unwrap().is_sensitive());
        assert!(resp.headers().get("x-api-key4").unwrap().is_sensitive());
    }

    #[tokio::test]
    async fn test_sensitive_header_both() {
        #[handler(internal)]
        fn index(headers: &HeaderMap) -> impl IntoResponse {
            assert!(headers.get("x-api-key1").unwrap().is_sensitive());
            assert!(headers.get("x-api-key2").unwrap().is_sensitive());

            ().with_header("x-api-key3", "c")
                .with_header("x-api-key4", "c")
        }

        let resp = index
            .with(create_middleware())
            .get_response(create_request())
            .await;

        assert!(resp.headers().get("x-api-key3").unwrap().is_sensitive());
        assert!(resp.headers().get("x-api-key4").unwrap().is_sensitive());
    }
}