security

package
v0.0.0-...-8acab51 Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2026 License: MIT Imports: 44 Imported by: 0

Documentation

Overview

Package security provides security utilities for ZimaOS Blue.

Package security provides security utilities for ZimaOS Blue.

Package security provides security utilities for ZimaOS Blue.

Package security provides security utilities for the application.

Package security provides security utilities for ZimaOS Blue.

Package security provides TLS certificate management.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ACMEProviderURL

func ACMEProviderURL(provider string) string

ACMEProviderURL returns the ACME directory URL for a provider.

func AddDynamicOriginDefault

func AddDynamicOriginDefault(origin string)

AddDynamicOriginDefault adds a dynamic origin to the default checker. Use this to add tunnel URLs or TLS domain origins at runtime.

func BuildDockerExecArgs

func BuildDockerExecArgs(params DockerExecParams) []string

BuildDockerExecArgs builds Docker exec arguments with PATH injection prevention. Instead of interpolating PATH into the shell command, it passes PATH via an internal environment variable to prevent shell injection attacks.

func CheckOriginDefault

func CheckOriginDefault(r *http.Request) bool

CheckOriginDefault checks the origin using the default configuration.

func CreateSecureDir

func CreateSecureDir(path string) error

CreateSecureDir creates a directory with secure permissions.

func GetDefaultAllowedOrigins

func GetDefaultAllowedOrigins() []string

GetDefaultAllowedOrigins returns the default allowed origins.

func GetDynamicOriginsDefault

func GetDynamicOriginsDefault() []string

GetDynamicOriginsDefault returns the dynamic origins from the default checker.

func GetServerPort

func GetServerPort() int

GetServerPort returns the current server port for CORS origins.

func IsDefaultAllowAllOrigins

func IsDefaultAllowAllOrigins() bool

IsDefaultAllowAllOrigins reports whether the default checker allows all origins.

func IsSafeOpenError

func IsSafeOpenError(err error) bool

IsSafeOpenError checks if an error is a SafeOpenError.

func OnCertReady

func OnCertReady(fn func())

OnCertReady registers a callback invoked after a certificate becomes available.

func RemoveDynamicOriginDefault

func RemoveDynamicOriginDefault(origin string)

RemoveDynamicOriginDefault removes a dynamic origin from the default checker.

func SanitizeCommand

func SanitizeCommand(cmd string) (string, error)

SanitizeCommand sanitizes a command string to prevent injection. This is a basic sanitization - for untrusted input, use a proper sandbox.

func SanitizeCommandArgs

func SanitizeCommandArgs(args []string) ([]string, error)

SanitizeCommandArgs sanitizes command arguments.

func SecureDirMode

func SecureDirMode() os.FileMode

SecureDirMode returns a secure directory mode for creating directories. Directories are created with owner-only read/write/execute permissions.

func SecureFileMode

func SecureFileMode() os.FileMode

SecureFileMode returns a secure file mode for creating files. Files are created with owner-only read/write permissions.

func SetGlobalTLSManagerConfig

func SetGlobalTLSManagerConfig(config *TLSManagerConfig)

SetGlobalTLSManagerConfig updates the global TLS manager configuration.

func SetServerPort

func SetServerPort(port int)

SetServerPort sets the server port for dynamic CORS origin generation. This should be called after the server starts and the actual port is known.

func StripPotentialInjections

func StripPotentialInjections(content string) string

StripPotentialInjections removes or neutralizes potential injection patterns. Use this for content that will be displayed but should not contain any instruction-like text.

func TimingSafeCompare

func TimingSafeCompare(a, b string) bool

TimingSafeCompare performs a constant-time comparison of two strings. This prevents timing attacks where an attacker could determine the correct value by measuring response times.

func TimingSafeCompareBytes

func TimingSafeCompareBytes(a, b []byte) bool

TimingSafeCompareBytes performs a constant-time comparison of two byte slices.

func TruncateContent

func TruncateContent(content string, maxLength int) string

TruncateContent truncates content to a maximum length, adding an indicator if truncation occurred.

func ValidateHMACSHA256Base64

func ValidateHMACSHA256Base64(body []byte, signature, secret string) bool

ValidateHMACSHA256Base64 validates an HMAC-SHA256 signature encoded as base64. Used for LINE webhook signature validation.

func ValidateHMACSHA256Hex

func ValidateHMACSHA256Hex(body []byte, signature, secret string) bool

ValidateHMACSHA256Hex validates an HMAC-SHA256 signature encoded as hex. Used for various webhook signature validations.

func ValidateHMACSignature

func ValidateHMACSignature(message, signature, secret string) bool

ValidateHMACSignature validates an HMAC-SHA256 signature using constant-time comparison. This is used for webhook signature validation to prevent timing attacks.

func ValidateMediaID

func ValidateMediaID(id string) error

ValidateMediaID validates a media ID to prevent path traversal. Media IDs should only contain safe characters.

func WriteSecureFile

func WriteSecureFile(path string, data []byte) error

WriteSecureFile writes data to a file with secure permissions.

Types

type ACMEConfig

type ACMEConfig struct {
	Email          string            `json:"email"`
	Domains        []string          `json:"domains"`
	Provider       string            `json:"provider"` // letsencrypt, zerossl, or custom URL
	CacheDir       string            `json:"cache_dir"`
	ChallengeType  string            `json:"challenge_type"`  // "http-01" (default) or "dns-01"
	DNSProvider    string            `json:"dns_provider"`    // e.g. "cloudflare", "route53"
	DNSCredentials map[string]string `json:"dns_credentials"` // provider-specific credentials
}

ACMEConfig holds ACME certificate configuration.

type ACMERequest

type ACMERequest struct {
	Email          string            `json:"email"`
	Domains        []string          `json:"domains"`
	Provider       string            `json:"provider"`        // letsencrypt, zerossl
	ChallengeType  string            `json:"challenge_type"`  // "http-01" or "dns-01"
	DNSProvider    string            `json:"dns_provider"`    // e.g. "cloudflare", "route53"
	DNSCredentials map[string]string `json:"dns_credentials"` // provider-specific credentials
}

ACMERequest represents an ACME certificate request.

type ACMEStatus

type ACMEStatus struct {
	Configured    bool             `json:"configured"`
	Email         string           `json:"email"`
	Domains       []string         `json:"domains"`
	Provider      string           `json:"provider"`
	ChallengeType string           `json:"challenge_type,omitempty"`
	DNSProvider   string           `json:"dns_provider,omitempty"`
	CertInfo      *CertificateInfo `json:"cert_info,omitempty"`
	Error         string           `json:"error,omitempty"`
	AutoRenewal   bool             `json:"auto_renewal"`
	NextRenewal   *time.Time       `json:"next_renewal,omitempty"`
	DaysUntilExp  int              `json:"days_until_expiry,omitempty"`
}

ACMEStatus represents the status of ACME certificate.

type AddPromptFirewallRuleRequest

type AddPromptFirewallRuleRequest struct {
	Keyword string `json:"keyword"`
	Enabled *bool  `json:"enabled,omitempty"`
}

type BlockedIP

type BlockedIP struct {
	IPAddress string    `json:"ip_address"`
	Reason    string    `json:"reason"`
	BlockedAt time.Time `json:"blocked_at"`
	ExpiresAt time.Time `json:"expires_at,omitempty"`
	Permanent bool      `json:"permanent"`
}

BlockedIP represents a blocked IP address.

type CORSConfigRequest

type CORSConfigRequest struct {
	AddOrigins    []string `json:"add_origins,omitempty"`
	RemoveOrigins []string `json:"remove_origins,omitempty"`
}

CORSConfigRequest represents the CORS configuration update request.

type CORSConfigResponse

type CORSConfigResponse struct {
	AllowedOrigins []string `json:"allowed_origins"`
	DynamicOrigins []string `json:"dynamic_origins"`
	AllowLocalhost bool     `json:"allow_localhost"`
}

CORSConfigResponse represents the CORS configuration response.

type CertificateInfo

type CertificateInfo struct {
	Subject      string    `json:"subject"`
	Issuer       string    `json:"issuer"`
	Domains      []string  `json:"domains"`
	NotBefore    time.Time `json:"not_before"`
	NotAfter     time.Time `json:"not_after"`
	IsCA         bool      `json:"is_ca"`
	IsSelfSigned bool      `json:"is_self_signed"`
	SerialNumber string    `json:"serial_number"`
	Fingerprint  string    `json:"fingerprint"`
}

CertificateInfo contains parsed certificate information.

func ParseCertificateFromPEM

func ParseCertificateFromPEM(certPEM []byte) (*CertificateInfo, error)

ParseCertificateFromPEM parses certificate info from PEM data.

type DayStats

type DayStats struct {
	Date   string         `json:"date"`
	Count  int            `json:"count"`
	ByType map[string]int `json:"by_type"`
}

DayStats represents statistics for a single day.

type DetectionResult

type DetectionResult struct {
	// IsSuspicious indicates if any suspicious patterns were found.
	IsSuspicious bool
	// Matches contains all matched patterns.
	Matches []PatternMatch
	// HighestSeverity is the highest severity level found.
	HighestSeverity string
}

DetectionResult contains the result of suspicious pattern detection.

type DockerExecParams

type DockerExecParams struct {
	// ContainerName is the name of the container to exec into.
	ContainerName string
	// Command is the command to execute.
	Command string
	// Env is a map of environment variables.
	Env map[string]string
	// TTY allocates a pseudo-TTY.
	TTY bool
	// Interactive keeps STDIN open.
	Interactive bool
}

DockerExecParams contains parameters for building Docker exec arguments.

type EnvSanitizer

type EnvSanitizer struct {
	// AllowedEnvVars is a list of environment variable names that are allowed.
	// If empty, all variables are allowed (subject to other checks).
	AllowedEnvVars []string
	// DeniedEnvVars is a list of environment variable names that are denied.
	DeniedEnvVars []string
	// MaxValueLength is the maximum length of an environment variable value.
	MaxValueLength int
}

EnvSanitizer provides utilities for sanitizing environment variables to prevent injection attacks.

func DefaultEnvSanitizer

func DefaultEnvSanitizer() *EnvSanitizer

DefaultEnvSanitizer returns a sanitizer with sensible defaults.

func (*EnvSanitizer) SanitizeEnv

func (s *EnvSanitizer) SanitizeEnv(env map[string]string) (map[string]string, error)

SanitizeEnv sanitizes environment variables for safe execution.

type EventStats

type EventStats struct {
	Period     string         `json:"period"` // "day", "week", "month"
	StartDate  time.Time      `json:"start_date"`
	EndDate    time.Time      `json:"end_date"`
	TotalCount int            `json:"total_count"`
	ByType     map[string]int `json:"by_type"`
	ByDay      []DayStats     `json:"by_day"`
}

EventStats represents aggregated event statistics.

type ExternalContentSanitizer

type ExternalContentSanitizer struct {
	// DetectSuspicious enables detection of suspicious patterns.
	DetectSuspicious bool
	// WrapContent enables wrapping content with security boundaries.
	WrapContent bool
}

ExternalContentSanitizer provides utilities for sanitizing external content to prevent prompt injection attacks.

func DefaultExternalContentSanitizer

func DefaultExternalContentSanitizer() *ExternalContentSanitizer

DefaultExternalContentSanitizer returns a sanitizer with sensible defaults.

func (*ExternalContentSanitizer) DetectSuspiciousPatterns

func (s *ExternalContentSanitizer) DetectSuspiciousPatterns(content string) *DetectionResult

DetectSuspiciousPatterns scans content for potential prompt injection patterns.

func (*ExternalContentSanitizer) SanitizeExternalContent

func (s *ExternalContentSanitizer) SanitizeExternalContent(content string, source string) (string, *DetectionResult)

SanitizeExternalContent sanitizes external content by detecting suspicious patterns and wrapping it with security boundaries.

func (*ExternalContentSanitizer) WrapExternalContent

func (s *ExternalContentSanitizer) WrapExternalContent(content string, source string) string

WrapExternalContent wraps external content with security boundaries. This helps the LLM understand that the content is untrusted and should not be treated as instructions.

type FixPreviewRequest

type FixPreviewRequest struct {
	FixAction string `json:"fix_action"`
}

FixPreviewRequest represents a request to preview a fix.

type FixPreviewResponse

type FixPreviewResponse struct {
	FixAction   string   `json:"fix_action"`
	Description string   `json:"description"`
	Changes     []string `json:"changes"`
	Reversible  bool     `json:"reversible"`
	Warning     string   `json:"warning,omitempty"`
}

FixPreviewResponse represents the preview of what a fix will do.

type FixScanIssueRequest

type FixScanIssueRequest struct {
	FixAction string `json:"fix_action"`
}

FixScanIssueRequest represents a request to fix a scan issue.

type FixScanIssueResponse

type FixScanIssueResponse struct {
	Success bool   `json:"success"`
	Message string `json:"message"`
	Details string `json:"details,omitempty"`
}

FixScanIssueResponse represents the response from fixing a scan issue.

type Handler

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

Handler handles security-related API endpoints.

func NewHandler

func NewHandler(detector *ThreatDetector) *Handler

NewHandler creates a new security handler.

func (*Handler) AddEvent

func (h *Handler) AddEvent(event SecurityEvent)

AddEvent adds a security event (for use by other packages).

func (*Handler) AddPromptFirewallRule

func (h *Handler) AddPromptFirewallRule(c echo.Context) error

AddPromptFirewallRule handles POST /api/v1/security/firewall/rules.

func (*Handler) AddSession

func (h *Handler) AddSession(session *Session)

AddSession adds a session (for use by other packages).

func (*Handler) BlockIP

func (h *Handler) BlockIP(c echo.Context) error

BlockIP handles POST /api/v1/security/blocked-ips

func (*Handler) DeletePromptFirewallRule

func (h *Handler) DeletePromptFirewallRule(c echo.Context) error

DeletePromptFirewallRule handles DELETE /api/v1/security/firewall/rules/:id.

func (*Handler) ExportThreats

func (h *Handler) ExportThreats(c echo.Context) error

ExportThreats handles GET /api/v1/security/threats/export Exports threat data as CSV for reporting purposes.

func (*Handler) FixScanIssue

func (h *Handler) FixScanIssue(c echo.Context) error

FixScanIssue handles POST /api/v1/security/scan/fix This endpoint attempts to fix a detected issue.

func (*Handler) GenerateSelfSignedCert

func (h *Handler) GenerateSelfSignedCert(c echo.Context) error

GenerateSelfSignedCert handles POST /api/v1/security/tls/self-signed

func (*Handler) GetACMEStatus

func (h *Handler) GetACMEStatus(c echo.Context) error

GetACMEStatus handles GET /api/v1/security/tls/acme

func (*Handler) GetCORSConfig

func (h *Handler) GetCORSConfig(c echo.Context) error

GetCORSConfig handles GET /api/v1/security/cors

func (*Handler) GetEventStats

func (h *Handler) GetEventStats(c echo.Context) error

GetEventStats handles GET /api/v1/security/events/stats Returns aggregated event statistics for the specified period (day, week, month).

func (*Handler) GetEvents

func (h *Handler) GetEvents(c echo.Context) error

GetEvents handles GET /api/v1/security/events

func (*Handler) GetPromptFirewall

func (h *Handler) GetPromptFirewall(c echo.Context) error

GetPromptFirewall handles GET /api/v1/security/firewall.

func (*Handler) GetRecentThreats

func (h *Handler) GetRecentThreats(c echo.Context) error

GetRecentThreats handles GET /api/v1/security/threats

func (*Handler) GetSettings

func (h *Handler) GetSettings(c echo.Context) error

GetSettings handles GET /api/v1/security/settings

func (*Handler) GetStats

func (h *Handler) GetStats(c echo.Context) error

GetStats handles GET /api/v1/security/stats

func (*Handler) GetTLSConfig

func (h *Handler) GetTLSConfig(c echo.Context) error

GetTLSConfig handles GET /api/v1/security/tls

func (*Handler) GetThreatStats

func (h *Handler) GetThreatStats(c echo.Context) error

GetThreatStats handles GET /api/v1/security/threats/stats

func (*Handler) GetThreatTrend

func (h *Handler) GetThreatTrend(c echo.Context) error

GetThreatTrend handles GET /api/v1/security/threats/trend Returns threat trend data for the specified period (day, week, month).

func (*Handler) IsIPBlocked

func (h *Handler) IsIPBlocked(ip string) bool

IsIPBlocked checks if an IP is blocked.

func (*Handler) ListBlockedIPs

func (h *Handler) ListBlockedIPs(c echo.Context) error

ListBlockedIPs handles GET /api/v1/security/blocked-ips

func (*Handler) ListSessions

func (h *Handler) ListSessions(c echo.Context) error

ListSessions handles GET /api/v1/security/sessions

func (*Handler) ParseCertificate

func (h *Handler) ParseCertificate(c echo.Context) error

ParseCertificate handles POST /api/v1/security/tls/parse

func (*Handler) PreviewScanFix

func (h *Handler) PreviewScanFix(c echo.Context) error

PreviewScanFix handles POST /api/v1/security/scan/preview This endpoint previews what a fix will do without applying it.

func (*Handler) RegisterRoutes

func (h *Handler) RegisterRoutes(g *echo.Group)

RegisterRoutes registers the security routes.

func (*Handler) ReloadTLSCert

func (h *Handler) ReloadTLSCert(c echo.Context) error

ReloadTLSCert handles POST /api/v1/security/tls/reload Hot-reload certificate from files without restarting the server.

func (*Handler) RequestACMECert

func (h *Handler) RequestACMECert(c echo.Context) error

RequestACMECert handles POST /api/v1/security/tls/acme

func (*Handler) RevokeAllSessions

func (h *Handler) RevokeAllSessions(c echo.Context) error

RevokeAllSessions handles POST /api/v1/security/sessions/revoke-all

func (*Handler) RevokeSession

func (h *Handler) RevokeSession(c echo.Context) error

RevokeSession handles DELETE /api/v1/security/sessions/:id

func (*Handler) RunSecurityScan

func (h *Handler) RunSecurityScan(c echo.Context) error

RunSecurityScan handles GET /api/v1/security/scan/run This endpoint performs a comprehensive security scan of the system.

func (*Handler) ScanInput

func (h *Handler) ScanInput(c echo.Context) error

func (*Handler) SetDataDir

func (h *Handler) SetDataDir(dataDir string)

SetDataDir sets the data directory for system checks.

func (*Handler) SetKVStore

func (h *Handler) SetKVStore(kv kvstore.Store)

SetKVStore sets the shared kvstore used for persisting security config.

func (*Handler) SetPromptGuard

func (h *Handler) SetPromptGuard(detector *promptguard.Detector)

SetPromptGuard wires chat promptguard detector into security handler for firewall management.

func (*Handler) SetScannerConfig

func (h *Handler) SetScannerConfig(config *ScannerConfig)

SetScannerConfig updates the scanner configuration.

func (*Handler) SetStorage

func (h *Handler) SetStorage(storage *Storage)

SetStorage sets the storage backend for persistence.

func (*Handler) UnblockIP

func (h *Handler) UnblockIP(c echo.Context) error

UnblockIP handles DELETE /api/v1/security/blocked-ips/:ip

func (*Handler) UpdateCORSConfig

func (h *Handler) UpdateCORSConfig(c echo.Context) error

UpdateCORSConfig handles PUT /api/v1/security/cors

func (*Handler) UpdatePromptFirewall

func (h *Handler) UpdatePromptFirewall(c echo.Context) error

UpdatePromptFirewall handles PUT /api/v1/security/firewall.

func (*Handler) UpdatePromptFirewallRule

func (h *Handler) UpdatePromptFirewallRule(c echo.Context) error

UpdatePromptFirewallRule handles PUT /api/v1/security/firewall/rules/:id.

func (*Handler) UpdateSettings

func (h *Handler) UpdateSettings(c echo.Context) error

UpdateSettings handles PUT /api/v1/security/settings

func (*Handler) UpdateTLSSettings

func (h *Handler) UpdateTLSSettings(c echo.Context) error

UpdateTLSSettings handles PUT /api/v1/security/tls/settings

func (*Handler) UploadTLSCert

func (h *Handler) UploadTLSCert(c echo.Context) error

UploadTLSCert handles POST /api/v1/security/tls/upload

type OriginChecker

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

OriginChecker validates request origins.

func NewOriginChecker

func NewOriginChecker(config OriginConfig) *OriginChecker

NewOriginChecker creates a new origin checker.

func (*OriginChecker) AddDynamicOrigin

func (c *OriginChecker) AddDynamicOrigin(origin string)

AddDynamicOrigin adds a dynamic origin (e.g., tunnel URL, TLS domain). This is thread-safe and can be called at runtime.

func (*OriginChecker) CheckOrigin

func (c *OriginChecker) CheckOrigin(r *http.Request) bool

CheckOrigin validates the origin of an HTTP request. Returns true if the origin is allowed, false otherwise.

func (*OriginChecker) CreateWebSocketCheckOrigin

func (c *OriginChecker) CreateWebSocketCheckOrigin() func(r *http.Request) bool

CreateWebSocketCheckOrigin creates a CheckOrigin function for WebSocket upgraders.

func (*OriginChecker) GetAllowedOrigins

func (c *OriginChecker) GetAllowedOrigins() []string

GetAllowedOrigins returns the list of allowed origins for CORS configuration.

func (*OriginChecker) GetDynamicOrigins

func (c *OriginChecker) GetDynamicOrigins() []string

GetDynamicOrigins returns a copy of the dynamic origins list.

func (*OriginChecker) IsAllowAll

func (c *OriginChecker) IsAllowAll() bool

IsAllowAll returns true when wildcard CORS ("*") is enabled.

func (*OriginChecker) IsAllowedOrigin

func (c *OriginChecker) IsAllowedOrigin(origin string) bool

IsAllowedOrigin checks if the given origin is allowed.

func (*OriginChecker) RemoveDynamicOrigin

func (c *OriginChecker) RemoveDynamicOrigin(origin string)

RemoveDynamicOrigin removes a dynamic origin.

type OriginConfig

type OriginConfig struct {
	// AllowedOrigins is a list of allowed origins.
	// Use "*" to allow all origins (not recommended for production).
	AllowedOrigins []string

	// AllowLocalhost allows localhost origins in development.
	AllowLocalhost bool
}

OriginConfig contains configuration for origin validation.

func DefaultOriginConfig

func DefaultOriginConfig() OriginConfig

DefaultOriginConfig returns the default origin configuration. In production, you should configure specific allowed origins.

func ProductionOriginConfig

func ProductionOriginConfig(allowedDomains []string) OriginConfig

ProductionOriginConfig returns a production-ready origin configuration. You should customize this with your actual production domains.

type PatternMatch

type PatternMatch struct {
	Pattern     SuspiciousPattern
	MatchedText string
	Position    int
}

PatternMatch represents a single pattern match.

type PromptFirewallConfig

type PromptFirewallConfig struct {
	Enabled          bool                 `json:"enabled"`
	Rules            []PromptFirewallRule `json:"rules"`
	BuiltinRuleState map[string]bool      `json:"builtin_rule_state,omitempty"`
}

PromptFirewallConfig represents prompt firewall settings.

type PromptFirewallConfigResponse

type PromptFirewallConfigResponse struct {
	Enabled   bool                 `json:"enabled"`
	Rules     []PromptFirewallRule `json:"rules"`
	RuleCount int                  `json:"rule_count"`
}

PromptFirewallConfigResponse is the API payload for firewall settings.

type PromptFirewallRule

type PromptFirewallRule struct {
	ID          string    `json:"id"`
	Keyword     string    `json:"keyword"`
	Enabled     bool      `json:"enabled"`
	CreatedAt   time.Time `json:"created_at,omitempty"`
	Type        string    `json:"type,omitempty"`
	BuiltIn     bool      `json:"built_in,omitempty"`
	Description string    `json:"description,omitempty"`
}

PromptFirewallRule represents one user-maintained prompt interception rule.

type SafeOpenError

type SafeOpenError struct {
	Code    SafeOpenErrorCode
	Message string
	Path    string
}

SafeOpenError represents an error during safe file operations.

func (*SafeOpenError) Error

func (e *SafeOpenError) Error() string

type SafeOpenErrorCode

type SafeOpenErrorCode string

SafeOpenErrorCode represents the type of error that occurred during safe file operations.

const (
	// ErrCodeInvalidPath indicates the path is invalid or escapes the root.
	ErrCodeInvalidPath SafeOpenErrorCode = "invalid-path"
	// ErrCodeNotFound indicates the file was not found.
	ErrCodeNotFound SafeOpenErrorCode = "not-found"
	// ErrCodePermissionDenied indicates permission was denied.
	ErrCodePermissionDenied SafeOpenErrorCode = "permission-denied"
	// ErrCodeSymlinkNotAllowed indicates a symlink was encountered but not allowed.
	ErrCodeSymlinkNotAllowed SafeOpenErrorCode = "symlink-not-allowed"
)

func GetSafeOpenErrorCode

func GetSafeOpenErrorCode(err error) (SafeOpenErrorCode, bool)

GetSafeOpenErrorCode returns the error code if the error is a SafeOpenError.

type SafeOpenResult

type SafeOpenResult struct {
	File     *os.File
	RealPath string
	Info     fs.FileInfo
}

SafeOpenResult contains the result of a safe file open operation.

func OpenFileWithinRoot

func OpenFileWithinRoot(rootDir, relativePath string, allowSymlinks bool) (*SafeOpenResult, error)

OpenFileWithinRoot safely opens a file within a root directory. It prevents path traversal attacks by: 1. Resolving the root directory to its real path 2. Checking that the resolved file path is within the root 3. Rejecting symlinks (optional) 4. Using O_NOFOLLOW on supported platforms

func (*SafeOpenResult) Close

func (r *SafeOpenResult) Close() error

Close closes the file handle.

type ScanCache

type ScanCache struct {
	Items     []SecurityScanItem `json:"items"`
	Summary   ScanSummary        `json:"summary"`
	Timestamp time.Time          `json:"timestamp"`
}

ScanCache stores cached scan results.

type ScanRequest

type ScanRequest struct {
	Input  string `json:"input" validate:"required"`
	Source string `json:"source"`
}

ScanInput handles POST /api/v1/security/scan This endpoint allows scanning arbitrary input for threats.

type ScanResponse

type ScanResponse struct {
	Safe    bool          `json:"safe"`
	Threats []ThreatEvent `json:"threats"`
}

type ScanSummary

type ScanSummary struct {
	Total    int `json:"total"`
	Passed   int `json:"passed"`
	Warnings int `json:"warnings"`
	Failed   int `json:"failed"`
}

ScanSummary represents the summary of a security scan.

type ScannerConfig

type ScannerConfig struct {
	// Environment
	Environment string // development, staging, production

	// TLS Configuration
	TLSEnabled    bool
	TLSCertPath   string
	TLSKeyPath    string
	TLSMinVersion uint16

	// CORS Configuration
	CORSAllowedOrigins []string
	CORSAllowAll       bool

	// Rate Limiting
	RateLimitEnabled bool
	RateLimitRPS     int

	// Sandbox Configuration
	SandboxEnabled        bool
	SandboxMemoryLimitMB  int
	SandboxCPULimitCores  float64
	SandboxTimeoutSeconds int
	SandboxNetworkEnabled bool

	// AI Security
	PromptGuardEnabled     bool
	AIOutputValidation     bool
	SensitiveDataFiltering bool
	ModelWhitelistEnabled  bool
	AllowedModels          []string

	// Debug Mode
	DebugMode bool

	// JWT Configuration
	JWTSecretLength int
	JWTExpirySecs   int

	// Error Handling
	ExposeErrorDetails bool
	LogSensitiveErrors bool
}

ScannerConfig holds configuration for the security scanner.

func DefaultScannerConfig

func DefaultScannerConfig() *ScannerConfig

DefaultScannerConfig returns a default scanner configuration.

type SecurityEvent

type SecurityEvent struct {
	ID        string                 `json:"id"`
	Type      string                 `json:"type"`
	UserID    string                 `json:"user_id,omitempty"`
	IPAddress string                 `json:"ip_address"`
	UserAgent string                 `json:"user_agent,omitempty"`
	Details   map[string]interface{} `json:"details,omitempty"`
	Timestamp time.Time              `json:"timestamp"`
	Severity  string                 `json:"severity"`
}

SecurityEvent represents a security-related event.

type SecurityScanItem

type SecurityScanItem struct {
	ID          string `json:"id"`
	Category    string `json:"category"`
	Name        string `json:"name"`
	Description string `json:"description"`
	Status      string `json:"status"` // passed, warning, failed
	Details     string `json:"details,omitempty"`
	Risk        string `json:"risk,omitempty"`        // Why this is a security concern
	Impact      string `json:"impact,omitempty"`      // What could happen if exploited
	Remediation string `json:"remediation,omitempty"` // How to fix the issue
	AutoFixable bool   `json:"auto_fixable,omitempty"`
	FixAction   string `json:"fix_action,omitempty"`
}

SecurityScanItem represents a single security check item.

type SecurityScanResult

type SecurityScanResult struct {
	Items     []SecurityScanItem `json:"items"`
	Summary   ScanSummary        `json:"summary"`
	Timestamp time.Time          `json:"timestamp"`
}

SecurityScanResult represents the result of a security scan.

type SecurityScanner

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

SecurityScanner performs real security checks on the system.

func NewSecurityScanner

func NewSecurityScanner(handler *Handler, config *ScannerConfig) *SecurityScanner

NewSecurityScanner creates a new security scanner.

func (*SecurityScanner) RunFullScan

func (s *SecurityScanner) RunFullScan() []SecurityScanItem

RunFullScan performs a comprehensive security scan.

func (*SecurityScanner) SetConfig

func (s *SecurityScanner) SetConfig(config *ScannerConfig)

SetConfig updates the scanner configuration.

type SecuritySettings

type SecuritySettings struct {
	PasswordMinLength        int  `json:"password_min_length"`
	PasswordRequireUppercase bool `json:"password_require_uppercase"`
	PasswordRequireLowercase bool `json:"password_require_lowercase"`
	PasswordRequireNumbers   bool `json:"password_require_numbers"`
	PasswordRequireSpecial   bool `json:"password_require_special"`
	SessionTimeoutMinutes    int  `json:"session_timeout_minutes"`
	MaxLoginAttempts         int  `json:"max_login_attempts"`
	LockoutDurationMinutes   int  `json:"lockout_duration_minutes"`
	MFARequired              bool `json:"mfa_required"`
	APIRateLimit             int  `json:"api_rate_limit"`
}

SecuritySettings represents security configuration.

type SecurityStats

type SecurityStats struct {
	ActiveSessions  int `json:"active_sessions"`
	FailedLogins24h int `json:"failed_logins_24h"`
	BlockedIPs      int `json:"blocked_ips"`
	MFAEnabledUsers int `json:"mfa_enabled_users"`
	TotalUsers      int `json:"total_users"`
	APIKeysActive   int `json:"api_keys_active"`
}

SecurityStats represents security statistics.

type Session

type Session struct {
	ID           string    `json:"id"`
	UserID       string    `json:"user_id"`
	IPAddress    string    `json:"ip_address"`
	UserAgent    string    `json:"user_agent"`
	CreatedAt    time.Time `json:"created_at"`
	LastActivity time.Time `json:"last_activity"`
	ExpiresAt    time.Time `json:"expires_at"`
	IsCurrent    bool      `json:"is_current"`
}

Session represents a user session for security tracking.

type Storage

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

Storage handles persistence of security data.

func NewStorage

func NewStorage(basePath string) (*Storage, error)

NewStorage creates a new security storage instance.

func (*Storage) CleanupExpired

func (s *Storage) CleanupExpired(retentionDays int) error

CleanupExpired removes expired data.

func (*Storage) Close

func (s *Storage) Close() error

Close closes the storage.

func (*Storage) GetBlockedIPs

func (s *Storage) GetBlockedIPs() map[string]*BlockedIP

GetBlockedIPs retrieves all blocked IPs.

func (*Storage) GetEventStats

func (s *Storage) GetEventStats(period string) (*EventStats, error)

GetEventStats returns aggregated event statistics for the specified period.

func (*Storage) GetEvents

func (s *Storage) GetEvents(limit, offset int, eventType string) ([]SecurityEvent, int, error)

GetEvents retrieves events with optional filtering.

func (*Storage) GetScanCache

func (s *Storage) GetScanCache() *ScanCache

GetScanCache retrieves cached scan results.

func (*Storage) IsIPBlocked

func (s *Storage) IsIPBlocked(ip string) bool

IsIPBlocked checks if an IP is blocked.

func (*Storage) RemoveBlockedIP

func (s *Storage) RemoveBlockedIP(ip string) error

RemoveBlockedIP removes a blocked IP from storage.

func (*Storage) SaveBlockedIP

func (s *Storage) SaveBlockedIP(blocked *BlockedIP) error

SaveBlockedIP saves a blocked IP to storage.

func (*Storage) SaveEvent

func (s *Storage) SaveEvent(event *SecurityEvent) error

SaveEvent saves a security event to storage.

func (*Storage) SaveScanCache

func (s *Storage) SaveScanCache(items []SecurityScanItem, summary ScanSummary) error

SaveScanCache saves scan results to cache.

type SuspiciousPattern

type SuspiciousPattern struct {
	Name        string
	Pattern     *regexp.Regexp
	Description string
	Severity    string // "low", "medium", "high"
}

SuspiciousPattern represents a pattern that may indicate prompt injection.

type TLSConfigResponse

type TLSConfigResponse struct {
	Enabled      bool             `json:"enabled"`
	Port         int              `json:"port"`
	HasCert      bool             `json:"has_cert"`
	CertInfo     *CertificateInfo `json:"cert_info,omitempty"`
	AutoCert     bool             `json:"auto_cert"`
	ACMEProvider string           `json:"acme_provider,omitempty"`
	ACMEDomains  []string         `json:"acme_domains,omitempty"`
	SelfSigned   bool             `json:"self_signed"`
	HTTPSOnly    bool             `json:"https_only"`
	HTTPSPort    int              `json:"https_port"`
}

TLSConfigResponse represents the TLS configuration response.

type TLSManager

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

TLSManager manages TLS certificates.

func GetGlobalTLSManager

func GetGlobalTLSManager() *TLSManager

GetGlobalTLSManager returns the global TLS manager instance.

func NewTLSManager

func NewTLSManager(config *TLSManagerConfig) *TLSManager

NewTLSManager creates a new TLS manager.

func (*TLSManager) GenerateSelfSigned

func (m *TLSManager) GenerateSelfSigned(domains []string, validDays int) error

GenerateSelfSigned generates a self-signed certificate.

func (*TLSManager) GetACMEStatus

func (m *TLSManager) GetACMEStatus() *ACMEStatus

GetACMEStatus returns the current ACME configuration status.

func (*TLSManager) GetAutocertManager

func (m *TLSManager) GetAutocertManager() *autocert.Manager

GetAutocertManager returns the autocert manager for use with HTTP server

func (*TLSManager) GetCertificate

func (m *TLSManager) GetCertificate() *tls.Certificate

GetCertificate returns the current certificate for TLS config.

func (*TLSManager) GetCertificateInfo

func (m *TLSManager) GetCertificateInfo() *CertificateInfo

GetCertificateInfo returns parsed certificate information.

func (*TLSManager) GetHTTPHandler

func (m *TLSManager) GetHTTPHandler() http.Handler

GetHTTPHandler returns an HTTP handler for ACME HTTP-01 challenges. This should be mounted on port 80 to handle Let's Encrypt challenges.

func (*TLSManager) GetHTTPSPort

func (m *TLSManager) GetHTTPSPort() int

GetHTTPSPort returns the HTTPS port.

func (*TLSManager) GetTLSConfig

func (m *TLSManager) GetTLSConfig() *tls.Config

GetTLSConfig returns a tls.Config for the server. The config uses GetCertificate callback for hot-reload support.

func (*TLSManager) HTTPSRedirectMiddleware

func (m *TLSManager) HTTPSRedirectMiddleware() echo.MiddlewareFunc

HTTPSRedirectMiddleware returns an Echo middleware that redirects HTTP to HTTPS.

func (*TLSManager) IsHTTPSOnly

func (m *TLSManager) IsHTTPSOnly() bool

IsHTTPSOnly returns whether HTTPS-only mode is enabled.

func (*TLSManager) IsHotReloadSupported

func (m *TLSManager) IsHotReloadSupported() bool

IsHotReloadSupported returns true (certificates can be updated without restart).

func (*TLSManager) LoadCertificate

func (m *TLSManager) LoadCertificate() error

LoadCertificate loads certificate from files.

func (*TLSManager) LoadSettings

func (m *TLSManager) LoadSettings() error

LoadSettings loads persisted TLS settings from kvstore, overriding in-memory defaults.

func (*TLSManager) ReloadCertificate

func (m *TLSManager) ReloadCertificate() error

ReloadCertificate reloads the certificate from files (hot-reload).

func (*TLSManager) RequestACMECertificate

func (m *TLSManager) RequestACMECertificate(config *ACMEConfig) error

RequestACMECertificate requests a certificate from an ACME provider. Uses golang.org/x/crypto/acme directly instead of lego.

func (*TLSManager) SaveCertificate

func (m *TLSManager) SaveCertificate(certPEM, keyPEM []byte) error

SaveCertificate saves certificate and key from PEM data.

func (*TLSManager) SaveSettings

func (m *TLSManager) SaveSettings() error

SaveSettings persists user-changeable TLS settings to kvstore.

func (*TLSManager) SetHTTPSOnly

func (m *TLSManager) SetHTTPSOnly(enabled bool)

SetHTTPSOnly enables or disables HTTPS-only mode.

func (*TLSManager) SetHTTPSPort

func (m *TLSManager) SetHTTPSPort(port int)

SetHTTPSPort sets the HTTPS port.

func (*TLSManager) SetKVStore

func (m *TLSManager) SetKVStore(kv kvstore.Store)

SetKVStore sets the kvstore for persisting TLS settings.

func (*TLSManager) StopRenewalChecker

func (m *TLSManager) StopRenewalChecker()

StopRenewalChecker stops the background renewal checker

type TLSManagerConfig

type TLSManagerConfig struct {
	CertFile     string
	KeyFile      string
	AutoCert     bool
	ACMEEmail    string
	ACMEDomains  []string
	ACMEProvider string // letsencrypt, zerossl
	ACMEDir      string
	SelfSigned   bool
	HTTPSOnly    bool // Redirect HTTP to HTTPS
	HTTPSPort    int  // HTTPS port, default 443
}

TLSManagerConfig holds TLS manager configuration.

type TLSSelfSignedRequest

type TLSSelfSignedRequest struct {
	Domains   []string `json:"domains"`
	ValidDays int      `json:"valid_days"`
}

TLSSelfSignedRequest represents a self-signed certificate generation request.

type TLSSettingsRequest

type TLSSettingsRequest struct {
	HTTPSOnly bool `json:"https_only"`
	HTTPSPort int  `json:"https_port"`
}

TLSSettingsRequest represents TLS settings update request.

type TLSUploadRequest

type TLSUploadRequest struct {
	CertPEM string `json:"cert_pem"`
	KeyPEM  string `json:"key_pem"`
}

TLSUploadRequest represents a certificate upload request.

type ThreatDetector

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

ThreatDetector detects and tracks security threats.

func NewThreatDetector

func NewThreatDetector() *ThreatDetector

NewThreatDetector creates a new threat detector.

func (*ThreatDetector) ClearOldEvents

func (td *ThreatDetector) ClearOldEvents(maxAge time.Duration) int

ClearOldEvents removes events older than the specified duration.

func (*ThreatDetector) DetectThreats

func (td *ThreatDetector) DetectThreats(input, source, ipAddress, userID string) []ThreatEvent

DetectThreats scans input for security threats.

func (*ThreatDetector) GetRecentThreats

func (td *ThreatDetector) GetRecentThreats(limit int) []ThreatEvent

GetRecentThreats returns recent threat events.

func (*ThreatDetector) GetStats

func (td *ThreatDetector) GetStats() *ThreatStats

GetStats returns aggregated threat statistics.

func (*ThreatDetector) GetThreatTrend

func (td *ThreatDetector) GetThreatTrend(period string) *ThreatTrend

GetThreatTrend returns threat trend data for the specified period.

func (*ThreatDetector) RecordBruteForce

func (td *ThreatDetector) RecordBruteForce(ipAddress, userID string, attempts int)

RecordBruteForce records a brute force attempt.

func (*ThreatDetector) RecordRateLimitHit

func (td *ThreatDetector) RecordRateLimitHit(ipAddress, endpoint string)

RecordRateLimitHit records a rate limit violation.

func (*ThreatDetector) SetOnThreat

func (td *ThreatDetector) SetOnThreat(callback func(ThreatEvent))

SetOnThreat sets a callback function that is called when a threat is detected.

type ThreatEvent

type ThreatEvent struct {
	ID          string         `json:"id"`
	Type        ThreatType     `json:"type"`
	Severity    ThreatSeverity `json:"severity"`
	Source      string         `json:"source"`
	IPAddress   string         `json:"ip_address"`
	UserID      string         `json:"user_id,omitempty"`
	Description string         `json:"description"`
	Details     string         `json:"details,omitempty"`
	Blocked     bool           `json:"blocked"`
	Timestamp   time.Time      `json:"timestamp"`
}

ThreatEvent represents a detected security threat.

type ThreatSeverity

type ThreatSeverity string

ThreatSeverity represents the severity level of a threat.

const (
	SeverityLow      ThreatSeverity = "low"
	SeverityMedium   ThreatSeverity = "medium"
	SeverityHigh     ThreatSeverity = "high"
	SeverityCritical ThreatSeverity = "critical"
)

type ThreatStats

type ThreatStats struct {
	TotalThreats24h    int            `json:"total_threats_24h"`
	BlockedThreats24h  int            `json:"blocked_threats_24h"`
	CriticalThreats24h int            `json:"critical_threats_24h"`
	HighThreats24h     int            `json:"high_threats_24h"`
	TopThreatTypes     map[string]int `json:"top_threat_types"`
	TopSourceIPs       map[string]int `json:"top_source_ips"`
	IsSecure           bool           `json:"is_secure"`
	RiskLevel          string         `json:"risk_level"` // "safe", "low", "medium", "high", "critical"
}

ThreatStats represents aggregated threat statistics.

type ThreatTrend

type ThreatTrend struct {
	Period     string             `json:"period"` // "day", "week", "month"
	StartDate  time.Time          `json:"start_date"`
	EndDate    time.Time          `json:"end_date"`
	Points     []ThreatTrendPoint `json:"points"`
	TotalCount int                `json:"total_count"`
	Summary    ThreatTrendSummary `json:"summary"`
}

ThreatTrend represents threat trend data over time.

type ThreatTrendPoint

type ThreatTrendPoint struct {
	Timestamp  time.Time      `json:"timestamp"`
	Date       string         `json:"date"`
	Hour       int            `json:"hour,omitempty"`
	Total      int            `json:"total"`
	Blocked    int            `json:"blocked"`
	BySeverity map[string]int `json:"by_severity"`
	ByType     map[string]int `json:"by_type"`
}

ThreatTrendPoint represents a single point in the threat trend.

type ThreatTrendSummary

type ThreatTrendSummary struct {
	TotalThreats   int            `json:"total_threats"`
	BlockedThreats int            `json:"blocked_threats"`
	BySeverity     map[string]int `json:"by_severity"`
	ByType         map[string]int `json:"by_type"`
	PeakHour       int            `json:"peak_hour"`
	PeakDay        string         `json:"peak_day"`
	TrendDirection string         `json:"trend_direction"` // "increasing", "decreasing", "stable"
}

ThreatTrendSummary provides summary statistics for the trend.

type ThreatType

type ThreatType string

ThreatType represents the type of security threat.

const (
	ThreatTypeInjection     ThreatType = "injection"
	ThreatTypeXSS           ThreatType = "xss"
	ThreatTypeSQLInjection  ThreatType = "sql_injection"
	ThreatTypePathTraversal ThreatType = "path_traversal"
	ThreatTypeCommandInject ThreatType = "command_injection"
	ThreatTypePromptInject  ThreatType = "prompt_injection"
	ThreatTypeBruteForce    ThreatType = "brute_force"
	ThreatTypeRateLimitHit  ThreatType = "rate_limit"
	ThreatTypeSuspiciousIP  ThreatType = "suspicious_ip"
)

type UpdatePromptFirewallRequest

type UpdatePromptFirewallRequest struct {
	Enabled *bool `json:"enabled"`
}

type UpdatePromptFirewallRuleRequest

type UpdatePromptFirewallRuleRequest struct {
	Keyword *string `json:"keyword,omitempty"`
	Enabled *bool   `json:"enabled,omitempty"`
}

Jump to

Keyboard shortcuts

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