contract

package
v0.9.289 Latest Latest
Warning

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

Go to latest
Published: Sep 5, 2026 License: MIT Imports: 30 Imported by: 0

Documentation

Index

Constants

View Source
const SessionIDHeader = "X-Session-ID"

SessionIDHeader is the HTTP header used to identify a client session for stateful scenarios.

Variables

This section is empty.

Functions

func AddMockResponse

func AddMockResponse(
	req *http.Request,
	reqHeaders http.Header,
	respHeaders http.Header,
	scenario *types.APIScenario,
	started time.Time,
	ended time.Time,
	config *types.Configuration,
	scenarioRepository repository.APIScenarioRepository,
	fixtureRepository repository.APIFixtureRepository,
	groupConfigRepository repository.GroupConfigRepository,
) (respBody []byte, sharedVariables map[string]any, err error)

AddMockResponse method is shared so it cannot be instance method

func CheckChaosForScenarioGroup

func CheckChaosForScenarioGroup(
	groupConfigRepository repository.GroupConfigRepository,
	scenario *types.APIScenario,
	respHeaders http.Header) []byte

CheckChaosForScenarioGroup helper method

func DeduplicateFailures

func DeduplicateFailures(
	errors map[string]string,
	details map[string]*types.ContractValidationDetail,
) []types.FailureCluster

DeduplicateFailures groups mutation failures by (statusCode, errorCategory, endpoint, responseHash) to reduce noise from repeated root causes. Returns clusters sorted by count descending.

func GenerateMutatedScenarios

func GenerateMutatedScenarios(scenario *types.APIScenario) ([]*types.APIScenario, error)

GenerateMutatedScenarios creates test variations of a scenario

func TrackFieldCoverage

func TrackFieldCoverage(expected, actual interface{}, path string, coverage *ContractCoverage)

TrackFieldCoverage tracks which fields were covered in the response

Types

type ConsumerExecutor

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

ConsumerExecutor structure

func NewConsumerExecutor

func NewConsumerExecutor(
	config *types.Configuration,
	scenarioRepository repository.APIScenarioRepository,
	fixtureRepository repository.APIFixtureRepository,
	groupConfigRepository repository.GroupConfigRepository,
) *ConsumerExecutor

NewConsumerExecutor instantiates controller for updating api-scenarios

func (*ConsumerExecutor) Execute

func (cx *ConsumerExecutor) Execute(c web.APIContext) (err error)

Execute request and replays stubbed response

func (*ConsumerExecutor) ExecuteWithKey

func (cx *ConsumerExecutor) ExecuteWithKey(
	req *http.Request,
	respHeaders http.Header,
	key *types.APIKeyData,
	overrides map[string]any) (matchedScenario *types.APIScenario, respBytes []byte,
	sharedVariables map[string]any, err error)

ExecuteWithKey request and replays stubbed response

type ContractCoverage

type ContractCoverage struct {
	ScenarioName    string          `json:"scenarioName"`
	Timestamp       time.Time       `json:"timestamp"`
	ResponseStatus  int             `json:"responseStatus"`
	ResponseTime    int64           `json:"responseTimeMs"`
	CoveredFields   []string        `json:"coveredFields"`
	UncoveredFields []string        `json:"uncoveredFields"`
	CoveragePercent float64         `json:"coveragePercent"`
	FieldCoverage   map[string]bool `json:"fieldCoverage"`
}

ContractCoverage include tracking

func (*ContractCoverage) CalculateCoverage

func (c *ContractCoverage) CalculateCoverage()

CalculateCoverage calculates the coverage percentage

type ContractDiffReport

type ContractDiffReport struct {
	ExpectedFields    map[string]interface{}   `json:"expectedFields"`
	ActualFields      map[string]interface{}   `json:"actualFields"`
	MissingFields     []string                 `json:"missingFields"`
	ExtraFields       []string                 `json:"extraFields"`
	TypeMismatches    map[string]string        `json:"typeMismatches"`
	ValueMismatches   map[string]ValueMismatch `json:"valueMismatches"`
	HeaderMismatches  map[string]ValueMismatch `json:"headerMismatches"`
	SchemaViolations  []OpenAPISchemaViolation `json:"schemaViolations,omitempty"`
	InjectionFindings []types.InjectionFinding `json:"injectionFindings,omitempty"`
}

ContractDiffReport diff reporting structure and helper functions

type ContractMutator

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

ContractMutator creates variations of a contract to test robustness

func NewContractMutator

func NewContractMutator(scenario *types.APIScenario) *ContractMutator

NewContractMutator creates a new mutator

func (*ContractMutator) GenerateMutations

func (m *ContractMutator) GenerateMutations() []*types.APIScenario

GenerateMutations Generate mutations to test boundary conditions and edge cases

type ContractValidationError

type ContractValidationError struct {
	OriginalError error
	DiffReport    *ContractDiffReport
	Scenario      string
	URL           string
}

func (*ContractValidationError) Error

func (e *ContractValidationError) Error() string

Error implements the error interface

func (*ContractValidationError) Unwrap

func (e *ContractValidationError) Unwrap() error

Unwrap returns the original error

type ContractValidationResult

type ContractValidationResult struct {
	Scenario        string                 `json:"scenario"`
	Path            string                 `json:"path"`
	Method          string                 `json:"method"`
	StatusCode      int                    `json:"statusCode"`
	ResponseTime    int64                  `json:"responseTimeMs"`
	Timestamp       time.Time              `json:"timestamp"`
	Success         bool                   `json:"success"`
	ErrorMessage    string                 `json:"errorMessage,omitempty"`
	ResponseBody    string                 `json:"responseBody,omitempty"`
	SharedVariables map[string]interface{} `json:"sharedVariables,omitempty"`
	DiffReport      *ContractDiffReport    `json:"diffReport,omitempty"`
}

ContractValidationResult stores the result of a contract validation test

type ContractValidationStats

type ContractValidationStats struct {
	ScenarioName    string
	TotalExecutions int
	SuccessCount    int
	FailureCount    int
	AverageLatency  float64
	Top5Failures    []string
	LastExecuted    time.Time
	SuccessRate     float64
}

ContractValidationStats summarizes validation results over time

type CoverageReport

type CoverageReport struct {
	TotalPaths     int                `json:"totalPaths"`
	CoveredPaths   int                `json:"coveredPaths"`
	Coverage       float64            `json:"coveragePercentage"`
	PathCoverage   map[string]float64 `json:"pathCoverage"`
	UncoveredPaths []string           `json:"uncoveredPaths"`
	StatusCodes    map[int]int        `json:"statusCodeCoverage"`
	MethodCoverage map[string]float64 `json:"methodCoverage"`
	TagCoverage    map[string]float64 `json:"tagCoverage"`
}

CoverageReport structure for API contract coverage

type GroupMutator

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

GroupMutator generates sequence-level mutations for a group of scenarios. While ContractMutator mutates individual request payloads, GroupMutator mutates the execution order and composition of scenario sequences.

func NewGroupMutator

func NewGroupMutator(scenarios []*types.APIScenario) *GroupMutator

NewGroupMutator creates a new group mutator.

func (*GroupMutator) GenerateSequenceMutations

func (gm *GroupMutator) GenerateSequenceMutations() [][]*types.APIScenario

GenerateSequenceMutations returns mutated groups of scenarios. Each inner slice is a complete sequence to execute as a unit.

type InjectionDetector

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

InjectionDetector scans HTTP responses for evidence of injection vulnerabilities. It pre-compiles all signature patterns at construction time for efficient reuse.

func NewInjectionDetector

func NewInjectionDetector() *InjectionDetector

NewInjectionDetector creates a detector with all signature patterns pre-compiled.

func (*InjectionDetector) Analyze

func (d *InjectionDetector) Analyze(payload, field, endpoint, responseBody string, statusCode int) []types.InjectionFinding

Analyze checks the response body for injection signatures and reflected payloads.

func (*InjectionDetector) AnalyzeWithTiming

func (d *InjectionDetector) AnalyzeWithTiming(
	payload, field, endpoint, responseBody string,
	statusCode int, elapsedMs int64, baselineMs int64, thresholdMultiplier float64,
) []types.InjectionFinding

AnalyzeWithTiming extends Analyze with timing-based blind injection detection.

func (*InjectionDetector) Summarize

Summarize aggregates a list of findings into a SecuritySummary with OWASP classification.

type JSONSummary

type JSONSummary struct {
	Group           string                 `json:"group"`
	Timestamp       string                 `json:"timestamp"`
	Succeeded       int                    `json:"succeeded"`
	Failed          int                    `json:"failed"`
	Total           int                    `json:"total"`
	PassRate        float64                `json:"passRate"`
	Coverage        *types.CoverageSummary `json:"coverage,omitempty"`
	SecuritySummary *types.SecuritySummary `json:"securitySummary,omitempty"`
	FailureClusters []types.FailureCluster `json:"failureClusters,omitempty"`
	TopErrors       []string               `json:"topErrors,omitempty"`
}

JSONSummary is a structured summary of a contract test run for CI/CD dashboards.

type OpenAPIContractCoverage

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

OpenAPIContractCoverage analyzes contract coverage against OpenAPI spec

func NewOpenAPIContractCoverage

func NewOpenAPIContractCoverage(spec *openapi3.T, contracts []*types.APIScenario) *OpenAPIContractCoverage

NewOpenAPIContractCoverage creates a new coverage analyzer

func (*OpenAPIContractCoverage) Analyze

Analyze Enhanced Analyze method to include additional coverage metrics

type OpenAPISchemaViolation

type OpenAPISchemaViolation struct {
	Field   string      `json:"field"`
	Message string      `json:"message"`
	Value   interface{} `json:"value,omitempty"`
}

OpenAPISchemaViolation represents a single schema violation found during response validation.

type ProducerExecutor

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

ProducerExecutor structure

func NewProducerExecutor

func NewProducerExecutor(
	scenarioRepository repository.APIScenarioRepository,
	groupConfigRepository repository.GroupConfigRepository,
	client web.HTTPClient) *ProducerExecutor

NewProducerExecutor executes contracts for producers

func (*ProducerExecutor) Execute

Execute an API with fuzz data request

func (*ProducerExecutor) ExecuteByGroup

func (px *ProducerExecutor) ExecuteByGroup(
	ctx context.Context,
	req *http.Request,
	group string,
	dataTemplate fuzz.DataTemplateRequest,
	contractReq *types.ProducerContractRequest,
) *types.ProducerContractResponse

ExecuteByGroup executes an API with fuzz data request

func (*ProducerExecutor) ExecuteByHistory

func (px *ProducerExecutor) ExecuteByHistory(
	ctx context.Context,
	req *http.Request,
	group string,
	dataTemplate fuzz.DataTemplateRequest,
	contractReq *types.ProducerContractRequest,
) *types.ProducerContractResponse

ExecuteByHistory executes execution history for an API with fuzz data request

func (*ProducerExecutor) ExecuteMutationsByGroup

func (px *ProducerExecutor) ExecuteMutationsByGroup(
	ctx context.Context,
	req *http.Request,
	group string,
	dataTemplate fuzz.DataTemplateRequest,
	contractReq *types.ProducerContractRequest,
) *types.ProducerContractResponse

ExecuteMutationsByGroup looks up all scenarios for a group, generates mutations for each, and executes them. Returns a ProducerContractResponse aggregating all mutation results. Mutations test robustness: null fields, boundary values, format violations, security payloads.

func (*ProducerExecutor) GetContractStats

func (px *ProducerExecutor) GetContractStats(scenarioName string) (*ContractValidationStats, error)

GetContractStats analyzes validation history for a scenario

func (*ProducerExecutor) LastCoverage

func (px *ProducerExecutor) LastCoverage(group string) *types.CoverageSummary

LastCoverage returns the coverage summary from the most recent ExecuteByGroup call for the given group. Returns nil if no coverage data is available.

func (*ProducerExecutor) LastReport

func (px *ProducerExecutor) LastReport(group string) *types.ProducerContractResponse

LastReport returns the ProducerContractResponse from the most recent mutation run for the given group. Returns nil if no report is available.

func (*ProducerExecutor) SetLastReport

func (px *ProducerExecutor) SetLastReport(group string, report *types.ProducerContractResponse)

SetLastReport stores a report in the cache (used for testing).

func (*ProducerExecutor) WithOpenAPISpec

func (px *ProducerExecutor) WithOpenAPISpec(doc *openapi3.T, router routers.Router) *ProducerExecutor

WithOpenAPISpec returns a new ProducerExecutor with the OpenAPI document and router attached for response schema validation. The original executor is not modified (safe for concurrent use).

type ProducerExecutorFailureDetector

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

ProducerExecutorFailureDetector adapts ProducerExecutor to the shrink.FailureDetector interface. It tests a single scenario against the remote service and reports whether it fails.

func NewProducerExecutorFailureDetector

func NewProducerExecutorFailureDetector(
	executor *ProducerExecutor,
	baseURL string,
	dataTemplate fuzz.DataTemplateRequest,
	contractReq *types.ProducerContractRequest,
) *ProducerExecutorFailureDetector

NewProducerExecutorFailureDetector creates a failure detector backed by a ProducerExecutor.

func (*ProducerExecutorFailureDetector) TestScenario

func (d *ProducerExecutorFailureDetector) TestScenario(ctx context.Context, scenario *types.APIScenario) error

TestScenario executes the scenario once and returns non-nil if it fails. Implements shrink.FailureDetector.

type ReportExporter

type ReportExporter struct{}

ReportExporter converts ProducerContractResponse into CI/CD-friendly formats.

func (*ReportExporter) ExportJSONSummary

func (e *ReportExporter) ExportJSONSummary(group string, response *types.ProducerContractResponse) ([]byte, error)

ExportJSONSummary produces a concise JSON summary from a ProducerContractResponse.

func (*ReportExporter) ExportJUnitXML

func (e *ReportExporter) ExportJUnitXML(group string, response *types.ProducerContractResponse) ([]byte, error)

ExportJUnitXML produces JUnit XML from a ProducerContractResponse.

type ValueMismatch

type ValueMismatch struct {
	Expected interface{} `json:"expected"`
	Actual   interface{} `json:"actual"`
}

Jump to

Keyboard shortcuts

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