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 ¶
- func ACMEProviderURL(provider string) string
- func AddDynamicOriginDefault(origin string)
- func BuildDockerExecArgs(params DockerExecParams) []string
- func CheckOriginDefault(r *http.Request) bool
- func CreateSecureDir(path string) error
- func GetDefaultAllowedOrigins() []string
- func GetDynamicOriginsDefault() []string
- func GetServerPort() int
- func IsDefaultAllowAllOrigins() bool
- func IsSafeOpenError(err error) bool
- func OnCertReady(fn func())
- func RemoveDynamicOriginDefault(origin string)
- func SanitizeCommand(cmd string) (string, error)
- func SanitizeCommandArgs(args []string) ([]string, error)
- func SecureDirMode() os.FileMode
- func SecureFileMode() os.FileMode
- func SetGlobalTLSManagerConfig(config *TLSManagerConfig)
- func SetServerPort(port int)
- func StripPotentialInjections(content string) string
- func TimingSafeCompare(a, b string) bool
- func TimingSafeCompareBytes(a, b []byte) bool
- func TruncateContent(content string, maxLength int) string
- func ValidateHMACSHA256Base64(body []byte, signature, secret string) bool
- func ValidateHMACSHA256Hex(body []byte, signature, secret string) bool
- func ValidateHMACSignature(message, signature, secret string) bool
- func ValidateMediaID(id string) error
- func WriteSecureFile(path string, data []byte) error
- type ACMEConfig
- type ACMERequest
- type ACMEStatus
- type AddPromptFirewallRuleRequest
- type BlockedIP
- type CORSConfigRequest
- type CORSConfigResponse
- type CertificateInfo
- type DayStats
- type DetectionResult
- type DockerExecParams
- type EnvSanitizer
- type EventStats
- type ExternalContentSanitizer
- func (s *ExternalContentSanitizer) DetectSuspiciousPatterns(content string) *DetectionResult
- func (s *ExternalContentSanitizer) SanitizeExternalContent(content string, source string) (string, *DetectionResult)
- func (s *ExternalContentSanitizer) WrapExternalContent(content string, source string) string
- type FixPreviewRequest
- type FixPreviewResponse
- type FixScanIssueRequest
- type FixScanIssueResponse
- type Handler
- func (h *Handler) AddEvent(event SecurityEvent)
- func (h *Handler) AddPromptFirewallRule(c echo.Context) error
- func (h *Handler) AddSession(session *Session)
- func (h *Handler) BlockIP(c echo.Context) error
- func (h *Handler) DeletePromptFirewallRule(c echo.Context) error
- func (h *Handler) ExportThreats(c echo.Context) error
- func (h *Handler) FixScanIssue(c echo.Context) error
- func (h *Handler) GenerateSelfSignedCert(c echo.Context) error
- func (h *Handler) GetACMEStatus(c echo.Context) error
- func (h *Handler) GetCORSConfig(c echo.Context) error
- func (h *Handler) GetEventStats(c echo.Context) error
- func (h *Handler) GetEvents(c echo.Context) error
- func (h *Handler) GetPromptFirewall(c echo.Context) error
- func (h *Handler) GetRecentThreats(c echo.Context) error
- func (h *Handler) GetSettings(c echo.Context) error
- func (h *Handler) GetStats(c echo.Context) error
- func (h *Handler) GetTLSConfig(c echo.Context) error
- func (h *Handler) GetThreatStats(c echo.Context) error
- func (h *Handler) GetThreatTrend(c echo.Context) error
- func (h *Handler) IsIPBlocked(ip string) bool
- func (h *Handler) ListBlockedIPs(c echo.Context) error
- func (h *Handler) ListSessions(c echo.Context) error
- func (h *Handler) ParseCertificate(c echo.Context) error
- func (h *Handler) PreviewScanFix(c echo.Context) error
- func (h *Handler) RegisterRoutes(g *echo.Group)
- func (h *Handler) ReloadTLSCert(c echo.Context) error
- func (h *Handler) RequestACMECert(c echo.Context) error
- func (h *Handler) RevokeAllSessions(c echo.Context) error
- func (h *Handler) RevokeSession(c echo.Context) error
- func (h *Handler) RunSecurityScan(c echo.Context) error
- func (h *Handler) ScanInput(c echo.Context) error
- func (h *Handler) SetDataDir(dataDir string)
- func (h *Handler) SetKVStore(kv kvstore.Store)
- func (h *Handler) SetPromptGuard(detector *promptguard.Detector)
- func (h *Handler) SetScannerConfig(config *ScannerConfig)
- func (h *Handler) SetStorage(storage *Storage)
- func (h *Handler) UnblockIP(c echo.Context) error
- func (h *Handler) UpdateCORSConfig(c echo.Context) error
- func (h *Handler) UpdatePromptFirewall(c echo.Context) error
- func (h *Handler) UpdatePromptFirewallRule(c echo.Context) error
- func (h *Handler) UpdateSettings(c echo.Context) error
- func (h *Handler) UpdateTLSSettings(c echo.Context) error
- func (h *Handler) UploadTLSCert(c echo.Context) error
- type OriginChecker
- func (c *OriginChecker) AddDynamicOrigin(origin string)
- func (c *OriginChecker) CheckOrigin(r *http.Request) bool
- func (c *OriginChecker) CreateWebSocketCheckOrigin() func(r *http.Request) bool
- func (c *OriginChecker) GetAllowedOrigins() []string
- func (c *OriginChecker) GetDynamicOrigins() []string
- func (c *OriginChecker) IsAllowAll() bool
- func (c *OriginChecker) IsAllowedOrigin(origin string) bool
- func (c *OriginChecker) RemoveDynamicOrigin(origin string)
- type OriginConfig
- type PatternMatch
- type PromptFirewallConfig
- type PromptFirewallConfigResponse
- type PromptFirewallRule
- type SafeOpenError
- type SafeOpenErrorCode
- type SafeOpenResult
- type ScanCache
- type ScanRequest
- type ScanResponse
- type ScanSummary
- type ScannerConfig
- type SecurityEvent
- type SecurityScanItem
- type SecurityScanResult
- type SecurityScanner
- type SecuritySettings
- type SecurityStats
- type Session
- type Storage
- func (s *Storage) CleanupExpired(retentionDays int) error
- func (s *Storage) Close() error
- func (s *Storage) GetBlockedIPs() map[string]*BlockedIP
- func (s *Storage) GetEventStats(period string) (*EventStats, error)
- func (s *Storage) GetEvents(limit, offset int, eventType string) ([]SecurityEvent, int, error)
- func (s *Storage) GetScanCache() *ScanCache
- func (s *Storage) IsIPBlocked(ip string) bool
- func (s *Storage) RemoveBlockedIP(ip string) error
- func (s *Storage) SaveBlockedIP(blocked *BlockedIP) error
- func (s *Storage) SaveEvent(event *SecurityEvent) error
- func (s *Storage) SaveScanCache(items []SecurityScanItem, summary ScanSummary) error
- type SuspiciousPattern
- type TLSConfigResponse
- type TLSManager
- func (m *TLSManager) GenerateSelfSigned(domains []string, validDays int) error
- func (m *TLSManager) GetACMEStatus() *ACMEStatus
- func (m *TLSManager) GetAutocertManager() *autocert.Manager
- func (m *TLSManager) GetCertificate() *tls.Certificate
- func (m *TLSManager) GetCertificateInfo() *CertificateInfo
- func (m *TLSManager) GetHTTPHandler() http.Handler
- func (m *TLSManager) GetHTTPSPort() int
- func (m *TLSManager) GetTLSConfig() *tls.Config
- func (m *TLSManager) HTTPSRedirectMiddleware() echo.MiddlewareFunc
- func (m *TLSManager) IsHTTPSOnly() bool
- func (m *TLSManager) IsHotReloadSupported() bool
- func (m *TLSManager) LoadCertificate() error
- func (m *TLSManager) LoadSettings() error
- func (m *TLSManager) ReloadCertificate() error
- func (m *TLSManager) RequestACMECertificate(config *ACMEConfig) error
- func (m *TLSManager) SaveCertificate(certPEM, keyPEM []byte) error
- func (m *TLSManager) SaveSettings() error
- func (m *TLSManager) SetHTTPSOnly(enabled bool)
- func (m *TLSManager) SetHTTPSPort(port int)
- func (m *TLSManager) SetKVStore(kv kvstore.Store)
- func (m *TLSManager) StopRenewalChecker()
- type TLSManagerConfig
- type TLSSelfSignedRequest
- type TLSSettingsRequest
- type TLSUploadRequest
- type ThreatDetector
- func (td *ThreatDetector) ClearOldEvents(maxAge time.Duration) int
- func (td *ThreatDetector) DetectThreats(input, source, ipAddress, userID string) []ThreatEvent
- func (td *ThreatDetector) GetRecentThreats(limit int) []ThreatEvent
- func (td *ThreatDetector) GetStats() *ThreatStats
- func (td *ThreatDetector) GetThreatTrend(period string) *ThreatTrend
- func (td *ThreatDetector) RecordBruteForce(ipAddress, userID string, attempts int)
- func (td *ThreatDetector) RecordRateLimitHit(ipAddress, endpoint string)
- func (td *ThreatDetector) SetOnThreat(callback func(ThreatEvent))
- type ThreatEvent
- type ThreatSeverity
- type ThreatStats
- type ThreatTrend
- type ThreatTrendPoint
- type ThreatTrendSummary
- type ThreatType
- type UpdatePromptFirewallRequest
- type UpdatePromptFirewallRuleRequest
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ACMEProviderURL ¶
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 ¶
CheckOriginDefault checks the origin using the default configuration.
func CreateSecureDir ¶
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 ¶
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 ¶
SanitizeCommand sanitizes a command string to prevent injection. This is a basic sanitization - for untrusted input, use a proper sandbox.
func SanitizeCommandArgs ¶
SanitizeCommandArgs sanitizes command arguments.
func SecureDirMode ¶
SecureDirMode returns a secure directory mode for creating directories. Directories are created with owner-only read/write/execute permissions.
func SecureFileMode ¶
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 ¶
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 ¶
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 ¶
TimingSafeCompareBytes performs a constant-time comparison of two byte slices.
func TruncateContent ¶
TruncateContent truncates content to a maximum length, adding an indicator if truncation occurred.
func ValidateHMACSHA256Base64 ¶
ValidateHMACSHA256Base64 validates an HMAC-SHA256 signature encoded as base64. Used for LINE webhook signature validation.
func ValidateHMACSHA256Hex ¶
ValidateHMACSHA256Hex validates an HMAC-SHA256 signature encoded as hex. Used for various webhook signature validations.
func ValidateHMACSignature ¶
ValidateHMACSignature validates an HMAC-SHA256 signature using constant-time comparison. This is used for webhook signature validation to prevent timing attacks.
func ValidateMediaID ¶
ValidateMediaID validates a media ID to prevent path traversal. Media IDs should only contain safe characters.
func WriteSecureFile ¶
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 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 ¶
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 ¶
AddPromptFirewallRule handles POST /api/v1/security/firewall/rules.
func (*Handler) AddSession ¶
AddSession adds a session (for use by other packages).
func (*Handler) DeletePromptFirewallRule ¶
DeletePromptFirewallRule handles DELETE /api/v1/security/firewall/rules/:id.
func (*Handler) ExportThreats ¶
ExportThreats handles GET /api/v1/security/threats/export Exports threat data as CSV for reporting purposes.
func (*Handler) FixScanIssue ¶
FixScanIssue handles POST /api/v1/security/scan/fix This endpoint attempts to fix a detected issue.
func (*Handler) GenerateSelfSignedCert ¶
GenerateSelfSignedCert handles POST /api/v1/security/tls/self-signed
func (*Handler) GetACMEStatus ¶
GetACMEStatus handles GET /api/v1/security/tls/acme
func (*Handler) GetCORSConfig ¶
GetCORSConfig handles GET /api/v1/security/cors
func (*Handler) GetEventStats ¶
GetEventStats handles GET /api/v1/security/events/stats Returns aggregated event statistics for the specified period (day, week, month).
func (*Handler) GetPromptFirewall ¶
GetPromptFirewall handles GET /api/v1/security/firewall.
func (*Handler) GetRecentThreats ¶
GetRecentThreats handles GET /api/v1/security/threats
func (*Handler) GetSettings ¶
GetSettings handles GET /api/v1/security/settings
func (*Handler) GetTLSConfig ¶
GetTLSConfig handles GET /api/v1/security/tls
func (*Handler) GetThreatStats ¶
GetThreatStats handles GET /api/v1/security/threats/stats
func (*Handler) GetThreatTrend ¶
GetThreatTrend handles GET /api/v1/security/threats/trend Returns threat trend data for the specified period (day, week, month).
func (*Handler) IsIPBlocked ¶
IsIPBlocked checks if an IP is blocked.
func (*Handler) ListBlockedIPs ¶
ListBlockedIPs handles GET /api/v1/security/blocked-ips
func (*Handler) ListSessions ¶
ListSessions handles GET /api/v1/security/sessions
func (*Handler) ParseCertificate ¶
ParseCertificate handles POST /api/v1/security/tls/parse
func (*Handler) PreviewScanFix ¶
PreviewScanFix handles POST /api/v1/security/scan/preview This endpoint previews what a fix will do without applying it.
func (*Handler) RegisterRoutes ¶
RegisterRoutes registers the security routes.
func (*Handler) ReloadTLSCert ¶
ReloadTLSCert handles POST /api/v1/security/tls/reload Hot-reload certificate from files without restarting the server.
func (*Handler) RequestACMECert ¶
RequestACMECert handles POST /api/v1/security/tls/acme
func (*Handler) RevokeAllSessions ¶
RevokeAllSessions handles POST /api/v1/security/sessions/revoke-all
func (*Handler) RevokeSession ¶
RevokeSession handles DELETE /api/v1/security/sessions/:id
func (*Handler) RunSecurityScan ¶
RunSecurityScan handles GET /api/v1/security/scan/run This endpoint performs a comprehensive security scan of the system.
func (*Handler) SetDataDir ¶
SetDataDir sets the data directory for system checks.
func (*Handler) SetKVStore ¶
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 ¶
SetStorage sets the storage backend for persistence.
func (*Handler) UpdateCORSConfig ¶
UpdateCORSConfig handles PUT /api/v1/security/cors
func (*Handler) UpdatePromptFirewall ¶
UpdatePromptFirewall handles PUT /api/v1/security/firewall.
func (*Handler) UpdatePromptFirewallRule ¶
UpdatePromptFirewallRule handles PUT /api/v1/security/firewall/rules/:id.
func (*Handler) UpdateSettings ¶
UpdateSettings handles PUT /api/v1/security/settings
func (*Handler) UpdateTLSSettings ¶
UpdateTLSSettings handles PUT /api/v1/security/tls/settings
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 ¶
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
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 ¶
NewStorage creates a new security storage instance.
func (*Storage) CleanupExpired ¶
CleanupExpired removes expired data.
func (*Storage) GetBlockedIPs ¶
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) GetScanCache ¶
GetScanCache retrieves cached scan results.
func (*Storage) IsIPBlocked ¶
IsIPBlocked checks if an IP is blocked.
func (*Storage) RemoveBlockedIP ¶
RemoveBlockedIP removes a blocked IP from storage.
func (*Storage) SaveBlockedIP ¶
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 ¶
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"`
}