security

package
v1.38.1 Latest Latest
Warning

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

Go to latest
Published: Mar 30, 2026 License: Apache-2.0 Imports: 20 Imported by: 0

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

Constants

This section is empty.

Variables

This section is empty.

Functions

func ClientIP deprecated

func ClientIP(r *http.Request) string

ClientIP extracts the client IP from a request, checking X-Forwarded-For and X-Real-IP headers before falling back to RemoteAddr.

Deprecated: ClientIP trusts forwarding headers from any source. Use ClientIPTrusted with an explicit set of trusted proxy IPs instead.

func ClientIPTrusted added in v1.12.0

func ClientIPTrusted(r *http.Request, trustedProxies map[string]bool) string

ClientIPTrusted extracts the client IP from a request. Forwarding headers (X-Forwarded-For, X-Real-IP) are only honoured when RemoteAddr is in trustedProxies. When trustedProxies is nil or RemoteAddr is not listed, the function returns the IP from RemoteAddr directly.

func Decrypt

func Decrypt(key, ciphertext []byte) ([]byte, error)

Decrypt decrypts ciphertext produced by Encrypt.

func Encrypt

func Encrypt(key, plaintext []byte) ([]byte, error)

Encrypt encrypts plaintext using AES-256-GCM with the given key. The key must be exactly 32 bytes.

func ValidateListenAddr

func ValidateListenAddr(addr string) error

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.

func (*APIKey) HasScope

func (k *APIKey) HasScope(s Scope) bool

HasScope reports whether the key has the given scope.

func (*APIKey) Valid

func (k *APIKey) Valid(now time.Time) bool

Valid reports whether the key is usable: not revoked and not expired.

type AlertHook

type AlertHook func(ctx context.Context, inc Incident) error

AlertHook is called when a security incident is detected.

type AuditReport

type AuditReport struct {
	Findings  []Finding
	ScannedAt time.Time
	TotalDeps int
}

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 BboltKeyStoreBackend added in v1.17.0

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

BboltKeyStoreBackend is a persistent KeyStoreBackend backed by a bbolt database.

func NewBboltKeyStoreBackend added in v1.17.0

func NewBboltKeyStoreBackend(path string) (*BboltKeyStoreBackend, error)

NewBboltKeyStoreBackend opens or creates a bbolt database at path and returns a backend ready for use with KeyStore.

func (*BboltKeyStoreBackend) Close added in v1.17.0

func (b *BboltKeyStoreBackend) Close() error

Close closes the underlying bbolt database.

func (*BboltKeyStoreBackend) Delete added in v1.17.0

func (b *BboltKeyStoreBackend) Delete(hash string) error

Delete removes an API key by its hash.

func (*BboltKeyStoreBackend) List added in v1.17.0

func (b *BboltKeyStoreBackend) List() []*APIKey

List returns all stored API keys.

func (*BboltKeyStoreBackend) Load added in v1.17.0

func (b *BboltKeyStoreBackend) Load(hash string) *APIKey

Load retrieves an API key by its hash. Returns nil if not found.

func (*BboltKeyStoreBackend) Store added in v1.17.0

func (b *BboltKeyStoreBackend) Store(hash string, key *APIKey) error

Store persists an API key under the given hash.

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

func NewIPFilter(allowList, denyList []string) *IPFilter

NewIPFilter creates an IP filter. If allowList is non-empty, only those IPs are permitted. denyList is always checked first.

func (*IPFilter) AddDeny

func (f *IPFilter) AddDeny(ip string)

AddDeny adds an IP to the deny list.

func (*IPFilter) Allowed

func (f *IPFilter) Allowed(ip string) bool

Allowed reports whether the given IP is permitted.

func (*IPFilter) RemoveDeny

func (f *IPFilter) RemoveDeny(ip string)

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 NewKeyStore

func NewKeyStore(opts ...KeyStoreOption) *KeyStore

NewKeyStore returns a KeyStore configured with the given options. If no backend is provided, an in-memory backend is used.

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.

func (*KeyStore) List

func (s *KeyStore) List() []*APIKey

List returns all non-revoked keys.

func (*KeyStore) Lookup

func (s *KeyStore) Lookup(rawKey string) *APIKey

Lookup finds a key by its raw value. Returns nil if not found.

func (*KeyStore) Revoke

func (s *KeyStore) Revoke(id string) error

Revoke marks a key as revoked by its ID.

func (*KeyStore) Rotate

func (s *KeyStore) Rotate(id string, newExpiry time.Time) (rawKey string, key *APIKey, err error)

Rotate revokes the old key and creates a new one with the same scopes. Returns the new raw key and key record.

type KeyStoreBackend added in v1.17.0

type KeyStoreBackend interface {
	Store(hash string, key *APIKey) error
	Load(hash string) *APIKey
	Delete(hash string) error
	List() []*APIKey
}

KeyStoreBackend abstracts storage operations for API keys.

type KeyStoreOption added in v1.17.0

type KeyStoreOption func(*KeyStore)

KeyStoreOption configures a KeyStore.

func WithBackend added in v1.17.0

func WithBackend(b KeyStoreBackend) KeyStoreOption

WithBackend sets the storage backend for a KeyStore.

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.

func (*RateLimiter) SetTrustedProxies added in v1.12.0

func (rl *RateLimiter) SetTrustedProxies(proxies []string)

SetTrustedProxies configures the set of proxy IPs whose X-Forwarded-For and X-Real-IP headers are trusted. When empty, forwarding headers are never trusted and ClientIPFromRequest always returns RemoteAddr.

func (*RateLimiter) TrustedProxies added in v1.12.0

func (rl *RateLimiter) TrustedProxies() map[string]bool

TrustedProxies returns a copy of the current trusted proxy set.

type Scope

type Scope string

Scope defines the permissions granted to an API key.

const (
	ScopeInference Scope = "inference"
	ScopeTraining  Scope = "training"
	ScopeAdmin     Scope = "admin"
	ScopeReadOnly  Scope = "read_only"
)

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 Severity

type Severity string

Severity indicates the severity of a vulnerability finding.

const (
	SeverityCritical Severity = "critical"
	SeverityHigh     Severity = "high"
	SeverityMedium   Severity = "medium"
	SeverityLow      Severity = "low"
	SeverityInfo     Severity = "info"
)

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

func (c *TLSConfig) BuildTLSConfig() (*tls.Config, error)

BuildTLSConfig returns a *tls.Config from the validated parameters.

func (*TLSConfig) Validate

func (c *TLSConfig) Validate() error

Validate checks that the TLS configuration is well-formed and that certificate files exist and parse correctly.

Jump to

Keyboard shortcuts

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