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
//! Strict-Transport-Security typed header.
//!
//! See [`StrictTransportSecurity`] docs.

use std::{convert::Infallible, str, time::Duration};

use actix_web::{
    error::ParseError,
    http::header::{
        from_one_raw_str, Header, HeaderName, HeaderValue, TryIntoHeaderValue,
        STRICT_TRANSPORT_SECURITY,
    },
    HttpMessage,
};

const SECS_IN_YEAR: u64 = 3600 * 24 * 365;

/// HTTP Strict Transport Security (HSTS) configuration.
///
/// Care should be taken when setting up HSTS for your site; misconfiguration can potentially leave
/// parts of your site in an unusable state.
///
/// # `Default`
/// The `Default` implementation uses a 5 minute `max-age` and does not include subdomains or
/// preloading. This default is intentionally conservative to prevent accidental misconfiguration
/// causing irrecoverable problems for users.
///
/// Once you have configured and tested the default HSTS config, [`recommended`](Self::recommended)
/// can be used as a secure default for production.
///
/// # References
/// See the [HSTS page on MDN] for more information.
///
/// [HSTS page on MDN]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[doc(alias = "hsts", alias = "sts")]
pub struct StrictTransportSecurity {
    duration: Duration,

    /// The `includeSubdomains` directive.
    pub include_subdomains: bool,

    /// The `preload` directive.
    pub preload: bool,
}

impl StrictTransportSecurity {
    /// Constructs a new HSTS configuration using the given `duration`.
    ///
    /// Other values take their default.
    pub fn new(duration: Duration) -> Self {
        Self {
            duration,
            ..Self::default()
        }
    }

    /// Constructs a secure, production-ready HSTS configuration.
    ///
    /// Uses a `max-age` of 2 years and includes subdomains.
    pub fn recommended() -> Self {
        Self {
            duration: Duration::from_secs(2 * SECS_IN_YEAR),
            include_subdomains: true,
            ..Self::default()
        }
    }

    /// Send `includeSubdomains` directive with header.
    pub fn include_subdomains(mut self) -> Self {
        self.include_subdomains = true;
        self
    }

    /// Send `preload` directive with header.
    ///
    /// See <https://hstspreload.org/> for more information.
    pub fn preload(mut self) -> Self {
        self.preload = true;
        self
    }
}

impl Default for StrictTransportSecurity {
    fn default() -> Self {
        Self {
            duration: Duration::from_secs(300),
            include_subdomains: false,
            preload: false,
        }
    }
}

impl str::FromStr for StrictTransportSecurity {
    type Err = ParseError;

    fn from_str(val: &str) -> Result<Self, Self::Err> {
        let mut parts = val.split(';').map(str::trim);

        // parse max-age/duration from first part of header
        let duration = parts
            .next()
            .ok_or(ParseError::Header)?
            .split_once('=')
            .and_then(|(key, max_age)| {
                if key.trim() != "max-age" {
                    return None;
                }

                max_age.trim().parse().ok()
            })
            .map(Duration::from_secs)
            .ok_or(ParseError::Header)?;

        let mut include_subdomains = false;
        let mut preload = false;

        // find known attributes in remaining parts
        for part in parts {
            if part == "includeSubdomains" {
                include_subdomains = true;
            }

            if part == "preload" {
                preload = true;
            }
        }

        Ok(Self {
            duration,
            include_subdomains,
            preload,
        })
    }
}

impl TryIntoHeaderValue for StrictTransportSecurity {
    type Error = Infallible;

    fn try_into_value(self) -> Result<HeaderValue, Self::Error> {
        let secs = self.duration.as_secs();
        let subdomains = if self.include_subdomains {
            "; includeSubDomains"
        } else {
            ""
        };
        let preload = if self.preload { "; preload" } else { "" };

        // eg: max-age=31536000; includeSubDomains; preload
        let sts = format!("max-age={secs}{subdomains}{preload}")
            .parse()
            .unwrap();

        Ok(sts)
    }
}

impl Header for StrictTransportSecurity {
    fn name() -> HeaderName {
        STRICT_TRANSPORT_SECURITY
    }

    fn parse<M: HttpMessage>(msg: &M) -> Result<Self, ParseError> {
        from_one_raw_str(msg.headers().get(Self::name()))
    }
}

#[cfg(test)]
mod test {
    use actix_web::HttpResponse;

    use super::*;

    #[test]
    fn hsts_as_header() {
        let res = HttpResponse::Ok()
            .insert_header(StrictTransportSecurity::default())
            .finish();
        assert_eq!(
            res.headers()
                .get(StrictTransportSecurity::name())
                .unwrap()
                .to_str()
                .unwrap(),
            "max-age=300"
        );

        let res = HttpResponse::Ok()
            .insert_header(StrictTransportSecurity::default().include_subdomains())
            .finish();
        assert_eq!(
            res.headers()
                .get(StrictTransportSecurity::name())
                .unwrap()
                .to_str()
                .unwrap(),
            "max-age=300; includeSubDomains"
        );

        let res = HttpResponse::Ok()
            .insert_header(StrictTransportSecurity::default().preload())
            .finish();
        assert_eq!(
            res.headers()
                .get(StrictTransportSecurity::name())
                .unwrap()
                .to_str()
                .unwrap(),
            "max-age=300; preload"
        );

        let res = HttpResponse::Ok()
            .insert_header(
                StrictTransportSecurity::default()
                    .include_subdomains()
                    .preload(),
            )
            .finish();
        assert_eq!(
            res.headers()
                .get(StrictTransportSecurity::name())
                .unwrap()
                .to_str()
                .unwrap(),
            "max-age=300; includeSubDomains; preload"
        );
    }

    #[test]
    fn recommended_config() {
        let res = HttpResponse::Ok()
            .insert_header(StrictTransportSecurity::recommended())
            .finish();
        assert_eq!(
            res.headers().get("strict-transport-security").unwrap(),
            "max-age=63072000; includeSubDomains"
        );
    }

    #[test]
    fn parsing() {
        assert!("".parse::<StrictTransportSecurity>().is_err());
        assert!("duration=1".parse::<StrictTransportSecurity>().is_err());

        assert_eq!(
            "max-age=1".parse::<StrictTransportSecurity>().unwrap(),
            StrictTransportSecurity {
                duration: Duration::from_secs(1),
                include_subdomains: false,
                preload: false,
            }
        );

        assert_eq!(
            "max-age=1; includeSubdomains"
                .parse::<StrictTransportSecurity>()
                .unwrap(),
            StrictTransportSecurity {
                duration: Duration::from_secs(1),
                include_subdomains: true,
                preload: false,
            }
        );

        assert_eq!(
            "max-age=1; preload"
                .parse::<StrictTransportSecurity>()
                .unwrap(),
            StrictTransportSecurity {
                duration: Duration::from_secs(1),
                include_subdomains: false,
                preload: true,
            }
        );

        assert_eq!(
            "max-age=1; includeSubdomains; preload"
                .parse::<StrictTransportSecurity>()
                .unwrap(),
            StrictTransportSecurity {
                duration: Duration::from_secs(1),
                include_subdomains: true,
                preload: true,
            }
        );
    }
}