Documentation
¶
Index ¶
- func CSRFGuard(cfg CSRFConfig) router.Middleware
- func Guard(cfg Config) router.Middleware
- func NoTimingLeak(duration time.Duration) router.Middleware
- func RemoveHeader(names ...string) router.Middleware
- func Token(c *http.Context) string
- func TokenField(c *http.Context) string
- func VerifyOrigin(allowedHosts ...string) router.Middleware
- type CSPBuilder
- func (b *CSPBuilder) BaseURI(sources ...string) *CSPBuilder
- func (b *CSPBuilder) BlockAllMixedContent() *CSPBuilder
- func (b *CSPBuilder) ChildSrc(sources ...string) *CSPBuilder
- func (b *CSPBuilder) ConnectSrc(sources ...string) *CSPBuilder
- func (b *CSPBuilder) DefaultSrc(sources ...string) *CSPBuilder
- func (b *CSPBuilder) Directive(name string, values ...string) *CSPBuilder
- func (b *CSPBuilder) FontSrc(sources ...string) *CSPBuilder
- func (b *CSPBuilder) FormAction(sources ...string) *CSPBuilder
- func (b *CSPBuilder) FrameAncestors(sources ...string) *CSPBuilder
- func (b *CSPBuilder) FrameSrc(sources ...string) *CSPBuilder
- func (b *CSPBuilder) ImgSrc(sources ...string) *CSPBuilder
- func (b *CSPBuilder) ManifestSrc(sources ...string) *CSPBuilder
- func (b *CSPBuilder) MediaSrc(sources ...string) *CSPBuilder
- func (b *CSPBuilder) NavigateTo(sources ...string) *CSPBuilder
- func (b *CSPBuilder) Nonce(directive string) string
- func (b *CSPBuilder) ObjectSrc(sources ...string) *CSPBuilder
- func (b *CSPBuilder) PrefetchSrc(sources ...string) *CSPBuilder
- func (b *CSPBuilder) ReportTo(group string) *CSPBuilder
- func (b *CSPBuilder) ReportURI(uri string) *CSPBuilder
- func (b *CSPBuilder) Sandbox(flags ...string) *CSPBuilder
- func (b *CSPBuilder) ScriptSrc(sources ...string) *CSPBuilder
- func (b *CSPBuilder) ScriptSrcAttr(sources ...string) *CSPBuilder
- func (b *CSPBuilder) ScriptSrcElem(sources ...string) *CSPBuilder
- func (b *CSPBuilder) String() string
- func (b *CSPBuilder) StyleSrc(sources ...string) *CSPBuilder
- func (b *CSPBuilder) StyleSrcAttr(sources ...string) *CSPBuilder
- func (b *CSPBuilder) StyleSrcElem(sources ...string) *CSPBuilder
- func (b *CSPBuilder) UpgradeInsecureRequests() *CSPBuilder
- func (b *CSPBuilder) WorkerSrc(sources ...string) *CSPBuilder
- type CSPConfig
- type CSRFConfig
- type Config
- type HSTSConfig
- type Plugin
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CSRFGuard ¶
func CSRFGuard(cfg CSRFConfig) router.Middleware
CSRFGuard returns a middleware that protects against Cross-Site Request Forgery using a signed double-submit cookie pattern.
On every request it ensures a CSRF token exists (generating one if needed) and stores it in the context so handlers and templates can access it via shield.Token(ctx) or shield.TokenField(ctx).
For unsafe HTTP methods (POST, PUT, PATCH, DELETE) it validates that the token supplied in the request (header or form field) matches the token in the cookie.
func Guard ¶
func Guard(cfg Config) router.Middleware
Guard returns a middleware that sets all configured security headers on every response. It does NOT include CSRF protection — use CSRFGuard() separately for that.
Usage in start/kernel.go:
cfg := shield.DefaultConfig()
app.Router.Use(
shield.Guard(cfg),
shield.CSRFGuard(cfg.CSRF),
)
func NoTimingLeak ¶
func NoTimingLeak(duration time.Duration) router.Middleware
NoTimingLeak sets a constant-time response delay to reduce timing side-channel information leakage. Useful on login / token endpoints.
app.Router.Post("/login", handler, shield.NoTimingLeak(500*time.Millisecond))
func RemoveHeader ¶
func RemoveHeader(names ...string) router.Middleware
RemoveHeader is a convenience middleware that strips response headers you never want to leak (e.g. "X-Powered-By", "Server").
app.Router.Use(shield.RemoveHeader("X-Powered-By", "Server"))
func Token ¶
Token returns the CSRF token for the current request. Use this when you need the raw token (e.g. for Ajax headers). For forms, use {{ .csrfField }} in templates — it is auto-injected by context.View when Shield CSRF is enabled.
func TokenField ¶
TokenField returns a full HTML hidden input for embedding in forms. Prefer {{ .csrfField }} in templates — it is auto-injected by context.View.
func VerifyOrigin ¶
func VerifyOrigin(allowedHosts ...string) router.Middleware
VerifyOrigin returns a middleware that validates the Origin and Referer headers against a list of allowed hosts. This provides an additional layer of CSRF defence.
app.Router.Use(shield.VerifyOrigin("example.com", "www.example.com"))
Types ¶
type CSPBuilder ¶
type CSPBuilder struct {
// contains filtered or unexported fields
}
CSPBuilder provides a fluent API for assembling a Content Security Policy. Each method returns the builder so calls can be chained.
policy := shield.NewCSP().
DefaultSrc("'self'").
ScriptSrc("'self'", "https://cdn.example.com").
StyleSrc("'self'", "'unsafe-inline'").
ImgSrc("'self'", "data:").
ReportURI("/csp-report")
func Relaxed ¶
func Relaxed() *CSPBuilder
Relaxed returns a more permissive policy that allows CDN assets and inline styles — useful during development or for apps that load resources from multiple origins.
func Strict ¶
func Strict() *CSPBuilder
Strict returns a restrictive baseline policy suitable for most server-rendered applications.
func (*CSPBuilder) BaseURI ¶
func (b *CSPBuilder) BaseURI(sources ...string) *CSPBuilder
func (*CSPBuilder) BlockAllMixedContent ¶
func (b *CSPBuilder) BlockAllMixedContent() *CSPBuilder
func (*CSPBuilder) ChildSrc ¶
func (b *CSPBuilder) ChildSrc(sources ...string) *CSPBuilder
func (*CSPBuilder) ConnectSrc ¶
func (b *CSPBuilder) ConnectSrc(sources ...string) *CSPBuilder
func (*CSPBuilder) DefaultSrc ¶
func (b *CSPBuilder) DefaultSrc(sources ...string) *CSPBuilder
func (*CSPBuilder) Directive ¶
func (b *CSPBuilder) Directive(name string, values ...string) *CSPBuilder
Directive sets an arbitrary directive. Useful for new directives not yet covered by a dedicated method.
func (*CSPBuilder) FontSrc ¶
func (b *CSPBuilder) FontSrc(sources ...string) *CSPBuilder
func (*CSPBuilder) FormAction ¶
func (b *CSPBuilder) FormAction(sources ...string) *CSPBuilder
func (*CSPBuilder) FrameAncestors ¶
func (b *CSPBuilder) FrameAncestors(sources ...string) *CSPBuilder
func (*CSPBuilder) FrameSrc ¶
func (b *CSPBuilder) FrameSrc(sources ...string) *CSPBuilder
func (*CSPBuilder) ImgSrc ¶
func (b *CSPBuilder) ImgSrc(sources ...string) *CSPBuilder
func (*CSPBuilder) ManifestSrc ¶
func (b *CSPBuilder) ManifestSrc(sources ...string) *CSPBuilder
func (*CSPBuilder) MediaSrc ¶
func (b *CSPBuilder) MediaSrc(sources ...string) *CSPBuilder
func (*CSPBuilder) NavigateTo ¶
func (b *CSPBuilder) NavigateTo(sources ...string) *CSPBuilder
func (*CSPBuilder) Nonce ¶
func (b *CSPBuilder) Nonce(directive string) string
Nonce generates a cryptographically random base64 nonce value and appends 'nonce-<value>' to the given directive. Returns the raw nonce string for embedding in a <script nonce="..."> tag.
nonce := policy.Nonce("script-src")
// In template: <script nonce="{{ nonce }}">...</script>
func (*CSPBuilder) ObjectSrc ¶
func (b *CSPBuilder) ObjectSrc(sources ...string) *CSPBuilder
func (*CSPBuilder) PrefetchSrc ¶
func (b *CSPBuilder) PrefetchSrc(sources ...string) *CSPBuilder
func (*CSPBuilder) ReportTo ¶
func (b *CSPBuilder) ReportTo(group string) *CSPBuilder
func (*CSPBuilder) ReportURI ¶
func (b *CSPBuilder) ReportURI(uri string) *CSPBuilder
func (*CSPBuilder) Sandbox ¶
func (b *CSPBuilder) Sandbox(flags ...string) *CSPBuilder
func (*CSPBuilder) ScriptSrc ¶
func (b *CSPBuilder) ScriptSrc(sources ...string) *CSPBuilder
func (*CSPBuilder) ScriptSrcAttr ¶
func (b *CSPBuilder) ScriptSrcAttr(sources ...string) *CSPBuilder
func (*CSPBuilder) ScriptSrcElem ¶
func (b *CSPBuilder) ScriptSrcElem(sources ...string) *CSPBuilder
func (*CSPBuilder) String ¶
func (b *CSPBuilder) String() string
String serializes the policy into a valid CSP header value.
func (*CSPBuilder) StyleSrc ¶
func (b *CSPBuilder) StyleSrc(sources ...string) *CSPBuilder
func (*CSPBuilder) StyleSrcAttr ¶
func (b *CSPBuilder) StyleSrcAttr(sources ...string) *CSPBuilder
func (*CSPBuilder) StyleSrcElem ¶
func (b *CSPBuilder) StyleSrcElem(sources ...string) *CSPBuilder
func (*CSPBuilder) UpgradeInsecureRequests ¶
func (b *CSPBuilder) UpgradeInsecureRequests() *CSPBuilder
func (*CSPBuilder) WorkerSrc ¶
func (b *CSPBuilder) WorkerSrc(sources ...string) *CSPBuilder
type CSPConfig ¶
type CSPConfig struct {
Enabled bool
ReportOnly bool
Policy *CSPBuilder
}
CSPConfig holds Content Security Policy settings.
type CSRFConfig ¶
type CSRFConfig struct {
Enabled bool
// Secret used for HMAC signing of tokens. Must be at least 32 bytes.
// If empty, a random secret is generated at startup.
Secret string
// CookieName is the name of the CSRF cookie (default: "__nimbus_csrf").
CookieName string
// SessionCookieName is the name of the session cookie the CSRF token is
// bound to (default: "nimbus_session"). Binding ties each token to the
// caller's session so a token issued for one session cannot be replayed
// against another (defends against cookie-injection / token fixation).
// Set to "-" to disable session binding.
SessionCookieName string
// HeaderName is the HTTP header checked for the token (default: "X-CSRF-Token").
HeaderName string
// FieldName is the form field checked for the token (default: "_csrf").
FieldName string
// MaxAge sets cookie lifetime in seconds (default: 86400 = 24h).
MaxAge int
// Secure marks the cookie as Secure (HTTPS only).
Secure bool
// SameSite sets the SameSite cookie attribute.
SameSite http.SameSite
// Path sets the cookie path (default: "/").
Path string
// Domain sets the cookie domain.
Domain string
// HttpOnly marks the cookie HttpOnly. When true, client-side JS
// cannot read the cookie — the token must be embedded in forms
// via a template helper. When false, JS can read the cookie and
// send it in a custom header.
HttpOnly bool
// ExceptPaths is a list of path prefixes to skip CSRF validation.
ExceptPaths []string
// RotateToken rotates the CSRF token after each successful validation.
// When true, tokens are one-time use — the form must be re-rendered
// with the new token for the next request. Set false for Unpoly/AJAX
// flows where forms are not replaced after submit (default: false).
RotateToken bool
// ErrorHandler is called when CSRF validation fails. If nil, a
// default 403 JSON response is sent.
ErrorHandler router.HandlerFunc
}
CSRFConfig holds CSRF protection settings.
type Config ¶
type Config struct {
// ContentTypeNosniff sets X-Content-Type-Options: nosniff to
// prevent MIME-type sniffing attacks.
ContentTypeNosniff bool
// XSSProtection controls the X-XSS-Protection header.
// Modern recommendation: "0" (disable browser's built-in XSS
// auditor; rely on CSP instead). Set to "1; mode=block" for
// legacy browsers.
XSSProtection string
// FrameGuard controls the X-Frame-Options header to prevent
// clickjacking. Values: "DENY", "SAMEORIGIN".
FrameGuard string
// HSTS configures HTTP Strict Transport Security.
HSTS HSTSConfig
// ReferrerPolicy sets the Referrer-Policy header.
// Common values: "no-referrer", "strict-origin-when-cross-origin",
// "same-origin", "origin".
ReferrerPolicy string
// DNSPrefetchControl sets X-DNS-Prefetch-Control.
// true = "on", false = "off".
DNSPrefetchControl bool
// DownloadOptions sets X-Download-Options: noopen to prevent
// old IE from executing downloads in the site's context.
DownloadOptions bool
// PermittedCrossDomainPolicies sets X-Permitted-Cross-Domain-Policies.
// Values: "none", "master-only", "by-content-type", "all".
PermittedCrossDomainPolicies string
// CrossOriginOpenerPolicy sets Cross-Origin-Opener-Policy.
// Values: "same-origin", "same-origin-allow-popups", "unsafe-none".
CrossOriginOpenerPolicy string
// CrossOriginResourcePolicy sets Cross-Origin-Resource-Policy.
// Values: "same-origin", "same-site", "cross-origin".
CrossOriginResourcePolicy string
// CrossOriginEmbedderPolicy sets Cross-Origin-Embedder-Policy.
// Values: "require-corp", "credentialless", "unsafe-none".
CrossOriginEmbedderPolicy string
// CSP configures Content-Security-Policy headers.
CSP CSPConfig
// CSRF configures Cross-Site Request Forgery protection.
CSRF CSRFConfig
}
Config holds all Shield security settings. Zero values are safe defaults — call DefaultConfig() for a production-ready baseline.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns a production-ready Shield configuration.
type HSTSConfig ¶
HSTSConfig controls HTTP Strict Transport Security.
type Plugin ¶
type Plugin struct {
nimbus.BasePlugin
// contains filtered or unexported fields
}
Plugin exposes Shield as a Nimbus plugin so it can be registered with app.Use(shield.NewPlugin(cfg)).
It provides two named middleware ("shield" and "csrf") that can be referenced in start/kernel.go or attached to specific route groups.
func NewPlugin ¶
NewPlugin creates a Shield plugin with the given configuration. Pass shield.DefaultConfig() for a production-ready baseline.
func (*Plugin) DefaultConfig ¶
DefaultConfig returns the plugin's default settings so the application can inspect or override them at boot time.
func (*Plugin) Middleware ¶
func (p *Plugin) Middleware() map[string]router.Middleware
Middleware exposes the security-header guard and CSRF guard as named middleware that the application can reference.