security

package
v0.2.6 Latest Latest
Warning

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

Go to latest
Published: Jan 3, 2026 License: MIT Imports: 26 Imported by: 0

Documentation

Overview

Package security provides security utilities for the aixgo framework.

Index

Constants

View Source
const MaxInputSize = 10 * 1024

MaxInputSize is the maximum input size (10KB) to prevent ReDoS attacks

Variables

View Source
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

func GetRequestID(ctx context.Context) string

GetRequestID retrieves the request ID from context

func IsValidAPIKeyFormat

func IsValidAPIKeyFormat(key string) bool

IsValidAPIKeyFormat validates the format of an API key

func MaskSecret

func MaskSecret(secret string) string

MaskSecret masks a secret for logging purposes

func SanitizeFilePath

func SanitizeFilePath(path string, baseDir string) (string, error)

SanitizeFilePath prevents path traversal attacks

func SanitizeString

func SanitizeString(input string) string

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

func ValidateEnvironment(env string) error

ValidateEnvironment validates an environment name This prevents command injection in environment parameters

func ValidateFilePath added in v0.1.2

func ValidateFilePath(path string) error

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

func ValidateImageName(imageName string) error

ValidateImageName validates a container image name This prevents command injection in image name parameters

func ValidateJSONObject

func ValidateJSONObject(value any) error

ValidateJSONObject validates that a value is a valid JSON object

func ValidateProjectID

func ValidateProjectID(projectID string) error

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

func ValidateRegion(region string) error

ValidateRegion validates a GCP region name This prevents command injection in region parameters

func ValidateRepositoryName

func ValidateRepositoryName(repoName string) error

ValidateRepositoryName validates an Artifact Registry repository name This prevents command injection in repository name parameters

func ValidateSIEMURL added in v0.1.2

func ValidateSIEMURL(rawURL string) error

ValidateSIEMURL validates that a URL is safe for SIEM connections and prevents SSRF attacks by blocking private IP ranges

func ValidateServiceName

func ValidateServiceName(serviceName string) error

ValidateServiceName validates a Cloud Run service name This prevents command injection in service name parameters

func ValidateToolName

func ValidateToolName(name string) error

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

func WithRequestID(ctx context.Context, requestID string) context.Context

WithRequestID adds a request ID to the context

func WithSpanID

func WithSpanID(ctx context.Context, spanID string) context.Context

WithSpanID adds a span ID to the context

func WithTraceID

func WithTraceID(ctx context.Context, traceID string) context.Context

WithTraceID adds a trace 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

func (a *APIKeyAuthenticator) Authenticate(ctx context.Context, token string) (*Principal, error)

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

type ArgValidator interface {
	Validate(value any) error
}

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

Logger returns the underlying audit logger

func (*AuditMiddleware) WrapHandler

func (m *AuditMiddleware) WrapHandler(toolName string, handler func(context.Context, map[string]interface{}) (interface{}, error)) func(context.Context, map[string]interface{}) (interface{}, error)

WrapHandler wraps a tool handler with audit logging

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) Close

func (b ElasticsearchBackend) Close() error

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"
	ErrCodeUnauthorized  ErrorCode = "UNAUTHORIZED"
	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) Close

func (b *FileAuditBackend) Close() error

Close closes the file

func (*FileAuditBackend) Write

func (b *FileAuditBackend) Write(event *StructuredAuditEvent) error

Write writes an event to the file

type FloatValidator

type FloatValidator struct {
	Min *float64
	Max *float64
}

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

func (e *HybridAuthExtractor) ExtractAuth(ctx context.Context, r *http.Request) (*Principal, error)

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 NewIAPKeyCache

func NewIAPKeyCache() *IAPKeyCache

NewIAPKeyCache creates a new IAP key cache

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

type IAPPublicKey struct {
	Kid string
	N   *big.Int
	E   int
	Key *rsa.PublicKey
}

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

type IntValidator struct {
	Min *int
	Max *int
}

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

Events returns all stored events

func (*MemoryAuditBackend) Write

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

func (a *NoAuthAuthenticator) Authenticate(ctx context.Context, token string) (*Principal, error)

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) Close

func (l *NoOpAuditLogger) Close() error

Close does nothing

func (*NoOpAuditLogger) Log

func (l *NoOpAuditLogger) Log(event *AuditEvent)

Log does nothing

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

func ExtractIAPIdentity(r *http.Request, verifyJWT bool, audience string) (*Principal, error)

ExtractIAPIdentity extracts identity from IAP headers This is a convenience function for common IAP scenarios

func GetPrincipal

func GetPrincipal(ctx context.Context) (*Principal, error)

GetPrincipal retrieves the principal from the context

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

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

func (*RateLimiter) Wait

func (rl *RateLimiter) Wait(ctx context.Context, clientID string) error

Wait blocks until a request can be made

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) Close

func (b SplunkBackend) Close() error

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

func (*ToolRateLimiter) Wait

func (trl *ToolRateLimiter) Wait(ctx context.Context, toolName string) error

Wait blocks until a tool execution can proceed

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) Close

func (b WebhookBackend) Close() error

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

Jump to

Keyboard shortcuts

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