Overview
Thenonce middleware generates cryptographic nonces for Content Security Policy (CSP) inline scripts and styles.
Use it when you need:
- CSP nonce-based security
- Inline script authorization
- Dynamic nonce generation
Installation
Quick Start
Configuration
Options
| Option | Type | Default | Description |
|---|---|---|---|
Length | int | 16 | Nonce byte length |
Header | string | "" | Expose in header |
Examples
Basic Usage
With CSP Header
Expose in Header
API Reference
Functions
Technical Details
Implementation
The nonce middleware generates cryptographically secure random nonces for each HTTP request and integrates them into Content Security Policy headers. The implementation follows these key patterns:Nonce Generation
- Uses
crypto/randfor cryptographically secure random byte generation - Default nonce length: 16 bytes (produces 22 character base64 strings)
- Base64 encoding with raw standard encoding (no padding)
- Custom generators can be provided via the
Generatoroption
Context Storage
- Nonces are stored in the request context using a private
contextKeytype - Retrieved via the
Get(c *mizu.Ctx)function - Context key is type-safe and collision-resistant
CSP Header Construction
The middleware builds Content Security Policy headers by:- Parsing existing base policies (if provided via
BasePolicyoption) - Adding nonce values to specified directives (
script-src,style-srcby default) - Using the format
'nonce-{base64-value}'as per CSP specification - Merging with existing directive values when a base policy is present
- Setting the header (default:
Content-Security-Policy)
Helper Functions
ScriptTag(c *mizu.Ctx): Returnsnonce="..."attribute for script tagsStyleTag(c *mizu.Ctx): Returnsnonce="..."attribute for style tags- Both return empty strings if no nonce is available in context
Preset Middleware Functions
The package provides several convenience constructors:New(): Default configuration with script-src and style-srcForScripts(): Nonce only for script-src directiveForStyles(): Nonce only for style-src directiveWithBasePolicy(policy string): Extends an existing CSP policyReportOnly(): UsesContent-Security-Policy-Report-Onlyheader
Security
- Nonces are cryptographically random
- New nonce per request
- Base64-encoded for HTML safety
- Use with strict CSP
Best Practices
- Use with Content-Security-Policy
- Generate new nonce per request
- Include in all inline scripts/styles
- Donβt reuse nonces
Testing
The nonce middleware includes comprehensive test coverage for all functionality:| Test Case | Description | Expected Behavior |
|---|---|---|
TestNew | Basic middleware initialization | Generates nonce, stores in context, sets CSP header with nonce |
TestWithOptions_CustomLength | Custom nonce byte length (32 bytes) | Generates longer nonce (~43 base64 characters) |
TestWithOptions_CustomDirectives | Custom CSP directives (script-src only) | CSP includes only script-src, excludes style-src |
TestWithOptions_BasePolicy | Extending existing CSP policy | Preserves base policy directives and adds nonce to specified directives |
TestWithOptions_CustomGenerator | Custom nonce generator function | Uses provided generator instead of default random generation |
TestScriptTag | Script tag nonce attribute helper | Returns properly formatted nonce="..." attribute |
TestStyleTag | Style tag nonce attribute helper | Returns properly formatted nonce="..." attribute |
TestForScripts | Scripts-only preset middleware | CSP contains script-src directive with nonce |
TestForStyles | Styles-only preset middleware | CSP contains style-src directive with nonce |
TestReportOnly | Report-only mode | Sets Content-Security-Policy-Report-Only header instead |
TestUniqueNonce | Nonce uniqueness across requests | Each request generates a unique nonce (no duplicates in 10 requests) |
TestGetWithoutMiddleware | Get() without middleware | Returns empty string when middleware not applied |