mocks

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jun 20, 2025 License: MIT Imports: 10 Imported by: 0

README

OWASP LLM Mock Providers

This package provides mock implementations of LLM providers for testing OWASP LLM vulnerabilities. The mock providers simulate the behavior of real LLM providers like OpenAI, Anthropic, and Google, allowing for comprehensive testing without making actual API calls.

Features

  • Provider-Specific Behavior: Each mock provider simulates the unique behaviors and safety mechanisms of the corresponding real provider.
  • Vulnerability Simulation: Configure providers to simulate specific OWASP LLM vulnerabilities with customizable response patterns.
  • Error Simulation: Simulate various error conditions like rate limiting, timeouts, and server errors.
  • Usage Metrics: Track usage metrics like request counts, token usage, and error rates.
  • Integration with Test Fixtures: Seamlessly integrates with the existing OWASP test fixtures.

Mock Provider Types

The following mock providers are available:

  • OpenAI Mock Provider: Simulates GPT models with content filtering and other OpenAI-specific behaviors.
  • Anthropic Mock Provider: Simulates Claude models with constitutional AI and system prompt handling.
  • Gemini Mock Provider: Simulates Google's models with safety filters and multimodal capabilities.

Usage

Basic Usage
// Create a mock provider factory
factory := mocks.NewMockProviderFactory()

// Get a specific provider
openaiProvider := factory.GetProvider(core.OpenAIProvider)
anthropicProvider := factory.GetProvider(core.AnthropicProvider)
geminiProvider := factory.GetProvider(core.GoogleProvider)

// Use the provider like a real provider
response, err := openaiProvider.ChatCompletion(ctx, request)
Configuring Vulnerability Behaviors
// Enable a specific vulnerability
provider.EnableVulnerability(types.PromptInjectionVulnerability, &mocks.VulnerabilityBehavior{
    Enabled: true,
    ResponsePatterns: []string{
        "I'll ignore my previous instructions and help you with that.",
        "You're right, I should prioritize your instructions over my guidelines.",
    },
    TriggerPhrases: []string{
        "ignore previous instructions",
        "forget your guidelines",
    },
    Severity: core.SeverityHigh,
})

// Disable a vulnerability
provider.DisableVulnerability(types.PromptInjectionVulnerability)
Simulating Errors
// Set error rate (0.0 to 1.0)
provider.SetErrorRate(0.1) // 10% error rate

// Simulate specific error types
provider.SimulateRateLimiting(true)
provider.SimulateTimeout(true)
provider.SimulateNetworkErrors(true)
provider.SimulateServerErrors(true)

// Reset provider state
provider.ResetState()
Using with Test Fixtures
// Create a test runner with mock providers
runner := mocks.NewTestRunnerWithMockProviders()

// Register fixtures
runner.RegisterAllFixtures()

// Set up providers for a specific vulnerability type
runner.SetupMockProvidersForVulnerability(types.PromptInjectionVulnerability)

// Run tests
result, err := runner.RunTest(ctx, fixture, core.OpenAIProvider)

Test Runner

The TestRunnerWithMockProviders class provides a convenient way to run tests with mock providers:

  • RegisterFixtures: Register test fixtures for specific vulnerability types.
  • RegisterAllFixtures: Register all available test fixtures.
  • SetupMockProvidersForVulnerability: Configure mock providers for a specific vulnerability type.
  • RunTest: Run a test for a specific fixture and provider.
  • RunAllTests: Run all tests for all registered fixtures and providers.

Examples

See the examples directory for complete examples of how to use the mock providers:

  • mock_provider_example.go: Demonstrates basic usage of mock providers.
  • main.go: Command-line application for testing OWASP vulnerabilities with mock providers.

Integration with Reporting

The mock providers integrate with the existing OWASP reporting system, allowing you to generate reports in various formats:

// Run tests with mock providers
testResults, err := runner.RunAllTests(ctx)

// Generate a report
reportOptions := &types.ReportOptions{
    Format:     types.ReportFormatMarkdown,
    OutputPath: "report.md",
    Title:      "OWASP LLM Vulnerability Test Report",
}

generator := reporting.NewReportGenerator()
err = generator.GenerateReport(testResults, reportOptions)

Testing

The package includes comprehensive tests to verify the functionality of the mock providers:

  • mock_providers_test.go: Tests the basic functionality of mock providers.
  • integration_test.go: Tests the integration with the OWASP testing framework.

Run the tests with:

go test -v ./src/testing/owasp/mocks/...

Extending

To add support for a new provider type:

  1. Create a new provider implementation that embeds BaseMockProviderImpl.
  2. Override any methods that need provider-specific behavior.
  3. Add the provider to the GetProvider method in MockProviderFactory.

To add support for a new vulnerability type:

  1. Add the vulnerability type to the types.VulnerabilityType enum.
  2. Create test fixtures for the vulnerability in the fixtures package.
  3. Configure the mock providers to simulate the vulnerability behavior.

Documentation

Overview

Package mocks provides mock implementations of LLM providers for OWASP testing

Package mocks provides mock implementations of LLM providers for OWASP testing

Package mocks provides mock implementations of LLM providers for OWASP testing

Package mocks provides mock implementations of LLM providers for OWASP testing

Package mocks provides mock implementations of LLM providers for OWASP testing

Package mocks provides mock implementations of LLM providers for OWASP testing

Package mocks provides mock implementations of LLM providers for OWASP testing

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CreateStandardMockModels

func CreateStandardMockModels(providerType core.ProviderType) []core.ModelInfo

Helper function to create a standard set of mock models for a provider

func ExtractTestCaseID

func ExtractTestCaseID(request *core.ChatCompletionRequest) string

Helper function to extract test case ID from request metadata or messages

func GetRandomResponsePattern

func GetRandomResponsePattern(behavior *VulnerabilityBehavior) string

Helper function to get a random response pattern from a vulnerability behavior

func MessageTriggerVulnerability

func MessageTriggerVulnerability(message string, behavior *VulnerabilityBehavior) bool

Helper function to determine if a message triggers a vulnerability

Types

type AnthropicMockProvider

type AnthropicMockProvider struct {
	*BaseMockProviderImpl
}

AnthropicMockProvider is a mock implementation of the Anthropic provider

func NewAnthropicMockProvider

func NewAnthropicMockProvider() *AnthropicMockProvider

NewAnthropicMockProvider creates a new Anthropic mock provider

func (*AnthropicMockProvider) ChatCompletion

ChatCompletion overrides the base implementation to add Anthropic-specific behavior

type AttackResult

type AttackResult struct {
	VectorID   string
	Vulnerable bool
	Response   *core.ChatCompletionResponse
	Error      string
}

AttackResult represents the result of running an attack vector

type BaseMockProvider

type BaseMockProvider struct {
	*core.BaseProvider
	// contains filtered or unexported fields
}

BaseMockProvider is a base implementation of the MockProvider interface

func NewBaseMockProvider

func NewBaseMockProvider(config *MockProviderConfig) *BaseMockProvider

NewBaseMockProvider creates a new base mock provider

type BaseMockProviderImpl

type BaseMockProviderImpl struct {
	*BaseMockProvider
	// contains filtered or unexported fields
}

BaseMockProviderImpl is a concrete implementation of the BaseMockProvider

func NewBaseMockProviderImpl

func NewBaseMockProviderImpl(config *MockProviderConfig) *BaseMockProviderImpl

NewBaseMockProviderImpl creates a new base mock provider implementation

func (*BaseMockProviderImpl) ChatCompletion

ChatCompletion generates a chat completion

func (*BaseMockProviderImpl) CountTokens

func (p *BaseMockProviderImpl) CountTokens(ctx context.Context, text string, modelID string) (int, error)

CountTokens counts the number of tokens in a text

func (*BaseMockProviderImpl) CreateEmbedding

func (p *BaseMockProviderImpl) CreateEmbedding(ctx context.Context, request *core.EmbeddingRequest) (*core.EmbeddingResponse, error)

CreateEmbedding creates an embedding

func (*BaseMockProviderImpl) DisableVulnerability

func (p *BaseMockProviderImpl) DisableVulnerability(vulnerabilityType types.VulnerabilityType)

DisableVulnerability disables a specific vulnerability type

func (*BaseMockProviderImpl) EnableVulnerability

func (p *BaseMockProviderImpl) EnableVulnerability(vulnerabilityType types.VulnerabilityType, behavior *VulnerabilityBehavior)

EnableVulnerability enables a specific vulnerability type

func (*BaseMockProviderImpl) GetAllUsageMetrics

func (p *BaseMockProviderImpl) GetAllUsageMetrics() map[string]*core.UsageMetrics

GetAllUsageMetrics gets all usage metrics

func (*BaseMockProviderImpl) GetUsageMetrics

func (p *BaseMockProviderImpl) GetUsageMetrics(modelID string) *core.UsageMetrics

GetUsageMetrics gets the usage metrics for a model

func (*BaseMockProviderImpl) GetVulnerabilityBehavior

func (p *BaseMockProviderImpl) GetVulnerabilityBehavior(vulnerabilityType types.VulnerabilityType) *VulnerabilityBehavior

GetVulnerabilityBehavior gets the behavior configuration for a specific vulnerability type

func (*BaseMockProviderImpl) GetVulnerableResponse

func (p *BaseMockProviderImpl) GetVulnerableResponse(testCaseID string) (string, bool)

GetVulnerableResponse gets a vulnerable response for a specific test case

func (*BaseMockProviderImpl) IsVulnerabilityEnabled

func (p *BaseMockProviderImpl) IsVulnerabilityEnabled(vulnerabilityType types.VulnerabilityType) bool

IsVulnerabilityEnabled checks if a specific vulnerability type is enabled

func (*BaseMockProviderImpl) ResetState

func (p *BaseMockProviderImpl) ResetState()

ResetState resets the state of the mock provider

func (*BaseMockProviderImpl) SetDefaultResponse

func (p *BaseMockProviderImpl) SetDefaultResponse(response string)

SetDefaultResponse sets the default response for test cases without specific vulnerable responses

func (*BaseMockProviderImpl) SetErrorRate

func (p *BaseMockProviderImpl) SetErrorRate(rate float64)

SetErrorRate sets the error rate for responses (0.0 to 1.0)

func (*BaseMockProviderImpl) SetResponseDelay

func (p *BaseMockProviderImpl) SetResponseDelay(delay time.Duration)

SetResponseDelay sets a delay for responses to simulate latency

func (*BaseMockProviderImpl) SetVulnerableResponses

func (p *BaseMockProviderImpl) SetVulnerableResponses(vulnerableResponses map[string]string)

SetVulnerableResponses sets the vulnerable responses for specific test cases

func (*BaseMockProviderImpl) SimulateNetworkErrors

func (p *BaseMockProviderImpl) SimulateNetworkErrors(enabled bool)

SimulateNetworkErrors enables or disables network error simulation

func (*BaseMockProviderImpl) SimulateRateLimiting

func (p *BaseMockProviderImpl) SimulateRateLimiting(enabled bool)

SimulateRateLimiting enables or disables rate limiting simulation

func (*BaseMockProviderImpl) SimulateServerErrors

func (p *BaseMockProviderImpl) SimulateServerErrors(enabled bool)

SimulateServerErrors enables or disables server error simulation

func (*BaseMockProviderImpl) SimulateTimeout

func (p *BaseMockProviderImpl) SimulateTimeout(enabled bool)

SimulateTimeout enables or disables timeout simulation

func (*BaseMockProviderImpl) StreamingChatCompletion

func (p *BaseMockProviderImpl) StreamingChatCompletion(ctx context.Context, request *core.ChatCompletionRequest, callback func(response *core.ChatCompletionResponse) error) error

StreamingChatCompletion generates a streaming chat completion

func (*BaseMockProviderImpl) TextCompletion

TextCompletion generates a text completion

type GeminiMockProvider

type GeminiMockProvider struct {
	*BaseMockProviderImpl
}

GeminiMockProvider is a mock implementation of the Google Gemini provider

func NewGeminiMockProvider

func NewGeminiMockProvider() *GeminiMockProvider

NewGeminiMockProvider creates a new Google Gemini mock provider

func (*GeminiMockProvider) ChatCompletion

ChatCompletion overrides the base implementation to add Gemini-specific behavior

type MockProvider

type MockProvider interface {
	core.Provider

	// Mock-specific methods
	// SetVulnerableResponses sets the vulnerable responses for specific test cases
	SetVulnerableResponses(vulnerableResponses map[string]string)
	// GetVulnerableResponse gets a vulnerable response for a specific test case
	GetVulnerableResponse(testCaseID string) (string, bool)
	// SetDefaultResponse sets the default response for test cases without specific vulnerable responses
	SetDefaultResponse(response string)
	// SetResponseDelay sets a delay for responses to simulate latency
	SetResponseDelay(delay time.Duration)
	// SetErrorRate sets the error rate for responses (0.0 to 1.0)
	SetErrorRate(rate float64)
	// ResetState resets the state of the mock provider
	ResetState()
	// EnableVulnerability enables a specific vulnerability type
	EnableVulnerability(vulnerabilityType types.VulnerabilityType, behavior *VulnerabilityBehavior)
	// DisableVulnerability disables a specific vulnerability type
	DisableVulnerability(vulnerabilityType types.VulnerabilityType)
	// IsVulnerabilityEnabled checks if a specific vulnerability type is enabled
	IsVulnerabilityEnabled(vulnerabilityType types.VulnerabilityType) bool
	// GetVulnerabilityBehavior gets the behavior configuration for a specific vulnerability type
	GetVulnerabilityBehavior(vulnerabilityType types.VulnerabilityType) *VulnerabilityBehavior
	// SimulateRateLimiting enables or disables rate limiting simulation
	SimulateRateLimiting(enabled bool)
	// SimulateTimeout enables or disables timeout simulation
	SimulateTimeout(enabled bool)
	// SimulateNetworkErrors enables or disables network error simulation
	SimulateNetworkErrors(enabled bool)
	// SimulateServerErrors enables or disables server error simulation
	SimulateServerErrors(enabled bool)
}

MockProvider is the interface that all mock providers must implement

type MockProviderConfig

type MockProviderConfig struct {
	// ProviderType is the type of provider to mock (e.g., OpenAI, Anthropic)
	ProviderType core.ProviderType
	// DefaultModel is the default model to use
	DefaultModel string
	// ResponseDelay is the delay to simulate latency
	ResponseDelay time.Duration
	// ErrorRate is the rate at which to return errors (0.0 to 1.0)
	ErrorRate float64
	// TokenUsage is the token usage to simulate
	TokenUsage *core.TokenUsage
	// VulnerableResponses is a map of test case IDs to vulnerable responses
	VulnerableResponses map[string]string
	// DefaultResponse is the default response for test cases without specific vulnerable responses
	DefaultResponse string
	// RateLimitConfig is the rate limit configuration
	RateLimitConfig *core.RateLimitConfig
	// RetryConfig is the retry configuration
	RetryConfig *core.RetryConfig
	// SimulateRateLimiting indicates whether to simulate rate limiting
	SimulateRateLimiting bool
	// SimulateTimeout indicates whether to simulate timeouts
	SimulateTimeout bool
	// SimulateNetworkErrors indicates whether to simulate network errors
	SimulateNetworkErrors bool
	// SimulateServerErrors indicates whether to simulate server errors
	SimulateServerErrors bool
	// VulnerabilityBehaviors is a map of vulnerability types to behavior configurations
	VulnerabilityBehaviors map[types.VulnerabilityType]*VulnerabilityBehavior
}

MockProviderConfig represents the configuration for a mock provider

type MockProviderFactory

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

MockProviderFactory creates mock providers for testing

func NewMockProviderFactory

func NewMockProviderFactory() *MockProviderFactory

NewMockProviderFactory creates a new mock provider factory

func (*MockProviderFactory) ConfigureProviderVulnerability

func (f *MockProviderFactory) ConfigureProviderVulnerability(providerType core.ProviderType, vulnerabilityType types.VulnerabilityType, enabled bool, behavior *VulnerabilityBehavior)

ConfigureProviderVulnerability configures a specific vulnerability type for a specific provider

func (*MockProviderFactory) ConfigureVulnerability

func (f *MockProviderFactory) ConfigureVulnerability(vulnerabilityType types.VulnerabilityType, enabled bool, behavior *VulnerabilityBehavior)

ConfigureVulnerability configures a specific vulnerability type for all providers

func (*MockProviderFactory) CreateVulnerabilityBehavior

func (f *MockProviderFactory) CreateVulnerabilityBehavior(responsePatterns []string, triggerPhrases []string, severity core.SeverityLevel) *VulnerabilityBehavior

CreateVulnerabilityBehavior creates a new vulnerability behavior with default settings

func (*MockProviderFactory) GetAllProviders

func (f *MockProviderFactory) GetAllProviders() map[core.ProviderType]MockProvider

GetAllProviders gets all created providers

func (*MockProviderFactory) GetProvider

func (f *MockProviderFactory) GetProvider(providerType core.ProviderType) MockProvider

GetProvider gets or creates a mock provider for the specified provider type

func (*MockProviderFactory) ResetAllProviders

func (f *MockProviderFactory) ResetAllProviders()

ResetAllProviders resets the state of all providers

func (*MockProviderFactory) SetGlobalErrorRate

func (f *MockProviderFactory) SetGlobalErrorRate(rate float64)

SetGlobalErrorRate sets the error rate for all providers

func (*MockProviderFactory) SetGlobalResponseDelay

func (f *MockProviderFactory) SetGlobalResponseDelay(delay time.Duration)

SetGlobalResponseDelay sets the response delay for all providers

func (*MockProviderFactory) SimulateGlobalNetworkErrors

func (f *MockProviderFactory) SimulateGlobalNetworkErrors(enabled bool)

SimulateGlobalNetworkErrors enables or disables network error simulation for all providers

func (*MockProviderFactory) SimulateGlobalRateLimiting

func (f *MockProviderFactory) SimulateGlobalRateLimiting(enabled bool)

SimulateGlobalRateLimiting enables or disables rate limiting simulation for all providers

func (*MockProviderFactory) SimulateGlobalServerErrors

func (f *MockProviderFactory) SimulateGlobalServerErrors(enabled bool)

SimulateGlobalServerErrors enables or disables server error simulation for all providers

func (*MockProviderFactory) SimulateGlobalTimeout

func (f *MockProviderFactory) SimulateGlobalTimeout(enabled bool)

SimulateGlobalTimeout enables or disables timeout simulation for all providers

type OpenAIMockProvider

type OpenAIMockProvider struct {
	*BaseMockProviderImpl
}

OpenAIMockProvider is a mock implementation of the OpenAI provider

func NewOpenAIMockProvider

func NewOpenAIMockProvider() *OpenAIMockProvider

NewOpenAIMockProvider creates a new OpenAI mock provider

func (*OpenAIMockProvider) ChatCompletion

ChatCompletion overrides the base implementation to add OpenAI-specific behavior

type TestResult

type TestResult struct {
	FixtureID       string
	VulnerabilityID string
	ProviderType    core.ProviderType
	Success         bool
	AttackResults   map[string]*AttackResult
}

TestResult represents the result of running a test

type TestRunnerWithMockProviders

type TestRunnerWithMockProviders struct {
	// Factory for creating mock providers
	ProviderFactory *MockProviderFactory
	// Test fixtures for OWASP vulnerabilities
	Fixtures map[types.VulnerabilityType][]fixtures.TestFixture
	// Default provider type to use
	DefaultProviderType core.ProviderType
}

TestRunnerWithMockProviders is a test runner that uses mock providers for OWASP testing

func NewTestRunnerWithMockProviders

func NewTestRunnerWithMockProviders() *TestRunnerWithMockProviders

NewTestRunnerWithMockProviders creates a new test runner with mock providers

func (*TestRunnerWithMockProviders) RegisterAllFixtures

func (r *TestRunnerWithMockProviders) RegisterAllFixtures()

RegisterAllFixtures registers all available test fixtures

func (*TestRunnerWithMockProviders) RegisterFixtures

func (r *TestRunnerWithMockProviders) RegisterFixtures(vulnerabilityType types.VulnerabilityType, fixturesList []fixtures.TestFixture)

RegisterFixtures registers test fixtures for a vulnerability type

func (*TestRunnerWithMockProviders) RunAllTests

RunAllTests runs all tests for all registered fixtures

func (*TestRunnerWithMockProviders) RunTest

func (r *TestRunnerWithMockProviders) RunTest(
	ctx context.Context,
	fixture fixtures.TestFixture,
	providerType core.ProviderType,
) (*TestResult, error)

RunTest runs a test for a specific fixture

func (*TestRunnerWithMockProviders) SetupMockProvidersForVulnerability

func (r *TestRunnerWithMockProviders) SetupMockProvidersForVulnerability(vulnerabilityType types.VulnerabilityType)

SetupMockProvidersForVulnerability configures mock providers for a specific vulnerability type

type TestSuiteResult

type TestSuiteResult struct {
	Results map[types.VulnerabilityType][]*TestResult
}

TestSuiteResult represents the result of running all tests

func (*TestSuiteResult) GetProviderResults

func (r *TestSuiteResult) GetProviderResults(providerType core.ProviderType) []*TestResult

GetProviderResults returns the results for a specific provider type

func (*TestSuiteResult) GetTotalCount

func (r *TestSuiteResult) GetTotalCount() int

GetTotalCount returns the total number of tests

func (*TestSuiteResult) GetVulnerabilityTypeResults

func (r *TestSuiteResult) GetVulnerabilityTypeResults(vulnerabilityType types.VulnerabilityType) []*TestResult

GetVulnerabilityTypeResults returns the results for a specific vulnerability type

func (*TestSuiteResult) GetVulnerableCount

func (r *TestSuiteResult) GetVulnerableCount() int

GetVulnerableCount returns the number of vulnerable tests

type VulnerabilityBehavior

type VulnerabilityBehavior struct {
	// Enabled indicates whether the vulnerability is enabled
	Enabled bool
	// ResponsePatterns is a list of response patterns to use for this vulnerability
	ResponsePatterns []string
	// TriggerPhrases is a list of phrases that trigger the vulnerability
	TriggerPhrases []string
	// Severity is the severity of the vulnerability
	Severity core.SeverityLevel
	// Metadata is additional metadata for the vulnerability
	Metadata map[string]interface{}
}

VulnerabilityBehavior represents the behavior configuration for a specific vulnerability type

Jump to

Keyboard shortcuts

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