CSP Builder — Rust source
Build a Content-Security-Policy header interactively. Toggle directives, add sources, see the assembled header in real time — with a security score that flags unsafe sources.
This is the Rust implementation — the same logic the interactive tool runs, in a shareable, citable form.
//! csp-builder — Content-Security-Policy assembly, parsing, linting and scoring.
//!
//! Language: Rust (std only — no external crates).
//! CosmoDev polyglot showcase port of the `csp-builder` tool, ported from
//! src/lib/csp-builder.ts (the canonical TypeScript implementation).
//!
//! A CSP is an ordered map of directive -> source list. std has no ordered
//! map, so the policy is a `Vec` of `(name, sources)` pairs — insertion order
//! is what decides where unknown directives land in the rebuilt header, the
//! same guarantee the TS Record leans on. Parse is lenient by design; nothing
//! here panics on content.
//!
//! display source — part of CosmoDev's polyglot tool pages.
/// A policy: directive name (lowercase) -> source list, insertion-ordered.
pub type Policy = Vec<(String, Vec<String>)>;
/// One policy problem: policy-wide when `directive` is empty.
pub struct Issue {
pub directive: String,
pub source: Option<String>,
pub message: String,
}
/// Catalog names in canonical build/display order; `true` marks flag
/// directives, which emit as a bare name. (Descriptions, risk labels and
/// default sources are UI metadata, omitted here.)
const CATALOG: &[(&str, bool)] = &[
("default-src", false), ("script-src", false), ("style-src", false),
("img-src", false), ("connect-src", false), ("font-src", false),
("frame-src", false), ("media-src", false), ("object-src", false),
("base-uri", false), ("form-action", false), ("frame-ancestors", false),
("report-uri", false), ("upgrade-insecure-requests", true),
("block-all-mixed-content", true),
];
fn is_flag(name: &str) -> bool {
CATALOG.iter().any(|(n, flag)| *flag && *n == name)
}
fn is_known(name: &str) -> bool {
CATALOG.iter().any(|(n, _)| *n == name)
}
fn get<'a>(policy: &'a Policy, name: &str) -> Option<&'a Vec<String>> {
policy.iter().find(|(n, _)| n == name).map(|(_, s)| s)
}
/// Append one directive fragment: flags as a bare name, source/url directives
/// as `name sources…` — empty lists are omitted (invalid CSP).
fn emit(parts: &mut Vec<String>, name: &str, sources: &[String]) {
if is_flag(name) {
parts.push(name.to_string());
} else if !sources.is_empty() {
parts.push(format!("{} {}", name, sources.join(" ")));
}
}
/// Assemble a policy map into the `Content-Security-Policy` header value.
/// Known directives emit in catalog order, unknown ones after them in
/// insertion order. An empty policy yields an empty string.
pub fn build(policy: &Policy) -> String {
let mut parts: Vec<String> = Vec::new();
for (name, _) in CATALOG {
if let Some(sources) = get(policy, name) {
emit(&mut parts, name, sources);
}
}
for (name, sources) in policy {
if !is_known(name) {
emit(&mut parts, name, sources);
}
}
parts.join("; ")
}
/// Parse a CSP header value back into a policy map. Lenient: splits on
/// semicolons and whitespace, lowercases directive names, ignores empty
/// tokens, and strips an optional leading `Content-Security-Policy:` label so
/// a pasted full header line works. Duplicate directives keep only the first
/// occurrence (matching how browsers honor them). Never panics on content.
pub fn parse(header: &str) -> Policy {
let trimmed = header.trim();
let lowered = trimmed.to_lowercase();
// Strip the label exactly like the TS regex: name, optional space, colon.
let text = match lowered.strip_prefix("content-security-policy") {
Some(tail) if tail.trim_start().starts_with(':') => {
// Everything before the colon is pure ASCII, so the byte offset
// computed on `lowered` is valid for `trimmed` too.
trimmed[trimmed.len() - tail.len()..].trim_start()[1..].trim_start()
}
_ => trimmed,
};
let mut policy: Policy = Vec::new();
for token in text.split(';') {
let mut words = token.split_whitespace();
let name = match words.next() {
Some(w) => w.to_lowercase(),
None => continue,
};
if policy.iter().any(|(n, _)| *n == name) {
continue; // browsers honor the first occurrence
}
policy.push((name, words.map(str::to_string).collect()));
}
policy
}
/// True when a source weakens the policy: 'unsafe-inline', 'unsafe-eval',
/// 'data:', 'http:', the bare wildcard '*', or any insecure http:// URL.
pub fn is_risky_source(source: &str) -> bool {
let s = source.trim().to_lowercase();
matches!(s.as_str(), "'unsafe-inline'" | "'unsafe-eval'" | "data:" | "http:" | "*")
|| s.starts_with("http://")
}
/// Short human explanation for each risky source (tooltip text in the UI).
fn explanation_for(s: &str) -> Option<&'static str> {
match s {
"'unsafe-inline'" => Some("Allows inline <script>/<style> and event handlers - defeats most of CSP's XSS protection."),
"'unsafe-eval'" => Some("Allows eval() and similar code execution - weakens XSS protection."),
"*" => Some("Allows every origin - effectively no restriction for this directive."),
"data:" => Some("data: URIs can carry arbitrary payloads and are same-origin - attackers can smuggle content through them."),
"http:" => Some("Allows insecure origins - a network attacker can inject or tamper with subresources."),
_ => None,
}
}
/// Explanation for any risky source; falls back to the generic insecure-origin text.
pub fn risk_explanation(source: &str) -> String {
explanation_for(source.trim().to_lowercase().as_str())
.unwrap_or("Insecure http:// URL - traffic can be tampered with in transit.")
.to_string()
}
/// Lint a policy: warns when default-src is missing (unset directives fall
/// back to the browser's allow-everything default) and flags every risky source.
pub fn validate(policy: &Policy) -> Vec<Issue> {
let mut issues = Vec::new();
if get(policy, "default-src").is_none() {
issues.push(Issue {
directive: String::new(),
source: None,
message: "No default-src - every directive you don't set explicitly falls back to the browser's permissive default.".to_string(),
});
}
for (name, sources) in policy {
for src in sources {
if is_risky_source(src) {
issues.push(Issue {
directive: name.clone(),
source: Some(src.clone()),
message: format!("{}: {} weakens this policy - {}", name, src, risk_explanation(src)),
});
}
}
}
issues
}
/// Score penalty per risky source (case-insensitive key).
fn penalty(s: &str) -> i32 {
match s {
"'unsafe-inline'" | "*" => 20,
"'unsafe-eval'" => 15,
"data:" | "http:" => 10,
_ if s.starts_with("http://") => 10,
_ => 0,
}
}
/// Security score, 0-100. Starts at 100; each risky source subtracts its
/// penalty (insecure http:// URLs subtract 10), and a missing default-src
/// subtracts 10. Clamped to 0-100. Deterministic.
pub fn security_score(policy: &Policy) -> i32 {
let mut score = 100;
if get(policy, "default-src").is_none() {
score -= 10;
}
for (_, sources) in policy {
for src in sources {
score -= penalty(src.trim().to_lowercase().as_str());
}
}
score.clamp(0, 100)
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →