> ## Documentation Index
> Fetch the complete documentation index at: https://docs.go-mizu.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Helmet

> Security headers middleware for protecting against common web vulnerabilities.

## Overview

The `helmet` middleware sets security-related HTTP headers to protect your application from common vulnerabilities like clickjacking, XSS, and content-type sniffing.

Use it when you need:

* Protection against common web vulnerabilities
* Content Security Policy (CSP)
* HTTP Strict Transport Security (HSTS)
* Compliance with security best practices

## Installation

```go theme={null}
import "github.com/go-mizu/mizu/middlewares/helmet"
```

## Quick Start

```go theme={null}
app := mizu.New()

// Use recommended security headers
app.Use(helmet.Default())
```

## Configuration

### Options

| Option                          | Type           | Default                             | Description                       |
| ------------------------------- | -------------- | ----------------------------------- | --------------------------------- |
| `ContentSecurityPolicy`         | `string`       | -                                   | Content-Security-Policy header    |
| `XFrameOptions`                 | `string`       | `"SAMEORIGIN"`                      | X-Frame-Options header            |
| `XContentTypeOptions`           | `bool`         | `true`                              | X-Content-Type-Options: nosniff   |
| `ReferrerPolicy`                | `string`       | `"strict-origin-when-cross-origin"` | Referrer-Policy header            |
| `StrictTransportSecurity`       | `*HSTSOptions` | -                                   | HSTS configuration                |
| `PermissionsPolicy`             | `string`       | -                                   | Permissions-Policy header         |
| `CrossOriginOpenerPolicy`       | `string`       | `"same-origin"`                     | Cross-Origin-Opener-Policy        |
| `CrossOriginEmbedderPolicy`     | `string`       | -                                   | Cross-Origin-Embedder-Policy      |
| `CrossOriginResourcePolicy`     | `string`       | `"same-origin"`                     | Cross-Origin-Resource-Policy      |
| `OriginAgentCluster`            | `bool`         | `true`                              | Origin-Agent-Cluster: ?1          |
| `XDNSPrefetchControl`           | `*bool`        | `false`                             | X-DNS-Prefetch-Control            |
| `XDownloadOptions`              | `bool`         | `true`                              | X-Download-Options: noopen        |
| `XPermittedCrossDomainPolicies` | `string`       | `"none"`                            | X-Permitted-Cross-Domain-Policies |

### HSTSOptions

| Option              | Type            | Default | Description                 |
| ------------------- | --------------- | ------- | --------------------------- |
| `MaxAge`            | `time.Duration` | -       | Time to remember HTTPS-only |
| `IncludeSubDomains` | `bool`          | `false` | Apply to subdomains         |
| `Preload`           | `bool`          | `false` | Enable HSTS preload         |

## Examples

### Default Security Headers

```go theme={null}
// Recommended settings for most applications
app.Use(helmet.Default())
```

Sets these headers:

```
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-DNS-Prefetch-Control: off
X-Download-Options: noopen
X-Permitted-Cross-Domain-Policies: none
Referrer-Policy: strict-origin-when-cross-origin
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Resource-Policy: same-origin
Origin-Agent-Cluster: ?1
```

### Content Security Policy

```go theme={null}
app.Use(helmet.ContentSecurityPolicy(
    "default-src 'self'; " +
    "script-src 'self' 'unsafe-inline' cdn.example.com; " +
    "style-src 'self' 'unsafe-inline'; " +
    "img-src 'self' data: https:; " +
    "font-src 'self' fonts.gstatic.com",
))
```

### HTTP Strict Transport Security

```go theme={null}
app.Use(helmet.StrictTransportSecurity(
    365*24*time.Hour, // 1 year
    true,             // include subdomains
    true,             // preload
))
```

### Frame Options

```go theme={null}
// Prevent any framing
app.Use(helmet.XFrameOptions("DENY"))

// Allow same origin only
app.Use(helmet.XFrameOptions("SAMEORIGIN"))
```

### Full Custom Configuration

```go theme={null}
app.Use(helmet.New(helmet.Options{
    ContentSecurityPolicy: "default-src 'self'",
    XFrameOptions:         "DENY",
    XContentTypeOptions:   true,
    ReferrerPolicy:        "no-referrer",
    StrictTransportSecurity: &helmet.HSTSOptions{
        MaxAge:            365 * 24 * time.Hour,
        IncludeSubDomains: true,
        Preload:           true,
    },
    PermissionsPolicy:             "geolocation=(), microphone=()",
    CrossOriginOpenerPolicy:       "same-origin-allow-popups",
    CrossOriginEmbedderPolicy:     "require-corp",
    CrossOriginResourcePolicy:     "same-site",
}))
```

### Individual Header Functions

```go theme={null}
// Apply only specific headers
app.Use(helmet.XContentTypeOptions())      // X-Content-Type-Options: nosniff
app.Use(helmet.XFrameOptions("DENY"))       // X-Frame-Options: DENY
app.Use(helmet.ReferrerPolicy("no-referrer"))
app.Use(helmet.OriginAgentCluster())
```

### Permissions Policy

```go theme={null}
// Disable dangerous browser features
app.Use(helmet.PermissionsPolicy(
    "geolocation=(), " +
    "microphone=(), " +
    "camera=(), " +
    "payment=(self), " +
    "usb=()",
))
```

### DNS Prefetch Control

```go theme={null}
// Enable DNS prefetching for performance
on := true
app.Use(helmet.XDNSPrefetchControl(true))

// Disable for privacy
app.Use(helmet.XDNSPrefetchControl(false))
```

### Cross-Origin Policies

```go theme={null}
app.Use(helmet.New(helmet.Options{
    // Isolate browsing context
    CrossOriginOpenerPolicy: "same-origin",

    // Require CORP for subresources
    CrossOriginEmbedderPolicy: "require-corp",

    // Control resource sharing
    CrossOriginResourcePolicy: "same-origin",
}))
```

## API Reference

### Functions

```go theme={null}
// Default creates middleware with recommended headers
func Default() mizu.Middleware

// New creates middleware with custom options
func New(opts Options) mizu.Middleware
```

### Individual Header Functions

```go theme={null}
func ContentSecurityPolicy(policy string) mizu.Middleware
func XFrameOptions(value string) mizu.Middleware
func XContentTypeOptions() mizu.Middleware
func ReferrerPolicy(policy string) mizu.Middleware
func StrictTransportSecurity(maxAge time.Duration, includeSubDomains, preload bool) mizu.Middleware
func PermissionsPolicy(policy string) mizu.Middleware
func CrossOriginOpenerPolicy(policy string) mizu.Middleware
func CrossOriginEmbedderPolicy(policy string) mizu.Middleware
func CrossOriginResourcePolicy(policy string) mizu.Middleware
func OriginAgentCluster() mizu.Middleware
func XDNSPrefetchControl(on bool) mizu.Middleware
func XDownloadOptions() mizu.Middleware
func XPermittedCrossDomainPolicies(policy string) mizu.Middleware
```

## Security Headers Explained

| Header                      | Protection             |
| --------------------------- | ---------------------- |
| `Content-Security-Policy`   | XSS, injection attacks |
| `X-Frame-Options`           | Clickjacking           |
| `X-Content-Type-Options`    | MIME type sniffing     |
| `Referrer-Policy`           | Information leakage    |
| `Strict-Transport-Security` | Downgrade attacks      |
| `Permissions-Policy`        | Feature abuse          |
| `Cross-Origin-*-Policy`     | Cross-origin attacks   |

## Technical Details

### Architecture

The helmet middleware is implemented as a higher-order function that wraps request handlers and injects security headers before passing control to the next handler in the chain. The middleware follows a configuration-based approach where all security headers are controlled through the `Options` struct.

### Implementation

* **Header Injection**: Headers are set conditionally based on non-empty/non-nil configuration values
* **HSTS Formatting**: The `formatHSTS` helper function constructs the Strict-Transport-Security header value from duration and boolean flags, converting the duration to seconds and appending directives as needed
* **DNS Prefetch Control**: Uses a pointer to `bool` to distinguish between unset (nil), enabled (true), and disabled (false) states
* **Default Configuration**: The `Default()` function provides a preset configuration aligned with modern security best practices
* **Individual Functions**: Convenience functions like `XFrameOptions()` and `ContentSecurityPolicy()` create middleware instances with single-header configurations

### Header Setting Logic

The `New()` function checks each option field and sets the corresponding header only if:

* String fields are non-empty
* Boolean fields are true (or pointer fields are non-nil)
* Struct pointer fields (like `HSTSOptions`) are non-nil

This approach ensures headers are only set when explicitly configured, preventing empty or unwanted headers from being sent.

### Performance Considerations

* Minimal overhead: Only string operations and header setting
* No dynamic allocations during request processing
* All configuration is computed once during middleware creation
* Headers are set before calling the next handler, ensuring they're present even if the handler fails

## Best Practices

1. **Start with Default()** - Then customize as needed
2. **Content Security Policy** - Start strict, loosen as needed
3. **HSTS** - Enable for HTTPS-only sites
4. **Test thoroughly** - Security headers can break functionality
5. **Report-Only mode** - Test CSP before enforcing

### CSP Development Strategy

```go theme={null}
// Development: Report-only mode
app.Use(helmet.New(helmet.Options{
    ContentSecurityPolicy: "default-src 'self'; report-uri /csp-report",
}))

// Production: Enforce
app.Use(helmet.New(helmet.Options{
    ContentSecurityPolicy: "default-src 'self'",
}))
```

## Testing

The helmet middleware includes comprehensive test coverage for all security headers and configuration options:

| Test Case                                              | Description                         | Expected Behavior                                                                                                                                                                                                                                                                                                                                                   |
| ------------------------------------------------------ | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `TestDefault`                                          | Validates default security headers  | Sets 9 recommended headers: X-Content-Type-Options (nosniff), X-Frame-Options (SAMEORIGIN), X-DNS-Prefetch-Control (off), X-Download-Options (noopen), X-Permitted-Cross-Domain-Policies (none), Referrer-Policy (strict-origin-when-cross-origin), Cross-Origin-Opener-Policy (same-origin), Cross-Origin-Resource-Policy (same-origin), Origin-Agent-Cluster (?1) |
| `TestContentSecurityPolicy`                            | Tests CSP header setting            | Sets Content-Security-Policy header with custom policy value                                                                                                                                                                                                                                                                                                        |
| `TestXFrameOptions` (DENY)                             | Tests frame options with DENY       | Sets X-Frame-Options: DENY                                                                                                                                                                                                                                                                                                                                          |
| `TestXFrameOptions` (SAMEORIGIN)                       | Tests frame options with SAMEORIGIN | Sets X-Frame-Options: SAMEORIGIN                                                                                                                                                                                                                                                                                                                                    |
| `TestStrictTransportSecurity` (basic)                  | Tests HSTS with max-age only        | Sets Strict-Transport-Security: max-age=31536000                                                                                                                                                                                                                                                                                                                    |
| `TestStrictTransportSecurity` (with subdomains)        | Tests HSTS with subdomains          | Sets Strict-Transport-Security: max-age=31536000; includeSubDomains                                                                                                                                                                                                                                                                                                 |
| `TestStrictTransportSecurity` (with preload)           | Tests HSTS with all options         | Sets Strict-Transport-Security: max-age=31536000; includeSubDomains; preload                                                                                                                                                                                                                                                                                        |
| `TestReferrerPolicy` (no-referrer)                     | Tests no-referrer policy            | Sets Referrer-Policy: no-referrer                                                                                                                                                                                                                                                                                                                                   |
| `TestReferrerPolicy` (no-referrer-when-downgrade)      | Tests downgrade policy              | Sets Referrer-Policy: no-referrer-when-downgrade                                                                                                                                                                                                                                                                                                                    |
| `TestReferrerPolicy` (origin)                          | Tests origin policy                 | Sets Referrer-Policy: origin                                                                                                                                                                                                                                                                                                                                        |
| `TestReferrerPolicy` (origin-when-cross-origin)        | Tests cross-origin policy           | Sets Referrer-Policy: origin-when-cross-origin                                                                                                                                                                                                                                                                                                                      |
| `TestReferrerPolicy` (same-origin)                     | Tests same-origin policy            | Sets Referrer-Policy: same-origin                                                                                                                                                                                                                                                                                                                                   |
| `TestReferrerPolicy` (strict-origin)                   | Tests strict-origin policy          | Sets Referrer-Policy: strict-origin                                                                                                                                                                                                                                                                                                                                 |
| `TestReferrerPolicy` (strict-origin-when-cross-origin) | Tests strict cross-origin policy    | Sets Referrer-Policy: strict-origin-when-cross-origin                                                                                                                                                                                                                                                                                                               |
| `TestReferrerPolicy` (unsafe-url)                      | Tests unsafe-url policy             | Sets Referrer-Policy: unsafe-url                                                                                                                                                                                                                                                                                                                                    |
| `TestPermissionsPolicy`                                | Tests permissions policy header     | Sets Permissions-Policy: geolocation=(), microphone=()                                                                                                                                                                                                                                                                                                              |
| `TestCrossOriginPolicies`                              | Tests all cross-origin headers      | Sets Cross-Origin-Opener-Policy (same-origin), Cross-Origin-Embedder-Policy (require-corp), Cross-Origin-Resource-Policy (same-site)                                                                                                                                                                                                                                |
| `TestOriginAgentCluster`                               | Tests origin agent cluster header   | Sets Origin-Agent-Cluster: ?1                                                                                                                                                                                                                                                                                                                                       |
| `TestXDNSPrefetchControl` (on)                         | Tests DNS prefetch enabled          | Sets X-DNS-Prefetch-Control: on                                                                                                                                                                                                                                                                                                                                     |
| `TestXDNSPrefetchControl` (off)                        | Tests DNS prefetch disabled         | Sets X-DNS-Prefetch-Control: off                                                                                                                                                                                                                                                                                                                                    |
| `TestXDownloadOptions`                                 | Tests download options header       | Sets X-Download-Options: noopen                                                                                                                                                                                                                                                                                                                                     |
| `TestXPermittedCrossDomainPolicies`                    | Tests cross-domain policies header  | Sets X-Permitted-Cross-Domain-Policies: master-only                                                                                                                                                                                                                                                                                                                 |
| `TestXContentTypeOptions`                              | Tests content type options header   | Sets X-Content-Type-Options: nosniff                                                                                                                                                                                                                                                                                                                                |

## Related Middlewares

* [secure](/middlewares/secure) - HTTPS enforcement
* [csrf](/middlewares/csrf) - CSRF protection
