Creating a preset | laravel-csp-rust | Spatie       

 SPATIE  

laravel-csp-rust
================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-csp-rust](https://spatie.be/docs/laravel-csp-rust/v1)  Creating a preset

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/laravel-csp-rust/v1) 

  Creating a preset    
- [ Introduction ](https://spatie.be/docs/laravel-csp-rust/v1/introduction)
- [ Support us ](https://spatie.be/docs/laravel-csp-rust/v1/support-us)
- [ Installation and setup ](https://spatie.be/docs/laravel-csp-rust/v1/installation-and-setup)
- [ Usage ](https://spatie.be/docs/laravel-csp-rust/v1/usage)
- [ Creating a preset ](https://spatie.be/docs/laravel-csp-rust/v1/creating-a-preset)
- [ Using inline scripts and styles ](https://spatie.be/docs/laravel-csp-rust/v1/using-inline-scripts-and-styles)
- [ Outputting a CSP policy as a meta tag ](https://spatie.be/docs/laravel-csp-rust/v1/outputting-a-csp-policy-as-a-meta-tag)
- [ Reporting CSP errors ](https://spatie.be/docs/laravel-csp-rust/v1/reporting-csp-errors)
- [ Testing ](https://spatie.be/docs/laravel-csp-rust/v1/testing)
- [ Changelog ](https://spatie.be/docs/laravel-csp-rust/v1/changelog)
- [ Releasing ](https://spatie.be/docs/laravel-csp-rust/v1/releasing)

 Creating a preset
=================

###  On this page 

1. [ Trusted Types ](#content-trusted-types)
2. [ Custom policies ](#content-custom-policies)

An example of a CSP directive is `script-src`. If this has the value `'self' www.google.com`, your site can only load scripts from its own domain or `www.google.com`. Mozilla maintains [a list of CSP directives](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Content-Security-Policy).

Certain directive values need quotes, such as `'self'`, `'none'` and `'unsafe-inline'`. Use `Keyword` and the package adds those quotes. Script and style hashes are detected and quoted automatically.

```
use spatie_csp::{Directive, Error, Keyword, Policy, Preset};

#[derive(Debug)]
struct MyCspPreset;

impl Preset for MyCspPreset {
    fn configure(&self, policy: &mut Policy, nonce: Option<&str>) -> Result<(), Error> {
        policy
            .add(Directive::Script, Keyword::Self_)?
            .add(Directive::Script, "www.google.com")?
            .add(Directive::Style, "sha256-hash")?
            .add_nonce(Directive::Script, nonce)?;
        Ok(())
    }
}
config.policy.preset(MyCspPreset);
```

Inside `with_config`, use `config.section_mut::<Config>().policy.preset(MyCspPreset)` to register it. Presets run in order, followed by global directives. Repeated values appear only once. Adding `Keyword::None` replaces all earlier values for that directive; adding another source afterward removes `'none'`. Mixing `none` with other sources in one operation returns `Error::NoneWithOtherSources`.

Use `add_many` for several values and a Rust loop for several directives:

```
for directive in [Directive::Script, Directive::Style] {
    policy.add_many(directive, [Keyword::Self_.into(), "www.google.com".into()])?;
}
policy.add(Directive::UpgradeInsecureRequests, Value::NoValue)?;
```

The builder rejects control characters, non-ASCII source expressions and semicolons rather than allowing directive or HTTP header injection. Encode international domain names as ASCII. `add` and `add_many` return `Result<&mut Policy, Error>`; use `?` to propagate errors. Configuration callbacks cannot return errors, so construct fallible policies beforehand and move them into the callback.

Trusted Types
-----------------------------------------------------------------------------------------------

Use `Directive::TrustedTypes` to allow specific Trusted Types policy names. Combine it with `Directive::RequireTrustedTypesFor` to require Trusted Types for script injection sinks:

```
policy.add_many(Directive::TrustedTypes, ["default".into(), "my-policy".into()])?
    .add(Directive::RequireTrustedTypesFor, Keyword::Script)?;
```

Policy names are not quoted. Use `Keyword::AllowDuplicates` alongside policy names to allow more than one policy with the same name. Use `Keyword::None` on its own to disallow policy creation, or `"*"` to allow any name.

Custom policies
-----------------------------------------------------------------------------------------------------

Implement `PolicyBuilder` when presets are not enough. Its `build(&self, nonce: Option<&str>) -> Result<Policy, Error>` method constructs the complete policy. Assign it to `custom_policy` or `custom_report_only_policy` using `Arc::new(...)`. Configured reporting settings are applied afterward. Builders and presets must be `Debug + Send + Sync`; keep request state in the supplied nonce, not in a shared singleton.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
