Skip to main content

parse/
parse.rs

1//! Parses a real multi-directive CSP and prints its structured
2//! directives. Run with `cargo run --example parse`.
3
4use csp_parse::{DirectiveValue, parse_policy_list};
5
6fn main() {
7    let policy = "default-src 'self'; \
8                  script-src 'self' 'nonce-2726c7f26c' https://cdn.example.com; \
9                  img-src 'self' data:; \
10                  frame-ancestors 'none'; \
11                  upgrade-insecure-requests; \
12                  report-to csp-endpoint";
13
14    println!("Parsing: {policy}\n");
15
16    let policy_list = parse_policy_list(policy);
17    for policy in &policy_list.policies {
18        for directive in &policy.directives {
19            println!("{}:", directive.name);
20            match directive.value() {
21                DirectiveValue::SourceList(list) => println!("  source list: {list:?}"),
22                DirectiveValue::AncestorSourceList(list) => {
23                    println!("  ancestor source list: {list:?}");
24                }
25                DirectiveValue::Boolean => println!("  (no value)"),
26                DirectiveValue::Token(token) => println!("  token: {token:?}"),
27                other => println!("  {other:?}"),
28            }
29        }
30    }
31}