Documentation
¶
Overview ¶
Package security implements SOC 2 security controls for the Zerfoo ML framework.
It provides access control (API key management), encryption helpers, network security (rate limiting, IP filtering, CORS), secrets management, vulnerability scanning interfaces, and incident response hooks.
Index ¶
- func ClientIP(r *http.Request) string
- func Decrypt(key, ciphertext []byte) ([]byte, error)
- func Encrypt(key, plaintext []byte) ([]byte, error)
- func ValidateListenAddr(addr string) error
- type APIKey
- type AlertHook
- type AuditReport
- type CORSPolicy
- type CVEChecker
- type DependencyAuditor
- type Finding
- type IPFilter
- type Incident
- type IncidentResponder
- type IncidentResponderOption
- type IncidentSeverity
- type KMS
- type KeyStore
- func (s *KeyStore) Create(id string, scopes []Scope, expiresAt time.Time) (rawKey string, key *APIKey, err error)
- func (s *KeyStore) List() []*APIKey
- func (s *KeyStore) Lookup(rawKey string) *APIKey
- func (s *KeyStore) Revoke(id string) error
- func (s *KeyStore) Rotate(id string, newExpiry time.Time) (rawKey string, key *APIKey, err error)
- type RateLimiter
- type Scope
- type SecretConfig
- type Severity
- type TLSConfig
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ClientIP ¶
ClientIP extracts the client IP from a request, checking X-Forwarded-For and X-Real-IP headers before falling back to RemoteAddr.
func Encrypt ¶
Encrypt encrypts plaintext using AES-256-GCM with the given key. The key must be exactly 32 bytes.
func ValidateListenAddr ¶
ValidateListenAddr checks that addr is a valid host:port for binding.
Types ¶
type APIKey ¶
type APIKey struct {
ID string
Hash string // SHA-256 hash of the raw key; raw key is never stored
Scopes []Scope
CreatedAt time.Time
ExpiresAt time.Time // zero value means no expiry
Revoked bool
RevokedAt time.Time
}
APIKey represents a managed API key with scopes and lifecycle metadata.
type AuditReport ¶
AuditReport summarizes a dependency audit.
func (*AuditReport) CountBySeverity ¶
func (r *AuditReport) CountBySeverity(minSeverity Severity) int
CountBySeverity returns the number of findings at or above the given severity.
func (*AuditReport) HasCritical ¶
func (r *AuditReport) HasCritical() bool
HasCritical reports whether the report contains any critical findings.
type CORSPolicy ¶
type CORSPolicy struct {
AllowedOrigins []string
AllowedMethods []string
AllowedHeaders []string
MaxAge int // seconds
}
CORSPolicy defines allowed CORS origins, methods, and headers.
func (*CORSPolicy) Middleware ¶
func (p *CORSPolicy) Middleware(next http.Handler) http.Handler
Middleware returns an HTTP middleware that applies the CORS policy.
type CVEChecker ¶
type CVEChecker interface {
// Check returns findings for the given package at the given version.
Check(ctx context.Context, pkg, version string) ([]Finding, error)
}
CVEChecker queries a CVE database for a specific package and version.
type DependencyAuditor ¶
type DependencyAuditor interface {
// Audit returns all known vulnerability findings for the project.
Audit(ctx context.Context) ([]Finding, error)
}
DependencyAuditor scans project dependencies for known vulnerabilities.
type Finding ¶
type Finding struct {
ID string
Severity Severity
Package string
Version string
FixVersion string // empty if no fix available
Description string
CVE string // e.g., "CVE-2024-1234"
FoundAt time.Time
}
Finding represents a single vulnerability or audit finding.
type IPFilter ¶
type IPFilter struct {
// contains filtered or unexported fields
}
IPFilter manages IP allowlists and denylists.
func NewIPFilter ¶
NewIPFilter creates an IP filter. If allowList is non-empty, only those IPs are permitted. denyList is always checked first.
func (*IPFilter) RemoveDeny ¶
RemoveDeny removes an IP from the deny list.
type Incident ¶
type Incident struct {
ID string
Severity IncidentSeverity
Source string // e.g., "rate_limiter", "auth", "ip_filter"
Message string
ClientIP string
Timestamp time.Time
}
Incident represents a security event that requires attention.
type IncidentResponder ¶
type IncidentResponder struct {
// contains filtered or unexported fields
}
IncidentResponder monitors security events and triggers alert hooks. It supports automatic lockout after repeated suspicious activity.
func NewIncidentResponder ¶
func NewIncidentResponder(hooks []AlertHook, opts ...IncidentResponderOption) *IncidentResponder
NewIncidentResponder creates an incident responder with the given alert hooks.
func (*IncidentResponder) IsLockedOut ¶
func (ir *IncidentResponder) IsLockedOut(ip string) bool
IsLockedOut reports whether the given IP is currently locked out.
func (*IncidentResponder) Report ¶
func (ir *IncidentResponder) Report(ctx context.Context, inc Incident) error
Report records an incident and fires all alert hooks. If automatic lockout is configured and the threshold is exceeded, the source IP is denied.
func (*IncidentResponder) ResetLockout ¶
func (ir *IncidentResponder) ResetLockout(ip string)
ResetLockout clears the lockout and failure count for the given IP.
type IncidentResponderOption ¶
type IncidentResponderOption func(*IncidentResponder)
IncidentResponderOption configures an IncidentResponder.
func WithLockout ¶
func WithLockout(limit int, duration time.Duration, filter *IPFilter) IncidentResponderOption
WithLockout enables automatic IP lockout after limit incidents within the lockout window. Requires an IPFilter to enforce the lockout.
type IncidentSeverity ¶
type IncidentSeverity string
IncidentSeverity classifies the severity of a security incident.
const ( IncidentCritical IncidentSeverity = "critical" IncidentHigh IncidentSeverity = "high" IncidentMedium IncidentSeverity = "medium" IncidentLow IncidentSeverity = "low" )
type KMS ¶
type KMS interface {
// Encrypt encrypts plaintext using the named key.
Encrypt(ctx context.Context, keyID string, plaintext []byte) ([]byte, error)
// Decrypt decrypts ciphertext using the named key.
Decrypt(ctx context.Context, keyID string, ciphertext []byte) ([]byte, error)
// RotateKey triggers key rotation for the named key.
RotateKey(ctx context.Context, keyID string) error
}
KMS is the interface for external key management systems. Implementations wrap services like AWS KMS, GCP Cloud KMS, or HashiCorp Vault.
type KeyStore ¶
type KeyStore struct {
// contains filtered or unexported fields
}
KeyStore manages API keys. It is safe for concurrent use.
func (*KeyStore) Create ¶
func (s *KeyStore) Create(id string, scopes []Scope, expiresAt time.Time) (rawKey string, key *APIKey, err error)
Create generates a new API key with the given scopes and optional expiry. It returns the raw key (shown once) and the stored APIKey record.
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter implements a token-bucket rate limiter keyed by client IP.
func NewRateLimiter ¶
func NewRateLimiter(rate float64, burst int) *RateLimiter
NewRateLimiter creates a rate limiter allowing rate requests/second with a burst capacity of burst.
func (*RateLimiter) Allow ¶
func (rl *RateLimiter) Allow(ip string) bool
Allow reports whether a request from the given IP should be allowed.
func (*RateLimiter) Cleanup ¶
func (rl *RateLimiter) Cleanup()
Cleanup removes stale entries older than the configured TTL.
type SecretConfig ¶
type SecretConfig struct {
// contains filtered or unexported fields
}
SecretConfig loads configuration values securely from environment variables.
func NewSecretConfig ¶
func NewSecretConfig(prefix string) *SecretConfig
NewSecretConfig creates a SecretConfig that reads environment variables with the given prefix (e.g., "ZERFOO_" reads ZERFOO_DB_PASSWORD as "DB_PASSWORD").
func (*SecretConfig) Get ¶
func (sc *SecretConfig) Get(key string) (string, error)
Get returns the value for the given key (without prefix).
func (*SecretConfig) Has ¶
func (sc *SecretConfig) Has(key string) bool
Has reports whether the given key exists.
func (*SecretConfig) Keys ¶
func (sc *SecretConfig) Keys() []string
Keys returns all available secret keys (without prefix).
func (*SecretConfig) MustGet ¶
func (sc *SecretConfig) MustGet(key string) string
MustGet returns the value for the given key or panics if not found.
type TLSConfig ¶
type TLSConfig struct {
CertFile string
KeyFile string
CAFile string // optional CA for mTLS
MinVersion uint16 // 0 defaults to TLS 1.2
}
TLSConfig holds parameters for TLS validation.
func (*TLSConfig) BuildTLSConfig ¶
BuildTLSConfig returns a *tls.Config from the validated parameters.