|
| 1 | +use crate::headers::{Header, HeaderName, HeaderValue, Headers}; |
| 2 | +use crate::Status; |
| 3 | + |
| 4 | +use crate::headers::STRICT_TRANSPORT_SECURITY; |
| 5 | +use std::time::Duration; |
| 6 | + |
| 7 | +/// Inform browsers that the site should only be accessed using HTTPS. |
| 8 | +/// |
| 9 | +/// # Specifications |
| 10 | +/// |
| 11 | +/// - [RFC 6797, section 6.1: Strict-Transport-Security](https://www.rfc-editor.org/rfc/rfc6797#section-6.1) |
| 12 | +#[derive(Debug)] |
| 13 | +#[doc(alias = "hsts")] |
| 14 | +pub struct StrictTransportSecurity { |
| 15 | + max_age: Duration, |
| 16 | + include_subdomains: bool, |
| 17 | + preload: bool, |
| 18 | +} |
| 19 | + |
| 20 | +impl Default for StrictTransportSecurity { |
| 21 | + /// Defaults to 1 year with "preload" enabled, passing the minimum requirements to |
| 22 | + /// qualify for inclusion in browser's HSTS preload lists. |
| 23 | + /// [Read more](https://hstspreload.org/) |
| 24 | + fn default() -> Self { |
| 25 | + Self { |
| 26 | + max_age: Duration::from_secs(31536000), // 1 year |
| 27 | + include_subdomains: false, |
| 28 | + preload: true, |
| 29 | + } |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +impl StrictTransportSecurity { |
| 34 | + /// Create a new instance. |
| 35 | + pub fn new(duration: Duration) -> Self { |
| 36 | + Self { |
| 37 | + max_age: duration, |
| 38 | + include_subdomains: false, |
| 39 | + preload: false, |
| 40 | + } |
| 41 | + } |
| 42 | + /// Get a reference to the strict transport security's include subdomains. |
| 43 | + pub fn include_subdomains(&self) -> bool { |
| 44 | + self.include_subdomains |
| 45 | + } |
| 46 | + |
| 47 | + /// Set the strict transport security's include subdomains. |
| 48 | + pub fn set_include_subdomains(&mut self, include_subdomains: bool) { |
| 49 | + self.include_subdomains = include_subdomains; |
| 50 | + } |
| 51 | + |
| 52 | + /// Get a reference to the strict transport security's preload. |
| 53 | + pub fn preload(&self) -> bool { |
| 54 | + self.preload |
| 55 | + } |
| 56 | + |
| 57 | + /// Set the strict transport security's preload. |
| 58 | + pub fn set_preload(&mut self, preload: bool) { |
| 59 | + self.preload = preload; |
| 60 | + } |
| 61 | + |
| 62 | + /// Get a reference to the strict transport security's max_age. |
| 63 | + pub fn max_age(&self) -> Duration { |
| 64 | + self.max_age |
| 65 | + } |
| 66 | + |
| 67 | + /// Set the strict transport security's max_age. |
| 68 | + pub fn set_max_age(&mut self, duration: Duration) { |
| 69 | + self.max_age = duration; |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +impl Header for StrictTransportSecurity { |
| 74 | + fn header_name(&self) -> HeaderName { |
| 75 | + STRICT_TRANSPORT_SECURITY |
| 76 | + } |
| 77 | + |
| 78 | + fn header_value(&self) -> HeaderValue { |
| 79 | + let max_age = self.max_age.as_secs(); |
| 80 | + let mut output = format!("max-age={}", max_age); |
| 81 | + if self.include_subdomains { |
| 82 | + output.push_str(";includeSubdomains"); |
| 83 | + } |
| 84 | + if self.preload { |
| 85 | + output.push_str(";preload"); |
| 86 | + } |
| 87 | + |
| 88 | + // SAFETY: the internal string is validated to be ASCII. |
| 89 | + unsafe { HeaderValue::from_bytes_unchecked(output.into()) } |
| 90 | + } |
| 91 | +} |
| 92 | + |
| 93 | +// TODO: move to new header traits |
| 94 | +impl StrictTransportSecurity { |
| 95 | + /// Create a new instance from headers. |
| 96 | + pub fn from_headers(headers: impl AsRef<Headers>) -> crate::Result<Option<Self>> { |
| 97 | + let headers = match headers.as_ref().get(STRICT_TRANSPORT_SECURITY) { |
| 98 | + Some(headers) => headers, |
| 99 | + None => return Ok(None), |
| 100 | + }; |
| 101 | + |
| 102 | + // If we successfully parsed the header then there's always at least one |
| 103 | + // entry. We want the last entry. |
| 104 | + let value = headers.iter().last().unwrap(); |
| 105 | + |
| 106 | + let mut max_age = None; |
| 107 | + let mut include_subdomains = false; |
| 108 | + let mut preload = false; |
| 109 | + |
| 110 | + // Attempt to parse all values. If we don't recognize a directive, per |
| 111 | + // the spec we should just ignore it. |
| 112 | + for s in value.as_str().split(';') { |
| 113 | + let s = s.trim(); |
| 114 | + if s == "includesubdomains" { |
| 115 | + include_subdomains = true; |
| 116 | + } else if s == "preload" { |
| 117 | + preload = true; |
| 118 | + } else { |
| 119 | + let (key, value) = match s.split_once("=") { |
| 120 | + Some(kv) => kv, |
| 121 | + None => continue, // We don't recognize the directive, continue. |
| 122 | + }; |
| 123 | + |
| 124 | + if key == "max-age" { |
| 125 | + let secs = value.parse::<u64>().status(400)?; |
| 126 | + max_age = Some(Duration::from_secs(secs)); |
| 127 | + } |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + let max_age = match max_age { |
| 132 | + Some(max_age) => max_age, |
| 133 | + None => { |
| 134 | + return Err(crate::format_err_status!( |
| 135 | + 400, |
| 136 | + "`Strict-Transport-Security` header did not contain a `max-age` directive", |
| 137 | + )); |
| 138 | + } |
| 139 | + }; |
| 140 | + |
| 141 | + Ok(Some(Self { |
| 142 | + max_age, |
| 143 | + include_subdomains, |
| 144 | + preload, |
| 145 | + })) |
| 146 | + } |
| 147 | +} |
| 148 | + |
| 149 | +impl From<StrictTransportSecurity> for Duration { |
| 150 | + fn from(stc: StrictTransportSecurity) -> Self { |
| 151 | + stc.max_age |
| 152 | + } |
| 153 | +} |
| 154 | + |
| 155 | +impl From<Duration> for StrictTransportSecurity { |
| 156 | + fn from(duration: Duration) -> Self { |
| 157 | + Self::new(duration) |
| 158 | + } |
| 159 | +} |
| 160 | + |
| 161 | +#[cfg(test)] |
| 162 | +mod test { |
| 163 | + use super::*; |
| 164 | + use crate::Response; |
| 165 | + use std::time::Duration; |
| 166 | + |
| 167 | + #[test] |
| 168 | + fn smoke() -> crate::Result<()> { |
| 169 | + let duration = Duration::from_secs(30); |
| 170 | + let stc = StrictTransportSecurity::new(duration); |
| 171 | + |
| 172 | + let mut headers = Response::new(200); |
| 173 | + stc.apply_header(&mut headers); |
| 174 | + |
| 175 | + let stc = StrictTransportSecurity::from_headers(headers)?.unwrap(); |
| 176 | + |
| 177 | + assert_eq!(stc.max_age(), duration); |
| 178 | + assert!(!stc.preload); |
| 179 | + assert!(!stc.include_subdomains); |
| 180 | + Ok(()) |
| 181 | + } |
| 182 | + |
| 183 | + #[test] |
| 184 | + fn bad_request_on_parse_error() { |
| 185 | + let mut headers = Response::new(200); |
| 186 | + headers |
| 187 | + .insert_header(STRICT_TRANSPORT_SECURITY, "<nori ate the tag. yum.>") |
| 188 | + .unwrap(); |
| 189 | + let err = StrictTransportSecurity::from_headers(headers).unwrap_err(); |
| 190 | + assert_eq!(err.status(), 400); |
| 191 | + } |
| 192 | + |
| 193 | + #[test] |
| 194 | + fn no_panic_on_invalid_number() { |
| 195 | + let mut headers = Response::new(200); |
| 196 | + headers |
| 197 | + .insert_header(STRICT_TRANSPORT_SECURITY, "max-age=birds") |
| 198 | + .unwrap(); |
| 199 | + let err = StrictTransportSecurity::from_headers(headers).unwrap_err(); |
| 200 | + assert_eq!(err.status(), 400); |
| 201 | + } |
| 202 | + |
| 203 | + #[test] |
| 204 | + fn parse_optional_whitespace() { |
| 205 | + let mut headers = Response::new(200); |
| 206 | + headers |
| 207 | + .insert_header(STRICT_TRANSPORT_SECURITY, "max-age=30; preload") |
| 208 | + .unwrap(); |
| 209 | + let policy = StrictTransportSecurity::from_headers(headers) |
| 210 | + .unwrap() |
| 211 | + .unwrap(); |
| 212 | + assert_eq!(policy.max_age, Duration::from_secs(30)); |
| 213 | + assert!(policy.preload()); |
| 214 | + } |
| 215 | +} |
0 commit comments