|
1 |
| -use std::fmt::Display; |
2 |
| - |
| 1 | +use actix_web::http::header::{ |
| 2 | + HeaderName, HeaderValue, TryIntoHeaderPair, CONTENT_SECURITY_POLICY, |
| 3 | +}; |
| 4 | +use actix_web::HttpResponseBuilder; |
3 | 5 | use awc::http::header::InvalidHeaderValue;
|
4 | 6 | use rand::random;
|
| 7 | +use serde::Deserialize; |
| 8 | +use std::fmt::{Display, Formatter}; |
| 9 | +use std::sync::Arc; |
| 10 | + |
| 11 | +pub const DEFAULT_CONTENT_SECURITY_POLICY: &str = "script-src 'self' 'nonce-{NONCE}'"; |
5 | 12 |
|
6 |
| -#[derive(Debug, Clone, Copy)] |
| 13 | +#[derive(Debug, Clone)] |
7 | 14 | pub struct ContentSecurityPolicy {
|
8 | 15 | pub nonce: u64,
|
| 16 | + template: ContentSecurityPolicyTemplate, |
| 17 | +} |
| 18 | + |
| 19 | +/// A template for the Content Security Policy header. |
| 20 | +/// The template is a string that contains the nonce placeholder. |
| 21 | +/// The nonce placeholder is replaced with the nonce value when the Content Security Policy is applied to a response. |
| 22 | +/// This struct is cheap to clone. |
| 23 | +#[derive(Debug, Clone, PartialEq, Eq)] |
| 24 | +pub struct ContentSecurityPolicyTemplate { |
| 25 | + pub before_nonce: Arc<str>, |
| 26 | + pub after_nonce: Option<Arc<str>>, |
9 | 27 | }
|
10 | 28 |
|
11 |
| -impl Default for ContentSecurityPolicy { |
| 29 | +impl Default for ContentSecurityPolicyTemplate { |
12 | 30 | fn default() -> Self {
|
13 |
| - Self { nonce: random() } |
| 31 | + Self::from(DEFAULT_CONTENT_SECURITY_POLICY) |
14 | 32 | }
|
15 | 33 | }
|
16 | 34 |
|
17 |
| -impl Display for ContentSecurityPolicy { |
18 |
| - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
19 |
| - write!(f, "script-src 'self' 'nonce-{}'", self.nonce) |
| 35 | +impl From<&str> for ContentSecurityPolicyTemplate { |
| 36 | + fn from(s: &str) -> Self { |
| 37 | + if let Some((before, after)) = s.split_once("{NONCE}") { |
| 38 | + Self { |
| 39 | + before_nonce: Arc::from(before), |
| 40 | + after_nonce: Some(Arc::from(after)), |
| 41 | + } |
| 42 | + } else { |
| 43 | + Self { |
| 44 | + before_nonce: Arc::from(s), |
| 45 | + after_nonce: None, |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +impl<'de> Deserialize<'de> for ContentSecurityPolicyTemplate { |
| 52 | + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> |
| 53 | + where |
| 54 | + D: serde::Deserializer<'de>, |
| 55 | + { |
| 56 | + let s: &str = Deserialize::deserialize(deserializer)?; |
| 57 | + Ok(Self::from(s)) |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +impl ContentSecurityPolicy { |
| 62 | + #[must_use] |
| 63 | + pub fn new(template: ContentSecurityPolicyTemplate) -> Self { |
| 64 | + Self { |
| 65 | + nonce: random(), |
| 66 | + template, |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + pub fn apply_to_response(&self, response: &mut HttpResponseBuilder) { |
| 71 | + if self.is_enabled() { |
| 72 | + response.insert_header(self); |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + fn is_enabled(&self) -> bool { |
| 77 | + !self.template.before_nonce.is_empty() || self.template.after_nonce.is_some() |
20 | 78 | }
|
21 | 79 | }
|
22 | 80 |
|
23 |
| -impl actix_web::http::header::TryIntoHeaderPair for &ContentSecurityPolicy { |
| 81 | +impl Display for ContentSecurityPolicy { |
| 82 | + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { |
| 83 | + let before = self.template.before_nonce.as_ref(); |
| 84 | + if let Some(after) = &self.template.after_nonce { |
| 85 | + let nonce = self.nonce; |
| 86 | + write!(f, "{before}{nonce}{after}") |
| 87 | + } else { |
| 88 | + write!(f, "{before}") |
| 89 | + } |
| 90 | + } |
| 91 | +} |
| 92 | +impl TryIntoHeaderPair for &ContentSecurityPolicy { |
24 | 93 | type Error = InvalidHeaderValue;
|
25 | 94 |
|
26 |
| - fn try_into_pair( |
27 |
| - self, |
28 |
| - ) -> Result< |
29 |
| - ( |
30 |
| - actix_web::http::header::HeaderName, |
31 |
| - actix_web::http::header::HeaderValue, |
32 |
| - ), |
33 |
| - Self::Error, |
34 |
| - > { |
| 95 | + fn try_into_pair(self) -> Result<(HeaderName, HeaderValue), Self::Error> { |
35 | 96 | Ok((
|
36 |
| - actix_web::http::header::CONTENT_SECURITY_POLICY, |
37 |
| - actix_web::http::header::HeaderValue::from_str(&self.to_string())?, |
| 97 | + CONTENT_SECURITY_POLICY, |
| 98 | + HeaderValue::from_maybe_shared(self.to_string())?, |
38 | 99 | ))
|
39 | 100 | }
|
40 | 101 | }
|
| 102 | + |
| 103 | +#[cfg(test)] |
| 104 | +mod tests { |
| 105 | + use super::*; |
| 106 | + |
| 107 | + #[test] |
| 108 | + fn test_content_security_policy_display() { |
| 109 | + let template = ContentSecurityPolicyTemplate::from( |
| 110 | + "script-src 'self' 'nonce-{NONCE}' 'unsafe-inline'", |
| 111 | + ); |
| 112 | + let csp = ContentSecurityPolicy::new(template.clone()); |
| 113 | + let csp_str = csp.to_string(); |
| 114 | + assert!(csp_str.starts_with("script-src 'self' 'nonce-")); |
| 115 | + assert!(csp_str.ends_with("' 'unsafe-inline'")); |
| 116 | + let second_csp = ContentSecurityPolicy::new(template); |
| 117 | + let second_csp_str = second_csp.to_string(); |
| 118 | + assert_ne!( |
| 119 | + csp_str, second_csp_str, |
| 120 | + "We should not generate the same nonce twice" |
| 121 | + ); |
| 122 | + } |
| 123 | +} |
0 commit comments