security

package
v1.0.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 14, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package security provides security middleware for HTTP servers

Package security provides essential security middleware and utilities for AegisGate. This includes panic recovery, CSRF protection, XSS prevention, and audit logging.

Package security provides security middleware for HTTP servers

Package security provides XSS protection middleware and utilities

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func APIHeadersMiddleware

func APIHeadersMiddleware(next http.Handler) http.Handler

APIHeadersMiddleware is a convenience middleware for API endpoints

func AuditMiddleware

func AuditMiddleware(logger *AuditLogger, next http.Handler) http.Handler

func CORSMiddleware

func CORSMiddleware(allowedOrigins []string, allowedMethods []string, allowedHeaders []string) func(http.Handler) http.Handler

CORSMiddleware adds CORS headers

func DashboardHeadersMiddleware

func DashboardHeadersMiddleware(next http.Handler) http.Handler

DashboardHeadersMiddleware is a convenience middleware for dashboard endpoints

func IsValidURL

func IsValidURL(url string) bool

IsValidURL checks if a URL is safe

func RecoveryHandler

func RecoveryHandler(fn http.HandlerFunc) http.HandlerFunc

RecoveryHandler wraps a http.HandlerFunc with panic recovery

func RecoveryMiddleware

func RecoveryMiddleware(next http.Handler) http.Handler

RecoveryMiddleware creates a panic recovery middleware

func RecoveryMiddlewareWithConfig

func RecoveryMiddlewareWithConfig(config RecoveryConfig) func(http.Handler) http.Handler

RecoveryMiddlewareWithConfig creates a panic recovery middleware with configuration

func SafeExecute

func SafeExecute(fn func() error) (err error)

SafeExecute runs a function with panic recovery and returns any error

func SafeExecuteWithContext

func SafeExecuteWithContext(ctx context.Context, fn func(context.Context) error) (err error)

SafeExecuteWithContext runs a function with panic recovery and context

func SafeRedirect

func SafeRedirect(url string, allowedHosts []string) string

SafeRedirect validates a redirect URL for open redirect vulnerabilities

func SanitizeHTML

func SanitizeHTML(input string) string

SanitizeHTML escapes HTML entities to prevent XSS

func SecureHandler

func SecureHandler(fn http.HandlerFunc) http.HandlerFunc

SecureHandler wraps an http.HandlerFunc with panic recovery

func SecureHandlerFunc

func SecureHandlerFunc(fn func(w http.ResponseWriter, r *http.Request) error) func(w http.ResponseWriter, r *http.Request)

SecureHandlerFunc wraps a function with panic recovery

func SecureHeadersMiddleware

func SecureHeadersMiddleware(next http.Handler) http.Handler

SecureHeadersMiddleware is a convenience middleware with default secure headers

func SecurityHeadersMiddleware

func SecurityHeadersMiddleware(config SecurityHeadersConfig) func(http.Handler) http.Handler

SecurityHeadersMiddleware adds security headers to responses

func StripTags

func StripTags(input string) string

StripTags removes all HTML tags from input For script and style tags, also removes their content

Types

type AdvancedRecoveryMiddleware

type AdvancedRecoveryMiddleware struct {
	// contains filtered or unexported fields
}

AdvancedRecoveryMiddleware provides configurable panic recovery

func NewAdvancedRecoveryMiddleware

func NewAdvancedRecoveryMiddleware(opts *RecoveryOptions) *AdvancedRecoveryMiddleware

NewAdvancedRecoveryMiddleware creates recovery middleware with options

func (*AdvancedRecoveryMiddleware) Handler

func (arm *AdvancedRecoveryMiddleware) Handler(next http.Handler) http.Handler

Handler wraps a handler with advanced panic recovery

type AuditEvent

type AuditEvent struct {
	Timestamp time.Time     `json:"timestamp"`
	EventType EventType     `json:"event_type"`
	Severity  Severity      `json:"severity"`
	UserID    string        `json:"user_id,omitempty"`
	IPAddress string        `json:"ip_address"`
	Resource  string        `json:"resource"`
	Action    string        `json:"action"`
	Status    string        `json:"status"`
	Message   string        `json:"message"`
	Duration  time.Duration `json:"duration,omitempty"`
}

type AuditLogger

type AuditLogger struct {
	// contains filtered or unexported fields
}

func NewAuditLogger

func NewAuditLogger(enabled bool, eventTypes []EventType) *AuditLogger

func (*AuditLogger) Log

func (al *AuditLogger) Log(event AuditEvent)

type CSRFConfig

type CSRFConfig struct {
	// TokenLength is the length of the CSRF token in bytes
	TokenLength int
	// CookieName is the name of the CSRF cookie
	CookieName string
	// CookieMaxAge is the max age of the cookie in seconds
	CookieMaxAge int
	// CookieSameSite sets the SameSite attribute
	CookieSameSite http.SameSite
	// CookieSecure ensures cookies are only sent over HTTPS
	CookieSecure bool
	// CookieHTTPOnly makes the cookie inaccessible to JavaScript
	CookieHTTPOnly bool
	// HeaderName is the header that contains the CSRF token
	HeaderName string
	// FormFieldName is the form field name for the CSRF token
	FormFieldName string
}

CSRFConfig holds configuration for CSRF protection

func DefaultCSRFConfig

func DefaultCSRFConfig() *CSRFConfig

DefaultCSRFConfig returns a secure default CSRF configuration

type CSRFMiddleware

type CSRFMiddleware struct {
	// contains filtered or unexported fields
}

CSRFMiddleware provides CSRF protection for HTTP handlers

func NewCSRFMiddleware

func NewCSRFMiddleware(config *CSRFConfig) *CSRFMiddleware

NewCSRFMiddleware creates a new CSRF protection middleware

func (*CSRFMiddleware) GenerateToken

func (cm *CSRFMiddleware) GenerateToken(w http.ResponseWriter, r *http.Request) string

GenerateToken generates a new CSRF token and sets the cookie

func (*CSRFMiddleware) GetToken

func (cm *CSRFMiddleware) GetToken(r *http.Request) string

GetToken extracts the CSRF token from a request

func (*CSRFMiddleware) Handler

func (cm *CSRFMiddleware) Handler(next http.Handler) http.Handler

Handler wraps an HTTP handler with CSRF protection

func (*CSRFMiddleware) Stop

func (cm *CSRFMiddleware) Stop()

Stop halts the cleanup goroutine

func (*CSRFMiddleware) WithLogger

func (cm *CSRFMiddleware) WithLogger(logger *slog.Logger) *CSRFMiddleware

WithLogger sets a custom logger

type EventType

type EventType string
const (
	AuditEventAuth     EventType = "AUTH"
	AuditEventAccess   EventType = "ACCESS"
	AuditEventSecurity EventType = "SECURITY"
)

type PanicRecoveryMiddleware

type PanicRecoveryMiddleware struct {
	// contains filtered or unexported fields
}

PanicRecoveryMiddleware recovers from panics and returns a safe error response

func NewPanicRecoveryMiddleware

func NewPanicRecoveryMiddleware() *PanicRecoveryMiddleware

NewPanicRecoveryMiddleware creates a new panic recovery middleware

func (*PanicRecoveryMiddleware) Handler

func (prm *PanicRecoveryMiddleware) Handler(next http.Handler) http.Handler

Handler wraps an http.Handler with panic recovery

func (*PanicRecoveryMiddleware) WithLogger

func (prm *PanicRecoveryMiddleware) WithLogger(logger *slog.Logger) *PanicRecoveryMiddleware

WithLogger sets a custom logger

type RecoveryConfig

type RecoveryConfig struct {
	// LogPanics logs panic details
	LogPanics bool
	// StackTrace enables stack trace logging
	StackTrace bool
	// CustomHandler allows custom panic response
	CustomHandler func(w http.ResponseWriter, r *http.Request, panicValue interface{})
}

RecoveryConfig holds panic recovery configuration

func DefaultRecoveryConfig

func DefaultRecoveryConfig() RecoveryConfig

DefaultRecoveryConfig returns default recovery configuration

type RecoveryOptions

type RecoveryOptions struct {
	// EnableStackTrace includes stack traces in logs
	EnableStackTrace bool
	// LogLevel controls the log level for recovered panics
	LogLevel slog.Level
}

RecoveryOptions configures panic recovery behavior

func DefaultRecoveryOptions

func DefaultRecoveryOptions() *RecoveryOptions

DefaultRecoveryOptions returns default recovery options

type SecurityHeadersConfig

type SecurityHeadersConfig struct {
	// ContentSecurityPolicy sets CSP header
	ContentSecurityPolicy string
	// XFrameOptions sets X-Frame-Options header
	XFrameOptions string
	// XContentTypeOptions sets X-Content-Type-Options header
	XContentTypeOptions string
	// XXSSProtection sets X-XSS-Protection header
	XXSSProtection string
	// ReferrerPolicy sets Referrer-Policy header
	ReferrerPolicy string
	// StrictTransportSecurity sets HSTS header
	StrictTransportSecurity string
	// PermissionsPolicy sets Permissions-Policy header
	PermissionsPolicy string
	// CrossOriginEmbedderPolicy sets COEP header
	CrossOriginEmbedderPolicy string
	// CrossOriginOpenerPolicy sets COOP header
	CrossOriginOpenerPolicy string
	// CrossOriginResourcePolicy sets CORP header
	CrossOriginResourcePolicy string
}

SecurityHeadersConfig holds security headers configuration

func APISecurityHeadersConfig

func APISecurityHeadersConfig() SecurityHeadersConfig

APISecurityHeadersConfig returns headers suitable for APIs

func DashboardSecurityHeadersConfig

func DashboardSecurityHeadersConfig() SecurityHeadersConfig

DashboardSecurityHeadersConfig returns headers suitable for web dashboards

func DefaultSecurityHeadersConfig

func DefaultSecurityHeadersConfig() SecurityHeadersConfig

DefaultSecurityHeadersConfig returns secure default headers

type Severity

type Severity string
const (
	SeverityInfo     Severity = "INFO"
	SeverityWarning  Severity = "WARNING"
	SeverityCritical Severity = "CRITICAL"
)

type XSSConfig

type XSSConfig struct {
	ContentSecurityPolicy string
	EnableCSP             bool
	EnableCSPReportOnly   bool
	CSPReportURI          string
	XSSProtection         bool
	ContentTypeOptions    bool
	FrameOptions          string
	ReferrerPolicy        string
	PermissionsPolicy     string
	AllowInlineScripts    bool
}

XSSConfig holds configuration for XSS protection

func DefaultXSSConfig

func DefaultXSSConfig() *XSSConfig

DefaultXSSConfig returns secure default XSS protection configuration

type XSSProtectionMiddleware

type XSSProtectionMiddleware struct {
	// contains filtered or unexported fields
}

XSSProtectionMiddleware provides XSS protection through security headers

func NewXSSProtectionMiddleware

func NewXSSProtectionMiddleware(config *XSSConfig) *XSSProtectionMiddleware

NewXSSProtectionMiddleware creates a new XSS protection middleware

func (*XSSProtectionMiddleware) Handler

func (x *XSSProtectionMiddleware) Handler(next http.Handler) http.Handler

Handler wraps an HTTP handler with XSS protection headers

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL