Class ConfigurationProperties
- Author:
- jamesdbloom
-
Field Summary
Fields -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic intstatic voidactionHandlerThreadCount(int count) Number of threads for the action handler thread poolstatic booleanstatic voidalwaysCloseSocketConnections(boolean alwaysClose) If true socket connections will always be closed after a response is returned, if false connection is only closed if request header indicate connection should be closed.static booleanstatic voidassumeAllRequestsAreHttp(boolean assumeAllRequestsAreHttp) If true requests are assumed as binary if the method isn't one of "GET", "POST", "PUT", "HEAD", "OPTIONS", "PATCH", "DELETE", "TRACE" or "CONNECT"static StringDefault Kafka bootstrap servers used when aPUT /mockserver/asyncapirequest body does not includebrokerConfig.kafkaBootstrapServers.static voidasyncKafkaBootstrapServers(String servers) static StringDefault MQTT broker URL used when aPUT /mockserver/asyncapirequest body does not includebrokerConfig.mqttBrokerUrl.static voidasyncMqttBrokerUrl(String url) static intMaximum number of recorded messages retained per channel in async messaging subscribers.static voidasyncRecordedMessageMaxEntries(int maxEntries) static booleanstatic voidattemptToProxyIfNoMatchingExpectation(boolean enable) If true (the default) when no matching expectation is found, and the host header of the request does not match MockServer's host, then MockServer attempts to proxy the request if that fails then a 404 is returned.static StringReturns the explicit access key ID for cloud blob store authentication.static voidblobStoreAccessKeyId(String blobStoreAccessKeyId) static StringReturns the cloud blob store bucket name (S3 or GCS bucket).static voidblobStoreBucket(String blobStoreBucket) static StringReturns the Azure Blob Storage connection string.static voidblobStoreConnectionString(String blobStoreConnectionString) static StringReturns the Azure Blob Storage container name.static voidblobStoreContainer(String blobStoreContainer) static StringReturns the cloud blob store endpoint override URL.static voidblobStoreEndpoint(String blobStoreEndpoint) static StringReturns the key prefix for cloud blob store objects.static voidblobStoreKeyPrefix(String blobStoreKeyPrefix) static StringReturns the GCS project ID.static voidblobStoreProjectId(String blobStoreProjectId) static StringReturns the cloud blob store region (e.g.static voidblobStoreRegion(String blobStoreRegion) static StringReturns the explicit secret access key for cloud blob store authentication.static voidblobStoreSecretAccessKey(String blobStoreSecretAccessKey) static StringReturns the blob store type.static voidblobStoreType(String blobStoreType) Sets the blob store type.static Stringstatic voidcertificateAuthorityCertificate(String certificateAuthorityCertificate) File system path or classpath location of custom X.509 Certificate for Certificate Authority for TLS, the certificate must be a X509 PEM file and must match the certificateAuthorityPrivateKeystatic Stringstatic voidcertificateAuthorityPrivateKey(String certificateAuthorityPrivateKey) File system path or classpath location of custom Private Key for Certificate Authority for TLS, the private key must be a PKCS#8 or PKCS#1 PEM file and must match the certificateAuthorityCertificate To convert a PKCS#1 (i.e. default for Bouncy Castle) to a PKCS#8 the following command can be used: openssl pkcs8 -topk8 -inform PEM -in private_key_PKCS_1.pem -out private_key_PKCS_8.pem -nocryptstatic intstatic voidclientNioEventLoopThreadCount(int count) Client Netty worker thread pool size for handling requests and response.static booleanReturns whether clustering is enabled.static voidclusterEnabled(boolean clusterEnabled) Enables or disables clustering.static StringReturns the JGroups cluster name.static voidclusterName(String clusterName) Sets the JGroups cluster name.static StringReturns the optional path to a JGroups XML transport configuration.static voidclusterTransportConfig(String clusterTransportConfig) Sets the path to a custom JGroups XML transport configuration.static booleanstatic voidcompactLogFormat(boolean enable) When enabled, log messages written to stdout/SLF4J use a compact single-line format showing summary information (e.g., method, path, status code, expectation ID) instead of full JSON-serialized request and response details.static longstatic voidconnectionDelayMillis(long milliseconds) static Stringstatic voidcontrolPlaneJWTAuthenticationExpectedAudience(String controlPlaneJWTAuthenticationExpectedAudience) Audience claim (i.e. aud) required when JWT authentication is enabled for control plane requestsstatic Stringstatic voidcontrolPlaneJWTAuthenticationJWKSource(String controlPlaneJWTAuthenticationJWKSource) JWK source used when JWT authentication is enabled for control plane requestsstatic voidcontrolPlaneJWTAuthenticationMatchingClaims(Map<String, String> controlPlaneJWTAuthenticationMatchingClaims) Matching claims expected when JWT authentication is enabled for control plane requestsstatic booleanstatic voidcontrolPlaneJWTAuthenticationRequired(boolean enable) Require JWT authentication for all control plane requestsstatic voidcontrolPlaneJWTAuthenticationRequiredClaims(Set<String> controlPlaneJWTAuthenticationRequiredClaims) Required claims that should exist (i.e. with any value) when JWT authentication is enabled for control plane requestsstatic Stringstatic voidcontrolPlanePrivateKeyPath(String privateKeyPath) File system path or classpath location of a fixed custom private key for control plane connections using mTLS for authentication.static Stringstatic voidcontrolPlaneTLSMutualAuthenticationCAChain(String trustCertificateChain) File system path or classpath location of custom mTLS (TLS client authentication) X.509 Certificate Chain for control plane mTLS authenticationstatic booleanstatic voidcontrolPlaneTLSMutualAuthenticationRequired(boolean enable) Require mTLS (also called client authentication and two-way TLS) for all control plane requestsstatic Stringstatic voidcontrolPlaneX509CertificatePath(String x509CertificatePath) File system path or classpath location of a fixed custom X.509 Certificate for control plane connections using mTLS for authentication.static booleanstatic voidcorsAllowCredentials(boolean allow) The value used for CORS in the access-control-allow-credentials header.static Stringstatic voidcorsAllowHeaders(String corsAllowHeaders) the value used for CORS in the access-control-allow-headers and access-control-expose-headers headers.static Stringstatic voidcorsAllowMethods(String corsAllowMethods) The value used for CORS in the access-control-allow-methods header.static Stringstatic voidcorsAllowOrigin(String corsAllowOrigin) the value used for CORS in the access-control-allow-origin header.static intstatic voidcorsMaxAgeInSeconds(int ageInSeconds) The value used for CORS in the access-control-max-age header.static Stringstatic voidcustomJsonUnitMatchersClass(String customJsonUnitMatchersClass) Fully qualified name of a class implementingorg.mockserver.matchers.CustomJsonUnitMatcherProvider.static booleanstatic voiddetailedMatchFailures(boolean enable) If true (the default) the log event recording that a request matcher did not match will include a detailed reason why each non matching field did not match.static booleanstatic voiddetailedVerificationFailures(boolean enable) If true (the default) verification failure messages include a detailed diff showing which fields did not match for the closest matching request.static Stringstatic voiddirectoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate) Directory used to save the dynamically generated Certificate Authority X.509 Certificate and Private Key.static booleanstatic voiddisableLogging(boolean disable) Disable all logging and processing of log eventsstatic booleanstatic voiddisableSystemOut(boolean disable) Disable printing log to system out for JVM, default is enabledstatic booleanstatic voiddnsEnabled(boolean enable) static intdnsPort()static voiddnsPort(int port) static longp95 response time threshold (in milliseconds) for performance drift detection.static voiddriftResponseTimeThresholdMs(long thresholdMs) static booleanWhether to enable LLM-powered semantic drift analysis.static voiddriftSemanticAnalysisEnabled(boolean enabled) static booleanstatic voiddynamicallyCreateCertificateAuthorityCertificate(boolean enable) Enable dynamic creation of Certificate Authority X509 certificate and private key.static booleanstatic voidenableCORSForAllResponses(boolean enable) Enable CORS for all responses from MockServer, including the REST API and expectation responsesstatic booleanstatic voidenableCORSForAPI(boolean enable) Enable CORS for MockServer REST API so that the API can be used for javascript running in browsers, such as seleniumstatic StringComma-separated JSON field names whose values are redacted from recorded fixture request/response bodies (in addition to the always-redacted sensitive headers).static voidfixtureBodyRedactFields(String fields) static booleanstatic voidforwardAdjustHostHeader(boolean enable) If true (the default) the Host header will be automatically adjusted to match the target server when forwarding requests.static booleanstatic voidforwardBinaryRequestsWithoutWaitingForResponse(boolean forwardBinaryRequestsAsynchronously) If true the BinaryRequestProxyingHandler.binaryExchangeCallback is called before a response is received from the remote host.static Stringstatic voidforwardDefaultHostHeader(String hostHeader) static InetSocketAddressstatic voidforwardHttpProxy(String hostAndPort) Use HTTP proxy (i.e. via Host header) for all outbound / forwarded requestsstatic voidforwardHttpProxy(InetSocketAddress hostAndPort) Use HTTP proxy (i.e. via Host header) for all outbound / forwarded requestsstatic InetSocketAddressstatic voidforwardHttpsProxy(String hostAndPort) Use HTTPS proxy (i.e.static voidforwardHttpsProxy(InetSocketAddress hostAndPort) Use HTTPS proxy (i.e.static Stringstatic voidforwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword) Password for proxy authentication when using HTTPS proxy (i.e.static Stringstatic voidforwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername) Username for proxy authentication when using HTTPS proxy (i.e.static booleanstatic voidforwardProxyBlockPrivateNetworks(boolean block) When set to true, MockServer rejects forward and proxy targets that resolve to loopback, link-local, RFC 1918 private, or cloud metadata addresses (such as 169.254.169.254).static Stringstatic voidforwardProxyCertificateChain(String certificateChain) File system path or classpath location of custom mTLS (TLS client authentication) X.509 Certificate Chain for Trusting (i.e. signature verification of) Client X.509 Certificates, the certificate chain must be a X509 PEM file.static Stringstatic voidforwardProxyPrivateKey(String privateKey) File system path or classpath location of custom Private Key for proxied TLS connections out of MockServer, the private key must be a PKCS#8 or PKCS#1 PEM filestatic Stringstatic voidforwardProxyTLSCustomTrustX509Certificates(String customX509Certificates) File system path or classpath location of custom file for trusted X509 Certificate Authority roots for forwarded or proxied requests, the certificate chain must be a X509 PEM file.static voidforwardProxyTLSX509CertificatesTrustManagerType(ForwardProxyTLSX509CertificatesTrustManager trustManagerType) Configure trusted set of certificates for forwarded or proxied requests.static InetSocketAddressstatic voidforwardSocksProxy(String hostAndPort) Use SOCKS proxy for all outbound / forwarded requests, support TLS tunnelling of TCP connectionsstatic voidforwardSocksProxy(InetSocketAddress hostAndPort) Use SOCKS proxy for all outbound / forwarded requests, support TLS tunnelling of TCP connectionsstatic Longstatic voidglobalResponseDelayMillis(Long millis) static booleanstatic voidgrpcBidiStreamingEnabled(boolean enable) If true the HTTP/2 pipeline uses Http2FrameCodec + Http2MultiplexHandler instead of HttpToHttp2ConnectionHandler + InboundHttp2ToHttpAdapter for connections where gRPC descriptors are loaded.static Stringstatic voidgrpcDescriptorDirectory(String directory) static booleanstatic voidgrpcEnabled(boolean enable) static Stringstatic voidgrpcProtocPath(String path) static Stringstatic voidgrpcProtoDirectory(String directory) static longstatic booleanstatic voidhttp2Enabled(boolean http2Enabled) If false HTTP/2 is disabled and ALPN no longer advertises h2, so HTTP/2 capable clients are forced to use HTTP/1.1 (and the HTTP/2 cleartext h2c upgrade is not detected)static booleanWhether to add anAlt-Svc: h3=":<http3Port>"; ma=<maxAge>header to every response served over the TCP (HTTP/1.1 and HTTP/2) paths whenhttp3Port > 0.static voidhttp3AdvertiseAltSvc(boolean advertise) static longMax-age in seconds for the Alt-Svc header advertising HTTP/3 on the TCP response path.static voidhttp3AltSvcMaxAge(long seconds) static booleanEnable the CONNECT-UDP (MASQUE, RFC 9298) forward proxy on the HTTP/3 server.static voidhttp3ConnectUdpEnabled(boolean enabled) static longInitial maximum data (connection-level flow control) in bytes.static voidhttp3InitialMaxData(long bytes) static longInitial maximum stream data for bidirectional streams (per-stream flow control) in bytes.static voidhttp3InitialMaxStreamDataBidirectional(long bytes) static longInitial maximum number of concurrent bidirectional streams.static voidhttp3InitialMaxStreamsBidirectional(long maxStreams) static longMax idle timeout in milliseconds for QUIC connections.static voidhttp3MaxIdleTimeout(long millis) static intstatic voidhttp3Port(int port) static longQPACK dynamic table maximum capacity in bytes.static voidhttp3QpackMaxTableCapacity(long bytes) static Stringstatic voidinitializationClass(String initializationClass) The class (and package) used to initialize expectations in MockServer at startup, if set MockServer will load and call this class to initialise expectations when is starts.static Stringstatic voidinitializationJsonPath(String initializationJsonPath) The path to the json file used to initialize expectations in MockServer at startup, if set MockServer will load this file and initialise expectations for each item in the file when is starts.static Stringstatic voidinitializationOpenAPIPath(String initializationOpenAPIPath) The path to the OpenAPI spec file used to initialize expectations in MockServer at startup, if set MockServer will load this file and create expectations for each operation when it starts.static Stringstatic Stringstatic voidjavascriptDisallowedClasses(String javascriptDisallowedClasses) Set comma separate list of classes not allowed to be used by javascript templatesstatic Stringstatic voidjavascriptDisallowedText(String javascriptDisallowedText) Set comma separate list of text not allowed to be contained in javascript templatesstatic booleanstatic voidlaunchUIForLogLevelDebug(boolean enable) If true (the default) the ClientAndServer constructor will open the UI in the default browser when the log level is set to DEBUG.static Stringstatic voidlivenessHttpGetPath(String livenessPath) Path to support HTTP GET requests for status response (also available on PUT /mockserver/status).static StringAPI key (secret) for the default runtime-LLM backend.static voidstatic StringPath to a JSON file declaring named runtime-LLM backends (layer 3 of backend resolution).static voidllmBackendsConfig(String path) static StringBase URL override for the default runtime-LLM backend; empty means the per-provider default applies.static voidllmBaseUrl(String baseUrl) static StringllmModel()Model for the default runtime-LLM backend; empty means the per-provider default applies.static voidstatic StringProvider type for the default runtime-LLM backend (one of theProviderenum names).static voidllmProvider(String provider) static longPer-request timeout (milliseconds) for outbound runtime-LLM calls.static voidllmRequestTimeoutMillis(long millis) static booleanOpt-in switch for fuzzy, LLM-judged semantic prompt matching (thesemanticMatchconversation predicate).static voidllmSemanticMatchingEnabled(boolean enabled) static booleanWhen true, loading LLM fixtures in strict VCR mode registers a low-priority catch-all per cassette path so a request that matches no recorded entry fails loudly (HTTP 599) instead of falling through.static voidllmVcrStrict(boolean strict) static Stringstatic voidlocalBoundIP(String localBoundIP) The local IP address to bind to for accepting new socket connectionsstatic org.slf4j.event.LevellogLevel()static voidOverride the default logging level of INFOstatic voidlogLevelOverrides(Map<String, String> overrides) Override the log level for specific log message type categories or individual log message types.static booleanstatic voidmatchersFailFast(boolean enable) If true (the default) request matchers will fail on the first non-matching field, if false request matchers will compare all fields.static intstatic voidmaxChunkSize(int size) Maximum size of HTTP chunks in request or responsesstatic intstatic voidmaxExpectations(int count) Maximum number of expectations stored in memory.static longstatic voidmaxFutureTimeout(long milliseconds) Maximum time allowed in milliseconds for any future to wait, for example when waiting for a response over a web socket callback.static intstatic voidmaxHeaderSize(int size) Maximum size of HTTP request headersstatic Integerstatic voidmaximumNumberOfRequestToReturnInVerificationFailure(Integer maximumNumberOfRequestToReturnInVerification) The maximum number of requests to return in verification failure result, if more expectations are found the failure result does not list them separatelystatic intstatic voidmaxInitialLineLength(int length) Maximum size of the first line of an HTTP requeststatic intstatic voidmaxLlmConversationBodySize(int size) Maximum body size (in bytes) for LLM conversation request bodies.static intstatic voidmaxLogEntries(int count) Maximum number of log entries stored in memory.static intstatic voidmaxRequestBodySize(int size) Maximum aggregated body size (in bytes) accepted on inbound HTTP/1.1 and HTTP/2 requests before MockServer responds with 413 Payload Too Large.static intstatic voidmaxResponseBodySize(int size) Maximum aggregated body size (in bytes) accepted on responses received from upstream servers when MockServer is acting as a proxy or forwarder.static longstatic voidmaxSocketTimeout(long milliseconds) Maximum time in milliseconds allowed for a response from a socketstatic intstatic voidmaxStreamingCaptureBytes(int bytes) The maximum number of bytes of a streaming response body captured into the event log while relaying it.static intstatic voidmaxWebSocketExpectations(int count) Maximum number of remote (not the same JVM) method callbacks (i.e. web sockets) registered for expectations.static booleanstatic voidmcpEnabled(boolean enable) Enable or disable the MCP (Model Context Protocol) endpoint, default is truestatic Stringstatic voidmemoryUsageCsvDirectory(String directory) Directory to output JVM memory usage metrics CSV files to when outputMemoryUsageCsv enabledstatic booleanstatic voidmetricsEnabled(boolean enable) Enable gathering of metrics, default is falsestatic booleanstatic voidmetricsRequestDurationRouteLabels(boolean enable) Enable per-route (HTTP method) latency metrics.static Stringstatic voidmustacheDisallowedText(String mustacheDisallowedText) Set comma separate list of text not allowed to be contained in mustache templatesstatic intstatic voidnioEventLoopThreadCount(int count) Netty worker thread pool size for handling requests and response.static Stringstatic voidnoProxyHosts(String noProxyHosts) The list of hostnames to not use the configured proxy.static Stringstatic voidopenAPIContextPathPrefix(String openAPIContextPathPrefix) A path prefix to add to all paths generated from OpenAPI specifications.static booleanstatic voidopenAPIResponseValidation(boolean enable) If enabled MockServer will validate that mock responses conform to the OpenAPI spec schema they were generated from.static StringBase OTLP HTTP endpoint for the collector (e.g.static voidotelEndpoint(String endpoint) static booleanWhen true, MockServer generates a new W3C trace ID for incoming requests that do not carry atraceparentheader.static voidotelGenerateTraceId(boolean enabled) static booleanWhen true, MockServer's explicitly-defined metrics (the same gauges exposed for Prometheus) are also exported via OpenTelemetry OTLP.static voidotelMetricsEnabled(boolean enabled) static longHow often (seconds) OTel metrics are exported.static voidotelMetricsExportIntervalSeconds(long seconds) static booleanWhen true, MockServer copies the incoming W3Ctraceparentandtracestateheaders into mock responses.static voidotelPropagateTraceContext(boolean enabled) static booleanWhen true, MockServer emits explicit GenAI semantic-convention spans for LLM traffic it serves (one span per completion, carrying provider, model, token usage and finish reason) via OpenTelemetry OTLP.static voidotelTracesEnabled(boolean enabled) static booleanstatic voidoutputMemoryUsageCsv(boolean enable) Output JVM memory usage metrics to CSV file periodically called memoryUsage_<yyyy-MM-dd>.csvstatic Stringstatic voidpersistedExpectationsPath(String persistedExpectationsPath) The file path used to save persisted expectations as json, which is updated whenever the expectation state is updated (i.e. add, clear, expires, etc)static Stringstatic voidpersistedRecordedExpectationsPath(String persistedRecordedExpectationsPath) The file path used to save persisted recorded expectations as json, which is updated whenever a new request is forwardedstatic booleanstatic voidpersistExpectations(boolean enable) Enable the persisting of expectations as json, which is updated whenever the expectation state is updated (i.e. add, clear, expires, etc)static booleanstatic voidpersistRecordedExpectations(boolean enable) Enable the persisting of recorded expectations (proxy traffic) as json, which is updated whenever a new request is forwardedstatic booleanstatic voidpreventCertificateDynamicUpdate(boolean prevent) Prevent certificates from dynamically updating when domain list changesstatic Stringstatic voidprivateKeyPath(String privateKeyPath) File system path or classpath location of a fixed custom private key for TLS connections into MockServer.static booleanstatic voidproactivelyInitialiseTLS(boolean enable) Proactively initialise TLS during start to ensure that if dynamicallyCreateCertificateAuthorityCertificate is enabled the Certificate Authority X.509 Certificate and Private Key will be created during start up and not when the first TLS connection is received.static Stringstatic voidproxyAuthenticationPassword(String proxyAuthenticationPassword) The required password for proxy authentication to MockServerstatic Stringstatic voidproxyAuthenticationRealm(String proxyAuthenticationRealm) The authentication realm for proxy authentication to MockServerstatic Stringstatic voidproxyAuthenticationUsername(String proxyAuthenticationUsername) The required username for proxy authentication to MockServerstatic List<ProxyPassMapping>static voidConfigure ProxyPass mappings that map incoming path prefixes to upstream servers with automatic path rewriting.static voidproxyPass(List<ProxyPassMapping> mappings) Configure ProxyPass mappings that map incoming path prefixes to upstream servers with automatic path rewriting.static Stringstatic voidproxyRemoteHost(String proxyRemoteHost) static Integerstatic voidproxyRemotePort(Integer proxyRemotePort) static longstatic voidregexMatchingTimeoutMillis(long milliseconds) Maximum time (in milliseconds) allowed for evaluating a single regular expression during request matching.static longstatic voidslowRequestThresholdMillis(long milliseconds) Threshold in milliseconds for flagging slow forwarded requests.static longstatic voidsocketConnectionTimeout(long milliseconds) Maximum time in milliseconds allowed to connect to a socketstatic Stringstatic voidsslCertificateDomainName(String domainName) The domain name for auto-generate TLS certificatesstatic voidsslSubjectAlternativeNameDomains(Set<String> sslSubjectAlternativeNameDomains) The Subject Alternative Name (SAN) domain names for auto-generate TLS certificates as a comma separated liststatic voidsslSubjectAlternativeNameIps(Set<String> sslSubjectAlternativeNameIps) The Subject Alternative Name (SAN) IP addresses for auto-generate TLS certificates as a comma separated liststatic StringReturns the state backend type.static voidstateBackend(String stateBackend) Sets the state backend type.static intstatic voidstreamIdleTimeoutSeconds(int seconds) The maximum time in seconds a streaming response connection may be idle (no chunk received) before it is considered dead and closed.static booleanstatic voidstreamingResponsesEnabled(boolean enable) If true (the default) streaming responses (Server-Sent Events withContent-Type: text/event-stream) received while proxying are relayed to the client incrementally as they arrive, instead of being fully buffered before being forwarded.static voidtemporaryLogLevel(String level, Runnable runnable) static booleanstatic voidtlsAllowInsecureProtocols(boolean allow) Whether to allow TLSv1 and TLSv1.1 in the effective TLS protocols list.static Stringstatic voidtlsMutualAuthenticationCertificateChain(String trustCertificateChain) File system path or classpath location of custom mTLS (TLS client authentication) X.509 Certificate Chain for trusting (i.e. signature verification of) Client X.509 Certificates, the certificate chain must be a X509 PEM file.static booleanstatic voidtlsMutualAuthenticationRequired(boolean enable) Require mTLS (also called client authentication and two-way TLS) for all TLS connections / HTTPS requests to MockServerstatic Stringstatic voidtlsProtocols(String tlsProtocols) Comma seperated list of TLS protocols, by default TLSv1,TLSv1.1,TLSv1.2static booleanEnable eBPF-based original destination resolution.static voidtransparentProxyEbpf(boolean enable) static StringPath to the pinned BPF map used by the eBPF original destination resolver.static voidstatic booleanstatic voidtransparentProxyEnabled(boolean enable) static booleanEnable TPROXY (IP_TRANSPARENT) mode for transparent proxy original destination resolution.static voidtransparentProxyTproxy(boolean enable) static booleanstatic voiduseNativeTransport(boolean enable) If true (the default) MockServer will use the native epoll transport on Linux for higher performance and to enable transparent-proxy SO_ORIGINAL_DST resolution.static booleanstatic voiduseSemicolonAsQueryParameterSeparator(boolean useAsQueryParameterSeparator) If true semicolons are treated as a separator for a query parameter string, if false the semicolon is treated as a normal character that is part of a query parameter value.static booleanstatic voidvelocityDisallowClassLoading(boolean velocityDisallowClassLoading) If true class loading is not allowed in velocity templatesstatic Stringstatic voidvelocityDisallowedText(String velocityDisallowedText) Set comma separate list of text not allowed to be contained in velocity templatesstatic booleanstatic voidwasmEnabled(boolean enable) static intstatic voidwasmMaxMemoryPages(int pages) static booleanstatic voidwatchInitializationJson(boolean enable) If enabled the initialization json file will be watched for changes, any changes found will result in expectations being created, remove or updated by matching against their key.static intstatic voidwebSocketClientEventLoopThreadCount(int count) Web socket thread pool size for expectations with remote (not the same JVM) method callbacks (i.e. web sockets).static Stringstatic voidx509CertificatePath(String x509CertificatePath) File system path or classpath location of a fixed custom X.509 Certificate for TLS connections into MockServer.static longstatic voidxpathMatchingTimeoutMillis(long milliseconds) Maximum time (in milliseconds) allowed for evaluating a single XPath expression against an XML document during request matching.
-
Field Details
-
DEFAULT_CERTIFICATE_AUTHORITY_PRIVATE_KEY
- See Also:
-
DEFAULT_CERTIFICATE_AUTHORITY_X509_CERTIFICATE
- See Also:
-
PROPERTIES
-
-
Constructor Details
-
ConfigurationProperties
public ConfigurationProperties()
-
-
Method Details
-
logLevel
public static org.slf4j.event.Level logLevel() -
javaLoggerLogLevel
-
logLevel
Override the default logging level of INFO- Parameters:
level- the log level, which can be TRACE, DEBUG, INFO, WARN, ERROR, OFF, FINEST, FINE, INFO, WARNING, SEVERE
-
temporaryLogLevel
-
disableSystemOut
public static boolean disableSystemOut() -
disableSystemOut
public static void disableSystemOut(boolean disable) Disable printing log to system out for JVM, default is enabled- Parameters:
disable- printing log to system out for JVM
-
disableLogging
public static boolean disableLogging() -
disableLogging
public static void disableLogging(boolean disable) Disable all logging and processing of log eventsThe default is false
- Parameters:
disable- disable all logging
-
detailedMatchFailures
public static boolean detailedMatchFailures() -
detailedMatchFailures
public static void detailedMatchFailures(boolean enable) If true (the default) the log event recording that a request matcher did not match will include a detailed reason why each non matching field did not match.- Parameters:
enable- enabled detailed match failure log events
-
launchUIForLogLevelDebug
public static boolean launchUIForLogLevelDebug() -
launchUIForLogLevelDebug
public static void launchUIForLogLevelDebug(boolean enable) If true (the default) the ClientAndServer constructor will open the UI in the default browser when the log level is set to DEBUG.- Parameters:
enable- enabled ClientAndServer constructor launching UI when log level is DEBUG
-
metricsEnabled
public static boolean metricsEnabled() -
metricsEnabled
public static void metricsEnabled(boolean enable) Enable gathering of metrics, default is false- Parameters:
enable- enable metrics
-
slowRequestThresholdMillis
public static long slowRequestThresholdMillis() -
slowRequestThresholdMillis
public static void slowRequestThresholdMillis(long milliseconds) Threshold in milliseconds for flagging slow forwarded requests. When a forwarded request's total time exceeds this threshold, a WARN-level log entry is emitted and themock_server_slow_requests_totalPrometheus counter is incremented.Default is 0 (disabled).
- Parameters:
milliseconds- threshold in milliseconds, 0 to disable
-
metricsRequestDurationRouteLabels
public static boolean metricsRequestDurationRouteLabels() -
metricsRequestDurationRouteLabels
public static void metricsRequestDurationRouteLabels(boolean enable) Enable per-route (HTTP method) latency metrics. When enabled, an additional histogrammock_server_request_duration_by_method_secondsis registered with amethodlabel for the HTTP method (GET, POST, etc.), alongside the unlabelledmock_server_request_duration_seconds. Default is false (no labelled histogram).Cardinality is bounded to the set of standard HTTP methods.
- Parameters:
enable- enable method labels on the request duration histogram
-
mcpEnabled
public static boolean mcpEnabled() -
mcpEnabled
public static void mcpEnabled(boolean enable) Enable or disable the MCP (Model Context Protocol) endpoint, default is true- Parameters:
enable- enable MCP endpoint
-
wasmEnabled
public static boolean wasmEnabled() -
wasmEnabled
public static void wasmEnabled(boolean enable) -
wasmMaxMemoryPages
public static int wasmMaxMemoryPages() -
wasmMaxMemoryPages
public static void wasmMaxMemoryPages(int pages) -
grpcDescriptorDirectory
-
grpcDescriptorDirectory
-
grpcProtoDirectory
-
grpcProtoDirectory
-
grpcEnabled
public static boolean grpcEnabled() -
grpcEnabled
public static void grpcEnabled(boolean enable) -
grpcProtocPath
-
grpcProtocPath
-
grpcBidiStreamingEnabled
public static boolean grpcBidiStreamingEnabled() -
grpcBidiStreamingEnabled
public static void grpcBidiStreamingEnabled(boolean enable) If true the HTTP/2 pipeline uses Http2FrameCodec + Http2MultiplexHandler instead of HttpToHttp2ConnectionHandler + InboundHttp2ToHttpAdapter for connections where gRPC descriptors are loaded. This is required for true client-streaming and bidirectional-streaming gRPC in a future phase. In Phase 0 the multiplex branch re-aggregates frames so behaviour is identical to the connection-level adapter.Requires gRPC descriptors to be loaded (grpcEnabled with descriptors present). When false (the default) or when no descriptors are loaded, the existing connection-level adapter is used.
Default is false
- Parameters:
enable- enable the multiplex HTTP/2 pipeline for gRPC bidi-streaming support
-
dnsEnabled
public static boolean dnsEnabled() -
dnsEnabled
public static void dnsEnabled(boolean enable) -
dnsPort
public static int dnsPort() -
dnsPort
public static void dnsPort(int port) -
http3Port
public static int http3Port() -
http3Port
public static void http3Port(int port) -
http3MaxIdleTimeout
public static long http3MaxIdleTimeout()Max idle timeout in milliseconds for QUIC connections. Default: 5000 (5 seconds). -
http3MaxIdleTimeout
public static void http3MaxIdleTimeout(long millis) -
http3InitialMaxData
public static long http3InitialMaxData()Initial maximum data (connection-level flow control) in bytes. Default: 10000000 (10 MB). -
http3InitialMaxData
public static void http3InitialMaxData(long bytes) -
http3InitialMaxStreamDataBidirectional
public static long http3InitialMaxStreamDataBidirectional()Initial maximum stream data for bidirectional streams (per-stream flow control) in bytes. Applied to both local and remote bidirectional streams. Default: 1000000 (1 MB). -
http3InitialMaxStreamDataBidirectional
public static void http3InitialMaxStreamDataBidirectional(long bytes) -
http3InitialMaxStreamsBidirectional
public static long http3InitialMaxStreamsBidirectional()Initial maximum number of concurrent bidirectional streams. Default: 100. -
http3InitialMaxStreamsBidirectional
public static void http3InitialMaxStreamsBidirectional(long maxStreams) -
http3QpackMaxTableCapacity
public static long http3QpackMaxTableCapacity()QPACK dynamic table maximum capacity in bytes. Controls the amount of memory allocated for QPACK header compression on the HTTP/3 control stream. Set to 0 to disable the dynamic table entirely. Default: 0 (dynamic table disabled — only static table used). -
http3QpackMaxTableCapacity
public static void http3QpackMaxTableCapacity(long bytes) -
http3ConnectUdpEnabled
public static boolean http3ConnectUdpEnabled()Enable the CONNECT-UDP (MASQUE, RFC 9298) forward proxy on the HTTP/3 server. When enabled, the server advertisesSETTINGS_ENABLE_CONNECT_PROTOCOL(RFC 9220) and extended-CONNECT requests with:protocol=connect-udpare relayed: a UDP socket is opened to the target authority and datagrams are forwarded in both directions (one HTTP/3 DATA frame per datagram). This is supported by the mainlineio.netty:netty-codec-http3codec (Netty 4.2). Normal (non-CONNECT) HTTP/3 requests are unaffected.Experimental and off by default. When enabled this is an open UDP relay with no target restriction (a client can reach any UDP host:port reachable from the server, including private/loopback/cloud-metadata addresses) — intended for controlled test environments only; do not expose to untrusted clients. Default: false (disabled).
-
http3ConnectUdpEnabled
public static void http3ConnectUdpEnabled(boolean enabled) -
http3AltSvcMaxAge
public static long http3AltSvcMaxAge()Max-age in seconds for the Alt-Svc header advertising HTTP/3 on the TCP response path. Only relevant whenhttp3Port > 0andhttp3AdvertiseAltSvcistrue. Default: 86400 (24 hours). -
http3AltSvcMaxAge
public static void http3AltSvcMaxAge(long seconds) -
http3AdvertiseAltSvc
public static boolean http3AdvertiseAltSvc()Whether to add anAlt-Svc: h3=":<http3Port>"; ma=<maxAge>header to every response served over the TCP (HTTP/1.1 and HTTP/2) paths whenhttp3Port > 0. Whenfalse, no Alt-Svc header is added even when HTTP/3 is enabled (useful for testing without client auto-upgrade). Default: true. -
http3AdvertiseAltSvc
public static void http3AdvertiseAltSvc(boolean advertise) -
transparentProxyEnabled
public static boolean transparentProxyEnabled() -
transparentProxyEnabled
public static void transparentProxyEnabled(boolean enable) -
transparentProxyTproxy
public static boolean transparentProxyTproxy()Enable TPROXY (IP_TRANSPARENT) mode for transparent proxy original destination resolution. When enabled, the listener socket is bound with IP_TRANSPARENT and the original destination is read from the socket's local address (preserved by the TPROXY iptables target). Requires Linux, epoll transport, CAP_NET_ADMIN, and TPROXY iptables rules instead of REDIRECT. Default: false. -
transparentProxyTproxy
public static void transparentProxyTproxy(boolean enable) -
transparentProxyEbpf
public static boolean transparentProxyEbpf()Enable eBPF-based original destination resolution. When enabled, the resolver reads from a pinned BPF hash map (populated by an external cgroup/connect4 BPF program) keyed by socket cookie. Requires Linux, CAP_BPF, a BTF-enabled kernel, and the external BPF program. Default: false. -
transparentProxyEbpf
public static void transparentProxyEbpf(boolean enable) -
transparentProxyEbpfMapPath
Path to the pinned BPF map used by the eBPF original destination resolver. The map must be a BPF hash map with u64 key (socket cookie) and 6-byte value (4-byte IPv4 address + 2-byte port in network byte order). Default: /sys/fs/bpf/mockserver_orig_dst. -
transparentProxyEbpfMapPath
-
asyncKafkaBootstrapServers
Default Kafka bootstrap servers used when aPUT /mockserver/asyncapirequest body does not includebrokerConfig.kafkaBootstrapServers. Empty string means no default (broker must be specified per-request). -
asyncKafkaBootstrapServers
-
asyncMqttBrokerUrl
Default MQTT broker URL used when aPUT /mockserver/asyncapirequest body does not includebrokerConfig.mqttBrokerUrl. Empty string means no default (broker must be specified per-request). -
asyncMqttBrokerUrl
-
asyncRecordedMessageMaxEntries
public static int asyncRecordedMessageMaxEntries()Maximum number of recorded messages retained per channel in async messaging subscribers. Default is 1000. -
asyncRecordedMessageMaxEntries
public static void asyncRecordedMessageMaxEntries(int maxEntries) -
logLevelOverrides
-
logLevelOverrides
Override the log level for specific log message type categories or individual log message types.Keys can be category group names (MATCHING, REQUEST_LIFECYCLE, EXPECTATION_MANAGEMENT, VERIFICATION, SERVER, GENERAL) or individual LogMessageType names (e.g., EXPECTATION_NOT_MATCHED, FORWARDED_REQUEST). Values are SLF4J log level names (TRACE, DEBUG, INFO, WARN, ERROR). Resolution order: individual type override > category group override > global logLevel.
- Parameters:
overrides- map of category/type names to log level names
-
compactLogFormat
public static boolean compactLogFormat() -
compactLogFormat
public static void compactLogFormat(boolean enable) When enabled, log messages written to stdout/SLF4J use a compact single-line format showing summary information (e.g., method, path, status code, expectation ID) instead of full JSON-serialized request and response details. The dashboard UI, verification, and log retrieval APIs are not affected.- Parameters:
enable- enable compact log format
-
heapAvailableInKB
public static long heapAvailableInKB() -
maxExpectations
public static int maxExpectations() -
maxExpectations
public static void maxExpectations(int count) Maximum number of expectations stored in memory. Expectations are stored in a circular queue so once this limit is reach the oldest and lowest priority expectations are overwritten
The default maximum depends on the available memory in the JVM with an upper limit of 15000
- Parameters:
count- maximum number of expectations to store
-
maxLogEntries
public static int maxLogEntries() -
maxLogEntries
public static void maxLogEntries(int count) Maximum number of log entries stored in memory. Log entries are stored in a circular queue so once this limit is reach the oldest log entries are overwritten.
The default maximum depends on the available memory in the JVM with an upper limit of 100000, but can be overridden using defaultMaxLogEntries
- Parameters:
count- maximum number of expectations to store
-
maxWebSocketExpectations
public static int maxWebSocketExpectations() -
maxWebSocketExpectations
public static void maxWebSocketExpectations(int count) Maximum number of remote (not the same JVM) method callbacks (i.e. web sockets) registered for expectations. The web socket client registry entries are stored in a circular queue so once this limit is reach the oldest are overwritten.
The default is 1500
- Parameters:
count- maximum number of method callbacks (i.e. web sockets) registered for expectations
-
outputMemoryUsageCsv
public static boolean outputMemoryUsageCsv() -
outputMemoryUsageCsv
public static void outputMemoryUsageCsv(boolean enable) Output JVM memory usage metrics to CSV file periodically called memoryUsage_<yyyy-MM-dd>.csv
- Parameters:
enable- output of JVM memory metrics
-
memoryUsageCsvDirectory
-
memoryUsageCsvDirectory
Directory to output JVM memory usage metrics CSV files to when outputMemoryUsageCsv enabled
- Parameters:
directory- directory to save JVM memory metrics CSV files
-
useNativeTransport
public static boolean useNativeTransport() -
useNativeTransport
public static void useNativeTransport(boolean enable) If true (the default) MockServer will use the native epoll transport on Linux for higher performance and to enable transparent-proxy SO_ORIGINAL_DST resolution. Set to false to force the NIO transport on all platforms.This property is read at start-up only.
- Parameters:
enable- enable native transport when available
-
nioEventLoopThreadCount
public static int nioEventLoopThreadCount() -
nioEventLoopThreadCount
public static void nioEventLoopThreadCount(int count) Netty worker thread pool size for handling requests and response. These threads are used for fast non-blocking activities such as, reading and de-serialise all requests and responses.
- Parameters:
count- Netty worker thread pool size
-
actionHandlerThreadCount
public static int actionHandlerThreadCount() -
actionHandlerThreadCount
public static void actionHandlerThreadCount(int count) Number of threads for the action handler thread pool
These threads are used for handling actions such as:
- serialising and writing expectation or proxied responses
- handling response delays in a non-blocking way (i.e. using a scheduler)
- executing class callbacks
- handling method / closure callbacks (using web sockets)
Default is maximum of 5 or available processors count
- Parameters:
count- Netty worker thread pool size
-
clientNioEventLoopThreadCount
public static int clientNioEventLoopThreadCount() -
clientNioEventLoopThreadCount
public static void clientNioEventLoopThreadCount(int count) Client Netty worker thread pool size for handling requests and response. These threads handle deserializing and serialising HTTP requests and responses and some other fast logic.
Default is 5 threads
- Parameters:
count- Client Netty worker thread pool size
-
webSocketClientEventLoopThreadCount
public static int webSocketClientEventLoopThreadCount() -
webSocketClientEventLoopThreadCount
public static void webSocketClientEventLoopThreadCount(int count) Web socket thread pool size for expectations with remote (not the same JVM) method callbacks (i.e. web sockets).
Default is 5 threads
- Parameters:
count- web socket worker thread pool size
-
maxFutureTimeout
public static long maxFutureTimeout() -
maxFutureTimeout
public static void maxFutureTimeout(long milliseconds) Maximum time allowed in milliseconds for any future to wait, for example when waiting for a response over a web socket callback.Default is 90,000 ms
- Parameters:
milliseconds- maximum time allowed in milliseconds
-
matchersFailFast
public static boolean matchersFailFast() -
matchersFailFast
public static void matchersFailFast(boolean enable) If true (the default) request matchers will fail on the first non-matching field, if false request matchers will compare all fields. This is useful to see all mismatching fields in the log event recording that a request matcher did not match.- Parameters:
enable- enabled request matchers failing fast
-
maxSocketTimeout
public static long maxSocketTimeout() -
maxSocketTimeout
public static void maxSocketTimeout(long milliseconds) Maximum time in milliseconds allowed for a response from a socketDefault is 20,000 ms
- Parameters:
milliseconds- maximum time in milliseconds allowed
-
socketConnectionTimeout
public static long socketConnectionTimeout() -
socketConnectionTimeout
public static void socketConnectionTimeout(long milliseconds) Maximum time in milliseconds allowed to connect to a socketDefault is 20,000 ms
- Parameters:
milliseconds- maximum time allowed in milliseconds
-
connectionDelayMillis
public static long connectionDelayMillis() -
connectionDelayMillis
public static void connectionDelayMillis(long milliseconds) -
alwaysCloseSocketConnections
public static void alwaysCloseSocketConnections(boolean alwaysClose) If true socket connections will always be closed after a response is returned, if false connection is only closed if request header indicate connection should be closed.
Default is false
- Parameters:
alwaysClose- true socket connections will always be closed after a response is returned
-
alwaysCloseSocketConnections
public static boolean alwaysCloseSocketConnections() -
streamingResponsesEnabled
public static boolean streamingResponsesEnabled() -
streamingResponsesEnabled
public static void streamingResponsesEnabled(boolean enable) If true (the default) streaming responses (Server-Sent Events withContent-Type: text/event-stream) received while proxying are relayed to the client incrementally as they arrive, instead of being fully buffered before being forwarded. This keeps streaming APIs (such as LLM APIs) responsive when proxied. Only SSE responses are detected as streaming; ordinary chunked responses are aggregated normally.Default is true
- Parameters:
enable- enable incremental relay of streaming responses while proxying
-
maxStreamingCaptureBytes
public static int maxStreamingCaptureBytes() -
maxStreamingCaptureBytes
public static void maxStreamingCaptureBytes(int bytes) The maximum number of bytes of a streaming response body captured into the event log while relaying it. The full stream is always relayed to the client; this only bounds how much is retained for the dashboard and retrieve API. Once exceeded the logged body is truncated and flagged.Default is 262144 (256 KB)
- Parameters:
bytes- maximum number of streaming response body bytes captured into the event log
-
streamIdleTimeoutSeconds
public static int streamIdleTimeoutSeconds() -
streamIdleTimeoutSeconds
public static void streamIdleTimeoutSeconds(int seconds) The maximum time in seconds a streaming response connection may be idle (no chunk received) before it is considered dead and closed. This replaces the fixed socket timeout for streaming responses, which would otherwise terminate long-lived streams.Default is 60 seconds
- Parameters:
seconds- maximum idle time in seconds between streaming response chunks
-
localBoundIP
-
localBoundIP
The local IP address to bind to for accepting new socket connectionsDefault is 0.0.0.0
- Parameters:
localBoundIP- local IP address to bind to for accepting new socket connections
-
maxInitialLineLength
public static int maxInitialLineLength() -
maxInitialLineLength
public static void maxInitialLineLength(int length) Maximum size of the first line of an HTTP requestThe default is Integer.MAX_VALUE
- Parameters:
length- maximum size of the first line of an HTTP request
-
maxHeaderSize
public static int maxHeaderSize() -
maxHeaderSize
public static void maxHeaderSize(int size) Maximum size of HTTP request headersThe default is Integer.MAX_VALUE
- Parameters:
size- maximum size of HTTP request headers
-
maxChunkSize
public static int maxChunkSize() -
maxChunkSize
public static void maxChunkSize(int size) Maximum size of HTTP chunks in request or responsesThe default is Integer.MAX_VALUE
- Parameters:
size- maximum size of HTTP chunks in request or responses
-
maxRequestBodySize
public static int maxRequestBodySize() -
maxRequestBodySize
public static void maxRequestBodySize(int size) Maximum aggregated body size (in bytes) accepted on inbound HTTP/1.1 and HTTP/2 requests before MockServer responds with 413 Payload Too Large.The default is 10,485,760 bytes (10 MiB). Raise this only if you intentionally mock large uploads; very large limits make MockServer susceptible to memory exhaustion.
- Parameters:
size- maximum inbound request body size in bytes
-
maxResponseBodySize
public static int maxResponseBodySize() -
maxResponseBodySize
public static void maxResponseBodySize(int size) Maximum aggregated body size (in bytes) accepted on responses received from upstream servers when MockServer is acting as a proxy or forwarder.The default is 52,428,800 bytes (50 MiB).
- Parameters:
size- maximum upstream response body size in bytes
-
maxLlmConversationBodySize
public static int maxLlmConversationBodySize() -
maxLlmConversationBodySize
public static void maxLlmConversationBodySize(int size) Maximum body size (in bytes) for LLM conversation request bodies.The default is 1,048,576 bytes (1 MiB). Valid range is [16384, 67108864]. Values outside this range are silently clamped.
- Parameters:
size- maximum LLM conversation body size in bytes
-
llmProvider
Provider type for the default runtime-LLM backend (one of theProviderenum names). Runtime-LLM features (drift detection, semantic matching) are off unless a backend resolves; this is layer 2 of backend resolution (single default backend). Empty by default. -
llmProvider
-
llmApiKey
API key (secret) for the default runtime-LLM backend. Never logged or emitted in config dumps — seeLlmBackend. -
llmApiKey
-
llmModel
Model for the default runtime-LLM backend; empty means the per-provider default applies. -
llmModel
-
llmBaseUrl
Base URL override for the default runtime-LLM backend; empty means the per-provider default applies. -
llmBaseUrl
-
llmBackendsConfig
Path to a JSON file declaring named runtime-LLM backends (layer 3 of backend resolution). Empty by default. -
llmBackendsConfig
-
llmRequestTimeoutMillis
public static long llmRequestTimeoutMillis()Per-request timeout (milliseconds) for outbound runtime-LLM calls. A backend's owntimeoutMillisoverrides this. Default 30000. -
llmRequestTimeoutMillis
public static void llmRequestTimeoutMillis(long millis) -
driftSemanticAnalysisEnabled
public static boolean driftSemanticAnalysisEnabled()Whether to enable LLM-powered semantic drift analysis. When enabled and a runtime LLM backend is available, each structural drift record is enriched with a severity classification (BREAKING / WARNING / INFORMATIONAL) and an explanation from the LLM. Default false (opt-in). -
driftSemanticAnalysisEnabled
public static void driftSemanticAnalysisEnabled(boolean enabled) -
driftResponseTimeThresholdMs
public static long driftResponseTimeThresholdMs()p95 response time threshold (in milliseconds) for performance drift detection. When set to a positive value, a PERFORMANCE drift record is emitted whenever the p95 response time for an expectation exceeds this threshold. Default 0 (disabled). -
driftResponseTimeThresholdMs
public static void driftResponseTimeThresholdMs(long thresholdMs) -
fixtureBodyRedactFields
Comma-separated JSON field names whose values are redacted from recorded fixture request/response bodies (in addition to the always-redacted sensitive headers). Empty by default. Used byrecord_llm_fixtures. -
fixtureBodyRedactFields
-
llmVcrStrict
public static boolean llmVcrStrict()When true, loading LLM fixtures in strict VCR mode registers a low-priority catch-all per cassette path so a request that matches no recorded entry fails loudly (HTTP 599) instead of falling through. Default false. -
llmVcrStrict
public static void llmVcrStrict(boolean strict) -
otelMetricsEnabled
public static boolean otelMetricsEnabled()When true, MockServer's explicitly-defined metrics (the same gauges exposed for Prometheus) are also exported via OpenTelemetry OTLP. Off by default. No spans or auto-instrumentation are added — metrics only. -
otelMetricsEnabled
public static void otelMetricsEnabled(boolean enabled) -
otelTracesEnabled
public static boolean otelTracesEnabled()When true, MockServer emits explicit GenAI semantic-convention spans for LLM traffic it serves (one span per completion, carrying provider, model, token usage and finish reason) via OpenTelemetry OTLP. Off by default. These are spans MockServer codes deliberately — no auto-instrumentation is added. -
otelTracesEnabled
public static void otelTracesEnabled(boolean enabled) -
otelEndpoint
Base OTLP HTTP endpoint for the collector (e.g.http://localhost:4318). The/v1/metricsand/v1/tracespaths are appended per signal. Empty uses the OTLP exporter defaults (http://localhost:4318). A value that already ends in/v1/metricsor/v1/tracesis accepted and normalised to the base. -
otelEndpoint
-
otelMetricsExportIntervalSeconds
public static long otelMetricsExportIntervalSeconds()How often (seconds) OTel metrics are exported. Default 60. -
otelMetricsExportIntervalSeconds
public static void otelMetricsExportIntervalSeconds(long seconds) -
otelPropagateTraceContext
public static boolean otelPropagateTraceContext()When true, MockServer copies the incoming W3Ctraceparentandtracestateheaders into mock responses. Off by default so responses are not modified unless the user opts in. -
otelPropagateTraceContext
public static void otelPropagateTraceContext(boolean enabled) -
otelGenerateTraceId
public static boolean otelGenerateTraceId()When true, MockServer generates a new W3C trace ID for incoming requests that do not carry atraceparentheader. Off by default. -
otelGenerateTraceId
public static void otelGenerateTraceId(boolean enabled) -
llmSemanticMatchingEnabled
public static boolean llmSemanticMatchingEnabled()Opt-in switch for fuzzy, LLM-judged semantic prompt matching (thesemanticMatchconversation predicate). Off by default. Even when on, it only activates if a runtime LLM backend resolves; otherwise the predicate is ignored. Non-deterministic by nature — exploratory only, never for CI assertions. SeeSemanticMatching. -
llmSemanticMatchingEnabled
public static void llmSemanticMatchingEnabled(boolean enabled) -
regexMatchingTimeoutMillis
public static long regexMatchingTimeoutMillis() -
regexMatchingTimeoutMillis
public static void regexMatchingTimeoutMillis(long milliseconds) Maximum time (in milliseconds) allowed for evaluating a single regular expression during request matching. A pathological pattern that exceeds this budget is treated as a non-match (and a WARN log entry is written) so the server cannot be wedged by exponential regex backtracking from an attacker-controlled expectation or input.The default is 5000 milliseconds. The headroom over typical matching time keeps normal patterns well clear of the cutoff while still bounding pathological backtracking (which takes minutes to hours). Set to 0 or a negative value to disable the timeout.
- Parameters:
milliseconds- regex evaluation timeout in milliseconds
-
xpathMatchingTimeoutMillis
public static long xpathMatchingTimeoutMillis() -
xpathMatchingTimeoutMillis
public static void xpathMatchingTimeoutMillis(long milliseconds) Maximum time (in milliseconds) allowed for evaluating a single XPath expression against an XML document during request matching. Exceeding this budget is treated as a non-match and a WARN log entry is written, protecting MockServer from XPath-based denial-of-service.The default is 5000 milliseconds, well above typical XPath evaluation time, so the timeout only fires on truly pathological expressions or documents. Set to 0 or a negative value to disable the timeout.
- Parameters:
milliseconds- XPath evaluation timeout in milliseconds
-
customJsonUnitMatchersClass
-
customJsonUnitMatchersClass
Fully qualified name of a class implementingorg.mockserver.matchers.CustomJsonUnitMatcherProvider. When set, the class is instantiated via its public no-arg constructor and the matchers it returns are registered with the json-unit configuration used for JSON body matching, so expectations can reference them via the${json-unit.matches:name}placeholder (e.g.{ "price": "${json-unit.matches:largerThan}" }).Misconfigured providers (class not found, wrong type, constructor failure) are logged at WARN and ignored - JSON body matching falls back to the built-in behaviour. Changing the property at runtime causes the provider to be reloaded on the next match.
The default is the empty string (no custom matchers).
- Parameters:
customJsonUnitMatchersClass- fully qualified provider class name
-
useSemicolonAsQueryParameterSeparator
public static void useSemicolonAsQueryParameterSeparator(boolean useAsQueryParameterSeparator) If true semicolons are treated as a separator for a query parameter string, if false the semicolon is treated as a normal character that is part of a query parameter value.The default is true
- Parameters:
useAsQueryParameterSeparator- true semicolons are treated as a separator for a query parameter string
-
useSemicolonAsQueryParameterSeparator
public static boolean useSemicolonAsQueryParameterSeparator() -
assumeAllRequestsAreHttp
public static void assumeAllRequestsAreHttp(boolean assumeAllRequestsAreHttp) If true requests are assumed as binary if the method isn't one of "GET", "POST", "PUT", "HEAD", "OPTIONS", "PATCH", "DELETE", "TRACE" or "CONNECT"The default is true
- Parameters:
assumeAllRequestsAreHttp- if true requests are assumed as binary if the method isn't one of "GET", "POST", "PUT", "HEAD", "OPTIONS", "PATCH", "DELETE", "TRACE" or "CONNECT"
-
assumeAllRequestsAreHttp
public static boolean assumeAllRequestsAreHttp() -
http2Enabled
public static void http2Enabled(boolean http2Enabled) If false HTTP/2 is disabled and ALPN no longer advertises h2, so HTTP/2 capable clients are forced to use HTTP/1.1 (and the HTTP/2 cleartext h2c upgrade is not detected)The default is true
- Parameters:
http2Enabled- if false HTTP/2 is disabled and clients are forced to use HTTP/1.1
-
http2Enabled
public static boolean http2Enabled() -
forwardBinaryRequestsWithoutWaitingForResponse
public static void forwardBinaryRequestsWithoutWaitingForResponse(boolean forwardBinaryRequestsAsynchronously) If true the BinaryRequestProxyingHandler.binaryExchangeCallback is called before a response is received from the remote host. This enables the proxying of messages without a response.The default is false
- Parameters:
forwardBinaryRequestsAsynchronously- target value
-
forwardBinaryRequestsWithoutWaitingForResponse
public static boolean forwardBinaryRequestsWithoutWaitingForResponse() -
enableCORSForAPI
public static boolean enableCORSForAPI() -
enableCORSForAPI
public static void enableCORSForAPI(boolean enable) Enable CORS for MockServer REST API so that the API can be used for javascript running in browsers, such as seleniumThe default is false
- Parameters:
enable- CORS for MockServer REST API
-
enableCORSForAllResponses
public static boolean enableCORSForAllResponses() -
enableCORSForAllResponses
public static void enableCORSForAllResponses(boolean enable) Enable CORS for all responses from MockServer, including the REST API and expectation responsesThe default is false
- Parameters:
enable- CORS for all responses from MockServer
-
corsAllowOrigin
-
corsAllowOrigin
the value used for CORS in the access-control-allow-origin header.
The default is ""
- Parameters:
corsAllowOrigin- the value used for CORS in the access-control-allow-methods header
-
corsAllowMethods
-
corsAllowMethods
The value used for CORS in the access-control-allow-methods header.
The property default is blank; when blank, MockServer applies "CONNECT, DELETE, GET, HEAD, OPTIONS, POST, PUT, PATCH, TRACE" as a built-in fallback (see CORSHeaders).
- Parameters:
corsAllowMethods- the value used for CORS in the access-control-allow-methods header
-
corsAllowHeaders
-
corsAllowHeaders
the value used for CORS in the access-control-allow-headers and access-control-expose-headers headers.
In addition to this default value any headers specified in the request header access-control-request-headers also get added to access-control-allow-headers and access-control-expose-headers headers in a CORS response.
The property default is blank; when blank, MockServer applies "Allow, Content-Encoding, Content-Length, Content-Type, ETag, Expires, Last-Modified, Location, Server, Vary, Authorization" as a built-in fallback (see CORSHeaders).
- Parameters:
corsAllowHeaders- the value used for CORS in the access-control-allow-headers and access-control-expose-headers headers
-
corsAllowCredentials
public static boolean corsAllowCredentials() -
corsAllowCredentials
public static void corsAllowCredentials(boolean allow) The value used for CORS in the access-control-allow-credentials header.The default is false
- Parameters:
allow- the value used for CORS in the access-control-allow-credentials header
-
corsMaxAgeInSeconds
public static int corsMaxAgeInSeconds() -
corsMaxAgeInSeconds
public static void corsMaxAgeInSeconds(int ageInSeconds) The value used for CORS in the access-control-max-age header.The default is 0
- Parameters:
ageInSeconds- the value used for CORS in the access-control-max-age header.
-
javascriptDisallowedClasses
-
javascriptDisallowedClasses
Set comma separate list of classes not allowed to be used by javascript templatesThe default is all allowed
- Parameters:
javascriptDisallowedClasses- comma separated list of classes not allowed to be used
-
javascriptDisallowedText
-
javascriptDisallowedText
Set comma separate list of text not allowed to be contained in javascript templatesThe default is all allowed
- Parameters:
javascriptDisallowedText- comma separated list of text not allowed to be contained in javascript templates
-
velocityDisallowClassLoading
public static boolean velocityDisallowClassLoading() -
velocityDisallowClassLoading
public static void velocityDisallowClassLoading(boolean velocityDisallowClassLoading) If true class loading is not allowed in velocity templatesThe default is false
- Parameters:
velocityDisallowClassLoading- class loading is not allowed in velocity templates
-
velocityDisallowedText
-
velocityDisallowedText
Set comma separate list of text not allowed to be contained in velocity templatesThe default is all allowed
- Parameters:
velocityDisallowedText- comma separated list of text not allowed to be contained in velocity templates
-
mustacheDisallowedText
-
mustacheDisallowedText
Set comma separate list of text not allowed to be contained in mustache templatesThe default is all allowed
- Parameters:
mustacheDisallowedText- comma separated list of text not allowed to be contained in mustache templates
-
initializationClass
-
initializationClass
The class (and package) used to initialize expectations in MockServer at startup, if set MockServer will load and call this class to initialise expectations when is starts.The default is null
- Parameters:
initializationClass- class (and package) used to initialize expectations in MockServer at startup
-
initializationJsonPath
-
initializationJsonPath
The path to the json file used to initialize expectations in MockServer at startup, if set MockServer will load this file and initialise expectations for each item in the file when is starts.
The expected format of the file is a JSON array of expectations, as per the REST API format
To watch multiple files use a file globs as documented here: https://mock-server.com/mock_server/initializing_expectations.html#expectation_initializer_json_glob_patterns
- Parameters:
initializationJsonPath- path to the json file used to initialize expectations in MockServer at startup
-
initializationOpenAPIPath
-
initializationOpenAPIPath
The path to the OpenAPI spec file used to initialize expectations in MockServer at startup, if set MockServer will load this file and create expectations for each operation when it starts.
The file can be a YAML (.yaml, .yml) or JSON (.json) OpenAPI v3 specification.
To watch multiple files use file globs as documented here: https://mock-server.com/mock_server/initializing_expectations.html#expectation_initializer_json_glob_patterns
- Parameters:
initializationOpenAPIPath- path to the OpenAPI spec file used to initialize expectations in MockServer at startup
-
openAPIContextPathPrefix
-
openAPIContextPathPrefix
A path prefix to add to all paths generated from OpenAPI specifications.
For example, if set to "/api/v1" then a path "/pets" from the spec becomes "/api/v1/pets".
- Parameters:
openAPIContextPathPrefix- the path prefix to add to OpenAPI paths
-
openAPIResponseValidation
public static boolean openAPIResponseValidation() -
openAPIResponseValidation
public static void openAPIResponseValidation(boolean enable) If enabled MockServer will validate that mock responses conform to the OpenAPI spec schema they were generated from.
Validation is advisory only - responses are still returned to the client even if validation fails.
The default is false
- Parameters:
enable- if enabled mock responses will be validated against the OpenAPI spec schema
-
watchInitializationJson
public static boolean watchInitializationJson() -
watchInitializationJson
public static void watchInitializationJson(boolean enable) If enabled the initialization json file will be watched for changes, any changes found will result in expectations being created, remove or updated by matching against their key.
If duplicate keys exist only the last duplicate key in the file will be processed and all duplicates except the last duplicate will be removed.
The order of expectations in the file is the order in which they are created if they are new, however, re-ordering existing expectations does not change the order they are matched against incoming requests.
The default is false
- Parameters:
enable- if enabled the initialization json file will be watched for changes
-
persistExpectations
public static boolean persistExpectations() -
persistExpectations
public static void persistExpectations(boolean enable) Enable the persisting of expectations as json, which is updated whenever the expectation state is updated (i.e. add, clear, expires, etc)The default is false
- Parameters:
enable- the persisting of expectations as json
-
persistedExpectationsPath
-
persistedExpectationsPath
The file path used to save persisted expectations as json, which is updated whenever the expectation state is updated (i.e. add, clear, expires, etc)The default is "persistedExpectations.json"
- Parameters:
persistedExpectationsPath- file path used to save persisted expectations as json
-
persistRecordedExpectations
public static boolean persistRecordedExpectations() -
persistRecordedExpectations
public static void persistRecordedExpectations(boolean enable) Enable the persisting of recorded expectations (proxy traffic) as json, which is updated whenever a new request is forwardedThe default is false
- Parameters:
enable- the persisting of recorded expectations as json
-
persistedRecordedExpectationsPath
-
persistedRecordedExpectationsPath
The file path used to save persisted recorded expectations as json, which is updated whenever a new request is forwardedThe default is "persistedRecordedExpectations.json"
- Parameters:
persistedRecordedExpectationsPath- file path used to save persisted recorded expectations as json
-
stateBackend
Returns the state backend type. Currently only "memory" is supported (default). Phase 2b will add "infinispan" for clustered state. -
stateBackend
Sets the state backend type. Currently only "memory" is supported.- Parameters:
stateBackend- the backend type (e.g. "memory")
-
blobStoreType
Returns the blob store type. "filesystem" (default) delegates to the existing file persistence paths so on-disk behaviour is unchanged; "memory" keeps blobs in-memory only (lost on process exit). -
blobStoreType
Sets the blob store type.- Parameters:
blobStoreType- the blob store type (e.g. "memory", "filesystem")
-
blobStoreBucket
Returns the cloud blob store bucket name (S3 or GCS bucket). -
blobStoreBucket
-
blobStoreRegion
Returns the cloud blob store region (e.g. "us-east-1" for S3). -
blobStoreRegion
-
blobStoreEndpoint
Returns the cloud blob store endpoint override URL. -
blobStoreEndpoint
-
blobStoreKeyPrefix
Returns the key prefix for cloud blob store objects. -
blobStoreKeyPrefix
-
blobStoreAccessKeyId
Returns the explicit access key ID for cloud blob store authentication. -
blobStoreAccessKeyId
-
blobStoreSecretAccessKey
Returns the explicit secret access key for cloud blob store authentication. -
blobStoreSecretAccessKey
-
blobStoreContainer
Returns the Azure Blob Storage container name. -
blobStoreContainer
-
blobStoreConnectionString
Returns the Azure Blob Storage connection string. -
blobStoreConnectionString
-
blobStoreProjectId
Returns the GCS project ID. -
blobStoreProjectId
-
clusterEnabled
public static boolean clusterEnabled()Returns whether clustering is enabled. Default isfalse. -
clusterEnabled
public static void clusterEnabled(boolean clusterEnabled) Enables or disables clustering.- Parameters:
clusterEnabled- true to enable JGroups transport
-
clusterName
Returns the JGroups cluster name. Default is"mockserver-cluster". -
clusterName
Sets the JGroups cluster name.- Parameters:
clusterName- the cluster identifier
-
clusterTransportConfig
Returns the optional path to a JGroups XML transport configuration. Default is empty string (use the built-in embedded stack). Empty string is used instead ofnullbecause the property cache is aConcurrentHashMapwhich does not permit null values. -
clusterTransportConfig
Sets the path to a custom JGroups XML transport configuration.- Parameters:
clusterTransportConfig- path to JGroups XML, or null for default
-
maximumNumberOfRequestToReturnInVerificationFailure
-
maximumNumberOfRequestToReturnInVerificationFailure
public static void maximumNumberOfRequestToReturnInVerificationFailure(Integer maximumNumberOfRequestToReturnInVerification) The maximum number of requests to return in verification failure result, if more expectations are found the failure result does not list them separately- Parameters:
maximumNumberOfRequestToReturnInVerification- maximum number of expectations to return in verification failure result
-
detailedVerificationFailures
public static boolean detailedVerificationFailures() -
detailedVerificationFailures
public static void detailedVerificationFailures(boolean enable) If true (the default) verification failure messages include a detailed diff showing which fields did not match for the closest matching request.- Parameters:
enable- enabled detailed verification failure messages
-
attemptToProxyIfNoMatchingExpectation
public static boolean attemptToProxyIfNoMatchingExpectation() -
attemptToProxyIfNoMatchingExpectation
public static void attemptToProxyIfNoMatchingExpectation(boolean enable) If true (the default) when no matching expectation is found, and the host header of the request does not match MockServer's host, then MockServer attempts to proxy the request if that fails then a 404 is returned. If false when no matching expectation is found, and MockServer is not being used as a proxy, then MockServer always returns a 404 immediately.- Parameters:
enable- enables automatically attempted proxying of request that don't match an expectation and look like they should be proxied
-
forwardHttpProxy
-
forwardHttpProxy
Use HTTP proxy (i.e. via Host header) for all outbound / forwarded requestsThe default is null
- Parameters:
hostAndPort- host and port for HTTP proxy (i.e. via Host header) for all outbound / forwarded requests
-
forwardHttpProxy
Use HTTP proxy (i.e. via Host header) for all outbound / forwarded requestsThe default is null
- Parameters:
hostAndPort- host and port for HTTP proxy (i.e. via Host header) for all outbound / forwarded requests
-
forwardHttpsProxy
-
forwardHttpsProxy
Use HTTPS proxy (i.e. HTTP CONNECT) for all outbound / forwarded requests, supports TLS tunnelling of HTTPS requestsThe default is null
- Parameters:
hostAndPort- host and port for HTTPS proxy (i.e. HTTP CONNECT) for all outbound / forwarded requests
-
forwardHttpsProxy
Use HTTPS proxy (i.e. HTTP CONNECT) for all outbound / forwarded requests, supports TLS tunnelling of HTTPS requestsThe default is null
- Parameters:
hostAndPort- host and port for HTTPS proxy (i.e. HTTP CONNECT) for all outbound / forwarded requests
-
forwardSocksProxy
-
forwardSocksProxy
Use SOCKS proxy for all outbound / forwarded requests, support TLS tunnelling of TCP connectionsThe default is null
- Parameters:
hostAndPort- host and port for SOCKS proxy for all outbound / forwarded requests
-
forwardSocksProxy
Use SOCKS proxy for all outbound / forwarded requests, support TLS tunnelling of TCP connectionsThe default is null
- Parameters:
hostAndPort- host and port for SOCKS proxy for all outbound / forwarded requests
-
forwardProxyAuthenticationUsername
-
forwardProxyAuthenticationUsername
Username for proxy authentication when using HTTPS proxy (i.e. HTTP CONNECT) for all outbound / forwarded requests
Note: 8u111 Update Release Notes state that the Basic authentication scheme has been deactivated when setting up an HTTPS tunnel. To resolve this clear or set to an empty string the following system properties:
jdk.http.auth.tunneling.disabledSchemesandjdk.http.auth.proxying.disabledSchemes.The default is null
- Parameters:
forwardProxyAuthenticationUsername- username for proxy authentication
-
forwardProxyAuthenticationPassword
-
forwardProxyAuthenticationPassword
Password for proxy authentication when using HTTPS proxy (i.e. HTTP CONNECT) for all outbound / forwarded requests
Note: 8u111 Update Release Notes state that the Basic authentication scheme has been deactivated when setting up an HTTPS tunnel. To resolve this clear or set to an empty string the following system properties:
jdk.http.auth.tunneling.disabledSchemesandjdk.http.auth.proxying.disabledSchemes.The default is null
- Parameters:
forwardProxyAuthenticationPassword- password for proxy authentication
-
proxyAuthenticationRealm
-
proxyAuthenticationRealm
The authentication realm for proxy authentication to MockServer- Parameters:
proxyAuthenticationRealm- the authentication realm for proxy authentication
-
proxyAuthenticationUsername
-
proxyAuthenticationUsername
The required username for proxy authentication to MockServer
Note: 8u111 Update Release Notes state that the Basic authentication scheme has been deactivated when setting up an HTTPS tunnel. To resolve this clear or set to an empty string the following system properties:
jdk.http.auth.tunneling.disabledSchemesandjdk.http.auth.proxying.disabledSchemes.The default is ""
- Parameters:
proxyAuthenticationUsername- required username for proxy authentication to MockServer
-
proxyAuthenticationPassword
-
noProxyHosts
The list of hostnames to not use the configured proxy. Several values may be present, seperated by comma (,)
The default is ""- Parameters:
noProxyHosts- Comma-seperated list of hosts to not be proxied.
-
noProxyHosts
-
proxyRemoteHost
-
proxyRemoteHost
-
proxyRemotePort
-
proxyRemotePort
-
forwardAdjustHostHeader
public static boolean forwardAdjustHostHeader() -
forwardAdjustHostHeader
public static void forwardAdjustHostHeader(boolean enable) If true (the default) the Host header will be automatically adjusted to match the target server when forwarding requests. This prevents HTTP 421 Misdirected Request errors when the target server validates Host headers. If false the original Host header is preserved.- Parameters:
enable- enables automatic Host header adjustment for forwarded requests
-
forwardDefaultHostHeader
-
forwardDefaultHostHeader
-
proxyPass
-
proxyPass
Configure ProxyPass mappings that map incoming path prefixes to upstream servers with automatic path rewriting. Value is a JSON array of objects with pathPrefix, targetUri, and optional preserveHost fields.- Parameters:
proxyPassJson- JSON array string, e.g. [{"pathPrefix":"/api/","targetUri":"https://backend:8443/services/"}]
-
proxyPass
Configure ProxyPass mappings that map incoming path prefixes to upstream servers with automatic path rewriting.- Parameters:
mappings- list of ProxyPassMapping objects
-
globalResponseDelayMillis
-
globalResponseDelayMillis
-
proxyAuthenticationPassword
The required password for proxy authentication to MockServer
Note: 8u111 Update Release Notes state that the Basic authentication scheme has been deactivated when setting up an HTTPS tunnel. To resolve this clear or set to an empty string the following system properties:
jdk.http.auth.tunneling.disabledSchemesandjdk.http.auth.proxying.disabledSchemes.The default is ""
- Parameters:
proxyAuthenticationPassword- required password for proxy authentication to MockServer
-
livenessHttpGetPath
-
livenessHttpGetPath
Path to support HTTP GET requests for status response (also available on PUT /mockserver/status).If this value is not modified then only PUT /mockserver/status but is a none blank value is provided for this value then GET requests to this path will return the 200 Ok status response showing the MockServer version and bound ports.
A GET request to this path will be matched before any expectation matching or proxying of requests.
The default is ""
- Parameters:
livenessPath- path to support HTTP GET requests for status response
-
controlPlaneTLSMutualAuthenticationRequired
public static boolean controlPlaneTLSMutualAuthenticationRequired() -
controlPlaneTLSMutualAuthenticationRequired
public static void controlPlaneTLSMutualAuthenticationRequired(boolean enable) Require mTLS (also called client authentication and two-way TLS) for all control plane requests- Parameters:
enable- TLS mutual authentication for all control plane requests
-
controlPlaneTLSMutualAuthenticationCAChain
-
controlPlaneTLSMutualAuthenticationCAChain
File system path or classpath location of custom mTLS (TLS client authentication) X.509 Certificate Chain for control plane mTLS authenticationThe X.509 Certificate Chain is for trusting (i.e. signature verification of) Client X.509 Certificates, the certificate chain must be a X509 PEM file.
This certificate chain will be used for to performs mTLS (client authentication) for inbound TLS connections if controlPlaneTLSMutualAuthenticationRequired is enabled
- Parameters:
trustCertificateChain- File system path or classpath location of custom mTLS (TLS client authentication) X.509 Certificate Chain for Trusting (i.e. signature verification of) Client X.509 Certificates
-
controlPlanePrivateKeyPath
-
controlPlanePrivateKeyPath
File system path or classpath location of a fixed custom private key for control plane connections using mTLS for authentication.The private key must be a PKCS#8 or PKCS#1 PEM file and must be the private key corresponding to the controlPlaneX509CertificatePath X509 (public key) configuration. The controlPlaneTLSMutualAuthenticationCAChain configuration must be the Certificate Authority for the corresponding X509 certificate (i.e. able to valid its signature).
To convert a PKCS#1 (i.e. default for Bouncy Castle) to a PKCS#8 the following command can be used: openssl pkcs8 -topk8 -inform PEM -in private_key_PKCS_1.pem -out private_key_PKCS_8.pem -nocrypt
This configuration will be ignored unless x509CertificatePath is also set.
- Parameters:
privateKeyPath- location of the PKCS#8 PEM file containing the private key
-
controlPlaneX509CertificatePath
-
controlPlaneX509CertificatePath
File system path or classpath location of a fixed custom X.509 Certificate for control plane connections using mTLS for authentication.The certificate must be a X509 PEM file and must be the public key corresponding to the controlPlanePrivateKeyPath private key configuration. The controlPlaneTLSMutualAuthenticationCAChain configuration must be the Certificate Authority for this certificate (i.e. able to valid its signature).
This configuration will be ignored unless privateKeyPath is also set.
- Parameters:
x509CertificatePath- location of the PEM file containing the X509 certificate
-
controlPlaneJWTAuthenticationRequired
public static boolean controlPlaneJWTAuthenticationRequired() -
controlPlaneJWTAuthenticationRequired
public static void controlPlaneJWTAuthenticationRequired(boolean enable) Require JWT authentication for all control plane requests
- Parameters:
enable- TLS mutual authentication for all control plane requests
-
controlPlaneJWTAuthenticationJWKSource
-
controlPlaneJWTAuthenticationJWKSource
public static void controlPlaneJWTAuthenticationJWKSource(String controlPlaneJWTAuthenticationJWKSource) JWK source used when JWT authentication is enabled for control plane requests
JWK source can be a file system path, classpath location or a URL
See: https://openid.net/specs/draft-jones-json-web-key-03.html
- Parameters:
controlPlaneJWTAuthenticationJWKSource- file system path, classpath location or a URL of JWK source
-
controlPlaneJWTAuthenticationExpectedAudience
-
controlPlaneJWTAuthenticationExpectedAudience
public static void controlPlaneJWTAuthenticationExpectedAudience(String controlPlaneJWTAuthenticationExpectedAudience) Audience claim (i.e. aud) required when JWT authentication is enabled for control plane requests
- Parameters:
controlPlaneJWTAuthenticationExpectedAudience- required value for audience claim (i.e. aud)
-
controlPlaneJWTAuthenticationMatchingClaims
-
controlPlaneJWTAuthenticationMatchingClaims
public static void controlPlaneJWTAuthenticationMatchingClaims(Map<String, String> controlPlaneJWTAuthenticationMatchingClaims) Matching claims expected when JWT authentication is enabled for control plane requests
Value should be string with comma separated key=value items, for example: scope=internal public,sub=some_subject
- Parameters:
controlPlaneJWTAuthenticationMatchingClaims- required values for claims
-
controlPlaneJWTAuthenticationRequiredClaims
-
controlPlaneJWTAuthenticationRequiredClaims
public static void controlPlaneJWTAuthenticationRequiredClaims(Set<String> controlPlaneJWTAuthenticationRequiredClaims) Required claims that should exist (i.e. with any value) when JWT authentication is enabled for control plane requests
Value should be string with comma separated values, for example: scope,sub
- Parameters:
controlPlaneJWTAuthenticationRequiredClaims- required claims
-
proactivelyInitialiseTLS
public static void proactivelyInitialiseTLS(boolean enable) Proactively initialise TLS during start to ensure that if dynamicallyCreateCertificateAuthorityCertificate is enabled the Certificate Authority X.509 Certificate and Private Key will be created during start up and not when the first TLS connection is received.
This setting will also ensure any configured private key and X.509 will be loaded during start up and not when the first TLS connection is received to give immediate feedback on any related TLS configuration errors.
- Parameters:
enable- proactively initialise TLS at startup
-
proactivelyInitialiseTLS
public static boolean proactivelyInitialiseTLS() -
tlsProtocols
-
tlsProtocols
Comma seperated list of TLS protocols, by default TLSv1,TLSv1.1,TLSv1.2- Parameters:
tlsProtocols- comma seperated list of TLS protocols
-
tlsAllowInsecureProtocols
public static boolean tlsAllowInsecureProtocols() -
tlsAllowInsecureProtocols
public static void tlsAllowInsecureProtocols(boolean allow) Whether to allow TLSv1 and TLSv1.1 in the effective TLS protocols list.Both protocols are deprecated by RFC 8996 and vulnerable to BEAST and POODLE. The default is true for backwards compatibility — MockServer's
tlsProtocols()default still includes them. Set this to false to opt into a hardened profile: any "TLSv1" or "TLSv1.1" entries intlsProtocols()are filtered out before the SSL context is built.A future major release is expected to flip this default to false.
- Parameters:
allow- if true, TLSv1 and TLSv1.1 are honoured intlsProtocols(); if false, they are stripped
-
dynamicallyCreateCertificateAuthorityCertificate
public static boolean dynamicallyCreateCertificateAuthorityCertificate() -
dynamicallyCreateCertificateAuthorityCertificate
public static void dynamicallyCreateCertificateAuthorityCertificate(boolean enable) Enable dynamic creation of Certificate Authority X509 certificate and private key.Enable this property to increase the security of trusting the MockServer Certificate Authority X509 by ensuring a local dynamic value is used instead of the public value in the MockServer git repo.
These PEM files will be created and saved in the directory specified with configuration property directoryToSaveDynamicSSLCertificate.
- Parameters:
enable- dynamic creation of Certificate Authority X509 certificate and private key.
-
directoryToSaveDynamicSSLCertificate
-
directoryToSaveDynamicSSLCertificate
public static void directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate) Directory used to save the dynamically generated Certificate Authority X.509 Certificate and Private Key.- Parameters:
directoryToSaveDynamicSSLCertificate- directory to save Certificate Authority X.509 Certificate and Private Key
-
preventCertificateDynamicUpdate
public static void preventCertificateDynamicUpdate(boolean prevent) Prevent certificates from dynamically updating when domain list changes- Parameters:
prevent- prevent certificates from dynamically updating when domain list changes
-
preventCertificateDynamicUpdate
public static boolean preventCertificateDynamicUpdate() -
sslCertificateDomainName
-
sslCertificateDomainName
The domain name for auto-generate TLS certificatesThe default is "localhost"
- Parameters:
domainName- domain name for auto-generate TLS certificates
-
sslSubjectAlternativeNameDomains
The Subject Alternative Name (SAN) domain names for auto-generate TLS certificates as a comma separated listThe default is "localhost"
- Parameters:
sslSubjectAlternativeNameDomains- Subject Alternative Name (SAN) domain names for auto-generate TLS certificates
-
sslSubjectAlternativeNameDomains
-
sslSubjectAlternativeNameIps
The Subject Alternative Name (SAN) IP addresses for auto-generate TLS certificates as a comma separated list
The default is "127.0.0.1,0.0.0.0"
- Parameters:
sslSubjectAlternativeNameIps- Subject Alternative Name (SAN) IP addresses for auto-generate TLS certificates
-
sslSubjectAlternativeNameIps
-
certificateAuthorityPrivateKey
-
certificateAuthorityPrivateKey
File system path or classpath location of custom Private Key for Certificate Authority for TLS, the private key must be a PKCS#8 or PKCS#1 PEM file and must match the certificateAuthorityCertificate To convert a PKCS#1 (i.e. default for Bouncy Castle) to a PKCS#8 the following command can be used: openssl pkcs8 -topk8 -inform PEM -in private_key_PKCS_1.pem -out private_key_PKCS_8.pem -nocrypt- Parameters:
certificateAuthorityPrivateKey- location of the PEM file containing the certificate authority private key
-
certificateAuthorityCertificate
-
certificateAuthorityCertificate
File system path or classpath location of custom X.509 Certificate for Certificate Authority for TLS, the certificate must be a X509 PEM file and must match the certificateAuthorityPrivateKey- Parameters:
certificateAuthorityCertificate- location of the PEM file containing the certificate authority X509 certificate
-
privateKeyPath
-
privateKeyPath
File system path or classpath location of a fixed custom private key for TLS connections into MockServer.The private key must be a PKCS#8 or PKCS#1 PEM file and must be the private key corresponding to the x509CertificatePath X509 (public key) configuration. The certificateAuthorityCertificate configuration must be the Certificate Authority for the corresponding X509 certificate (i.e. able to valid its signature), see: x509CertificatePath.
To convert a PKCS#1 (i.e. default for Bouncy Castle) to a PKCS#8 the following command can be used: openssl pkcs8 -topk8 -inform PEM -in private_key_PKCS_1.pem -out private_key_PKCS_8.pem -nocrypt
This configuration will be ignored unless x509CertificatePath is also set.
- Parameters:
privateKeyPath- location of the PKCS#8 PEM file containing the private key
-
x509CertificatePath
-
x509CertificatePath
File system path or classpath location of a fixed custom X.509 Certificate for TLS connections into MockServer.The certificate must be a X509 PEM file and must be the public key corresponding to the privateKeyPath private key configuration. The certificateAuthorityCertificate configuration must be the Certificate Authority for this certificate (i.e. able to valid its signature).
This configuration will be ignored unless privateKeyPath is also set.
- Parameters:
x509CertificatePath- location of the PEM file containing the X509 certificate
-
tlsMutualAuthenticationRequired
public static boolean tlsMutualAuthenticationRequired() -
tlsMutualAuthenticationRequired
public static void tlsMutualAuthenticationRequired(boolean enable) Require mTLS (also called client authentication and two-way TLS) for all TLS connections / HTTPS requests to MockServer- Parameters:
enable- TLS mutual authentication
-
tlsMutualAuthenticationCertificateChain
-
tlsMutualAuthenticationCertificateChain
File system path or classpath location of custom mTLS (TLS client authentication) X.509 Certificate Chain for trusting (i.e. signature verification of) Client X.509 Certificates, the certificate chain must be a X509 PEM file.This certificate chain will be used if MockServer performs mTLS (client authentication) for inbound TLS connections because tlsMutualAuthenticationRequired is enabled
- Parameters:
trustCertificateChain- File system path or classpath location of custom mTLS (TLS client authentication) X.509 Certificate Chain for Trusting (i.e. signature verification of) Client X.509 Certificates
-
forwardProxyTLSX509CertificatesTrustManagerType
public static ForwardProxyTLSX509CertificatesTrustManager forwardProxyTLSX509CertificatesTrustManagerType() -
forwardProxyTLSX509CertificatesTrustManagerType
public static void forwardProxyTLSX509CertificatesTrustManagerType(ForwardProxyTLSX509CertificatesTrustManager trustManagerType) Configure trusted set of certificates for forwarded or proxied requests.MockServer will only be able to establish a TLS connection to endpoints that have a trusted X509 certificate according to the trust manager type, as follows:
ANY - Insecure will trust all X509 certificates and not perform host name verification. JVM - Will trust all X509 certificates trust by the JVM. CUSTOM - Will trust all X509 certificates specified in forwardProxyTLSCustomTrustX509Certificates configuration value.
- Parameters:
trustManagerType- trusted set of certificates for forwarded or proxied requests, allowed values: ANY, JVM, CUSTOM.
-
forwardProxyBlockPrivateNetworks
public static boolean forwardProxyBlockPrivateNetworks() -
forwardProxyBlockPrivateNetworks
public static void forwardProxyBlockPrivateNetworks(boolean block) When set to true, MockServer rejects forward and proxy targets that resolve to loopback, link-local, RFC 1918 private, or cloud metadata addresses (such as 169.254.169.254). This blocks server-side request forgery (SSRF) attacks where a malicious expectation forwards through MockServer to internal infrastructure.The default is false because MockServer is primarily used to mock services in private or loopback test networks (Docker bridges, Kubernetes service IPs, localhost), so blocking those targets by default would break the common case. Enable this in hardened or multi-tenant deployments where untrusted callers can register expectations.
- Parameters:
block- if true, block forwarding to private or metadata addresses
-
forwardProxyTLSCustomTrustX509Certificates
-
forwardProxyTLSCustomTrustX509Certificates
File system path or classpath location of custom file for trusted X509 Certificate Authority roots for forwarded or proxied requests, the certificate chain must be a X509 PEM file.MockServer will only be able to establish a TLS connection to endpoints that have an X509 certificate chain that is signed by one of the provided custom certificates, i.e. where a path can be established from the endpoints X509 certificate to one or more of the custom X509 certificates provided.
- Parameters:
customX509Certificates- custom set of trusted X509 certificate authority roots for forwarded or proxied requests in PEM format.
-
forwardProxyPrivateKey
-
forwardProxyPrivateKey
File system path or classpath location of custom Private Key for proxied TLS connections out of MockServer, the private key must be a PKCS#8 or PKCS#1 PEM fileTo convert a PKCS#1 (i.e. default for Bouncy Castle) to a PKCS#8 the following command can be used: openssl pkcs8 -topk8 -inform PEM -in private_key_PKCS_1.pem -out private_key_PKCS_8.pem -nocrypt
This private key will be used if MockServer needs to perform mTLS (client authentication) for outbound TLS connections.
- Parameters:
privateKey- location of the PEM file containing the private key
-
forwardProxyCertificateChain
-
forwardProxyCertificateChain
File system path or classpath location of custom mTLS (TLS client authentication) X.509 Certificate Chain for Trusting (i.e. signature verification of) Client X.509 Certificates, the certificate chain must be a X509 PEM file.This certificate chain will be used if MockServer needs to perform mTLS (client authentication) for outbound TLS connections.
- Parameters:
certificateChain- location of the PEM file containing the certificate chain
-