testing

package
v5.32.6 Latest Latest
Warning

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

Go to latest
Published: Sep 25, 2026 License: Apache-2.0 Imports: 58 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

## Service Testing - **Lifecycle Management**: Test service creation, management, and deletion - **Dependency Management**: Validate service dependency resolution - **State Transitions**: Test service state changes and event handling - **Integration**: Test service interaction with other system components

Mock MCP Server Support

The testing framework includes comprehensive mock MCP server functionality:

- **Mock Tool Definitions**: Define tools with configurable responses - **Conditional Responses**: Different responses based on input args - **Template-Based Responses**: Dynamic response generation using Go templates - **Error Simulation**: Simulate various error conditions and failures - **Standalone Mode**: Run mock servers independently for external testing

Mock servers can be embedded in test scenarios or run standalone:

# Embedded in test scenario
mcpServers:
  - name: "mock-kubernetes"
    type: "mock"
    tools:
      - name: "kubectl_get_pods"
        responses:
          - condition: {namespace: "default"}
            response: "pod1\npod2\npod3"

# Standalone mode
muster test --mock-mcp-server --mock-config=mock-config.yaml

Extension Points

The testing framework is designed for extensibility through several mechanisms:

## Custom Test Steps - Implement custom step types by extending the TestStep interface - Register custom step handlers with the TestRunner - Support for domain-specific validation logic

## Custom Reporters - Implement the TestReporter interface for custom output formats - Support for custom metrics collection and analysis - Integration with external monitoring and alerting systems

## Custom Scenario Loaders - Implement the TestScenarioLoader interface for alternative configuration sources - Support for dynamic scenario generation - Integration with external test management systems

Thread Safety

The testing framework is designed with thread safety as a core requirement:

- **Concurrent Execution**: All components support concurrent access - **Immutable Data**: Test scenarios and configuration are immutable after loading - **Thread-Safe Reporting**: Reporter implementations handle concurrent access - **Resource Isolation**: Each test execution maintains isolated state

**Safety Guarantees**: - TestRunner can safely execute multiple scenarios concurrently - MCPTestClient instances are thread-safe for concurrent tool calls - TestReporter can safely handle concurrent progress and result reporting - Shared resources (connections, files) are protected with appropriate synchronization

Performance Characteristics

The framework is optimized for both development and CI/CD environments:

## Execution Performance - **Parallel Execution**: Configurable worker pools (1-10 workers recommended) - **Connection Pooling**: Reuse MCP connections across multiple test steps - **Lazy Loading**: Scenarios loaded only when needed - **Memory Efficiency**: Streaming result processing for large test suites

## Scaling Characteristics - **Linear Scaling**: Performance scales linearly with parallel worker count - **Memory Usage**: O(n) memory usage relative to active scenarios - **Network Efficiency**: Connection reuse and request batching - **Resource Cleanup**: Automatic cleanup prevents resource leaks

**Performance Recommendations**: - Use 2-4 parallel workers for development testing - Use 4-8 parallel workers for CI/CD environments - Implement timeouts appropriate for your environment (30s-5m recommended) - Monitor memory usage with large test suites (>100 scenarios)

Usage Patterns

## Basic Testing

```bash
muster test                          # Run all tests
muster test --category=behavioral    # Category-specific
muster test --concept=workflow      # Concept-specific
muster test --scenario=basic-create # Scenario-specific
```

## Advanced Configuration

```bash
muster test --parallel=50 --timeout=10m --fail-fast
muster test --verbose --debug --output-format=json
```

## CI/CD Integration

```bash
muster test --category=integration --output-format=junit --report-file=results.xml
```

## Mock MCP Server Testing

```bash
# Run with mock servers defined in scenarios
muster test --scenario=test-with-mock

# Run standalone mock server
muster test --mock-mcp-server --mock-config=mock-tools.yaml
```

Dependencies

The testing framework requires: - A running muster aggregator server (muster serve) - MCP protocol communication capabilities - Access to all core_* MCP tools exposed by the aggregator - Write access for temporary files and test artifacts

Error Handling

The framework implements comprehensive error handling: - **Graceful Degradation**: Continue execution when possible - **Detailed Error Messages**: Context-rich error information - **Error Classification**: Distinguish between test failures and framework errors - **Recovery Mechanisms**: Fallback logic where appropriate

Integration with CI/CD

The framework provides first-class CI/CD support: - **Structured Output**: JSON, JUnit XML, and TAP output formats - **Exit Codes**: Proper exit codes for automation (0=success, 1=failures, 2=errors) - **Report Files**: File-based output for artifact collection - **Environment Integration**: Support for CI environment variables and configuration

For complete usage documentation, see docs/testing/README.md For scenario authoring guidance, see docs/testing/scenarios.md For comprehensive examples, see docs/testing/examples/

Package testing provides test helper tools for BDD test scenarios. These tools allow test scenarios to interact with mock infrastructure components that run in the test orchestrator process.

Index

Constants

View Source
const (
	// IntervalsShort (the default) runs the reconnect backoff, the
	// orchestrator's retry and health ticks, the reconciler's resync and the
	// core catalogue's age in seconds through environment knobs, so a
	// scenario sees them act within its wait_for_state budgets.
	IntervalsShort = "short"
	// IntervalsProduction keeps every timer the controllable clock reaches on
	// its production default (a 30 s initial backoff capped at 2 min, 30 s
	// retry and health ticks, a 5 min capability poll, a 5 min catalogue
	// age); a scenario moves them with test_advance_clock. The reconciler's
	// resync is controller-runtime's and out of the clock's reach, so it
	// stays shortened.
	IntervalsProduction = "production"
)

Interval schedules an instance's lifecycle timers run on, selected by pre_configuration.intervals.

View Source
const (
	// ModeFilesystem is the default: definitions are files in the instance's
	// config directory, watched by the filesystem detector.
	ModeFilesystem = "filesystem"
	// ModeKubernetes runs the instance in Kubernetes mode against the run's
	// envtest API server: definitions are MCPServer and Workflow CRs in the
	// instance's own namespace, read through informers; the reconciler and the
	// boot pass drive the services the way they do on an installation.
	ModeKubernetes = "kubernetes"
)

Definition sources a scenario can run its muster serve instance on.

View Source
const (
	// StorageMemory is the default: every store dies with the process.
	StorageMemory = "memory"
	// StorageValkey runs the instance on an in-process Valkey stand-in
	// (miniredis) that outlives the process the way an installation's
	// Valkey outlives a pod. Every store muster keeps outside the process --
	// session auth, capabilities, OAuth tokens, state, client credentials and
	// the OAuth server's own store -- lands there.
	StorageValkey = "valkey"
)

Storage backends a scenario can run its muster serve instance on.

View Source
const (
	// TestToolSimulateOAuthCallback simulates completing an OAuth flow for testing.
	TestToolSimulateOAuthCallback = "test_simulate_oauth_callback"
	// TestToolInjectToken directly injects an access token for testing.
	TestToolInjectToken = "test_inject_token"
	// TestToolGetOAuthServerInfo returns information about mock OAuth servers.
	TestToolGetOAuthServerInfo = "test_get_oauth_server_info"

	// TestToolForgetOAuthRegistrations makes a mock OAuth server drop every
	// RFC 7591 client registration it holds, the way an authorization server
	// with an in-memory client store forgets its clients when it restarts.
	TestToolForgetOAuthRegistrations = "test_forget_oauth_registrations"
	// TestToolRestartMockOAuthServer replaces a mock OAuth server's process
	// behind its port and issuer; under profile pro (or
	// forget_registrations_on_restart) its RFC 7591 registrations go with the
	// old process.
	TestToolRestartMockOAuthServer = "test_restart_mock_oauth_server"
	// TestToolAdvanceOAuthClock advances the mock OAuth server's clock for testing.
	TestToolAdvanceOAuthClock = "test_advance_oauth_clock"
	// TestToolReadAuthStatus reads the auth://status resource to verify auth state.
	TestToolReadAuthStatus = "test_read_auth_status"
	// TestToolRevokeToken revokes a token on the mock OAuth server for testing.
	TestToolRevokeToken = "test_revoke_token"
	// TestToolCreateUser creates a new user session for multi-user testing.
	TestToolCreateUser = "test_create_user"
	// TestToolSwitchUser switches to a different user session for multi-user testing.
	TestToolSwitchUser = "test_switch_user"
	// TestToolListToolsForUser lists tools visible to a specific user.
	TestToolListToolsForUser = "test_list_tools_for_user"
	// TestToolGetCurrentUser returns the current active user name.
	TestToolGetCurrentUser = "test_get_current_user"
	// TestToolSimulateMusterReauth simulates re-authentication to muster with a new token
	// while preserving the session ID. Used to test proactive SSO re-triggering.
	TestToolSimulateMusterReauth = "test_simulate_muster_reauth"
	// TestToolMusterAuthLogin simulates `muster auth login` by completing the OAuth
	// callback to muster's token store. This is required for SSO token forwarding tests.
	TestToolMusterAuthLogin = "test_muster_auth_login"
	// TestToolAddMockTool dynamically adds a tool to a running mock MCP server.
	// This triggers a notifications/tools/list_changed notification to all connected clients.
	TestToolAddMockTool = "test_add_mock_tool"
	// TestToolRemoveMockTool dynamically removes a tool from a running mock MCP server.
	// This triggers a notifications/tools/list_changed notification to all connected clients.
	TestToolRemoveMockTool = "test_remove_mock_tool"
	// TestToolStopMockServer stops a running mock MCP HTTP server while muster
	// keeps its MCPServer definition, so a scenario can drive the server into a
	// failed/unreachable service state (connection refused on the next probe).
	// The port is kept for TestToolStartMockServer.
	TestToolStopMockServer = "test_stop_mock_server"
	// TestToolStartMockServer starts a mock MCP HTTP server stopped with
	// TestToolStopMockServer again, on the port muster knows it by.
	TestToolStartMockServer = "test_start_mock_server"
	// TestToolSetMockServerOutage makes a running mock MCP HTTP server answer
	// its next N requests with a fixed HTTP status (504 by default) and serve
	// normally afterwards: a gateway in front of a healthy server timing out,
	// as opposed to the server being gone (TestToolStopMockServer).
	TestToolSetMockServerOutage = "test_set_mock_server_outage"
	// TestToolCallMetaTool invokes a meta-tool (e.g. filter_tools, describe_tool,
	// list_core_tools) directly on the aggregator MCP server. Meta-tools are
	// registered as first-class MCP tools and are NOT reachable through the
	// call_tool wrapper that the standard scenario path uses, so discovery-tier
	// scenarios need this direct path. The meta-tool's JSON result is parsed and
	// returned so scenarios can assert on it with json_path / contains.
	TestToolCallMetaTool = "test_call_meta_tool"
	// TestToolGetServerInfo returns the protocol version and server capabilities
	// negotiated during the current session's initialize handshake.
	TestToolGetServerInfo = "test_get_server_info"
	// TestToolScrapeMetrics scrapes the instance's Prometheus /metrics endpoint
	// and returns the matching exposition lines, so a scenario can assert on
	// what muster actually exports rather than on internal state. Optional
	// "filter" argument narrows the body to lines containing that substring;
	// without it the whole scrape is returned.
	TestToolScrapeMetrics = "test_scrape_metrics"
	// TestToolSetMCPServerLabels replaces the metadata.labels of an MCPServer
	// definition where muster reads it -- the CR in Kubernetes mode, the file
	// in filesystem mode -- while muster runs: what a chart upgrade or a
	// kubectl label does to the resource, so a scenario can prove that
	// label-based toolset presets follow the live labels without a restart.
	// Args: "server" (required), "labels" (object; empty removes every label).
	TestToolSetMCPServerLabels = "test_set_mcpserver_labels"

	// TestToolResolveAuthRedirect asks core_auth_login for a challenge and
	// follows the muster-hosted start URL one hop, the way a browser would,
	// reporting which mock authorization server the flow is sent to.
	TestToolResolveAuthRedirect = "test_resolve_auth_redirect"
	// TestToolPinMCPServerAuthorizationServer rewrites an MCPServer's
	// spec.auth.authorizationServer in its definition -- the CR in Kubernetes
	// mode, the file in filesystem mode -- (pin a mock server's issuer,
	// optionally another's endpoints; or clear the pin) so the reconciler
	// picks the change up as a definition update.
	TestToolPinMCPServerAuthorizationServer = "test_pin_mcpserver_authorization_server"

	// TestToolRestartInstance stops and starts the scenario's muster serve
	// process on the same configuration while the Valkey stand-in and the
	// mock servers keep running, then reconnects every user client with the
	// bearer it held -- the sessions that lived through a rollout. The steps
	// after it run against the new process without a new sign-in.
	TestToolRestartInstance = "test_restart_instance"
	// TestToolStopValkey takes the instance's Valkey stand-in off its port,
	// data kept: a Valkey pod being rescheduled while muster keeps running.
	// Requires pre_configuration.storage.type: valkey.
	TestToolStopValkey = "test_stop_valkey"
	// TestToolStartValkey brings the Valkey stand-in back on its port with
	// its data.
	TestToolStartValkey = "test_start_valkey"

	// TestToolSetAPIServerReachable closes (reachable: false) or opens
	// (reachable: true) the proxy between a Kubernetes-mode instance and the
	// run's API server: the API server gone mid-run, and back. Requires
	// pre_configuration.mode: kubernetes.
	TestToolSetAPIServerReachable = "test_set_apiserver_reachable"
	// TestToolPatchCR applies a JSON merge patch to a CR the scenario applied
	// (kind MCPServer or Workflow, in the instance's namespace) -- e.g.
	// {spec: {suspended: true}} -- so the reconciler is driven by a real CR
	// update. Returns the stored object. Requires mode kubernetes.
	TestToolPatchCR = "test_patch_cr"
	// TestToolGetCR reads a CR of the instance's namespace as the API server
	// stores it, status included, so a scenario can assert on what muster
	// wrote there. Requires mode kubernetes.
	TestToolGetCR = "test_get_cr"

	// TestToolRedeployMockServer replaces a mock MCP server's process behind
	// its port: sessions forgotten, the port never refusing, the tools kept
	// or changed as the step says -- a backend pod replaced behind the same
	// Service, by the same image or by one with other tools.
	TestToolRedeployMockServer = "test_redeploy_mock_server"
	// TestToolSetMockServerAuth flips an OAuth-capable mock MCP server
	// between anonymous and 401-with-metadata while it runs.
	TestToolSetMockServerAuth = "test_set_mock_server_auth"
	// TestToolGetMockServerRejections reports how many requests an
	// OAuth-capable mock MCP server answered with 401, and how many of them
	// presented a bearer past its exp: the backend's own count of what a
	// caller sent it with a dead token.
	TestToolGetMockServerRejections = "test_get_mock_server_rejections"
	// TestToolAdvanceClock moves muster serve's clock and every mock
	// authorization server's clock forward together.
	TestToolAdvanceClock = "test_advance_clock"
)

Test tool name constants for BDD test scenarios.

View Source
const (
	// TestToolMintToken mints an ES256-signed JWT on a mock OAuth server and stores
	// it under a name for later use as a broker subject/actor token.
	TestToolMintToken = "test_mint_token"
	// TestToolBrokerTokenExchange performs an RFC 8693 token exchange against
	// muster's /oauth/token broker and verifies the minted JWT against muster's JWKS.
	TestToolBrokerTokenExchange = "test_broker_token_exchange"
	// TestToolCallProtectedMCP calls a tool on a protected mock MCP server with a
	// previously minted bearer token, proving downstream acceptance end-to-end.
	TestToolCallProtectedMCP = "test_call_protected_mcp"
	// TestToolReconnectWithToken reconnects the caller's MCP client to muster using
	// a previously minted or exchanged token as the bearer, simulating an agent
	// that presents a muster-issued OBO access token on /mcp.
	TestToolReconnectWithToken = "test_reconnect_with_token"
)
View Source
const (
	// TestToolMeasureMetaTool calls a meta-tool as the current user, once or
	// repeatedly, and reports its wall-clock duration, the bytes of its
	// response and the Valkey commands the instance issued while it ran.
	TestToolMeasureMetaTool = "test_measure_meta_tool"
	// TestToolValkeyFootprint reports what the instance's Valkey stand-in
	// holds: keys and bytes by prefix, the sessions with capability entries
	// and the capability bytes per session.
	TestToolValkeyFootprint = "test_valkey_footprint"
)

Test tools that measure what a call costs and what the store holds, for the budgets an installation-shaped scenario asserts (pre_configuration. fixture: scale). Neither changes anything; both report numbers a step bounds with json_path_max.

Variables

This section is empty.

Functions

func CleanupStaleMusterTestProcesses

func CleanupStaleMusterTestProcesses(logger TestLogger, debug bool)

CleanupStaleMusterTestProcesses terminates the muster serve instances an earlier `muster test` run left behind. A run that ends normally destroys its instances itself; one that crashed, was SIGKILLed, or lost its terminal leaves them running with their ports bound, and the next run would collide with them.

An instance is stale when the harness that started it is gone: every instance is a direct child of its `muster test` process, so an instance whose parent is not a muster test harness (it was re-parented to init or a subreaper) has no run left to belong to. Instances whose harness is alive are left alone, so several `muster test` runs -- other terminals, another developer session on the same machine, CI jobs sharing a pid namespace -- coexist without terminating each other's instances mid-scenario.

Best-effort: failures are logged in debug mode rather than returned, since a failed sweep must not block test execution.

func FormatValidationResults

func FormatValidationResults(results *ScenarioValidationResults, verbose bool) string

FormatValidationResults formats validation results for CLI output

func GenerateScenarioPrefix

func GenerateScenarioPrefix(scenarioName string) string

GenerateScenarioPrefix generates a short unique prefix for a scenario. The prefix is formatted as [XXXXXX] where XXXXXX is derived from the scenario name. For readability, it combines: - First 3 chars of the cleaned scenario name - First 3 chars of a SHA256 hash of the full name (for uniqueness)

func GetDefaultScenarioPath

func GetDefaultScenarioPath() string

GetDefaultScenarioPath returns the default path for test scenarios

func GetScenarioPath

func GetScenarioPath(configPath string) string

GetScenarioPath determines the actual scenario path to use, handling empty/default cases

func IsTestTool

func IsTestTool(toolName string) bool

IsTestTool returns true if the tool name is a test helper tool.

func LoadSchemaFromFile

func LoadSchemaFromFile(filename string) (map[string]interface{}, error)

LoadSchemaFromFile loads a JSON schema from file

func PortAllocationBanner

func PortAllocationBanner(basePort int) string

PortAllocationBanner describes the port-allocation environment for the run banner: the port window, the OS ephemeral range (its overlap with the window is the precondition for stolen-port flakes) and whether guard listeners are active. One line per run so a CI log carries what "address already in use" diagnostics need.

func WithRequestHeaders

func WithRequestHeaders(ctx context.Context, headers map[string]string) context.Context

WithRequestHeaders returns a context carrying HTTP headers the test client adds to every request it sends under that context. A step's headers are stashed this way so they ride on exactly that step's requests — same client, same MCP session, different headers per request.

Types

type APIServerConfig

type APIServerConfig struct {
	// ReachableAfter keeps the API server unreachable for this long after
	// muster serve was started: connects are refused until then, the way a
	// kube-apiserver that is still coming up refuses. For "the API server is
	// late at start" scenarios. Requires mode kubernetes.
	ReachableAfter time.Duration `yaml:"reachable_after,omitempty"`
}

APIServerConfig describes how the API server behaves towards a Kubernetes-mode instance. The harness relays every request through a TCP proxy it owns, so the API server can be absent for one instance while the others keep it.

type BrokerClientTestConfig

type BrokerClientTestConfig struct {
	ClientID     string   `yaml:"client_id"`
	ClientSecret string   `yaml:"client_secret"`
	Audiences    []string `yaml:"audiences"`
}

BrokerClientTestConfig is one confidential broker client of a test instance and the audiences it may request.

type BrokerGrantTargetConfig

type BrokerGrantTargetConfig struct {
	OAuthServerRef string `yaml:"oauth_server_ref"`
}

BrokerGrantTargetConfig references the mock OAuth server a broker grant target releases grants from.

type BrokerTrustedIssuerConfig

type BrokerTrustedIssuerConfig struct {
	// OAuthServerRef references the mock OAuth server (by name) whose JWKS and
	// issuer URL muster should trust. The referenced server is forced to sign
	// tokens and serve TLS.
	OAuthServerRef string `yaml:"oauth_server_ref"`
	// AllowedAudiences lists accepted aud values. When empty, muster binds tokens
	// from this issuer to its own issuer as the default audience (anti-replay).
	// Set it (e.g. to the client_id) to accept ID tokens whose aud is the client.
	AllowedAudiences []string `yaml:"allowed_audiences,omitempty"`
	// AllowedClaims requires each named claim to match its glob (e.g. sub ->
	// "system:serviceaccount:kagent:*"). Optional.
	AllowedClaims map[string]string `yaml:"allowed_claims,omitempty"`
	// SubjectClaim names the claim that becomes the canonical subject. Optional.
	SubjectClaim string `yaml:"subject_claim,omitempty"`
	// AcceptedTypHeaders lists accepted JWT typ headers. Use [""] for SA-style
	// tokens that carry no typ header. Empty keeps the RFC 9068 default.
	AcceptedTypHeaders []string `yaml:"accepted_typ_headers,omitempty"`
}

BrokerTrustedIssuerConfig references a mock OAuth server as a trusted issuer for muster's broker and carries the per-issuer claim/typ constraints.

type ExecutionMode

type ExecutionMode string

ExecutionMode represents the mode of test execution

const (
	// ExecutionModeCLI represents command line interface execution
	ExecutionModeCLI ExecutionMode = "cli"
	// ExecutionModeMCPServer represents MCP server execution via stdio
	ExecutionModeMCPServer ExecutionMode = "mcp-server"
)

type InstanceLogExpectation

type InstanceLogExpectation struct {
	// Contains lists substrings the combined stdout+stderr must include.
	Contains []string `yaml:"contains,omitempty"`
	// NotContains lists substrings the combined stdout+stderr must not include.
	NotContains []string `yaml:"not_contains,omitempty"`
	// Occurrences maps a substring to the exact number of lines of the
	// combined stdout+stderr that must contain it. It is the assertion for
	// behaviour that has to happen once and only once -- a lifecycle action
	// the reconciler must not repeat on its resync ticks -- which contains
	// and not_contains cannot express between them.
	Occurrences map[string]int `yaml:"occurrences,omitempty"`
}

InstanceLogExpectation defines what the captured muster serve output must and must not contain once the scenario has run. At least one list must be set.

type InstanceLogs

type InstanceLogs struct {
	// Stdout contains the standard output
	Stdout string
	// Stderr contains the standard error output
	Stderr string
	// Combined contains both stdout and stderr in chronological order
	Combined string
}

InstanceLogs contains the captured logs from an muster instance

type MCPServerConfig

type MCPServerConfig struct {
	// Name is the unique identifier for the MCP server
	Name string `yaml:"name"`
	// Labels are written to the MCPServer definition's metadata.labels, the
	// way a chart labels the resources it ships (e.g.
	// agent-platform.giantswarm.io/tool-group), so scenarios can exercise
	// label-based toolset presets.
	Labels map[string]string `yaml:"labels,omitempty"`
	// Config contains the server-specific configuration (can include tools for mock servers)
	Config map[string]interface{} `yaml:"config"`
}

MCPServerConfig represents an MCP server configuration

type MCPServerOAuthConfig

type MCPServerOAuthConfig struct {
	// Required indicates this server requires OAuth authentication. With
	// MockOAuthServerRef set and Required false the mock starts anonymous --
	// the old pod of a backend being rolled over to OAuth -- and
	// test_set_mock_server_auth flips it.
	Required bool `yaml:"required"`

	// MockOAuthServerRef references a mock OAuth server by name
	MockOAuthServerRef string `yaml:"mock_oauth_server_ref"`

	// GrantScope, when set, pins the referenced mock OAuth server as the
	// MCPServer's authorization server (spec.auth.authorizationServer) with
	// this grantScope. "subject" files the grant under the person, so any
	// session of the same subject reuses it and a logout revokes it for all
	// of them -- the GitHub-style connector configuration.
	GrantScope string `yaml:"grant_scope,omitempty"`

	// OmitResourceMetadata makes the mock backend publish no RFC 9728
	// resource metadata (bare 401 challenge, no well-known document), so the
	// aggregator learns the issuer only from the pin -- see
	// mock.ProtectedMCPServerConfig.OmitResourceMetadata. Unset follows the
	// referenced mock OAuth server's profile (true for github).
	OmitResourceMetadata *bool `yaml:"omit_resource_metadata,omitempty"`

	// PinIdentityPath, appended to the referenced mock OAuth server's issuer
	// URL, is the identity the pin files the grant under instead of that
	// issuer -- a GitHub App pinned under https://github.com/apps/<slug>.
	// Implies the pin; needs the server's endpoints (pin_endpoints_ref, or a
	// profile that implies them) and, for a callback that carries `iss` to
	// complete, expected_issuer_ref naming the server.
	PinIdentityPath string `yaml:"pin_identity_path,omitempty"`

	// ExpectedIssuerRef names the mock OAuth server whose issuer URL the pin
	// carries as spec.auth.authorizationServer.expectedIssuer: the issuer the
	// server puts in the RFC 9207 `iss` parameter (test_simulate_oauth_callback
	// with send_iss: true) when the pinned identity differs from it. Implies
	// the pin.
	ExpectedIssuerRef string `yaml:"expected_issuer_ref,omitempty"`

	// AdvertisedIssuerRef names the mock OAuth server the backend's RFC 9728
	// metadata lists as its authorization server, while tokens are still
	// validated against MockOAuthServerRef -- a backend that accepts tokens
	// from an authorization server other than the one it advertises (muster's
	// own /mcp trusts its IdP's tokens but names muster's OAuth server).
	AdvertisedIssuerRef string `yaml:"advertised_issuer_ref,omitempty"`

	// PinAuthorizationServer pins MockOAuthServerRef as the MCPServer's
	// authorization server (spec.auth.authorizationServer.issuer, with Scope
	// as scopes) without a grant scope; GrantScope implies it. Unset follows
	// the referenced mock OAuth server's profile (a github server is pinned
	// with its endpoints and grant_scope subject).
	PinAuthorizationServer *bool `yaml:"pin_authorization_server,omitempty"`

	// PinEndpointsRef names the mock OAuth server whose authorize and token
	// endpoints the pin carries as authorizationEndpoint/tokenEndpoint (the
	// GitHub shape: explicit endpoints, no discovery) -- possibly a different
	// server than the pinned issuer. A github-profile server names itself.
	PinEndpointsRef string `yaml:"pin_endpoints_ref,omitempty"`

	// Scope is the required OAuth scope
	Scope string `yaml:"scope,omitempty"`

	// TrustIssuerRef makes this backend validate bearer tokens as JWTs signed
	// by the referenced mock OAuth server (against its JWKS) instead of the
	// mock OAuth server's opaque-token check. Used to prove a downstream
	// accepts a forwarded dex-issued token end-to-end. muster is never a
	// token issuer, so there is no option to trust muster's JWKS.
	TrustIssuerRef string `yaml:"trust_issuer_ref,omitempty"`

	// ExpectedAudience is the aud the forwarded token must carry when
	// TrustIssuerRef is set. Empty accepts any audience.
	ExpectedAudience string `yaml:"expected_audience,omitempty"`
}

MCPServerOAuthConfig defines OAuth protection for an MCP server in tests

type MCPTestClient

type MCPTestClient interface {
	// Connect establishes connection to the MCP aggregator
	Connect(ctx context.Context, endpoint string) error
	// ConnectWithAuth establishes connection to the MCP aggregator with an access token.
	// This is used when muster's OAuth server is enabled and requires authentication.
	ConnectWithAuth(ctx context.Context, endpoint, accessToken string) error
	// CallTool invokes an MCP tool with the given args (wrapped through call_tool meta-tool)
	CallTool(ctx context.Context, toolName string, args map[string]interface{}) (interface{}, error)
	// CallToolDirect invokes an MCP tool directly without wrapping through call_tool.
	// Use this for calling meta-tools (list_tools, describe_tool, etc.) that are
	// registered on the MCP server but cannot be dispatched through CallToolInternal.
	CallToolDirect(ctx context.Context, toolName string, args map[string]interface{}) (*mcp.CallToolResult, error)
	// ListTools returns available MCP tools
	ListTools(ctx context.Context) ([]string, error)
	// ListToolsWithSchemas returns available MCP tools with their full schemas
	ListToolsWithSchemas(ctx context.Context) ([]mcp.Tool, error)
	// ReadResource reads an MCP resource by URI
	ReadResource(ctx context.Context, uri string) (*mcp.ReadResourceResult, error)
	// InitializeResult returns the negotiated handshake result, or nil when the
	// client is not connected.
	InitializeResult() *mcp.InitializeResult
	// AccessToken returns the bearer this client presents, or "" for an
	// anonymous connection. What lets a client be re-created as the same
	// session after the instance restarted.
	AccessToken() string
	// Close closes the MCP connection
	Close() error
}

MCPTestClient interface defines the MCP client for testing

func NewMCPTestClient

func NewMCPTestClient(debug bool) MCPTestClient

NewMCPTestClient creates a new MCP test client

func NewMCPTestClientWithLogger

func NewMCPTestClientWithLogger(debug bool, logger TestLogger) MCPTestClient

NewMCPTestClientWithLogger creates a new MCP test client with custom logger

type MainConfig

type MainConfig struct {
	// Config contains the main configuration
	Config map[string]interface{} `yaml:"config"`
}

MainConfig represents the main muster configuration

type MockHTTPServerInfo

type MockHTTPServerInfo struct {
	// Name is the name of the MCP server
	Name string
	// Port is the port the mock HTTP server is listening on
	Port int
	// Transport is the transport type (sse or streamable-http)
	Transport string
	// Endpoint is the full URL endpoint for the server
	Endpoint string
}

MockHTTPServerInfo contains information about a running mock HTTP server

type MockOAuthServerConfig

type MockOAuthServerConfig struct {
	// Name is the unique identifier for this OAuth server
	Name string `yaml:"name"`

	// Profile selects the bundle of behaviours of a named authorization
	// server -- "github", "dex" or "pro" (mock.Profile) -- so a scenario
	// reproduces that server's quirks without listing them one by one. Every
	// flag below that is set overrides the bundle for that flag alone; a flag
	// the bundle switches on is switched off by setting it to false. The
	// bundle also gives the MCP servers that reference this server their
	// defaults (bare 401, subject-scoped grants, a pin with explicit
	// endpoints for github), see MCPServerOAuthConfig.
	Profile string `yaml:"profile,omitempty"`

	// Issuer is the OAuth issuer URL (auto-generated if not specified)
	Issuer string `yaml:"issuer,omitempty"`

	// Scopes are the scopes this OAuth server accepts
	Scopes []string `yaml:"scopes,omitempty"`

	// AutoApprove automatically approves authentication requests
	AutoApprove bool `yaml:"auto_approve,omitempty"`

	// PKCERequired enforces PKCE flow
	PKCERequired bool `yaml:"pkce_required,omitempty"`

	// TokenLifetime is how long tokens are valid (e.g., "1h", "30m")
	TokenLifetime string `yaml:"token_lifetime,omitempty"`

	// ClientID is the expected OAuth client ID
	ClientID string `yaml:"client_id,omitempty"`

	// ClientSecret is the expected OAuth client secret
	ClientSecret string `yaml:"client_secret,omitempty"`

	// SimulateError can simulate error conditions
	SimulateError string `yaml:"simulate_error,omitempty"`

	// UseMockClock enables a mock clock for testing token expiry
	// When true, the test_advance_oauth_clock tool can be used to
	// advance time without waiting
	UseMockClock bool `yaml:"use_mock_clock,omitempty"`

	// UseAsMusterOAuthServer configures this mock OAuth server as muster's
	// OAuth server (aggregator.oauthServer), enabling SSO token forwarding
	// tests where muster itself requires OAuth authentication.
	// When true, the aggregator will be configured with oauthServer.enabled=true
	// and the issuer will be set to this mock server's URL.
	UseAsMusterOAuthServer bool `yaml:"use_as_muster_oauth_server,omitempty"`

	// TrustedIssuers configures RFC 8693 token exchange support.
	// When configured, this OAuth server can exchange tokens from the listed
	// issuers for tokens valid on this server. This enables cross-cluster SSO testing.
	// Each entry maps a connector_id to a trusted OAuth server name.
	TrustedIssuers []TrustedIssuerConfig `yaml:"trusted_issuers,omitempty"`

	// UseTLS enables HTTPS mode with a self-signed certificate.
	// This is required for OAuth servers used as token exchange targets,
	// since RFC 8693 token exchange endpoints must use HTTPS for security.
	// Note: This is automatically set to true when UseAsMusterOAuthServer is true.
	UseTLS bool `yaml:"use_tls,omitempty"`

	// SignTokens makes this server issue ES256-signed tokens and serve a real
	// JWKS, so muster's broker can validate its tokens as a trusted issuer.
	// Automatically enabled (with UseTLS) when referenced by muster_broker.
	SignTokens bool `yaml:"sign_tokens,omitempty"`

	// SupportsCIMD advertises client_id_metadata_document_supported in the
	// AS metadata (CIMD URLs are accepted as client_id).
	SupportsCIMD bool `yaml:"supports_cimd,omitempty"`

	// SupportsDCR advertises a registration_endpoint and serves RFC 7591
	// Dynamic Client Registration. Unset follows the profile.
	SupportsDCR *bool `yaml:"supports_dcr,omitempty"`

	// RequireRegisteredClient makes the token endpoint reject client_ids
	// that are neither the configured client_id nor DCR-registered —
	// mimicking DCR-only authorization servers ("Client Not Registered").
	// Unset follows the profile.
	RequireRegisteredClient *bool `yaml:"require_registered_client,omitempty"`

	// RejectRegistrationScope makes the registration endpoint reject RFC 7591
	// requests that carry a scope member with invalid_client_metadata —
	// mimicking authorization servers (e.g. Miro's) that reject scopes they
	// don't know instead of ignoring them.
	RejectRegistrationScope bool `yaml:"reject_registration_scope,omitempty"`

	// AuthorizeAcceptsAnyClient makes the authorization endpoint skip its
	// client_id check so only the token endpoint enforces registration —
	// mimicking authorization servers whose authorize responses reveal
	// nothing about an unknown client. Muster's pre-challenge registration
	// probe cannot detect a lost registration on such a server; the token
	// endpoint's invalid_client has to.
	AuthorizeAcceptsAnyClient bool `yaml:"authorize_accepts_any_client,omitempty"`

	// AdvertiseIssParameter advertises
	// authorization_response_iss_parameter_supported in the AS metadata. A
	// callback without an `iss` parameter must then be refused.
	AdvertiseIssParameter bool `yaml:"advertise_iss_parameter,omitempty"`

	// OmitTokenScope leaves `scope` out of the token responses, as Dex does
	// (RFC 6749 §5.1 allows it when the granted scope is the requested one).
	// Unset follows the profile.
	OmitTokenScope *bool `yaml:"omit_token_scope,omitempty"`

	// OmitDiscovery serves no RFC 8414 / OIDC discovery document, as GitHub
	// does; muster then needs a pin with explicit endpoints. Unset follows
	// the profile.
	OmitDiscovery *bool `yaml:"omit_discovery,omitempty"`

	// OmitTokenExpiry leaves `expires_in` out of the token responses, as
	// GitHub does. Unset follows the profile.
	OmitTokenExpiry *bool `yaml:"omit_token_expiry,omitempty"`

	// OmitRegistrationClientURI leaves registration_client_uri and
	// registration_access_token out of RFC 7591 registration responses, as
	// the MCP TypeScript SDK's authorization server does. Unset follows the
	// profile.
	OmitRegistrationClientURI *bool `yaml:"omit_registration_client_uri,omitempty"`

	// ForgetRegistrationsOnRestart makes test_restart_mock_oauth_server drop
	// every RFC 7591 registration, as a server with an in-memory client store
	// does. Unset follows the profile.
	ForgetRegistrationsOnRestart *bool `yaml:"forget_registrations_on_restart,omitempty"`
}

MockOAuthServerConfig defines a mock OAuth server for testing

type MockOAuthServerInfo

type MockOAuthServerInfo struct {
	// Name is the unique identifier for this OAuth server
	Name string
	// Port is the port the OAuth server is listening on
	Port int
	// IssuerURL is the OAuth issuer URL
	IssuerURL string
	// Profile is the authorization-server profile the scenario selected for
	// this server ("" for the well-behaved default), see mock.Profile.
	Profile string
	// AccessToken is a pre-generated access token for test framework authentication.
	// This is only set when the OAuth server is used as muster's OAuth server
	// (UseAsMusterOAuthServer=true), allowing the test framework to authenticate
	// with muster without implementing the full OAuth browser flow.
	AccessToken string
	// IDToken is the ID token from the OAuth response.
	// This is used for SSO token forwarding tests.
	IDToken string
	// UseAsMusterOAuthServer indicates this OAuth server is used as muster's OAuth server.
	UseAsMusterOAuthServer bool
}

MockOAuthServerInfo contains info about a running mock OAuth server

type MusterBrokerConfig

type MusterBrokerConfig struct {
	// TrustedIssuers lists the issuers whose subject/actor tokens muster's
	// exchange will validate (against each referenced mock server's JWKS).
	TrustedIssuers []BrokerTrustedIssuerConfig `yaml:"trusted_issuers"`

	// Clients seeds confidential broker clients (tokenExchangeBroker.
	// brokerClients + clientAudiences): the harness writes each secret to a
	// file in the instance's config directory and points muster at it.
	// test_broker_token_exchange presents them with client_id/client_secret.
	Clients []BrokerClientTestConfig `yaml:"clients,omitempty"`

	// GrantTargets maps an audience to the mock OAuth server whose grants
	// the broker releases (tokenExchangeBroker.targets.<audience>.grantIssuer
	// = that server's issuer URL). The referenced server must be the pinned
	// authorization server of an MCPServer with grant_scope: subject.
	GrantTargets map[string]BrokerGrantTargetConfig `yaml:"grant_targets,omitempty"`
}

MusterBrokerConfig configures muster's self-issued RFC 8693 token exchange for a test instance: JWT mode and trusted issuers, resolving mock-server references to live issuer/JWKS URLs at instance startup.

type MusterInstance

type MusterInstance struct {
	// ID is the unique identifier for this instance
	ID string
	// ConfigPath is the path to the temporary configuration directory
	ConfigPath string
	// Port is the port the instance is listening on
	Port int
	// MetricsPort is the port the instance serves its Prometheus /metrics
	// endpoint on. The harness always enables the prometheus exporter so
	// scenarios can assert on exported metrics (see test_scrape_metrics).
	MetricsPort int
	// Endpoint is the full MCP endpoint URL
	Endpoint string
	// Process is the running muster serve process
	Process *os.Process
	// StartTime when the instance was started
	StartTime time.Time
	// Logs contains the collected stdout and stderr from the instance
	Logs *InstanceLogs
	// ExpectedTools contains the list of tools expected to be available from MCP servers
	ExpectedTools []string
	// ExpectedMCPServers contains the list of MCP server names expected to be registered.
	// This includes OAuth-protected servers which may be in "auth_required" state.
	// Used by WaitForReady to ensure servers are registered before tests run.
	ExpectedMCPServers []string
	// MockHTTPServers contains references to mock HTTP servers started for this instance
	MockHTTPServers map[string]*MockHTTPServerInfo
	// MockOAuthServers contains references to mock OAuth servers started for this instance
	MockOAuthServers map[string]*MockOAuthServerInfo
	// MusterOAuthAccessToken is the access token for authenticating with muster's OAuth server.
	// This is set when a mock OAuth server is configured with UseAsMusterOAuthServer=true.
	// The test framework uses this token to authenticate with muster without a browser flow.
	MusterOAuthAccessToken string
	// MusterOAuthRefreshToken is the refresh token from the last OAuth code exchange.
	// Used by handleSimulateMusterReauth to obtain a new access token without re-registering.
	MusterOAuthRefreshToken string
	// MusterOAuthClientID is the registered client ID from the last OAuth flow.
	// Used by handleSimulateMusterReauth for the refresh token grant.
	MusterOAuthClientID string
	// ValkeyAddr is the address of the instance's Valkey stand-in when the
	// scenario runs on valkey storage, "" on memory.
	ValkeyAddr string
	// Mode is the definition source the instance runs on: ModeFilesystem or
	// ModeKubernetes.
	Mode string
	// Namespace is the instance's own namespace on the run's envtest API
	// server in Kubernetes mode, "" in filesystem mode.
	Namespace string
	// KubeconfigPath is the kubeconfig muster serve was given in Kubernetes
	// mode; it points at the instance's API server proxy.
	KubeconfigPath string
	// APIServerAddr is the address of the instance's API server proxy in
	// Kubernetes mode, "" in filesystem mode.
	APIServerAddr string
	// Intervals is the schedule the instance's timers run on: IntervalsShort
	// or IntervalsProduction.
	Intervals string
	// ClockSocketPath is the Unix socket muster serve exposes its clock
	// control on (MUSTER_TEST_CLOCK); test_advance_clock talks to it.
	ClockSocketPath string
	// ClockOffset is how far the scenario has advanced the instance's clock.
	// A restarted process is advanced by it again, so time never goes back.
	ClockOffset time.Duration
}

MusterInstance represents a managed muster serve instance

type MusterInstanceManager

type MusterInstanceManager interface {
	// CreateInstance creates a new muster serve instance with the given configuration.
	// The logger parameter allows scenario-specific logging with prefixes for parallel execution.
	CreateInstance(ctx context.Context, scenarioName string, config *MusterPreConfiguration, logger TestLogger) (*MusterInstance, error)
	// DestroyInstance stops and cleans up an muster serve instance.
	// The logger parameter allows scenario-specific logging with prefixes for parallel execution.
	DestroyInstance(ctx context.Context, instance *MusterInstance, logger TestLogger) error
	// WaitForReady waits for an instance to be ready to accept connections.
	// The logger parameter allows scenario-specific logging with prefixes for parallel execution.
	WaitForReady(ctx context.Context, instance *MusterInstance, logger TestLogger) error
	// InstanceExitStatus reports whether the instance's muster serve process has
	// already exited, and with what result. Used to distinguish "step failed
	// against a live instance" from "the instance died mid-scenario" in failure
	// reports.
	InstanceExitStatus(instance *MusterInstance) (exited bool, waitErr error)
	// RestartInstance stops the instance's muster serve process and starts it
	// again on the same configuration, ports and environment while the
	// instance's Valkey stand-in and mock servers keep running; returns once
	// the new process is ready. The state a pod finds after a rollout.
	RestartInstance(ctx context.Context, instance *MusterInstance, logger TestLogger) error
	// StopValkey takes the instance's Valkey stand-in off its port, data kept;
	// StartValkey brings it back. Both fail for an instance on memory storage.
	StopValkey(instanceID string) error
	StartValkey(instanceID string) error
	// SetAPIServerReachable closes or opens the proxy between a
	// Kubernetes-mode instance and the run's API server: closed, muster's
	// watches end and its next request is refused; open again, they resume.
	// Fails for a filesystem-mode instance.
	SetAPIServerReachable(instanceID string, reachable bool) error
	// PatchCR applies a JSON merge patch to a CR of the instance's namespace
	// (kind MCPServer or Workflow) and returns the object as the API server
	// stores it afterwards. Fails for a filesystem-mode instance.
	PatchCR(ctx context.Context, instanceID, kind, name string, patch map[string]interface{}) (map[string]interface{}, error)
	// GetCR reads a CR of the instance's namespace as the API server stores
	// it -- metadata, spec and the status muster wrote. Fails for a
	// filesystem-mode instance.
	GetCR(ctx context.Context, instanceID, kind, name string) (map[string]interface{}, error)
}

MusterInstanceManager manages muster serve instances for testing

func NewMusterInstanceManagerWithConfig

func NewMusterInstanceManagerWithConfig(debug bool, basePort int, logger TestLogger, keepTempConfig bool, readinessTimeout time.Duration) (MusterInstanceManager, error)

NewMusterInstanceManagerWithConfig creates a new muster instance manager with custom logger and config options. A readinessTimeout of zero (or negative) selects defaultReadinessTimeout.

func NewMusterInstanceManagerWithLogger

func NewMusterInstanceManagerWithLogger(debug bool, basePort int, logger TestLogger) (MusterInstanceManager, error)

NewMusterInstanceManagerWithLogger creates a new muster instance manager with custom logger

type MusterPreConfiguration

type MusterPreConfiguration struct {
	// Fixture names a committed, generated set of definitions the instance
	// boots from before the scenario's own (the installation-shaped "scale"
	// fixture, internal/testing/fixtures/scale). The fixture's servers,
	// workflows and mock authorization servers come first; the scenario's
	// entries are appended, or overlay a fixture entry of the same name.
	Fixture string `yaml:"fixture,omitempty"`
	// MCPServers defines MCP server configurations to load
	MCPServers []MCPServerConfig `yaml:"mcp_servers,omitempty"`
	// Workflows defines workflow definitions to load
	Workflows []WorkflowConfig `yaml:"workflows,omitempty"`

	// Services defines service instance definitions to load
	Services []ServiceConfig `yaml:"services,omitempty"`
	// MainConfig defines the main muster configuration
	MainConfig *MainConfig `yaml:"main_config,omitempty"`

	// MockOAuthServers defines mock OAuth servers to start for testing
	MockOAuthServers []MockOAuthServerConfig `yaml:"mock_oauth_servers,omitempty"`

	// MusterBroker configures muster's RFC 8693 token exchange at /oauth/token:
	// JWT mode (muster signs issued tokens) plus the trusted issuers whose
	// subject/actor tokens the exchange validates.
	MusterBroker *MusterBrokerConfig `yaml:"muster_broker,omitempty"`

	// Storage selects the store backend the instance runs on. Absent means
	// memory: every store dies with the process. See StorageConfig.
	Storage *StorageConfig `yaml:"storage,omitempty"`

	// Mode selects where the instance reads its definitions from:
	// "filesystem" (default) writes them into the instance's config
	// directory; "kubernetes" applies them as MCPServer and Workflow CRs to
	// the run's envtest API server and runs muster serve in Kubernetes mode
	// against it -- informers, reconciler and boot pass included. Needs the
	// envtest binaries (KUBEBUILDER_ASSETS); without them the scenario is
	// reported as skipped.
	Mode string `yaml:"mode,omitempty"`

	// APIServer shapes the instance's view of the API server in Kubernetes
	// mode. Absent means reachable from the start.
	APIServer *APIServerConfig `yaml:"apiserver,omitempty"`

	// Intervals selects the schedule of the instance's lifecycle timers:
	// "short" (default) runs them in seconds through environment knobs;
	// "production" keeps the timers the controllable clock reaches on their
	// production defaults, for scenarios that move time with
	// test_advance_clock instead. See IntervalsShort and IntervalsProduction.
	Intervals string `yaml:"intervals,omitempty"`
}

MusterPreConfiguration defines how to pre-configure an muster serve instance

type ScenarioContext

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

ScenarioContext holds the execution context for a test scenario including stored results from previous steps for template variable resolution

func NewScenarioContext

func NewScenarioContext() *ScenarioContext

NewScenarioContext creates a new scenario execution context

func (*ScenarioContext) GetAllStoredResults

func (sc *ScenarioContext) GetAllStoredResults() map[string]interface{}

GetAllStoredResults returns a copy of all stored results for debugging

func (*ScenarioContext) StoreResult

func (sc *ScenarioContext) StoreResult(name string, result interface{})

StoreResult stores a step result under the given variable name

type ScenarioState

type ScenarioState struct {
	Scenario    TestScenario     `json:"scenario"`
	StartTime   time.Time        `json:"start_time"`
	StepResults []TestStepResult `json:"step_results"`
	Status      string           `json:"status"` // "running", "completed", "failed"
}

ScenarioState tracks the state of a running scenario

type ScenarioValidationResult

type ScenarioValidationResult struct {
	ScenarioName string                 `json:"scenario_name"`
	Valid        bool                   `json:"valid"`
	Errors       []ValidationError      `json:"errors,omitempty"`
	StepResults  []StepValidationResult `json:"step_results"`
}

ScenarioValidationResult represents the validation result for a single scenario

type ScenarioValidationResults

type ScenarioValidationResults struct {
	TotalScenarios    int                        `json:"total_scenarios"`
	ValidScenarios    int                        `json:"valid_scenarios"`
	TotalErrors       int                        `json:"total_errors"`
	ScenarioResults   []ScenarioValidationResult `json:"scenario_results"`
	ValidationSummary map[string]int             `json:"validation_summary"`
}

ScenarioValidationResults represents the results of validating multiple scenarios

func ValidateScenariosAgainstSchema

func ValidateScenariosAgainstSchema(scenarios []TestScenario, schema map[string]interface{}, verbose, debug bool) *ScenarioValidationResults

ValidateScenariosAgainstSchema validates scenarios against the API schema

type ServiceConfig

type ServiceConfig struct {
	// Name is the unique identifier for the service instance
	Name string `yaml:"name"`
	// Config contains the service instance definition
	Config map[string]interface{} `yaml:"config"`
}

ServiceConfig represents a service instance configuration

type StepValidationResult

type StepValidationResult struct {
	StepID string            `json:"step_id"`
	Tool   string            `json:"tool"`
	Valid  bool              `json:"valid"`
	Errors []ValidationError `json:"errors,omitempty"`
}

StepValidationResult represents the validation result for a single step

type StorageConfig

type StorageConfig struct {
	// Type is "memory" (default) or "valkey".
	Type string `yaml:"type,omitempty"`
	// StartDelay makes the Valkey stand-in answer only this long after muster
	// serve was started: until then a connect is refused, the way a Valkey
	// pod that is not scheduled yet refuses. For "Valkey is late at start"
	// scenarios; requires type valkey.
	StartDelay time.Duration `yaml:"start_delay,omitempty"`
}

StorageConfig selects the store backend a scenario's muster serve instance runs on. With type valkey the harness starts an in-process Valkey stand-in (miniredis) per instance and points muster's oauth.server.storage at it, so the session auth store, the capability store, the OAuth token, state and client credential stores and the OAuth server's own store outlive the process the way an installation's do -- and survive test_restart_instance.

type StructuredTestReporter

type StructuredTestReporter interface {
	TestReporter
	// GetCurrentSuiteResult returns the current test suite result
	GetCurrentSuiteResult() *TestSuiteResult
	// GetScenarioStates returns the current state of all scenarios
	GetScenarioStates() map[string]*ScenarioState
	// GetCurrentResults returns the current scenario results
	GetCurrentResults() []TestScenarioResult
	// GetResultsAsJSON returns the current results as JSON
	GetResultsAsJSON() (string, error)
	// IsVerbose returns whether verbose reporting is enabled
	IsVerbose() bool
	// IsDebug returns whether debug reporting is enabled
	IsDebug() bool
}

StructuredTestReporter extends TestReporter with methods for structured data access This is typically used in MCP server mode where results need to be queried programmatically

type TemplateProcessor

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

TemplateProcessor handles template variable resolution in test step arguments using the existing enhanced template engine

func NewTemplateProcessor

func NewTemplateProcessor(context *ScenarioContext) *TemplateProcessor

NewTemplateProcessor creates a new template processor with the given scenario context

func (*TemplateProcessor) ResolveArgs

func (tp *TemplateProcessor) ResolveArgs(args map[string]interface{}) (map[string]interface{}, error)

ResolveArgs processes a map of arguments and resolves any template variables

type TestCategory

type TestCategory string

TestCategory represents the category of tests to execute

const (
	// CategoryBehavioral represents BDD-style behavioral tests
	CategoryBehavioral TestCategory = "behavioral"
	// CategoryIntegration represents integration and end-to-end tests
	CategoryIntegration TestCategory = "integration"
)

type TestConcept

type TestConcept string

TestConcept represents the core muster concept being tested

const (
	// ConceptWorkflow represents Workflow execution tests
	ConceptWorkflow TestConcept = "workflow"
	// ConceptMCPServer represents MCPServer management tests
	ConceptMCPServer TestConcept = "mcpserver"

	// ConceptService represents Service lifecycle tests
	ConceptService TestConcept = "service"
)

type TestConfiguration

type TestConfiguration struct {
	// Timeout is the overall test execution timeout
	Timeout time.Duration `yaml:"timeout"`
	// Category filter for test execution
	Category TestCategory `yaml:"category,omitempty"`
	// Concept filter for test execution
	Concept TestConcept `yaml:"concept,omitempty"`
	// Scenario filter for specific scenario execution
	Scenario string `yaml:"scenario,omitempty"`
	// Mode filter: run only the scenarios whose pre_configuration.mode is
	// this ("filesystem" or "kubernetes"); empty runs both.
	Mode string `yaml:"mode,omitempty"`
	// Parallel is the number of parallel test workers
	Parallel int `yaml:"parallel"`
	// StartupParallel bounds how many scenarios may be in their
	// instance-startup phase concurrently. 0 selects the default; negative
	// disables the bound. See defaultStartupParallel.
	StartupParallel int `yaml:"startup_parallel,omitempty"`
	// FailFast stops execution on first failure
	FailFast bool `yaml:"fail_fast"`
	// Verbose enables detailed output
	Verbose bool `yaml:"verbose"`
	// Debug enables debug logging and MCP tracing
	Debug bool `yaml:"debug"`
	// ConfigPath is the path to test scenario definitions
	ConfigPath string `yaml:"config_path,omitempty"`
	// ReportPath is the path to save detailed test reports
	ReportPath string `yaml:"report_path,omitempty"`
	// BasePort is the starting port number for muster instances
	BasePort int `yaml:"base_port,omitempty"`
	// KeepTempConfig keeps temporary config directory after test execution
	KeepTempConfig bool `yaml:"keep_temp_config,omitempty"`
}

TestConfiguration defines the overall test execution configuration

type TestExpectation

type TestExpectation struct {
	// Success indicates whether the tool call should succeed
	Success bool `yaml:"success"`
	// ErrorContains checks if error message contains specific text
	ErrorContains []string `yaml:"error_contains,omitempty"`
	// Contains checks if response contains specific text
	Contains []string `yaml:"contains,omitempty"`
	// NotContains checks if response does not contain specific text
	NotContains []string `yaml:"not_contains,omitempty"`
	// JSONPath allows checking specific JSON response fields
	JSONPath map[string]interface{} `yaml:"json_path,omitempty"`
	// JSONPathMax bounds numeric JSON response fields from above: each path
	// must resolve to a number no greater than the given limit. It is how a
	// scenario states a budget -- bytes on the wire, commands per call,
	// milliseconds -- and a failing budget names the path, the measured value
	// and the limit.
	JSONPathMax map[string]float64 `yaml:"json_path_max,omitempty"`
	// StatusCode is not supported and is rejected at load time by
	// validateStep. It is kept as a field so that a scenario declaring
	// status_code fails with an explanation instead of having the key silently
	// dropped by the non-strict YAML decode. Assert an HTTP status that a test
	// tool reports in its payload with JSONPath instead.
	StatusCode int `yaml:"status_code,omitempty"`
	// WaitForState enables polling for state changes with timeout
	WaitForState time.Duration `yaml:"wait_for_state,omitempty"`
}

TestExpectation defines what result is expected from a test step

type TestFramework

type TestFramework struct {
	Runner          TestRunner
	Client          MCPTestClient
	Loader          TestScenarioLoader
	Reporter        TestReporter
	InstanceManager MusterInstanceManager
	Logger          TestLogger
}

TestFramework holds all components needed for testing

func NewTestFrameworkForMode

func NewTestFrameworkForMode(mode ExecutionMode, verbose, debug bool, basePort int, reportPath string, keepTempConfig bool, readinessTimeout time.Duration) (*TestFramework, error)

NewTestFrameworkForMode creates a fully configured test framework for the specified execution mode

Execution Modes:

  • ExecutionModeCLI: Uses standard stdio output for reporting (compatible with existing behavior)
  • ExecutionModeMCPServer: Uses structured reporting that captures data without stdio output to avoid contaminating the MCP protocol stream. Results can be retrieved programmatically.

Note: In MCP server mode, verbose defaults to true and debug output is controlled by the silent logger to prevent stdio contamination.

func NewTestFrameworkWithConfig

func NewTestFrameworkWithConfig(verbose, debug bool, basePort int, reportPath string, keepTempConfig bool, readinessTimeout time.Duration) (*TestFramework, error)

NewTestFrameworkWithConfig creates a fully configured test framework with all configuration options. A readinessTimeout of zero selects the default instance readiness deadline.

func (*TestFramework) Cleanup

func (tf *TestFramework) Cleanup() error

Cleanup cleans up resources used by the test framework

type TestLogger

type TestLogger interface {
	// Debug logs debug-level messages (only shown when debug=true)
	Debug(format string, args ...interface{})
	// Info logs info-level messages (shown when verbose=true or debug=true)
	Info(format string, args ...interface{})
	// Error logs error-level messages (always shown)
	Error(format string, args ...interface{})
	// IsDebugEnabled returns whether debug logging is enabled
	IsDebugEnabled() bool
	// IsVerboseEnabled returns whether verbose logging is enabled
	IsVerboseEnabled() bool
}

TestLogger provides centralized logging for test execution

func NewPrefixedLogger

func NewPrefixedLogger(base TestLogger, prefix string) TestLogger

NewPrefixedLogger creates a new logger that wraps the base logger and adds a prefix to all log messages. The prefix is typically a short unique identifier for the scenario being executed.

func NewSilentLogger

func NewSilentLogger(verbose, debug bool) TestLogger

NewSilentLogger creates a logger that suppresses all output (for MCP server mode)

func NewStdoutLogger

func NewStdoutLogger(verbose, debug bool) TestLogger

NewStdoutLogger creates a logger that outputs to stdout/stderr

type TestReporter

type TestReporter interface {
	// ReportStart is called when test execution begins
	ReportStart(config TestConfiguration)
	// ReportScenarioStart is called when a scenario begins
	ReportScenarioStart(scenario TestScenario)
	// ReportStepResult is called when a step completes
	ReportStepResult(stepResult TestStepResult)
	// ReportScenarioResult is called when a scenario completes
	ReportScenarioResult(scenarioResult TestScenarioResult)
	// ReportSuiteResult is called when all tests complete
	ReportSuiteResult(suiteResult TestSuiteResult)
	// SetParallelMode enables or disables parallel output buffering
	SetParallelMode(parallel bool)
}

TestReporter interface defines how test results are reported

func NewStructuredReporter

func NewStructuredReporter(verbose, debug bool, reportPath string) TestReporter

NewStructuredReporter creates a reporter that captures structured data without stdio output

func NewTestReporter

func NewTestReporter(verbose, debug bool, reportPath string) TestReporter

NewTestReporter creates a new test reporter

type TestResult

type TestResult string

TestResult represents the result of test execution

const (
	// ResultPassed indicates the test passed successfully
	ResultPassed TestResult = "PASSED"
	// ResultFailed indicates the test failed
	ResultFailed TestResult = "FAILED"
	// ResultSkipped indicates the test was skipped
	ResultSkipped TestResult = "SKIPPED"
	// ResultError indicates an error occurred during test execution
	ResultError TestResult = "ERROR"
)

type TestRunner

type TestRunner interface {
	// Run executes test scenarios according to the configuration
	Run(ctx context.Context, config TestConfiguration, scenarios []TestScenario) (*TestSuiteResult, error)
}

TestRunner interface defines the test execution engine

func NewTestRunnerWithLogger

func NewTestRunnerWithLogger(client MCPTestClient, loader TestScenarioLoader, reporter TestReporter, instanceManager MusterInstanceManager, debug bool, logger TestLogger) TestRunner

NewTestRunnerWithLogger creates a new test runner with custom logger

type TestScenario

type TestScenario struct {
	// Name is the unique identifier for the scenario
	Name string `yaml:"name"`
	// Category is the test category (behavioral, integration)
	Category TestCategory `yaml:"category"`
	// Concept is the core concept being tested
	Concept TestConcept `yaml:"concept"`
	// Description provides human-readable scenario description
	Description string `yaml:"description"`
	// Prerequisites define setup requirements
	Prerequisites []string `yaml:"prerequisites,omitempty"`
	// Steps define the test execution steps
	Steps []TestStep `yaml:"steps"`
	// Cleanup defines teardown steps
	Cleanup []TestStep `yaml:"cleanup,omitempty"`
	// Timeout for this specific scenario
	Timeout time.Duration `yaml:"timeout,omitempty"`
	// Tags for additional categorization
	Tags []string `yaml:"tags,omitempty"`
	// Skip indicates whether this scenario should be skipped
	Skip bool `yaml:"skip,omitempty"`
	// PreConfiguration defines muster instance setup
	PreConfiguration *MusterPreConfiguration `yaml:"pre_configuration,omitempty"`
	// InstanceLogs asserts on the stdout/stderr the muster serve instance
	// produced over the whole scenario, and is the only expectation kind that
	// sees the instance side of a behavior -- e.g. that a credential never
	// reached the logs. It is evaluated once, after the last step and cleanup
	// step ran; while a contains or occurrences expectation is unmet the
	// runner first reads up to ten more seconds of output, so a line logged
	// by work a step started in the background is seen.
	InstanceLogs *InstanceLogExpectation `yaml:"instance_logs,omitempty"`
}

TestScenario defines a single test scenario

func LoadAndFilterScenarios

func LoadAndFilterScenarios(configPath string, config TestConfiguration, logger TestLogger) ([]TestScenario, error)

LoadAndFilterScenarios provides a unified way to load and filter scenarios

func LoadScenariosForCompletion

func LoadScenariosForCompletion(configPath string) ([]TestScenario, error)

LoadScenariosForCompletion provides a simple way to load scenarios for shell completion This uses minimal logging to avoid interfering with completion output

type TestScenarioLoader

type TestScenarioLoader interface {
	// LoadScenarios loads test scenarios from the given path
	LoadScenarios(configPath string) ([]TestScenario, error)
	// FilterScenarios filters scenarios based on the configuration
	FilterScenarios(scenarios []TestScenario, config TestConfiguration) []TestScenario
}

TestScenarioLoader interface defines how test scenarios are loaded

func CreateScenarioLoaderForContext

func CreateScenarioLoaderForContext(debug bool, logger TestLogger) TestScenarioLoader

CreateScenarioLoaderForContext creates a scenario loader appropriate for the given context

func NewTestScenarioLoader

func NewTestScenarioLoader(debug bool) TestScenarioLoader

NewTestScenarioLoader creates a new test scenario loader

func NewTestScenarioLoaderWithLogger

func NewTestScenarioLoaderWithLogger(debug bool, logger TestLogger) TestScenarioLoader

NewTestScenarioLoaderWithLogger creates a new test scenario loader with custom logger

type TestScenarioResult

type TestScenarioResult struct {
	// Scenario is the scenario that was executed
	Scenario TestScenario `json:"scenario"`
	// Result is the overall result of the scenario
	Result TestResult `json:"result"`
	// StartTime when scenario execution began
	StartTime time.Time `json:"start_time"`
	// EndTime when scenario execution completed
	EndTime time.Time `json:"end_time"`
	// Duration of scenario execution
	Duration time.Duration `json:"duration"`
	// StepResults contains individual step results
	StepResults []TestStepResult `json:"step_results"`
	// Error message if the scenario failed or had an error
	Error string `json:"error,omitempty"`
	// Output from scenario execution
	Output string `json:"output,omitempty"`
	// InstanceLogs contains logs from the muster serve instance
	InstanceLogs *InstanceLogs `json:"instance_logs,omitempty"`
	// HarnessGoroutines is the harness's goroutine dump, taken when a step's
	// call to muster serve never returned (see TestStepResult.Stalled); the
	// instance's own dump is at the end of InstanceLogs.Stderr.
	HarnessGoroutines string `json:"harness_goroutines,omitempty"`
}

TestScenarioResult represents the result of a single test scenario

type TestStep

type TestStep struct {
	// ID is the step identifier
	ID string `yaml:"id"`
	// Description explains what the step does
	Description string `yaml:"description,omitempty"`
	// Tool is the MCP tool to invoke
	Tool string `yaml:"tool"`
	// Args are the tool arguments as a map
	Args map[string]interface{} `yaml:"args"`
	// Expected defines the expected outcome
	Expected TestExpectation `yaml:"expected"`
	// Retry is not supported and is rejected at load time by validateStep.
	// It is kept as a field so that a scenario declaring retry fails with an
	// explanation instead of having the key silently dropped by the
	// non-strict YAML decode. The runner never read it, so a step declaring
	// retry got exactly one attempt while reading as if it polled. Poll for
	// eventually-consistent state with expected.wait_for_state instead.
	Retry map[string]interface{} `yaml:"retry,omitempty"`
	// Timeout for this specific step
	Timeout time.Duration `yaml:"timeout,omitempty"`
	// MaxDuration fails the step when its single invocation took longer --
	// the assertion for "this request is not held for background work"
	// (a session's first request answering while its SSO fan-out runs). It
	// is judged on the invocation itself, so it cannot be combined with
	// expected.wait_for_state, whose polling would count towards it.
	MaxDuration time.Duration `yaml:"max_duration,omitempty"`
	// AsUser specifies which user session to execute this step as.
	// For multi-user testing scenarios. If not set, uses the current user.
	AsUser string `yaml:"as_user,omitempty"`
	// Headers are HTTP headers sent on this step's requests to the muster
	// instance (e.g. X-Muster-Toolset). They apply to this step only, on the
	// same client and session as the surrounding steps, which is what lets a
	// scenario prove per-request evaluation: two steps on one session with
	// different headers, or a step without any.
	Headers map[string]string `yaml:"headers,omitempty"`
}

TestStep defines a single step within a test scenario

type TestStepResult

type TestStepResult struct {
	// Step is the step that was executed
	Step TestStep `json:"step"`
	// Result is the result of the step
	Result TestResult `json:"result"`
	// StartTime when step execution began
	StartTime time.Time `json:"start_time"`
	// EndTime when step execution completed
	EndTime time.Time `json:"end_time"`
	// Duration of step execution
	Duration time.Duration `json:"duration"`
	// Response from the MCP tool call
	Response interface{} `json:"response,omitempty"`
	// Error message if the step failed
	Error string `json:"error,omitempty"`
	// Stalled reports that the step's last call to muster serve never
	// returned: it ended with context.DeadlineExceeded, its budget spent
	// waiting for the response. The runner then captures goroutine dumps of
	// the instance and the harness (see captureStallDiagnostics).
	Stalled bool `json:"stalled,omitempty"`
}

TestStepResult represents the result of a single test step

type TestSuiteResult

type TestSuiteResult struct {
	// StartTime when test execution began
	StartTime time.Time `json:"start_time"`
	// EndTime when test execution completed
	EndTime time.Time `json:"end_time"`
	// Duration of test execution
	Duration time.Duration `json:"duration"`
	// TotalScenarios is the total number of scenarios executed
	TotalScenarios int `json:"total_scenarios"`
	// PassedScenarios is the number of scenarios that passed
	PassedScenarios int `json:"passed_scenarios"`
	// FailedScenarios is the number of scenarios that failed
	FailedScenarios int `json:"failed_scenarios"`
	// SkippedScenarios is the number of scenarios that were skipped
	SkippedScenarios int `json:"skipped_scenarios"`
	// ErrorScenarios is the number of scenarios that had errors
	ErrorScenarios int `json:"error_scenarios"`
	// ScenarioResults contains individual scenario results
	ScenarioResults []TestScenarioResult `json:"scenario_results"`
	// Configuration used for this test run
	Configuration TestConfiguration `json:"configuration"`
}

TestSuiteResult represents the overall result of test suite execution

type TestToolContent

type TestToolContent struct {
	Type string `json:"type"`
	Text string `json:"text"`
}

TestToolContent represents content in a test tool result.

type TestToolResult

type TestToolResult struct {
	Content []TestToolContent `json:"content"`
	IsError bool              `json:"isError,omitempty"`
}

TestToolResult wraps a result from a test tool to match MCP response format.

func WrapTestToolResult

func WrapTestToolResult(result interface{}, err error) *TestToolResult

WrapTestToolResult wraps a test tool result in MCP-compatible format.

type TestToolsHandler

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

TestToolsHandler handles test-specific tools that operate on mock infrastructure. These tools are NOT exposed through the muster serve MCP server - they are handled directly by the test runner before delegating to the real MCP client.

func NewTestToolsHandler

func NewTestToolsHandler(instanceManager MusterInstanceManager, instance *MusterInstance, debug bool, logger TestLogger) *TestToolsHandler

NewTestToolsHandler creates a new test tools handler.

func (*TestToolsHandler) CloseAllUserClients

func (h *TestToolsHandler) CloseAllUserClients()

CloseAllUserClients closes all user MCP clients except the default one. The default client is managed by the test runner.

func (*TestToolsHandler) GetCurrentClient

func (h *TestToolsHandler) GetCurrentClient() MCPTestClient

GetCurrentClient returns the MCP client for the currently active user.

func (*TestToolsHandler) GetCurrentUserName

func (h *TestToolsHandler) GetCurrentUserName() string

GetCurrentUserName returns the name of the currently active user.

func (*TestToolsHandler) HandleTestTool

func (h *TestToolsHandler) HandleTestTool(ctx context.Context, toolName string, args map[string]interface{}) (interface{}, error)

HandleTestTool executes a test helper tool and returns the result.

func (*TestToolsHandler) HasUser

func (h *TestToolsHandler) HasUser(name string) bool

HasUser returns true if a user session with the given name exists. This provides encapsulated access to check user existence without exposing the internal userClients map.

func (*TestToolsHandler) SetMCPClient

func (h *TestToolsHandler) SetMCPClient(client MCPTestClient)

SetMCPClient sets the MCP client for calling tools in the muster instance. This is used by test_simulate_oauth_callback to call the authenticate tool.

func (*TestToolsHandler) SwitchToUser

func (h *TestToolsHandler) SwitchToUser(name string) bool

SwitchToUser switches the current user context to the specified user. This is used by the test runner to switch user context for as_user steps. Returns false if the user doesn't exist.

type TrustedIssuerConfig

type TrustedIssuerConfig struct {
	// ConnectorID is the identifier used in the token exchange request
	// to specify which connector to use (maps to audience in RFC 8693)
	ConnectorID string `yaml:"connector_id"`

	// OAuthServerRef references the mock OAuth server by name whose tokens
	// should be accepted for exchange
	OAuthServerRef string `yaml:"oauth_server_ref"`
}

TrustedIssuerConfig defines a trusted issuer for RFC 8693 token exchange

type ValidationError

type ValidationError struct {
	Type       string `json:"type"`
	Message    string `json:"message"`
	Field      string `json:"field,omitempty"`
	Suggestion string `json:"suggestion,omitempty"`
}

ValidationError represents a validation error

type WorkflowConfig

type WorkflowConfig struct {
	// Name is the unique identifier for the workflow
	Name string `yaml:"name"`
	// Labels are written to the Workflow CRD's metadata.labels. They are
	// propagated onto the workflow's execution tool and are filterable by the
	// discovery tier (filter_tools labels facet).
	Labels map[string]string `yaml:"labels,omitempty"`
	// Config contains the workflow definition
	Config map[string]interface{} `yaml:"config"`
}

WorkflowConfig represents a workflow configuration

Directories

Path Synopsis
fixtures
oauth
Package oauth contains test fixtures for OAuth authentication testing.
Package oauth contains test fixtures for OAuth authentication testing.
scale
Package scale is the installation-shaped fixture the scale budgets run on: 87 MCPServers (84 of them session-authenticated, in five families with an instanceArg, on 28 installations; three in-house servers without authentication), 18 distinct capability documents shared by the family members, 282 workflows referencing their tools, and 450 sessions each authenticated to every session-authenticated server -- the shape of a production installation, with every name invented.
Package scale is the installation-shaped fixture the scale budgets run on: 87 MCPServers (84 of them session-authenticated, in five families with an instanceArg, on 28 installations; three in-house servers without authentication), 18 distinct capability documents shared by the family members, 282 workflows referencing their tools, and 450 sessions each authenticated to every session-authenticated server -- the shape of a production installation, with every name invented.
scale/gen command
Command gen rewrites the scale fixture's YAML files from the generator, so `go generate ./internal/testing/fixtures/scale/` is the one way to change the committed fixture.
Command gen rewrites the scale fixture's YAML files from the generator, so `go generate ./internal/testing/fixtures/scale/` is the one way to change the committed fixture.
Package mock provides mock MCP server functionality for testing muster components.
Package mock provides mock MCP server functionality for testing muster components.

Jump to

Keyboard shortcuts

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