Skip to main content

Overview

The nonce 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

import "github.com/go-mizu/mizu/middlewares/nonce"

Quick Start

app := mizu.New()

app.Use(nonce.New())

app.Get("/", func(c *mizu.Ctx) error {
    n := nonce.Get(c)
    return c.HTML(200, `<script nonce="`+n+`">alert('Safe!')</script>`)
})

Configuration

Options

OptionTypeDefaultDescription
Lengthint16Nonce byte length
Headerstring""Expose in header

Examples

Basic Usage

app.Use(nonce.New())

app.Get("/", func(c *mizu.Ctx) error {
    n := nonce.Get(c)
    html := fmt.Sprintf(`
        <html>
        <head>
            <style nonce="%s">body { color: blue; }</style>
        </head>
        <body>
            <script nonce="%s">console.log('Hello');</script>
        </body>
        </html>
    `, n, n)
    return c.HTML(200, html)
})

With CSP Header

app.Use(nonce.New())
app.Use(helmet.WithOptions(helmet.Options{
    ContentSecurityPolicy: func(c *mizu.Ctx) string {
        n := nonce.Get(c)
        return fmt.Sprintf("script-src 'nonce-%s'", n)
    },
}))

Expose in Header

app.Use(nonce.New(nonce.Options{
    Header: "X-Nonce",
}))
// Response header: X-Nonce: abc123...

API Reference

Functions

// New creates nonce middleware
func New(opts ...Options) mizu.Middleware

// Get returns nonce from context
func Get(c *mizu.Ctx) string

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/rand for 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 Generator option

Context Storage

  • Nonces are stored in the request context using a private contextKey type
  • 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:
  1. Parsing existing base policies (if provided via BasePolicy option)
  2. Adding nonce values to specified directives (script-src, style-src by default)
  3. Using the format 'nonce-{base64-value}' as per CSP specification
  4. Merging with existing directive values when a base policy is present
  5. Setting the header (default: Content-Security-Policy)

Helper Functions

  • ScriptTag(c *mizu.Ctx): Returns nonce="..." attribute for script tags
  • StyleTag(c *mizu.Ctx): Returns nonce="..." 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-src
  • ForScripts(): Nonce only for script-src directive
  • ForStyles(): Nonce only for style-src directive
  • WithBasePolicy(policy string): Extends an existing CSP policy
  • ReportOnly(): Uses Content-Security-Policy-Report-Only header

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 CaseDescriptionExpected Behavior
TestNewBasic middleware initializationGenerates nonce, stores in context, sets CSP header with nonce
TestWithOptions_CustomLengthCustom nonce byte length (32 bytes)Generates longer nonce (~43 base64 characters)
TestWithOptions_CustomDirectivesCustom CSP directives (script-src only)CSP includes only script-src, excludes style-src
TestWithOptions_BasePolicyExtending existing CSP policyPreserves base policy directives and adds nonce to specified directives
TestWithOptions_CustomGeneratorCustom nonce generator functionUses provided generator instead of default random generation
TestScriptTagScript tag nonce attribute helperReturns properly formatted nonce="..." attribute
TestStyleTagStyle tag nonce attribute helperReturns properly formatted nonce="..." attribute
TestForScriptsScripts-only preset middlewareCSP contains script-src directive with nonce
TestForStylesStyles-only preset middlewareCSP contains style-src directive with nonce
TestReportOnlyReport-only modeSets Content-Security-Policy-Report-Only header instead
TestUniqueNonceNonce uniqueness across requestsEach request generates a unique nonce (no duplicates in 10 requests)
TestGetWithoutMiddlewareGet() without middlewareReturns empty string when middleware not applied