#security

csp

A small Content Security Policy creation helper

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

#414 in Configuration

Download history 2/week @ 2024-07-21 31/week @ 2024-07-28 9/week @ 2024-08-04 14/week @ 2024-08-25 41/week @ 2024-09-01 21/week @ 2024-09-08 32/week @ 2024-09-22 37/week @ 2024-09-29 1/week @ 2024-10-06 24/week @ 2024-10-13 21/week @ 2024-10-20 26/week @ 2024-10-27 1/week @ 2024-11-03

72 downloads per month
Used in 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