[][src]Crate csp

This crate is a helper to quickly construct a CSP and then turn it into a String.

This library can help you when you don't want to remember some weird formatting rules of CSP, and want to avoid typos. And it certainly can be handy if you need to re-use things, for example a list of sources (just .clone() them everywhere and you're good to go!).

WARNING: this library does not care if you create invalid CSP rules, and happily allows them and turns them into Strings. But it does force you to use a typed structure, so it'll be harder to mess up than when manually writing CSP. Another thing that this crate does not do: It does not do any base64 or percent encoding or anything like that.

Example usage

use csp::{CSP, Directive, Sources, Source};

let csp = CSP::new()
  .add(Directive::ImgSrc(
    Sources::new_with(Source::Self_)
      .add(Source::Host("https://*.example.org"))
      .add(Source::Host("https://shields.io")),
  ))
  .add(Directive::ConnectSrc(
    Sources::new()
      .add(Source::Host("http://crates.io"))
      .add(Source::Scheme("https"))
      .add(Source::Self_),
  ))
  .add(Directive::StyleSrc(
    Sources::new_with(Source::Self_).add(Source::UnsafeInline),
  ))
  .add(Directive::ObjectSrc(Sources::new()));

let csp_header = "Content-Security-Policy: ".to_owned() + &csp.to_string();

Copyright notice for this crate's docs:

Most of the comments for various CSP things are from MDN, so they licensed under CC-BY-SA 2.5 So attribution of most of the docs goes to Mozilla Contributors.

Please go to MDN to read up to date docs, as these ones might not be up to date.

Structs

CSP

The starting point for building a Content Security Policy.

Plugins

Used for PluginTypes Directive.

ReportUris

Used for ReportUri Directive.

SandboxAllowedList

Used for Sandbox Directive.

Sources

A struct to give source(s) to a Directive which might require it.

Enums

Directive

A CSP directive.

SandboxAllow

Optionally used for the Sandbox directive. Not uing it but using the sandbox directive disallows everything that you could allow with the optional values.

Source

The source that a bunch of directives can have multiple of.

SriFor

Used for RequireSriFor Directive.