Documentation
¶
Overview ¶
Package security provides security utilities for the aixgo framework.
Index ¶
- Constants
- Variables
- func ExtractAuthContext(extractor AuthExtractor) func(http.Handler) http.Handler
- func GetOllamaAllowedHosts() []string
- func GetRequestID(ctx context.Context) string
- func IsValidAPIKeyFormat(key string) bool
- func MaskSecret(secret string) string
- func SanitizeFilePath(path string, baseDir string) (string, error)
- func SanitizeString(input string) string
- func ValidateDeploymentInputs(projectID, region, serviceName, repoName, imageName, environment string) error
- func ValidateEnvironment(env string) error
- func ValidateFilePath(path string) error
- func ValidateImageName(imageName string) error
- func ValidateJSONObject(value any) error
- func ValidateProjectID(projectID string) error
- func ValidateRegion(region string) error
- func ValidateRepositoryName(repoName string) error
- func ValidateSIEMURL(rawURL string) error
- func ValidateServiceName(serviceName string) error
- func ValidateToolName(name string) error
- func ValidateYAMLFile(data []byte, limits YAMLLimits) error
- func WithAuthContext(ctx context.Context, authCtx *AuthContext) context.Context
- func WithRequestID(ctx context.Context, requestID string) context.Context
- func WithSpanID(ctx context.Context, spanID string) context.Context
- func WithTraceID(ctx context.Context, traceID string) context.Context
- type APIKeyAuthenticator
- type APIKeyConfig
- type AllowAllAuthorizer
- type ArgValidator
- type AuditBackend
- type AuditConfig
- type AuditEvent
- type AuditEventType
- type AuditLogger
- type AuditMiddleware
- type AuthContext
- type AuthExtractor
- type AuthMode
- type Authenticator
- type AuthorizationConfig
- type Authorizer
- type BuiltinAuthConfig
- type BuiltinAuthExtractor
- type CircuitBreaker
- type CircuitState
- type ClientInfo
- type DelegatedAuthConfig
- type DelegatedAuthExtractor
- type DetectionCategory
- type DetectionResult
- type DisabledAuthExtractor
- type ElasticsearchBackend
- type ElasticsearchConfig
- type ErrorCode
- type FileAuditBackend
- type FloatValidator
- type HybridAuthExtractor
- type IAPConfig
- type IAPJWTClaims
- type IAPKeyCache
- type IAPPublicKey
- type InMemoryAuditLogger
- func (l *InMemoryAuditLogger) Close() error
- func (l *InMemoryAuditLogger) GetEvents() []AuditEvent
- func (l *InMemoryAuditLogger) Log(event *AuditEvent)
- func (l *InMemoryAuditLogger) LogAuthAttempt(ctx context.Context, success bool, err error)
- func (l *InMemoryAuditLogger) LogAuthorizationCheck(ctx context.Context, resource string, permission Permission, allowed bool)
- func (l *InMemoryAuditLogger) LogToolExecution(ctx context.Context, toolName string, args map[string]interface{}, ...)
- type IntValidator
- type IntegratedAuditLogger
- func (l *IntegratedAuditLogger) AddBackend(backend AuditBackend)
- func (l *IntegratedAuditLogger) Close() error
- func (l *IntegratedAuditLogger) Log(event *AuditEvent)
- func (l *IntegratedAuditLogger) LogAuthAttempt(ctx context.Context, success bool, err error)
- func (l *IntegratedAuditLogger) LogAuthorizationCheck(ctx context.Context, resource string, permission Permission, allowed bool)
- func (l *IntegratedAuditLogger) LogRateLimitExceeded(ctx context.Context, resource string, clientID string)
- func (l *IntegratedAuditLogger) LogToolExecution(ctx context.Context, toolName string, args map[string]interface{}, ...)
- func (l *IntegratedAuditLogger) LogValidationError(ctx context.Context, resource string, err error)
- type JSONAuditLogger
- func (l *JSONAuditLogger) Close() error
- func (l *JSONAuditLogger) Log(event *AuditEvent)
- func (l *JSONAuditLogger) LogAuthAttempt(ctx context.Context, success bool, err error)
- func (l *JSONAuditLogger) LogAuthorizationCheck(ctx context.Context, resource string, permission Permission, allowed bool)
- func (l *JSONAuditLogger) LogToolExecution(ctx context.Context, toolName string, args map[string]interface{}, ...)
- type JWTClaims
- type MemoryAuditBackend
- type NoAuthAuthenticator
- type NoOpAuditLogger
- func (l *NoOpAuditLogger) Close() error
- func (l *NoOpAuditLogger) Log(event *AuditEvent)
- func (l *NoOpAuditLogger) LogAuthAttempt(ctx context.Context, success bool, err error)
- func (l *NoOpAuditLogger) LogAuthorizationCheck(ctx context.Context, resource string, permission Permission, allowed bool)
- func (l *NoOpAuditLogger) LogToolExecution(ctx context.Context, toolName string, args map[string]interface{}, ...)
- type Pattern
- type Permission
- type Principal
- type PrincipalInfo
- type PromptInjectionDetector
- type RBACAuthorizer
- type RateLimiter
- type SIEMConfig
- type SSRFConfig
- type SSRFValidator
- type SafeYAMLParser
- type SecureError
- type SecurityConfig
- type Sensitivity
- type SplunkBackend
- type SplunkConfig
- type SplunkEvent
- type StringValidator
- type StructuredAuditEvent
- type TimeoutManager
- type ToolRateLimiter
- type WebhookBackend
- type WebhookConfig
- type WebhookPayload
- type YAMLLimits
Constants ¶
const MaxInputSize = 10 * 1024
MaxInputSize is the maximum input size (10KB) to prevent ReDoS attacks
Variables ¶
var DefaultOllamaAllowlist = []string{
"localhost",
"127.0.0.1",
"::1",
"ollama",
"ollama-service",
}
DefaultOllamaAllowlist returns the default allowlist for Ollama services
Functions ¶
func ExtractAuthContext ¶
func ExtractAuthContext(extractor AuthExtractor) func(http.Handler) http.Handler
ExtractAuthContext is a middleware helper that extracts auth and adds it to context
func GetOllamaAllowedHosts ¶ added in v0.1.3
func GetOllamaAllowedHosts() []string
GetOllamaAllowedHosts returns the default allowlist plus any from OLLAMA_ALLOWED_HOSTS
func GetRequestID ¶
GetRequestID retrieves the request ID from context
func IsValidAPIKeyFormat ¶
IsValidAPIKeyFormat validates the format of an API key
func MaskSecret ¶
MaskSecret masks a secret for logging purposes
func SanitizeFilePath ¶
SanitizeFilePath prevents path traversal attacks
func SanitizeString ¶
SanitizeString removes potentially dangerous characters from strings
func ValidateDeploymentInputs ¶
func ValidateDeploymentInputs(projectID, region, serviceName, repoName, imageName, environment string) error
ValidateDeploymentInputs validates all deployment-related inputs at once This provides a convenient function to validate all parameters before executing any commands Prevents command injection by ensuring all inputs match safe patterns
func ValidateEnvironment ¶
ValidateEnvironment validates an environment name This prevents command injection in environment parameters
func ValidateFilePath ¶ added in v0.1.2
ValidateFilePath validates a file path for safe file operations It prevents path traversal attacks and ensures the path doesn't contain dangerous patterns This is critical for TLS certificate loading and other file read operations
func ValidateImageName ¶
ValidateImageName validates a container image name This prevents command injection in image name parameters
func ValidateJSONObject ¶
ValidateJSONObject validates that a value is a valid JSON object
func ValidateProjectID ¶
ValidateProjectID validates a GCP project ID Returns error if the project ID doesn't match GCP naming requirements This prevents command injection by ensuring only safe characters are used
func ValidateRegion ¶
ValidateRegion validates a GCP region name This prevents command injection in region parameters
func ValidateRepositoryName ¶
ValidateRepositoryName validates an Artifact Registry repository name This prevents command injection in repository name parameters
func ValidateSIEMURL ¶ added in v0.1.2
ValidateSIEMURL validates that a URL is safe for SIEM connections and prevents SSRF attacks by blocking private IP ranges
func ValidateServiceName ¶
ValidateServiceName validates a Cloud Run service name This prevents command injection in service name parameters
func ValidateToolName ¶
ValidateToolName checks if a tool name is valid and safe
func ValidateYAMLFile ¶
func ValidateYAMLFile(data []byte, limits YAMLLimits) error
ValidateYAMLFile validates a YAML file's structure without unmarshaling
func WithAuthContext ¶
func WithAuthContext(ctx context.Context, authCtx *AuthContext) context.Context
WithAuthContext adds authentication context to the context
func WithRequestID ¶
WithRequestID adds a request ID to the context
func WithSpanID ¶
WithSpanID adds a span ID to the context
Types ¶
type APIKeyAuthenticator ¶
type APIKeyAuthenticator struct {
// contains filtered or unexported fields
}
APIKeyAuthenticator implements simple API key authentication
func NewAPIKeyAuthenticator ¶
func NewAPIKeyAuthenticator() *APIKeyAuthenticator
NewAPIKeyAuthenticator creates a new API key authenticator
func (*APIKeyAuthenticator) AddKey ¶
func (a *APIKeyAuthenticator) AddKey(apiKey string, principal *Principal)
AddKey registers an API key with associated principal
func (*APIKeyAuthenticator) Authenticate ¶
Authenticate verifies an API key and returns the associated principal
type APIKeyConfig ¶
type APIKeyConfig struct {
Source string `yaml:"source"` // environment, file
FilePath string `yaml:"file_path,omitempty"`
EnvPrefix string `yaml:"env_prefix,omitempty"`
}
APIKeyConfig for API key auth
type AllowAllAuthorizer ¶
type AllowAllAuthorizer struct{}
AllowAllAuthorizer allows all requests (use only for testing/development)
func NewAllowAllAuthorizer ¶
func NewAllowAllAuthorizer() *AllowAllAuthorizer
NewAllowAllAuthorizer creates a new allow-all authorizer (INSECURE - testing only)
func (*AllowAllAuthorizer) Authorize ¶
func (a *AllowAllAuthorizer) Authorize(ctx context.Context, principal *Principal, resource string, permission Permission) error
Authorize always returns nil (allows all access)
type ArgValidator ¶
ArgValidator defines an interface for validating arguments
type AuditBackend ¶
type AuditBackend interface {
Write(event *StructuredAuditEvent) error
Close() error
}
AuditBackend defines the interface for audit storage backends
type AuditConfig ¶
type AuditConfig struct {
Enabled bool `yaml:"enabled"`
Backend string `yaml:"backend"` // memory, json, syslog
LogAuthDecisions bool `yaml:"log_auth_decisions"`
SIEM *SIEMConfig `yaml:"siem,omitempty"`
}
AuditConfig for audit logging
type AuditEvent ¶
type AuditEvent struct {
Timestamp time.Time `json:"timestamp"`
EventType string `json:"event_type"`
UserID string `json:"user_id,omitempty"`
SessionID string `json:"session_id,omitempty"`
IPAddress string `json:"ip_address,omitempty"`
UserAgent string `json:"user_agent,omitempty"`
Resource string `json:"resource"`
Action string `json:"action"`
Result string `json:"result"`
Error string `json:"error,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
AuditEvent represents a security-relevant event
type AuditEventType ¶
type AuditEventType string
AuditEventType defines the types of audit events
const ( AuditEventToolCall AuditEventType = "tool.call" AuditEventToolResult AuditEventType = "tool.result" AuditEventAuthSuccess AuditEventType = "auth.success" AuditEventAuthFailure AuditEventType = "auth.failure" AuditEventAuthzAllowed AuditEventType = "authz.allowed" AuditEventAuthzDenied AuditEventType = "authz.denied" AuditEventRateLimit AuditEventType = "ratelimit.exceeded" AuditEventValidation AuditEventType = "validation.error" AuditEventError AuditEventType = "error" )
type AuditLogger ¶
type AuditLogger interface {
Log(event *AuditEvent)
LogToolExecution(ctx context.Context, toolName string, args map[string]interface{}, result interface{}, err error)
LogAuthAttempt(ctx context.Context, success bool, err error)
LogAuthorizationCheck(ctx context.Context, resource string, permission Permission, allowed bool)
Close() error
}
AuditLogger defines the interface for audit logging
type AuditMiddleware ¶
type AuditMiddleware struct {
// contains filtered or unexported fields
}
AuditMiddleware provides middleware functionality for MCP servers
func NewAuditMiddleware ¶
func NewAuditMiddleware(logger *IntegratedAuditLogger) *AuditMiddleware
NewAuditMiddleware creates a new audit middleware
func (*AuditMiddleware) Logger ¶
func (m *AuditMiddleware) Logger() *IntegratedAuditLogger
Logger returns the underlying audit logger
type AuthContext ¶
type AuthContext struct {
Principal *Principal
SessionID string
IPAddress string
UserAgent string
RequestTime time.Time
}
AuthContext contains authentication and authorization information
func GetAuthContext ¶
func GetAuthContext(ctx context.Context) (*AuthContext, error)
GetAuthContext retrieves authentication context from the context
type AuthExtractor ¶
type AuthExtractor interface {
// ExtractAuth extracts authentication information and returns a Principal
ExtractAuth(ctx context.Context, r *http.Request) (*Principal, error)
}
AuthExtractor extracts authentication information from HTTP requests
func NewAuthExtractorFromConfig ¶
func NewAuthExtractorFromConfig(config *SecurityConfig) (AuthExtractor, error)
NewAuthExtractorFromConfig creates an appropriate auth extractor based on config
type AuthMode ¶
type AuthMode string
AuthMode defines how authentication is handled
const ( // AuthModeDisabled - No authentication (local dev only) AuthModeDisabled AuthMode = "disabled" // AuthModeDelegated - Infrastructure handles auth (IAP, Istio, etc.) AuthModeDelegated AuthMode = "delegated" // AuthModeBuiltin - Application validates credentials AuthModeBuiltin AuthMode = "builtin" // AuthModeHybrid - Both infrastructure and app validation AuthModeHybrid AuthMode = "hybrid" )
type Authenticator ¶
type Authenticator interface {
Authenticate(ctx context.Context, token string) (*Principal, error)
}
Authenticator handles authentication of requests
type AuthorizationConfig ¶
type AuthorizationConfig struct {
Enabled bool `yaml:"enabled"`
DefaultDeny bool `yaml:"default_deny"`
PolicyFile string `yaml:"policy_file,omitempty"`
}
AuthorizationConfig for access control
type Authorizer ¶
type Authorizer interface {
Authorize(ctx context.Context, principal *Principal, resource string, permission Permission) error
}
Authorizer handles authorization decisions
type BuiltinAuthConfig ¶
type BuiltinAuthConfig struct {
Method string `yaml:"method"` // api_key, jwt, oauth2
// API Key configuration
APIKeys *APIKeyConfig `yaml:"api_keys,omitempty"`
}
BuiltinAuthConfig for app-level auth
type BuiltinAuthExtractor ¶
type BuiltinAuthExtractor struct {
// contains filtered or unexported fields
}
BuiltinAuthExtractor validates credentials using application logic
func NewBuiltinAuthExtractor ¶
func NewBuiltinAuthExtractor(config *BuiltinAuthConfig) (*BuiltinAuthExtractor, error)
NewBuiltinAuthExtractor creates a new builtin auth extractor
func (*BuiltinAuthExtractor) ExtractAuth ¶
func (e *BuiltinAuthExtractor) ExtractAuth(ctx context.Context, r *http.Request) (*Principal, error)
ExtractAuth validates credentials and returns principal
type CircuitBreaker ¶
type CircuitBreaker struct {
// contains filtered or unexported fields
}
CircuitBreaker implements the circuit breaker pattern
func NewCircuitBreaker ¶
func NewCircuitBreaker(maxFailures int, resetTimeout time.Duration) *CircuitBreaker
NewCircuitBreaker creates a new circuit breaker
func (*CircuitBreaker) Execute ¶
func (cb *CircuitBreaker) Execute(fn func() error) error
Execute runs a function through the circuit breaker
func (*CircuitBreaker) GetState ¶
func (cb *CircuitBreaker) GetState() CircuitState
GetState returns the current state of the circuit breaker
func (*CircuitBreaker) Reset ¶
func (cb *CircuitBreaker) Reset()
Reset manually resets the circuit breaker
type CircuitState ¶
type CircuitState int
CircuitState represents the state of a circuit breaker
const ( CircuitClosed CircuitState = iota CircuitOpen CircuitHalfOpen )
type ClientInfo ¶
type ClientInfo struct {
IPAddress string `json:"ip_address,omitempty"`
UserAgent string `json:"user_agent,omitempty"`
}
ClientInfo contains client connection information
type DelegatedAuthConfig ¶
type DelegatedAuthConfig struct {
// Header containing identity
IdentityHeader string `yaml:"identity_header"`
// IAP configuration
IAP *IAPConfig `yaml:"iap,omitempty"`
// Header mapping for extracting identity fields
HeaderMapping map[string]string `yaml:"header_mapping,omitempty"`
}
DelegatedAuthConfig for infrastructure-provided auth
type DelegatedAuthExtractor ¶
type DelegatedAuthExtractor struct {
// contains filtered or unexported fields
}
DelegatedAuthExtractor extracts auth from infrastructure-provided headers
func NewDelegatedAuthExtractor ¶
func NewDelegatedAuthExtractor(config *DelegatedAuthConfig) (*DelegatedAuthExtractor, error)
NewDelegatedAuthExtractor creates a new delegated auth extractor
func (*DelegatedAuthExtractor) ExtractAuth ¶
func (e *DelegatedAuthExtractor) ExtractAuth(ctx context.Context, r *http.Request) (*Principal, error)
ExtractAuth extracts principal from delegated auth headers
type DetectionCategory ¶
type DetectionCategory string
DetectionCategory represents the type of injection attack detected
const ( CategorySystemOverride DetectionCategory = "system_override" CategoryRoleHijacking DetectionCategory = "role_hijacking" CategoryDelimiterInjection DetectionCategory = "delimiter_injection" CategoryEncodingAttack DetectionCategory = "encoding_attack" CategoryJailbreak DetectionCategory = "jailbreak" )
type DetectionResult ¶
type DetectionResult struct {
Detected bool `json:"detected"`
Confidence float64 `json:"confidence"`
Category DetectionCategory `json:"category,omitempty"`
MatchedPatterns []string `json:"matched_patterns,omitempty"`
Details string `json:"details,omitempty"`
}
DetectionResult contains information about a detected injection attempt
type DisabledAuthExtractor ¶
type DisabledAuthExtractor struct{}
DisabledAuthExtractor allows all requests without authentication
func NewDisabledAuthExtractor ¶
func NewDisabledAuthExtractor() *DisabledAuthExtractor
NewDisabledAuthExtractor creates a new disabled auth extractor
func (*DisabledAuthExtractor) ExtractAuth ¶
func (e *DisabledAuthExtractor) ExtractAuth(ctx context.Context, r *http.Request) (*Principal, error)
ExtractAuth returns a default anonymous principal with read-only permissions WARNING: Disabled auth should only be used in development/testing environments
type ElasticsearchBackend ¶
type ElasticsearchBackend struct {
// contains filtered or unexported fields
}
ElasticsearchBackend sends audit events to Elasticsearch
func NewElasticsearchBackend ¶
func NewElasticsearchBackend(config *ElasticsearchConfig, batchSize int, flushInterval time.Duration) (*ElasticsearchBackend, error)
NewElasticsearchBackend creates a new Elasticsearch audit backend
func (ElasticsearchBackend) Write ¶
func (b ElasticsearchBackend) Write(event *StructuredAuditEvent) error
type ElasticsearchConfig ¶
type ElasticsearchConfig struct {
URLs []string `yaml:"urls"`
Index string `yaml:"index"`
Username string `yaml:"username,omitempty"`
Password string `yaml:"password,omitempty"`
TLSVerify bool `yaml:"tls_verify"`
}
ElasticsearchConfig holds Elasticsearch-specific configuration
type ErrorCode ¶
type ErrorCode string
ErrorCode represents a standardized error code for API responses
const ( ErrCodeInternal ErrorCode = "INTERNAL_ERROR" ErrCodeInvalidInput ErrorCode = "INVALID_INPUT" ErrCodeNotFound ErrorCode = "NOT_FOUND" ErrCodeForbidden ErrorCode = "FORBIDDEN" ErrCodeRateLimit ErrorCode = "RATE_LIMIT" ErrCodeTimeout ErrorCode = "TIMEOUT" ErrCodeToolNotFound ErrorCode = "TOOL_NOT_FOUND" ErrCodeToolExecution ErrorCode = "TOOL_EXECUTION_ERROR" ErrCodeValidation ErrorCode = "VALIDATION_ERROR" )
type FileAuditBackend ¶
type FileAuditBackend struct {
// contains filtered or unexported fields
}
FileAuditBackend writes events to a file as JSON lines
func NewFileAuditBackend ¶
func NewFileAuditBackend(path string) (*FileAuditBackend, error)
NewFileAuditBackend creates a file-based audit backend
func NewFileAuditBackendWithWriter ¶
func NewFileAuditBackendWithWriter(w io.WriteCloser) *FileAuditBackend
NewFileAuditBackendWithWriter creates a file backend with a custom writer
func (*FileAuditBackend) Write ¶
func (b *FileAuditBackend) Write(event *StructuredAuditEvent) error
Write writes an event to the file
type FloatValidator ¶
FloatValidator validates floating-point arguments
func (*FloatValidator) Validate ¶
func (v *FloatValidator) Validate(value any) error
Validate checks if the value is a float within specified bounds
type HybridAuthExtractor ¶
type HybridAuthExtractor struct {
// contains filtered or unexported fields
}
HybridAuthExtractor tries delegated auth first, falls back to builtin
func NewHybridAuthExtractor ¶
func NewHybridAuthExtractor(delegatedConfig *DelegatedAuthConfig, builtinConfig *BuiltinAuthConfig) (*HybridAuthExtractor, error)
NewHybridAuthExtractor creates a new hybrid auth extractor
func (*HybridAuthExtractor) ExtractAuth ¶
ExtractAuth tries delegated auth first, then builtin
type IAPConfig ¶
type IAPConfig struct {
Enabled bool `yaml:"enabled"`
VerifyJWT bool `yaml:"verify_jwt"`
Audience string `yaml:"audience,omitempty"`
}
IAPConfig for Google Cloud IAP
type IAPJWTClaims ¶
type IAPJWTClaims struct {
Email string `json:"email"`
Sub string `json:"sub"`
Aud string `json:"aud"`
Iss string `json:"iss"`
Iat int64 `json:"iat"`
Exp int64 `json:"exp"`
Hd string `json:"hd"`
EmailVerified bool `json:"email_verified"`
}
IAPJWTClaims represents the claims in an IAP JWT
func ParseIAPJWT ¶
func ParseIAPJWT(token string) (*IAPJWTClaims, error)
ParseIAPJWT parses an IAP JWT without verification This is used when JWT verification is disabled but we still want to extract claims
func VerifyIAPJWT ¶
func VerifyIAPJWT(ctx context.Context, token string, audience string, keyCache *IAPKeyCache) (*IAPJWTClaims, error)
VerifyIAPJWT verifies an IAP JWT signature and claims
type IAPKeyCache ¶
type IAPKeyCache struct {
// contains filtered or unexported fields
}
IAPKeyCache caches Google's public keys for IAP JWT verification
func (*IAPKeyCache) GetKey ¶
func (c *IAPKeyCache) GetKey(ctx context.Context, kid string) (*IAPPublicKey, error)
GetKey retrieves a public key by key ID, fetching from Google if needed
type IAPPublicKey ¶
IAPPublicKey represents a Google public key for JWT verification
type InMemoryAuditLogger ¶
type InMemoryAuditLogger struct {
// contains filtered or unexported fields
}
InMemoryAuditLogger stores audit events in memory (for testing)
func NewInMemoryAuditLogger ¶
func NewInMemoryAuditLogger() *InMemoryAuditLogger
NewInMemoryAuditLogger creates a new in-memory audit logger
func (*InMemoryAuditLogger) Close ¶
func (l *InMemoryAuditLogger) Close() error
Close closes the audit logger
func (*InMemoryAuditLogger) GetEvents ¶
func (l *InMemoryAuditLogger) GetEvents() []AuditEvent
GetEvents returns all logged events (for testing)
func (*InMemoryAuditLogger) Log ¶
func (l *InMemoryAuditLogger) Log(event *AuditEvent)
Log records an audit event
func (*InMemoryAuditLogger) LogAuthAttempt ¶
func (l *InMemoryAuditLogger) LogAuthAttempt(ctx context.Context, success bool, err error)
LogAuthAttempt logs an authentication attempt
func (*InMemoryAuditLogger) LogAuthorizationCheck ¶
func (l *InMemoryAuditLogger) LogAuthorizationCheck(ctx context.Context, resource string, permission Permission, allowed bool)
LogAuthorizationCheck logs an authorization check
func (*InMemoryAuditLogger) LogToolExecution ¶
func (l *InMemoryAuditLogger) LogToolExecution(ctx context.Context, toolName string, args map[string]interface{}, result interface{}, err error)
LogToolExecution logs a tool execution event
type IntValidator ¶
IntValidator validates integer arguments
func (*IntValidator) Validate ¶
func (v *IntValidator) Validate(value any) error
Validate checks if the value is an integer within specified bounds
type IntegratedAuditLogger ¶
type IntegratedAuditLogger struct {
// contains filtered or unexported fields
}
IntegratedAuditLogger provides comprehensive audit logging with multiple backends
func NewIntegratedAuditLogger ¶
func NewIntegratedAuditLogger(backends ...AuditBackend) *IntegratedAuditLogger
NewIntegratedAuditLogger creates a new integrated audit logger
func (*IntegratedAuditLogger) AddBackend ¶
func (l *IntegratedAuditLogger) AddBackend(backend AuditBackend)
AddBackend adds a new backend to the logger
func (*IntegratedAuditLogger) Close ¶
func (l *IntegratedAuditLogger) Close() error
Close closes all backends
func (*IntegratedAuditLogger) Log ¶
func (l *IntegratedAuditLogger) Log(event *AuditEvent)
Log implements the AuditLogger interface
func (*IntegratedAuditLogger) LogAuthAttempt ¶
func (l *IntegratedAuditLogger) LogAuthAttempt(ctx context.Context, success bool, err error)
LogAuthAttempt implements the AuditLogger interface
func (*IntegratedAuditLogger) LogAuthorizationCheck ¶
func (l *IntegratedAuditLogger) LogAuthorizationCheck(ctx context.Context, resource string, permission Permission, allowed bool)
LogAuthorizationCheck implements the AuditLogger interface
func (*IntegratedAuditLogger) LogRateLimitExceeded ¶
func (l *IntegratedAuditLogger) LogRateLimitExceeded(ctx context.Context, resource string, clientID string)
LogRateLimitExceeded logs a rate limit event
func (*IntegratedAuditLogger) LogToolExecution ¶
func (l *IntegratedAuditLogger) LogToolExecution(ctx context.Context, toolName string, args map[string]interface{}, result interface{}, err error)
LogToolExecution implements the AuditLogger interface
func (*IntegratedAuditLogger) LogValidationError ¶
func (l *IntegratedAuditLogger) LogValidationError(ctx context.Context, resource string, err error)
LogValidationError logs a validation error event
type JSONAuditLogger ¶
type JSONAuditLogger struct {
// contains filtered or unexported fields
}
JSONAuditLogger logs audit events to a JSON file or stdout
func NewJSONAuditLogger ¶
func NewJSONAuditLogger() *JSONAuditLogger
NewJSONAuditLogger creates a new JSON audit logger
func (*JSONAuditLogger) Close ¶
func (l *JSONAuditLogger) Close() error
Close closes the audit logger
func (*JSONAuditLogger) Log ¶
func (l *JSONAuditLogger) Log(event *AuditEvent)
Log records an audit event as JSON
func (*JSONAuditLogger) LogAuthAttempt ¶
func (l *JSONAuditLogger) LogAuthAttempt(ctx context.Context, success bool, err error)
LogAuthAttempt logs an authentication attempt
func (*JSONAuditLogger) LogAuthorizationCheck ¶
func (l *JSONAuditLogger) LogAuthorizationCheck(ctx context.Context, resource string, permission Permission, allowed bool)
LogAuthorizationCheck logs an authorization check
func (*JSONAuditLogger) LogToolExecution ¶
func (l *JSONAuditLogger) LogToolExecution(ctx context.Context, toolName string, args map[string]interface{}, result interface{}, err error)
LogToolExecution logs a tool execution event
type JWTClaims ¶
type JWTClaims struct {
Email string `json:"email"`
Issuer string `json:"iss"`
Audience string `json:"aud"`
Subject string `json:"sub"`
IssuedAt int64 `json:"iat"`
Expires int64 `json:"exp"`
}
JWTClaims represents the claims in a JWT token
type MemoryAuditBackend ¶
type MemoryAuditBackend struct {
// contains filtered or unexported fields
}
MemoryAuditBackend stores events in memory (for testing)
func NewMemoryAuditBackend ¶
func NewMemoryAuditBackend() *MemoryAuditBackend
NewMemoryAuditBackend creates a new in-memory audit backend
func (*MemoryAuditBackend) Close ¶
func (b *MemoryAuditBackend) Close() error
Close closes the backend
func (*MemoryAuditBackend) Events ¶
func (b *MemoryAuditBackend) Events() []StructuredAuditEvent
Events returns all stored events
func (*MemoryAuditBackend) Write ¶
func (b *MemoryAuditBackend) Write(event *StructuredAuditEvent) error
Write stores an event in memory
type NoAuthAuthenticator ¶
type NoAuthAuthenticator struct {
// contains filtered or unexported fields
}
NoAuthAuthenticator allows all requests without authentication (INSECURE - testing only)
func NewNoAuthAuthenticator ¶
func NewNoAuthAuthenticator() *NoAuthAuthenticator
NewNoAuthAuthenticator creates a no-auth authenticator (INSECURE - testing only)
func (*NoAuthAuthenticator) Authenticate ¶
Authenticate returns the default principal
type NoOpAuditLogger ¶
type NoOpAuditLogger struct{}
NoOpAuditLogger is a no-op implementation (for when audit logging is disabled)
func NewNoOpAuditLogger ¶
func NewNoOpAuditLogger() *NoOpAuditLogger
NewNoOpAuditLogger creates a new no-op audit logger
func (*NoOpAuditLogger) LogAuthAttempt ¶
func (l *NoOpAuditLogger) LogAuthAttempt(ctx context.Context, success bool, err error)
LogAuthAttempt does nothing
func (*NoOpAuditLogger) LogAuthorizationCheck ¶
func (l *NoOpAuditLogger) LogAuthorizationCheck(ctx context.Context, resource string, permission Permission, allowed bool)
LogAuthorizationCheck does nothing
func (*NoOpAuditLogger) LogToolExecution ¶
func (l *NoOpAuditLogger) LogToolExecution(ctx context.Context, toolName string, args map[string]interface{}, result interface{}, err error)
LogToolExecution does nothing
type Pattern ¶
type Pattern struct {
Regex *regexp.Regexp
Category DetectionCategory
Weight float64
Description string
MinLevel Sensitivity
}
Pattern defines a detection pattern with its category and weight
type Permission ¶
type Permission string
Permission represents a security permission
const ( PermRead Permission = "read" PermWrite Permission = "write" PermExecute Permission = "execute" PermAdmin Permission = "admin" )
type Principal ¶
type Principal struct {
ID string
Name string
Roles []string
Permissions []Permission
Metadata map[string]string
}
Principal represents an authenticated entity
func ExtractIAPIdentity ¶
ExtractIAPIdentity extracts identity from IAP headers This is a convenience function for common IAP scenarios
type PrincipalInfo ¶
type PrincipalInfo struct {
ID string `json:"id"`
Type string `json:"type"`
Roles []string `json:"roles,omitempty"`
}
PrincipalInfo contains sanitized principal information for audit logs
type PromptInjectionDetector ¶
type PromptInjectionDetector struct {
// contains filtered or unexported fields
}
PromptInjectionDetector detects prompt injection attacks
func NewPromptInjectionDetector ¶
func NewPromptInjectionDetector(sensitivity Sensitivity) *PromptInjectionDetector
NewPromptInjectionDetector creates a new detector with the specified sensitivity
func (*PromptInjectionDetector) AddPattern ¶
func (d *PromptInjectionDetector) AddPattern(pattern Pattern)
AddPattern adds a custom detection pattern
func (*PromptInjectionDetector) Detect ¶
func (d *PromptInjectionDetector) Detect(input string) DetectionResult
Detect analyzes input text for prompt injection attempts
func (*PromptInjectionDetector) GetSensitivity ¶
func (d *PromptInjectionDetector) GetSensitivity() Sensitivity
GetSensitivity returns the current sensitivity level
func (*PromptInjectionDetector) SetSensitivity ¶
func (d *PromptInjectionDetector) SetSensitivity(level Sensitivity)
SetSensitivity changes the detection sensitivity level
type RBACAuthorizer ¶
type RBACAuthorizer struct {
// contains filtered or unexported fields
}
RBACAuthorizer implements role-based access control
func NewRBACAuthorizer ¶
func NewRBACAuthorizer() *RBACAuthorizer
NewRBACAuthorizer creates a new RBAC authorizer
func (*RBACAuthorizer) AddRolePermission ¶
func (a *RBACAuthorizer) AddRolePermission(role string, perm Permission)
AddRolePermission adds a permission to a role
func (*RBACAuthorizer) Authorize ¶
func (a *RBACAuthorizer) Authorize(ctx context.Context, principal *Principal, resource string, permission Permission) error
Authorize checks if a principal has permission for a resource
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter provides rate limiting functionality
func NewRateLimiter ¶
func NewRateLimiter(requestsPerSecond float64, burst int) *RateLimiter
NewRateLimiter creates a new rate limiter
func (*RateLimiter) Allow ¶
func (rl *RateLimiter) Allow(clientID string) bool
Allow checks if a request should be allowed
type SIEMConfig ¶
type SIEMConfig struct {
// Elasticsearch configuration
Elasticsearch *ElasticsearchConfig `yaml:"elasticsearch,omitempty"`
// Splunk configuration
Splunk *SplunkConfig `yaml:"splunk,omitempty"`
// Generic webhook configuration
Webhook *WebhookConfig `yaml:"webhook,omitempty"`
// Batch configuration
BatchSize int `yaml:"batch_size"`
FlushInterval time.Duration `yaml:"flush_interval"`
}
SIEMConfig holds configuration for SIEM backends
func DefaultSIEMConfig ¶
func DefaultSIEMConfig() *SIEMConfig
DefaultSIEMConfig returns sensible defaults
type SSRFConfig ¶ added in v0.1.3
type SSRFConfig struct {
// AllowedHosts is the list of allowed hostnames
AllowedHosts []string
// AllowedSchemes is the list of allowed URL schemes (default: http, https)
AllowedSchemes []string
// AllowLocalhost allows localhost connections (default: true)
AllowLocalhost bool
// BlockPrivateIPs blocks RFC1918 private IP ranges (default: true)
BlockPrivateIPs bool
// BlockMetadata blocks cloud metadata endpoints (169.254.x.x) (default: true)
BlockMetadata bool
// BlockLinkLocal blocks link-local addresses (default: true)
BlockLinkLocal bool
}
SSRFConfig configures SSRF protection
func DefaultSSRFConfig ¶ added in v0.1.3
func DefaultSSRFConfig() SSRFConfig
DefaultSSRFConfig returns a secure default configuration
type SSRFValidator ¶ added in v0.1.3
type SSRFValidator struct {
// contains filtered or unexported fields
}
SSRFValidator validates URLs against SSRF attacks
func NewOllamaSSRFValidator ¶ added in v0.1.3
func NewOllamaSSRFValidator() *SSRFValidator
NewOllamaSSRFValidator creates a new SSRF validator configured for Ollama
func NewSSRFValidator ¶ added in v0.1.3
func NewSSRFValidator(config SSRFConfig) *SSRFValidator
NewSSRFValidator creates a new SSRF validator
func (*SSRFValidator) CreateSecureTransport ¶ added in v0.1.3
func (v *SSRFValidator) CreateSecureTransport() *http.Transport
CreateSecureTransport creates an http.Transport with SSRF protection in DialContext
func (*SSRFValidator) ValidateHost ¶ added in v0.1.3
func (v *SSRFValidator) ValidateHost(host string) error
ValidateHost validates a hostname against the allowlist
func (*SSRFValidator) ValidateIP ¶ added in v0.1.3
func (v *SSRFValidator) ValidateIP(ip net.IP) error
ValidateIP validates an IP address is not private/blocked
func (*SSRFValidator) ValidateURL ¶ added in v0.1.3
func (v *SSRFValidator) ValidateURL(rawURL string) error
ValidateURL validates a URL against SSRF attacks
type SafeYAMLParser ¶
type SafeYAMLParser struct {
// contains filtered or unexported fields
}
SafeYAMLParser provides secure YAML parsing with resource limits
func NewSafeYAMLParser ¶
func NewSafeYAMLParser(limits YAMLLimits) *SafeYAMLParser
NewSafeYAMLParser creates a new YAML parser with security limits
func (*SafeYAMLParser) UnmarshalYAML ¶
func (p *SafeYAMLParser) UnmarshalYAML(data []byte, v interface{}) error
UnmarshalYAML safely unmarshals YAML data with security limits
func (*SafeYAMLParser) UnmarshalYAMLFromReader ¶
func (p *SafeYAMLParser) UnmarshalYAMLFromReader(r io.Reader, v interface{}) error
UnmarshalYAMLFromReader safely unmarshals YAML from a reader with size limits
type SecureError ¶
type SecureError struct {
Code ErrorCode `json:"code"`
Message string `json:"message"`
Details map[string]interface{} `json:"details,omitempty"`
}
SecureError represents a sanitized error safe to return to clients
func SanitizeError ¶
func SanitizeError(err error, debugMode bool) *SecureError
SanitizeError converts an internal error to a safe error for clients
func SanitizeErrorWithCode ¶
func SanitizeErrorWithCode(err error, code ErrorCode, message string, debugMode bool) *SecureError
SanitizeErrorWithCode creates a secure error with a specific error code
func (*SecureError) Error ¶
func (e *SecureError) Error() string
Error implements the error interface
type SecurityConfig ¶
type SecurityConfig struct {
// Environment: development, staging, production
Environment string `yaml:"environment" env:"ENVIRONMENT"`
// Auth mode selection
AuthMode AuthMode `yaml:"auth_mode" env:"AUTH_MODE"`
// Delegated auth configuration
DelegatedAuth *DelegatedAuthConfig `yaml:"delegated_auth,omitempty"`
// Builtin auth configuration
BuiltinAuth *BuiltinAuthConfig `yaml:"builtin_auth,omitempty"`
// Authorization configuration
Authorization *AuthorizationConfig `yaml:"authorization"`
// Audit configuration
Audit *AuditConfig `yaml:"audit"`
}
SecurityConfig holds all security-related configuration
func DefaultSecurityConfig ¶
func DefaultSecurityConfig(environment string) *SecurityConfig
DefaultSecurityConfig returns environment-appropriate defaults
func (*SecurityConfig) PrintSecuritySummary ¶
func (sc *SecurityConfig) PrintSecuritySummary()
PrintSecuritySummary logs the security configuration
func (*SecurityConfig) Validate ¶
func (sc *SecurityConfig) Validate() error
Validate checks security configuration for issues
type Sensitivity ¶
type Sensitivity int
Sensitivity levels for prompt injection detection
const ( // SensitivityLow catches obvious injection attempts SensitivityLow Sensitivity = iota // SensitivityMedium catches moderate injection attempts SensitivityMedium // SensitivityHigh catches subtle injection attempts (may have higher false positives) SensitivityHigh )
type SplunkBackend ¶
type SplunkBackend struct {
// contains filtered or unexported fields
}
SplunkBackend sends audit events to Splunk HEC
func NewSplunkBackend ¶
func NewSplunkBackend(config *SplunkConfig, batchSize int, flushInterval time.Duration) (*SplunkBackend, error)
NewSplunkBackend creates a new Splunk HEC audit backend
func (SplunkBackend) Write ¶
func (b SplunkBackend) Write(event *StructuredAuditEvent) error
type SplunkConfig ¶
type SplunkConfig struct {
URL string `yaml:"url"`
Token string `yaml:"token"`
Index string `yaml:"index,omitempty"`
Source string `yaml:"source,omitempty"`
TLSVerify bool `yaml:"tls_verify"`
}
SplunkConfig holds Splunk HEC configuration
type SplunkEvent ¶
type SplunkEvent struct {
Time int64 `json:"time"`
Host string `json:"host,omitempty"`
Source string `json:"source,omitempty"`
Index string `json:"index,omitempty"`
Event *StructuredAuditEvent `json:"event"`
}
SplunkEvent wraps audit event for Splunk HEC format
type StringValidator ¶
type StringValidator struct {
Pattern *regexp.Regexp
MaxLength int
MinLength int
AllowedVals []string
DisallowNullBytes bool
DisallowControlChars bool
CheckSQLInjection bool
}
StringValidator validates string arguments with various constraints
func (*StringValidator) Validate ¶
func (v *StringValidator) Validate(value any) error
Validate checks if the value meets all string validation constraints
type StructuredAuditEvent ¶
type StructuredAuditEvent struct {
ID string `json:"id"`
Timestamp time.Time `json:"timestamp"`
Type AuditEventType `json:"type"`
RequestID string `json:"request_id,omitempty"`
TraceID string `json:"trace_id,omitempty"`
SpanID string `json:"span_id,omitempty"`
Principal *PrincipalInfo `json:"principal,omitempty"`
Resource string `json:"resource,omitempty"`
Action string `json:"action,omitempty"`
Result string `json:"result"`
Error string `json:"error,omitempty"`
Duration time.Duration `json:"duration_ns,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
ClientInfo *ClientInfo `json:"client_info,omitempty"`
}
StructuredAuditEvent represents a structured audit event with request tracing
type TimeoutManager ¶
type TimeoutManager struct {
// contains filtered or unexported fields
}
TimeoutManager manages execution timeouts
func NewTimeoutManager ¶
func NewTimeoutManager(defaultTimeout time.Duration) *TimeoutManager
NewTimeoutManager creates a new timeout manager
func (*TimeoutManager) GetTimeout ¶
func (tm *TimeoutManager) GetTimeout(toolName string) time.Duration
GetTimeout returns the timeout for a specific tool
func (*TimeoutManager) SetToolTimeout ¶
func (tm *TimeoutManager) SetToolTimeout(toolName string, timeout time.Duration)
SetToolTimeout sets a specific timeout for a tool
func (*TimeoutManager) WithTimeout ¶
func (tm *TimeoutManager) WithTimeout(ctx context.Context, toolName string) (context.Context, context.CancelFunc)
WithTimeout creates a context with the appropriate timeout for a tool
type ToolRateLimiter ¶
type ToolRateLimiter struct {
// contains filtered or unexported fields
}
ToolRateLimiter provides per-tool rate limiting
func NewToolRateLimiter ¶
func NewToolRateLimiter() *ToolRateLimiter
NewToolRateLimiter creates a new tool-specific rate limiter
func (*ToolRateLimiter) Allow ¶
func (trl *ToolRateLimiter) Allow(toolName string) bool
Allow checks if a tool execution should be allowed
func (*ToolRateLimiter) SetToolLimit ¶
func (trl *ToolRateLimiter) SetToolLimit(toolName string, requestsPerSecond float64, burst int)
SetToolLimit configures rate limit for a specific tool
type WebhookBackend ¶
type WebhookBackend struct {
// contains filtered or unexported fields
}
WebhookBackend sends audit events to a generic webhook
func NewWebhookBackend ¶
func NewWebhookBackend(config *WebhookConfig, batchSize int, flushInterval time.Duration) (*WebhookBackend, error)
NewWebhookBackend creates a new generic webhook audit backend
func (WebhookBackend) Write ¶
func (b WebhookBackend) Write(event *StructuredAuditEvent) error
type WebhookConfig ¶
type WebhookConfig struct {
URL string `yaml:"url"`
Method string `yaml:"method"`
Headers map[string]string `yaml:"headers,omitempty"`
TLSVerify bool `yaml:"tls_verify"`
}
WebhookConfig holds generic webhook configuration
type WebhookPayload ¶
type WebhookPayload struct {
Events []*StructuredAuditEvent `json:"events"`
Timestamp time.Time `json:"timestamp"`
Count int `json:"count"`
}
WebhookPayload wraps events for webhook delivery
type YAMLLimits ¶
type YAMLLimits struct {
MaxFileSize int64 // Maximum file size in bytes (default: 10MB)
MaxDepth int // Maximum nesting depth (default: 20)
MaxNodes int // Maximum number of nodes (default: 10000)
MaxKeyLength int // Maximum key length in bytes (default: 1024)
MaxValueSize int64 // Maximum value size in bytes (default: 1MB)
}
YAMLLimits defines security limits for YAML parsing
func DefaultYAMLLimits ¶
func DefaultYAMLLimits() YAMLLimits
DefaultYAMLLimits returns secure default limits for YAML parsing