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
mod csp;
pub mod directives;
pub mod domains;
mod parse;
use csp::generate;
use directives::GetDirectives;
use serde_json::error;
pub struct Csp {
pub header: String,
pub csp: String,
}
fn parse_csp_result(header: String, result: Result<String, error::Error>) -> Csp {
match result {
Ok(result) => Csp {
header,
csp: result,
},
Err(e) => panic!("Could not parse JSON: {}", e),
}
}
pub fn enforce(directives: impl GetDirectives, json: &str) -> Csp {
parse_csp_result(
"Content-Security-Policy".to_string(),
generate(directives, json),
)
}
pub fn report_only(directives: impl GetDirectives, json: &str) -> Csp {
parse_csp_result(
"Content-Security-Policy-Report-Only".to_string(),
generate(directives, json),
)
}
pub fn csp_only(directives: impl GetDirectives, json: &str) -> String {
parse_csp_result(
"Content-Security-Policy".to_string(),
generate(directives, json),
)
.csp
}
#[cfg(test)]
mod csp_generator_test {
#[test]
fn test_csp_struct() {
let csp = super::Csp {
header: String::from("header"),
csp: String::from("csp"),
};
assert_eq!(csp.header, String::from("header"));
assert_eq!(csp.csp, String::from("csp"));
}
#[test]
fn test_parse_csp_result() {
let csp = super::parse_csp_result(String::from("CSP"), Ok(String::from("Hello World")));
assert_eq!(csp.header, String::from("CSP"));
assert_eq!(csp.csp, String::from("Hello World"));
}
}