http_security_headers/policy/
frame_options.rs

1//! X-Frame-Options header configuration.
2//!
3//! The X-Frame-Options header protects against clickjacking attacks by controlling
4//! whether a browser should be allowed to render a page in a `<frame>`, `<iframe>`,
5//! `<embed>`, or `<object>`.
6
7use crate::error::{Error, Result};
8
9/// X-Frame-Options header value.
10///
11/// # Examples
12///
13/// ```
14/// use http_security_headers::XFrameOptions;
15///
16/// let deny = XFrameOptions::Deny;
17/// let sameorigin = XFrameOptions::SameOrigin;
18/// ```
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum XFrameOptions {
21    /// The page cannot be displayed in a frame, regardless of the site attempting to do so.
22    Deny,
23    /// The page can only be displayed in a frame on the same origin as the page itself.
24    SameOrigin,
25}
26
27impl XFrameOptions {
28    /// Converts the policy to its header value string.
29    pub fn as_str(&self) -> &'static str {
30        match self {
31            Self::Deny => "DENY",
32            Self::SameOrigin => "SAMEORIGIN",
33        }
34    }
35
36    /// Parses an X-Frame-Options value from a string.
37    pub fn from_str(s: &str) -> Result<Self> {
38        match s.to_uppercase().as_str() {
39            "DENY" => Ok(Self::Deny),
40            "SAMEORIGIN" => Ok(Self::SameOrigin),
41            _ => Err(Error::InvalidFrameOptions(format!(
42                "Expected 'DENY' or 'SAMEORIGIN', got '{}'",
43                s
44            ))),
45        }
46    }
47}
48
49impl std::fmt::Display for XFrameOptions {
50    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51        write!(f, "{}", self.as_str())
52    }
53}
54
55#[cfg(test)]
56mod tests {
57    use super::*;
58
59    #[test]
60    fn test_as_str() {
61        assert_eq!(XFrameOptions::Deny.as_str(), "DENY");
62        assert_eq!(XFrameOptions::SameOrigin.as_str(), "SAMEORIGIN");
63    }
64
65    #[test]
66    fn test_from_str() {
67        assert_eq!(XFrameOptions::from_str("DENY").unwrap(), XFrameOptions::Deny);
68        assert_eq!(XFrameOptions::from_str("deny").unwrap(), XFrameOptions::Deny);
69        assert_eq!(
70            XFrameOptions::from_str("SAMEORIGIN").unwrap(),
71            XFrameOptions::SameOrigin
72        );
73        assert_eq!(
74            XFrameOptions::from_str("sameorigin").unwrap(),
75            XFrameOptions::SameOrigin
76        );
77
78        assert!(XFrameOptions::from_str("invalid").is_err());
79    }
80
81    #[test]
82    fn test_display() {
83        assert_eq!(XFrameOptions::Deny.to_string(), "DENY");
84        assert_eq!(XFrameOptions::SameOrigin.to_string(), "SAMEORIGIN");
85    }
86}