Skip to main content

ContentSecurityPolicy

Struct ContentSecurityPolicy 

Source
pub struct ContentSecurityPolicy { /* private fields */ }
Expand description

A Content-Security-Policy header, built directive by directive, and the layer that sends it.

Rails’ content_security_policy initializer as plain Rust: build the policy in src/lib.rs and add it to the router with .layer(policy) (generated apps do, in content_security_policy()). Every response gets the header unless the handler (or a layer closer to it) set one already, which is how routes override the global policy: give a nested router its own .layer(...), or return the header from the handler.

Sources are written as in the header: SELF, NONE, DATA, "https://unpkg.com", … NONCE stands for the request’s random nonce (see CspNonce). Calling a directive twice replaces it. report_only sends Content-Security-Policy-Report-Only instead, to try a policy without breaking pages; report_uri and report_to collect violations.

§Free plan

A header per response and, when the policy uses NONCE, 16 random bytes per request: no binding call, microseconds of CPU.

§Examples

use axum::{Router, routing::get};
use ocre::security::{ContentSecurityPolicy, DATA, NONCE, NONE, SELF};

let policy = ContentSecurityPolicy::new()
    .default_src(&[SELF])
    .script_src(&[SELF, NONCE, "https://unpkg.com"])
    .img_src(&[SELF, DATA])
    .object_src(&[NONE])
    .report_uri("/csp-reports");
assert_eq!(
    policy.header_value(Some("r4nd0m")),
    "default-src 'self'; script-src 'self' 'nonce-r4nd0m' https://unpkg.com; img-src 'self' data:; \
     object-src 'none'; report-uri /csp-reports"
);

let app: Router = Router::new().route("/", get(|| async { "home" })).layer(policy);

Implementations§

Source§

impl ContentSecurityPolicy

Source

pub fn new() -> Self

An empty policy: add directives with the builder methods.

§Examples
assert_eq!(ocre::security::ContentSecurityPolicy::new().header_value(None), "");
Source

pub fn directive(self, name: &str, sources: &[&str]) -> Self

Sets any directive, e.g. directive("sandbox", &["allow-forms"]); replaces a previous value.

An empty sources list writes the directive alone (upgrade-insecure-requests).

§Examples
use ocre::security::{ContentSecurityPolicy, SELF};

let csp = ContentSecurityPolicy::new().directive("worker-src", &[SELF]).directive("worker-src", &["blob:"]);
assert_eq!(csp.header_value(None), "worker-src blob:");
Source

pub fn default_src(self, sources: &[&str]) -> Self

default-src: the fallback for every fetch directive not set.

§Examples
use ocre::security::{ContentSecurityPolicy, SELF};

assert_eq!(ContentSecurityPolicy::new().default_src(&[SELF]).header_value(None), "default-src 'self'");
Source

pub fn script_src(self, sources: &[&str]) -> Self

script-src: where scripts may come from.

§Examples
use ocre::security::{ContentSecurityPolicy, SELF};

let csp = ContentSecurityPolicy::new().script_src(&[SELF, "https://unpkg.com"]);
assert_eq!(csp.header_value(None), "script-src 'self' https://unpkg.com");
Source

pub fn style_src(self, sources: &[&str]) -> Self

style-src: where stylesheets and inline styles may come from.

§Examples
use ocre::security::{ContentSecurityPolicy, SELF, UNSAFE_INLINE};

let csp = ContentSecurityPolicy::new().style_src(&[SELF, UNSAFE_INLINE]);
assert_eq!(csp.header_value(None), "style-src 'self' 'unsafe-inline'");
Source

pub fn img_src(self, sources: &[&str]) -> Self

img-src: images and favicons.

§Examples
use ocre::security::{ContentSecurityPolicy, DATA, SELF};

assert_eq!(ContentSecurityPolicy::new().img_src(&[SELF, DATA]).header_value(None), "img-src 'self' data:");
Source

pub fn font_src(self, sources: &[&str]) -> Self

font-src: web fonts.

§Examples
use ocre::security::{ContentSecurityPolicy, SELF};

assert_eq!(ContentSecurityPolicy::new().font_src(&[SELF]).header_value(None), "font-src 'self'");
Source

pub fn connect_src(self, sources: &[&str]) -> Self

connect-src: fetch, XHR (htmx requests), WebSockets and EventSource.

§Examples
use ocre::security::{ContentSecurityPolicy, SELF};

assert_eq!(ContentSecurityPolicy::new().connect_src(&[SELF]).header_value(None), "connect-src 'self'");
Source

pub fn media_src(self, sources: &[&str]) -> Self

media-src: <audio> and <video>.

§Examples
use ocre::security::{ContentSecurityPolicy, SELF};

assert_eq!(ContentSecurityPolicy::new().media_src(&[SELF]).header_value(None), "media-src 'self'");
Source

pub fn object_src(self, sources: &[&str]) -> Self

object-src: <object> and <embed>; set it to NONE.

§Examples
use ocre::security::{ContentSecurityPolicy, NONE};

assert_eq!(ContentSecurityPolicy::new().object_src(&[NONE]).header_value(None), "object-src 'none'");
Source

pub fn frame_src(self, sources: &[&str]) -> Self

frame-src: pages this app may put in an <iframe>.

§Examples
use ocre::security::ContentSecurityPolicy;

let csp = ContentSecurityPolicy::new().frame_src(&["https://www.youtube-nocookie.com"]);
assert_eq!(csp.header_value(None), "frame-src https://www.youtube-nocookie.com");
Source

pub fn frame_ancestors(self, sources: &[&str]) -> Self

frame-ancestors: sites that may put this app in a frame (the modern X-Frame-Options).

§Examples
use ocre::security::{ContentSecurityPolicy, SELF};

assert_eq!(ContentSecurityPolicy::new().frame_ancestors(&[SELF]).header_value(None), "frame-ancestors 'self'");
Source

pub fn form_action(self, sources: &[&str]) -> Self

form-action: where forms may be submitted.

§Examples
use ocre::security::{ContentSecurityPolicy, SELF};

assert_eq!(ContentSecurityPolicy::new().form_action(&[SELF]).header_value(None), "form-action 'self'");
Source

pub fn base_uri(self, sources: &[&str]) -> Self

base-uri: allowed <base href> values.

§Examples
use ocre::security::{ContentSecurityPolicy, SELF};

assert_eq!(ContentSecurityPolicy::new().base_uri(&[SELF]).header_value(None), "base-uri 'self'");
Source

pub fn upgrade_insecure_requests(self) -> Self

upgrade-insecure-requests: browsers load http: resources over HTTPS.

§Examples
use ocre::security::ContentSecurityPolicy;

let csp = ContentSecurityPolicy::new().upgrade_insecure_requests();
assert_eq!(csp.header_value(None), "upgrade-insecure-requests");
Source

pub fn report_uri(self, uri: &str) -> Self

report-uri: where browsers POST violation reports (JSON), e.g. a route of the app.

§Examples
use ocre::security::ContentSecurityPolicy;

let csp = ContentSecurityPolicy::new().report_uri("/csp-reports");
assert_eq!(csp.header_value(None), "report-uri /csp-reports");
Source

pub fn report_to(self, group: &str) -> Self

report-to: the Reporting-Endpoints group violation reports go to.

Send the Reporting-Endpoints: csp="/csp-reports" header too (browsers without Reporting API support use report_uri).

§Examples
use ocre::security::ContentSecurityPolicy;

assert_eq!(ContentSecurityPolicy::new().report_to("csp").header_value(None), "report-to csp");
Source

pub fn report_only(self) -> Self

Sends Content-Security-Policy-Report-Only: browsers report violations but block nothing.

§Examples
use ocre::security::{ContentSecurityPolicy, SELF};

let csp = ContentSecurityPolicy::new().default_src(&[SELF]).report_only();
assert_eq!(csp.header_name(), "content-security-policy-report-only");
Source

pub fn header_name(&self) -> HeaderName

content-security-policy, or content-security-policy-report-only after report_only.

§Examples
assert_eq!(ocre::security::ContentSecurityPolicy::new().header_name(), "content-security-policy");
Source

pub fn header_value(&self, nonce: Option<&str>) -> String

The header value, with NONCE replaced by 'nonce-<nonce>' (and dropped when nonce is None).

§Examples
use ocre::security::{ContentSecurityPolicy, NONCE, SELF};

let csp = ContentSecurityPolicy::new().default_src(&[SELF]).script_src(&[SELF, NONCE]);
assert_eq!(csp.header_value(Some("n0nce")), "default-src 'self'; script-src 'self' 'nonce-n0nce'");
assert_eq!(csp.header_value(None), "default-src 'self'; script-src 'self'");

Trait Implementations§

Source§

impl Clone for ContentSecurityPolicy

Source§

fn clone(&self) -> ContentSecurityPolicy

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ContentSecurityPolicy

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for ContentSecurityPolicy

Source§

fn default() -> ContentSecurityPolicy

Returns the “default value” for a type. Read more
Source§

impl Eq for ContentSecurityPolicy

Source§

impl<S> Layer<S> for ContentSecurityPolicy

Source§

type Service = PolicyService<S, ContentSecurityPolicy>

The wrapped service
Source§

fn layer(&self, inner: S) -> Self::Service

Wrap the given service with the middleware, returning a new service that has been decorated with the middleware.
Source§

impl PartialEq for ContentSecurityPolicy

Source§

fn eq(&self, other: &ContentSecurityPolicy) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl StructuralPartialEq for ContentSecurityPolicy

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> FromRef<T> for T
where T: Clone,

§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<S, T> Upcast<T> for S
where T: UpcastFrom<S> + ?Sized, S: ?Sized,

Source§

fn upcast(&self) -> &T
where Self: ErasableGeneric, T: Sized + ErasableGeneric<Repr = Self::Repr>,

Perform a zero-cost type-safe upcast to a wider ref type within the Wasm bindgen generics type system. Read more
Source§

fn upcast_into(self) -> T
where Self: Sized + ErasableGeneric, T: Sized + ErasableGeneric<Repr = Self::Repr>,

Perform a zero-cost type-safe upcast to a wider type within the Wasm bindgen generics type system. Read more
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V