4 releases (stable)

2.0.0 Oct 24, 2023
1.1.0 Oct 2, 2022
1.0.1 Sep 12, 2022
0.1.0 Dec 18, 2019

#183 in Configuration

Download history 74/week @ 2024-01-07 46/week @ 2024-01-28 28/week @ 2024-02-18 27/week @ 2024-02-25 45/week @ 2024-03-03 62/week @ 2024-03-10 16/week @ 2024-03-17 52/week @ 2024-03-24 90/week @ 2024-03-31

223 downloads per month
Used in 4 crates (via product-os-server)

MIT license

38KB
495 lines

CSP-rs

This is a very small rust crate to help avoid typos when creating a Content-Security-Policy string.

Any contributions to improve it are welcome, but keep in mind that the goal of this crate is to be very minimal, and without dependencies. This should be kept simple enough that anyone who decides to use this care would do so with the confidence that they could maintain it themselves if needed.


lib.rs:

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()
  .push(Directive::ImgSrc(
    Sources::new_with(Source::Self_)
      .push(Source::Host("https://*.example.org"))
      .push(Source::Host("https://shields.io")),
  ))
  .push(Directive::ConnectSrc(
    Sources::new()
      .push(Source::Host("http://crates.io"))
      .push(Source::Scheme("https"))
      .push(Source::Self_),
  ))
  .push(Directive::StyleSrc(
    Sources::new_with(Source::Self_).push(Source::UnsafeInline),
  ))
  .push(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.

No runtime deps