actix_cloud/
security.rs

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
use std::fmt::Display;

use actix_web::middleware;

#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone, Debug)]
pub enum RefererPolicy {
    NoReferrer,
    NoReferrerWhenDowngrade,
    Origin,
    OriginWhenCrossOrigin,
    SameOrigin,
    StrictOrigin,
    StrictOriginWhenCrossOrigin,
    UnsafeUrl,
}

impl Display for RefererPolicy {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            RefererPolicy::NoReferrer => "no-referrer",
            RefererPolicy::NoReferrerWhenDowngrade => "no-referrer-when-downgrade",
            RefererPolicy::Origin => "origin",
            RefererPolicy::OriginWhenCrossOrigin => "origin-when-cross-origin",
            RefererPolicy::SameOrigin => "same-origin",
            RefererPolicy::StrictOrigin => "strict-origin",
            RefererPolicy::StrictOriginWhenCrossOrigin => "strict-origin-when-cross-origin",
            RefererPolicy::UnsafeUrl => "unsafe-url",
        })
    }
}

#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone, Debug)]
pub enum XFrameOptions {
    Deny,
    SameOrigin,
}

impl Display for XFrameOptions {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            XFrameOptions::Deny => "DENY",
            XFrameOptions::SameOrigin => "SAMEORIGIN",
        })
    }
}

#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone, Debug)]
pub enum XXSSProtection {
    Disable,
    Enable,
    EnableBlock,
    EnableReport(String),
}

impl Display for XXSSProtection {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            XXSSProtection::Disable => f.write_str("0"),
            XXSSProtection::Enable => f.write_str("1"),
            XXSSProtection::EnableBlock => f.write_str("1; mode=block"),
            XXSSProtection::EnableReport(x) => f.write_str(&format!("1; report={}", x)),
        }
    }
}

#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone, Debug)]
pub enum CrossOriginOpenerPolicy {
    UnsafeNone,
    SameOriginAllowPopups,
    SameOrigin,
}

impl Display for CrossOriginOpenerPolicy {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            CrossOriginOpenerPolicy::UnsafeNone => "unsafe-none",
            CrossOriginOpenerPolicy::SameOriginAllowPopups => "same-origin-allow-popups",
            CrossOriginOpenerPolicy::SameOrigin => "same-origin",
        })
    }
}

#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone, Debug)]
pub enum StrictTransportSecurity {
    MaxAge(u32),
    IncludeSubDomains(u32),
    Preload(u32),
}

impl Display for StrictTransportSecurity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            StrictTransportSecurity::MaxAge(x) => f.write_str(&format!("max-age={}", x)),
            StrictTransportSecurity::IncludeSubDomains(x) => {
                f.write_str(&format!("max-age={}; includeSubDomains", x))
            }
            StrictTransportSecurity::Preload(x) => {
                f.write_str(&format!("max-age={}; includeSubDomains; preload", x))
            }
        }
    }
}

#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone, Debug)]
pub struct SecurityHeader {
    pub referer_policy: RefererPolicy,
    pub x_frame_options: XFrameOptions,
    pub x_xss_protection: XXSSProtection,
    pub cross_origin_opener_policy: CrossOriginOpenerPolicy,
    pub content_security_policy: String,
    pub strict_transport_security: Option<StrictTransportSecurity>,
}

impl Default for SecurityHeader {
    fn default() -> Self {
        Self {
            referer_policy: RefererPolicy::StrictOriginWhenCrossOrigin,
            x_frame_options: XFrameOptions::Deny,
            x_xss_protection: XXSSProtection::EnableBlock,
            cross_origin_opener_policy: CrossOriginOpenerPolicy::SameOrigin,
            content_security_policy: String::from("default-src 'none'; script-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'"),
            strict_transport_security: None,
        }
    }
}

impl SecurityHeader {
    /// Set default HSTS to 1 year, includeSubDomains and preload.
    ///
    /// `max-age=31536000; includeSubDomains; preload`
    pub fn set_default_hsts(&mut self) {
        self.strict_transport_security = Some(StrictTransportSecurity::Preload(31536000));
    }

    pub fn build(self) -> middleware::DefaultHeaders {
        let mut ret = middleware::DefaultHeaders::new()
            .add(("X-Content-Type-Options", "nosniff"))
            .add(("Referrer-Policy", self.referer_policy.to_string()))
            .add(("X-Frame-Options", self.x_frame_options.to_string()))
            .add(("X-XSS-Protection", self.x_xss_protection.to_string()))
            .add((
                "Cross-Origin-Opener-Policy",
                self.cross_origin_opener_policy.to_string(),
            ))
            .add(("Content-Security-Policy", self.content_security_policy));
        if let Some(hsts) = self.strict_transport_security {
            ret = ret.add(("Strict-Transport-Security", hsts.to_string()));
        }
        ret
    }
}