Go API Documentation

github.com/TykTechnologies/tyk/apidef/oas

No package summary is available.

Package

Files: 19. Third party imports: 5. Imports from organisation: 2. Tests: 0. Benchmarks: 0.

Constants

const (
	invalidServerURLFmt		= "Please update %q to be a valid URL and try again."
	unsupportedSecuritySchemeFmt	= "unsupported security scheme: %s"

	middlewareValidateRequest	= "validateRequest"
	middlewareAllowList		= "allowList"
	middlewareMockResponse		= "mockResponse"
)
// WebhookKind is an alias maintained to be used in imports.
const (
	WebhookKind	= event.WebhookKind
	JSVMKind	= event.JSVMKind
	LogKind		= event.LogKind
)
const (
	// ExtensionTykAPIGateway is the OAS schema key for the Tyk extension.
	ExtensionTykAPIGateway	= "x-tyk-api-gateway"

	// ExtensionTykStreaming is the OAS schema key for the Tyk Streams extension.
	ExtensionTykStreaming	= "x-tyk-streaming"

	// Main holds the default version value (empty).
	Main	= ""

	// DefaultOpenAPI is the default open API version which is set to migrated APIs.
	DefaultOpenAPI	= "3.0.6"
)
const (
	allow			AllowanceType	= 0
	block			AllowanceType	= 1
	ignoreAuthentication	AllowanceType	= 2

	contentTypeJSON	= "application/json"
)
const (
	typeAPIKey	= "apiKey"
	typeHTTP	= "http"
	typeOAuth2	= "oauth2"
	schemeBearer	= "bearer"
	schemeBasic	= "basic"
	bearerFormatJWT	= "JWT"

	defaultAuthSourceName	= "Authorization"

	header	= "header"
	query	= "query"
	cookie	= "cookie"
)
// Enumerated constants for inputs and conditions.
const (
	InputQuery		URLRewriteInput	= "query"
	InputPath		URLRewriteInput	= "path"
	InputHeader		URLRewriteInput	= "header"
	InputSessionMetadata	URLRewriteInput	= "sessionMetadata"
	InputRequestBody	URLRewriteInput	= "requestBody"
	InputRequestContext	URLRewriteInput	= "requestContext"

	ConditionAll	URLRewriteCondition	= "all"
	ConditionAny	URLRewriteCondition	= "any"
)
const (
	keyDefinitions			= "definitions"
	keyProperties			= "properties"
	keyRequired			= "required"
	keyAnyOf			= "anyOf"
	oasSchemaVersionNotFoundFmt	= "Schema not found for version %q"
)

Vars

ShouldOmit is a compatibility alias. It may be removed in the future.

var ShouldOmit = internalreflect.IsEmpty
var (
	errEmptyServersObject	= errors.New("The ‘servers’ object is empty in your OAS. You can either add a ‘servers’ section to your OpenAPI description or provide a Custom Upstream URL in the manual configuration options below.")
	errEmptySecurityObject	= errors.New("The ‘security’ object is empty in your OAS. When enabling authentication, your OpenAPI description must include a ‘security’ object that defines the authentication schemes. You can either add a ‘security’ object or disable authentication in the API settings.")
	errInvalidUpstreamURL	= errors.New("The manually configured upstream URL is not valid. The URL must be absolute and properly formatted (e.g. https://example.com). Please check the URL format and try again.")
	errInvalidServerURL	= errors.New("The first entry in the ‘servers’ object of your OAS is not valid. The URL must be absolute and properly formatted (e.g. https://example.com).")

	allowedMethods	= []string{
		http.MethodConnect,
		http.MethodDelete,
		http.MethodGet,
		http.MethodHead,
		http.MethodOptions,
		http.MethodPatch,
		http.MethodPost,
		http.MethodPut,
		http.MethodTrace,
	}
)
var (
	// URLRewriteConditions contains all valid URL rewrite condition values.
	URLRewriteConditions	= []URLRewriteCondition{
		ConditionAll,
		ConditionAny,
	}

	// URLRewriteInputs contains all valid URL rewrite input values.
	URLRewriteInputs	= []URLRewriteInput{
		InputQuery,
		InputPath,
		InputHeader,
		InputSessionMetadata,
		InputRequestBody,
		InputRequestContext,
	}
)
var (
	log	= logger.Get()

	schemaOnce	sync.Once

	oasJSONSchemas	map[string][]byte

	defaultVersion	string
)

detect possible regex pattern:

  • character match ([a-z])
  • greedy match (.*)
  • ungreedy match (.+)
  • end of string ($).

var regexPatterns = []string{
	".+", ".*", "[", "]", "$",
}
var schemaDir embed.FS

Types

APIDef

APIDef holds both OAS and Classic forms of an API definition.

Field name Field type Comment
OAS

*OAS

OAS contains the OAS API definition.

Classic

*apidef.APIDefinition

Classic contains the Classic API definition.

type APIDef struct {
	// OAS contains the OAS API definition.
	OAS	*OAS
	// Classic contains the Classic API definition.
	Classic	*apidef.APIDefinition
}

Allowance

Allowance describes allowance actions and behaviour.

Field name Field type Comment
Enabled

bool

Enabled is a boolean flag, if set to true, then individual allowances (allow, block, ignore) will be enforced.

IgnoreCase

bool

IgnoreCase is a boolean flag, If set to true, checks for requests allowance will be case insensitive.

type Allowance struct {
	// Enabled is a boolean flag, if set to `true`, then individual allowances (allow, block, ignore) will be enforced.
	Enabled	bool	`bson:"enabled" json:"enabled"`

	// IgnoreCase is a boolean flag, If set to `true`, checks for requests allowance will be case insensitive.
	IgnoreCase	bool	`bson:"ignoreCase,omitempty" json:"ignoreCase,omitempty"`
}

AllowanceType

AllowanceType holds the valid allowance types values.

Field name Field type Comment
type

int

No comment on field.
type AllowanceType int

AuthSource

AuthSource defines an authentication source.

Field name Field type Comment
Enabled

bool

Enabled activates the auth source.

Tyk classic API definition: auth_configs[X].use_param/use_cookie.

Name

string

Name is the name of the auth source.

Tyk classic API definition: auth_configs[X].param_name/cookie_name.

type AuthSource struct {
	// Enabled activates the auth source.
	//
	// Tyk classic API definition: `auth_configs[X].use_param/use_cookie`.
	Enabled	bool	`bson:"enabled" json:"enabled"`	// required
	// Name is the name of the auth source.
	//
	// Tyk classic API definition: `auth_configs[X].param_name/cookie_name`.
	Name	string	`bson:"name,omitempty" json:"name,omitempty"`
}

AuthSources

AuthSources defines authentication source configuration: headers, cookies and query parameters.

Tyk classic API definition: auth_configs{}.

Field name Field type Comment
Header

*AuthSource

Header contains configurations for the header value auth source, it is enabled by default.

Tyk classic API definition: auth_configs[x].header

Cookie

*AuthSource

Cookie contains configurations for the cookie value auth source.

Tyk classic API definition: auth_configs[x].cookie

Query

*AuthSource

Query contains configurations for the query parameters auth source.

Tyk classic API definition: auth_configs[x].query

type AuthSources struct {
	// Header contains configurations for the header value auth source, it is enabled by default.
	//
	// Tyk classic API definition: `auth_configs[x].header`
	Header	*AuthSource	`bson:"header,omitempty" json:"header,omitempty"`

	// Cookie contains configurations for the cookie value auth source.
	//
	// Tyk classic API definition: `auth_configs[x].cookie`
	Cookie	*AuthSource	`bson:"cookie,omitempty" json:"cookie,omitempty"`

	// Query contains configurations for the query parameters auth source.
	//
	// Tyk classic API definition: `auth_configs[x].query`
	Query	*AuthSource	`bson:"query,omitempty" json:"query,omitempty"`
}

Authentication

Authentication contains configuration about the authentication methods and security policies applied to requests.

Field name Field type Comment
Enabled

bool

Enabled makes the API protected when one of the authentication modes is enabled.

Tyk classic API definition: !use_keyless.

StripAuthorizationData

bool

StripAuthorizationData ensures that any security tokens used for accessing APIs are stripped and not passed to the upstream.

Tyk classic API definition: strip_auth_data.

BaseIdentityProvider

apidef.AuthTypeEnum

BaseIdentityProvider enables the use of multiple authentication mechanisms. It provides the session object that determines access control, rate limits and usage quotas.

It should be set to one of the following:

  • auth_token
  • hmac_key
  • basic_auth_user
  • jwt_claim
  • oidc_user
  • oauth_key
  • custom_auth

Tyk classic API definition: base_identity_provided_by.

HMAC

*HMAC

HMAC contains the configurations related to HMAC authentication mode.

Tyk classic API definition: auth_configs["hmac"]

OIDC

*OIDC

OIDC contains the configurations related to OIDC authentication mode.

Tyk classic API definition: auth_configs["oidc"]

Custom

*CustomPluginAuthentication

Custom contains the configurations related to Custom authentication mode.

Tyk classic API definition: auth_configs["coprocess"]

SecuritySchemes

SecuritySchemes

SecuritySchemes contains security schemes definitions.

CustomKeyLifetime

*CustomKeyLifetime

CustomKeyLifetime contains configuration for the maximum retention period for access tokens.

type Authentication struct {
	// Enabled makes the API protected when one of the authentication modes is enabled.
	//
	// Tyk classic API definition: `!use_keyless`.
	Enabled	bool	`bson:"enabled" json:"enabled"`	// required

	// StripAuthorizationData ensures that any security tokens used for accessing APIs are stripped and not passed to the upstream.
	//
	// Tyk classic API definition: `strip_auth_data`.
	StripAuthorizationData	bool	`bson:"stripAuthorizationData,omitempty" json:"stripAuthorizationData,omitempty"`

	// BaseIdentityProvider enables the use of multiple authentication mechanisms.
	// It provides the session object that determines access control, rate limits and usage quotas.
	//
	// It should be set to one of the following:
	//
	// - `auth_token`
	// - `hmac_key`
	// - `basic_auth_user`
	// - `jwt_claim`
	// - `oidc_user`
	// - `oauth_key`
	// - `custom_auth`
	//
	// Tyk classic API definition: `base_identity_provided_by`.
	BaseIdentityProvider	apidef.AuthTypeEnum	`bson:"baseIdentityProvider,omitempty" json:"baseIdentityProvider,omitempty"`

	// HMAC contains the configurations related to HMAC authentication mode.
	//
	// Tyk classic API definition: `auth_configs["hmac"]`
	HMAC	*HMAC	`bson:"hmac,omitempty" json:"hmac,omitempty"`

	// OIDC contains the configurations related to OIDC authentication mode.
	//
	// Tyk classic API definition: `auth_configs["oidc"]`
	OIDC	*OIDC	`bson:"oidc,omitempty" json:"oidc,omitempty"`

	// Custom contains the configurations related to Custom authentication mode.
	//
	// Tyk classic API definition: `auth_configs["coprocess"]`
	Custom	*CustomPluginAuthentication	`bson:"custom,omitempty" json:"custom,omitempty"`

	// SecuritySchemes contains security schemes definitions.
	SecuritySchemes	SecuritySchemes	`bson:"securitySchemes,omitempty" json:"securitySchemes,omitempty"`

	// CustomKeyLifetime contains configuration for the maximum retention period for access tokens.
	CustomKeyLifetime	*CustomKeyLifetime	`bson:"customKeyLifetime,omitempty" json:"customKeyLifetime,omitempty"`
}

AuthenticationPlugin

AuthenticationPlugin holds the configuration for custom authentication plugin.

Field name Field type Comment
Enabled

bool

Enabled activates custom authentication plugin.

Tyk classic API definition: custom_middleware.auth_check.disabled (negated).

FunctionName

string

FunctionName is the name of authentication method.

Tyk classic API definition: custom_middleware.auth_check.name.

Path

string

Path is the path to shared object file in case of goplugin mode or path to JS code in case of otto auth plugin.

Tyk classic API definition: custom_middleware.auth_check.path.

RawBodyOnly

bool

RawBodyOnly if set to true, do not fill body in request or response object.

Tyk classic API definition: custom_middleware.auth_check.raw_body_only.

RequireSession

bool

RequireSession passes down the session information for plugins after authentication.

Tyk classic API definition: custom_middleware.auth_check.require_session.

IDExtractor

*IDExtractor

IDExtractor configures ID extractor with coprocess custom authentication.

Tyk classic API definition: custom_middleware.id_extractor.

type AuthenticationPlugin struct {
	// Enabled activates custom authentication plugin.
	//
	// Tyk classic API definition: `custom_middleware.auth_check.disabled` (negated).
	Enabled	bool	`bson:"enabled" json:"enabled"`	// required.
	// FunctionName is the name of authentication method.
	//
	// Tyk classic API definition: `custom_middleware.auth_check.name`.
	FunctionName	string	`bson:"functionName" json:"functionName"`	// required.
	// Path is the path to shared object file in case of goplugin mode or path to JS code in case of otto auth plugin.
	//
	// Tyk classic API definition: `custom_middleware.auth_check.path`.
	Path	string	`bson:"path" json:"path"`
	// RawBodyOnly if set to true, do not fill body in request or response object.
	//
	// Tyk classic API definition: `custom_middleware.auth_check.raw_body_only`.
	RawBodyOnly	bool	`bson:"rawBodyOnly,omitempty" json:"rawBodyOnly,omitempty"`
	// RequireSession passes down the session information for plugins after authentication.
	//
	// Tyk classic API definition: `custom_middleware.auth_check.require_session`.
	RequireSession	bool	`bson:"requireSession,omitempty" json:"requireSession,omitempty"`
	// IDExtractor configures ID extractor with coprocess custom authentication.
	//
	// Tyk classic API definition: `custom_middleware.id_extractor`.
	IDExtractor	*IDExtractor	`bson:"idExtractor,omitempty" json:"idExtractor,omitempty"`
}

Basic

Basic type holds configuration values related to http basic authentication.

Field name Field type Comment
Enabled

bool

Enabled activates the basic authentication mode. Tyk classic API definition: use_basic_auth

AuthSources

AuthSources contains the source for HTTP Basic Auth credentials.

DisableCaching

bool

DisableCaching disables the caching of basic authentication key. Tyk classic API definition: basic_auth.disable_caching

CacheTTL

int

CacheTTL is the TTL for a cached basic authentication key in seconds. Tyk classic API definition: basic_auth.cache_ttl

ExtractCredentialsFromBody

*ExtractCredentialsFromBody

ExtractCredentialsFromBody helps to extract username and password from body. In some cases, like dealing with SOAP, user credentials can be passed via request body.

type Basic struct {
	// Enabled activates the basic authentication mode.
	// Tyk classic API definition: `use_basic_auth`
	Enabled	bool	`bson:"enabled" json:"enabled"`	// required
	// AuthSources contains the source for HTTP Basic Auth credentials.
	AuthSources	`bson:",inline" json:",inline"`
	// DisableCaching disables the caching of basic authentication key.
	// Tyk classic API definition: `basic_auth.disable_caching`
	DisableCaching	bool	`bson:"disableCaching,omitempty" json:"disableCaching,omitempty"`
	// CacheTTL is the TTL for a cached basic authentication key in seconds.
	// Tyk classic API definition: `basic_auth.cache_ttl`
	CacheTTL	int	`bson:"cacheTTL,omitempty" json:"cacheTTL,omitempty"`
	// ExtractCredentialsFromBody helps to extract username and password from body. In some cases, like dealing with SOAP,
	// user credentials can be passed via request body.
	ExtractCredentialsFromBody	*ExtractCredentialsFromBody	`bson:"extractCredentialsFromBody,omitempty" json:"extractCredentialsFromBody,omitempty"`
}

BatchProcessing

BatchProcessing represents the configuration for enabling or disabling batch request support for an API.

Field name Field type Comment
Enabled

bool

Enabled determines whether batch request support is enabled or disabled for the API.

Tyk classic API definition: enable_batch_request_support.

type BatchProcessing struct {
	// Enabled determines whether batch request support is enabled or disabled for the API.
	//
	// Tyk classic API definition: `enable_batch_request_support`.
	Enabled bool `bson:"enabled" json:"enabled"`	// required
}

CORS

CORS holds configuration for cross-origin resource sharing.

Field name Field type Comment
Enabled

bool

Enabled is a boolean flag, if set to true, this option enables CORS processing.

Tyk classic API definition: CORS.enable.

MaxAge

int

MaxAge indicates how long (in seconds) the results of a preflight request can be cached. The default is 0 which stands for no max age.

Tyk classic API definition: CORS.max_age.

AllowCredentials

bool

AllowCredentials indicates if the request can include user credentials like cookies, HTTP authentication or client side SSL certificates.

Tyk classic API definition: CORS.allow_credentials.

ExposedHeaders

[]string

ExposedHeaders indicates which headers are safe to expose to the API of a CORS API specification.

Tyk classic API definition: CORS.exposed_headers.

AllowedHeaders

[]string

AllowedHeaders holds a list of non simple headers the client is allowed to use with cross-domain requests.

Tyk classic API definition: CORS.allowed_headers.

OptionsPassthrough

bool

OptionsPassthrough is a boolean flag. If set to true, it will proxy the CORS OPTIONS pre-flight request directly to upstream, without authentication and any CORS checks. This means that pre-flight requests generated by web-clients such as SwaggerUI or the Tyk Portal documentation system will be able to test the API using trial keys.

If your service handles CORS natively, then enable this option.

Tyk classic API definition: CORS.options_passthrough.

Debug

bool

Debug is a boolean flag, If set to true, this option produces log files for the CORS middleware.

Tyk classic API definition: CORS.debug.

AllowedOrigins

[]string

AllowedOrigins holds a list of origin domains to allow access from. Wildcards are also supported, e.g. http://*.foo.com

Tyk classic API definition: CORS.allowed_origins.

AllowedMethods

[]string

AllowedMethods holds a list of methods to allow access via.

Tyk classic API definition: CORS.allowed_methods.

type CORS struct {
	// Enabled is a boolean flag, if set to `true`, this option enables CORS processing.
	//
	// Tyk classic API definition: `CORS.enable`.
	Enabled	bool	`bson:"enabled" json:"enabled"`	// required

	// MaxAge indicates how long (in seconds) the results of a preflight request can be cached. The default is 0 which stands for no max age.
	//
	// Tyk classic API definition: `CORS.max_age`.
	MaxAge	int	`bson:"maxAge,omitempty" json:"maxAge,omitempty"`

	// AllowCredentials indicates if the request can include user credentials like cookies,
	// HTTP authentication or client side SSL certificates.
	//
	// Tyk classic API definition: `CORS.allow_credentials`.
	AllowCredentials	bool	`bson:"allowCredentials,omitempty" json:"allowCredentials,omitempty"`

	// ExposedHeaders indicates which headers are safe to expose to the API of a CORS API specification.
	//
	// Tyk classic API definition: `CORS.exposed_headers`.
	ExposedHeaders	[]string	`bson:"exposedHeaders,omitempty" json:"exposedHeaders,omitempty"`

	// AllowedHeaders holds a list of non simple headers the client is allowed to use with cross-domain requests.
	//
	// Tyk classic API definition: `CORS.allowed_headers`.
	AllowedHeaders	[]string	`bson:"allowedHeaders,omitempty" json:"allowedHeaders,omitempty"`

	// OptionsPassthrough is a boolean flag. If set to `true`, it will proxy the CORS OPTIONS pre-flight
	// request directly to upstream, without authentication and any CORS checks. This means that pre-flight
	// requests generated by web-clients such as SwaggerUI or the Tyk Portal documentation system
	// will be able to test the API using trial keys.
	//
	// If your service handles CORS natively, then enable this option.
	//
	// Tyk classic API definition: `CORS.options_passthrough`.
	OptionsPassthrough	bool	`bson:"optionsPassthrough,omitempty" json:"optionsPassthrough,omitempty"`

	// Debug is a boolean flag, If set to `true`, this option produces log files for the CORS middleware.
	//
	// Tyk classic API definition: `CORS.debug`.
	Debug	bool	`bson:"debug,omitempty" json:"debug,omitempty"`

	// AllowedOrigins holds a list of origin domains to allow access from. Wildcards are also supported, e.g. `http://*.foo.com`
	//
	// Tyk classic API definition: `CORS.allowed_origins`.
	AllowedOrigins	[]string	`bson:"allowedOrigins,omitempty" json:"allowedOrigins,omitempty"`

	// AllowedMethods holds a list of methods to allow access via.
	//
	// Tyk classic API definition: `CORS.allowed_methods`.
	AllowedMethods	[]string	`bson:"allowedMethods,omitempty" json:"allowedMethods,omitempty"`
}

Cache

Cache holds configuration for caching the requests.

Field name Field type Comment
Enabled

bool

Enabled turns global cache middleware on or off. It is still possible to enable caching on a per-path basis by explicitly setting the endpoint cache middleware.

Tyk classic API definition: cache_options.enable_cache

Timeout

int64

Timeout is the TTL for a cached object in seconds.

Tyk classic API definition: cache_options.cache_timeout

CacheAllSafeRequests

bool

CacheAllSafeRequests caches responses to (GET, HEAD, OPTIONS) requests overrides per-path cache settings in versions, applies across versions.

Tyk classic API definition: cache_options.cache_all_safe_requests

CacheResponseCodes

[]int

CacheResponseCodes is an array of response codes which are safe to cache e.g. 404.

Tyk classic API definition: cache_options.cache_response_codes

CacheByHeaders

[]string

CacheByHeaders allows header values to be used as part of the cache key.

Tyk classic API definition: cache_options.cache_by_headers

EnableUpstreamCacheControl

bool

EnableUpstreamCacheControl instructs Tyk Cache to respect upstream cache control headers.

Tyk classic API definition: cache_options.enable_upstream_cache_control

ControlTTLHeaderName

string

ControlTTLHeaderName is the response header which tells Tyk how long it is safe to cache the response for.

Tyk classic API definition: cache_options.cache_control_ttl_header

type Cache struct {
	// Enabled turns global cache middleware on or off. It is still possible to enable caching on a per-path basis
	// by explicitly setting the endpoint cache middleware.
	//
	// Tyk classic API definition: `cache_options.enable_cache`
	Enabled	bool	`bson:"enabled" json:"enabled"`	// required

	// Timeout is the TTL for a cached object in seconds.
	//
	// Tyk classic API definition: `cache_options.cache_timeout`
	Timeout	int64	`bson:"timeout,omitempty" json:"timeout,omitempty"`

	// CacheAllSafeRequests caches responses to (`GET`, `HEAD`, `OPTIONS`) requests overrides per-path cache settings in versions,
	// applies across versions.
	//
	// Tyk classic API definition: `cache_options.cache_all_safe_requests`
	CacheAllSafeRequests	bool	`bson:"cacheAllSafeRequests,omitempty" json:"cacheAllSafeRequests,omitempty"`

	// CacheResponseCodes is an array of response codes which are safe to cache e.g. `404`.
	//
	// Tyk classic API definition: `cache_options.cache_response_codes`
	CacheResponseCodes	[]int	`bson:"cacheResponseCodes,omitempty" json:"cacheResponseCodes,omitempty"`

	// CacheByHeaders allows header values to be used as part of the cache key.
	//
	// Tyk classic API definition: `cache_options.cache_by_headers`
	CacheByHeaders	[]string	`bson:"cacheByHeaders,omitempty" json:"cacheByHeaders,omitempty"`

	// EnableUpstreamCacheControl instructs Tyk Cache to respect upstream cache control headers.
	//
	// Tyk classic API definition: `cache_options.enable_upstream_cache_control`
	EnableUpstreamCacheControl	bool	`bson:"enableUpstreamCacheControl,omitempty" json:"enableUpstreamCacheControl,omitempty"`

	// ControlTTLHeaderName is the response header which tells Tyk how long it is safe to cache the response for.
	//
	// Tyk classic API definition: `cache_options.cache_control_ttl_header`
	ControlTTLHeaderName	string	`bson:"controlTTLHeaderName,omitempty" json:"controlTTLHeaderName,omitempty"`
}

CachePlugin

CachePlugin holds the configuration for the cache plugins.

Field name Field type Comment
Enabled

bool

Enabled is a boolean flag. If set to true, the advanced caching plugin will be enabled.

Tyk classic API definition: version_data.versions..extended_paths.advance_cache_config[].disabled (negated).

CacheByRegex

string

CacheByRegex defines a regular expression used against the request body to produce a cache key.

Example value: \"id\":[^,]* (quoted json value).

Tyk classic API definition: version_data.versions..extended_paths.advance_cache_config[].cache_key_regex.

CacheResponseCodes

[]int

CacheResponseCodes contains a list of valid response codes for responses that are okay to add to the cache.

Tyk classic API definition: version_data.versions..extended_paths.advance_cache_config[].cache_response_codes.

Timeout

int64

Timeout is the TTL for the endpoint level caching in seconds. 0 means no caching.

Tyk classic API definition: version_data.versions..extended_paths.advance_cache_config[].timeout.

type CachePlugin struct {
	// Enabled is a boolean flag. If set to `true`, the advanced caching plugin will be enabled.
	//
	// Tyk classic API definition: `version_data.versions..extended_paths.advance_cache_config[].disabled` (negated).
	Enabled	bool	`bson:"enabled" json:"enabled"`

	// CacheByRegex defines a regular expression used against the request body to produce a cache key.
	//
	// Example value: `\"id\":[^,]*` (quoted json value).
	//
	// Tyk classic API definition: `version_data.versions..extended_paths.advance_cache_config[].cache_key_regex`.
	CacheByRegex	string	`bson:"cacheByRegex,omitempty" json:"cacheByRegex,omitempty"`

	// CacheResponseCodes contains a list of valid response codes for responses that are okay to add to the cache.
	//
	// Tyk classic API definition: `version_data.versions..extended_paths.advance_cache_config[].cache_response_codes`.
	CacheResponseCodes	[]int	`bson:"cacheResponseCodes,omitempty" json:"cacheResponseCodes,omitempty"`

	// Timeout is the TTL for the endpoint level caching in seconds. 0 means no caching.
	//
	// Tyk classic API definition: `version_data.versions..extended_paths.advance_cache_config[].timeout`.
	Timeout	int64	`bson:"timeout,omitempty" json:"timeout,omitempty"`
}

CertificatePinning

CertificatePinning holds the configuration about mapping of domains to pinned public keys.

Field name Field type Comment
Enabled

bool

Enabled is a boolean flag, if set to true, it enables certificate pinning for the API.

Tyk classic API definition: certificate_pinning_disabled

DomainToPublicKeysMapping

PinnedPublicKeys

DomainToPublicKeysMapping maintains the mapping of domain to pinned public keys.

Tyk classic API definition: pinned_public_keys

type CertificatePinning struct {
	// Enabled is a boolean flag, if set to `true`, it enables certificate pinning for the API.
	//
	// Tyk classic API definition: `certificate_pinning_disabled`
	Enabled	bool	`bson:"enabled" json:"enabled"`

	// DomainToPublicKeysMapping maintains the mapping of domain to pinned public keys.
	//
	// Tyk classic API definition: `pinned_public_keys`
	DomainToPublicKeysMapping	PinnedPublicKeys	`bson:"domainToPublicKeysMapping" json:"domainToPublicKeysMapping"`
}

CircuitBreaker

CircuitBreaker holds configuration for the circuit breaker middleware. Tyk classic API definition: version_data.versions..extended_paths.circuit_breakers[*].

Field name Field type Comment
Enabled

bool

Enabled activates the Circuit Breaker functionality.

Tyk classic API definition: version_data.versions..extended_paths.circuit_breakers[*].disabled (negated).

Threshold

float64

Threshold is the proportion from each sampleSize requests that must fail for the breaker to be tripped. This must be a value between 0.0 and 1.0. If sampleSize is 100 then a threshold of 0.4 means that the breaker will be tripped if 40 out of every 100 requests fails.

Tyk classic API definition: version_data.versions..extended_paths.circuit_breakers[*].threshold_percent.

SampleSize

int

SampleSize is the size of the circuit breaker sampling window. Combining this with threshold gives the failure rate required to trip the circuit breaker.

Tyk classic API definition: version_data.versions..extended_paths.circuit_breakers[*].samples.

CoolDownPeriod

int

CoolDownPeriod is the period of time (in seconds) for which the circuit breaker will remain open before returning to service.

Tyk classic API definition: version_data.versions..extended_paths.circuit_breakers[*].return_to_service_after.

HalfOpenStateEnabled

bool

HalfOpenStateEnabled , if enabled, allows some requests to pass through the circuit breaker during the cool down period. If Tyk detects that the path is now working, the circuit breaker will be automatically reset and traffic will be resumed to the upstream.

Tyk classic API definition: version_data.versions..extended_paths.circuit_breakers[*].disable_half_open_state (negated).

type CircuitBreaker struct {
	// Enabled activates the Circuit Breaker functionality.
	//
	// Tyk classic API definition: `version_data.versions..extended_paths.circuit_breakers[*].disabled` (negated).
	Enabled	bool	`bson:"enabled" json:"enabled"`
	// Threshold is the proportion from each `sampleSize` requests that must fail for the breaker to be tripped. This must be a value between 0.0 and 1.0. If `sampleSize` is 100 then a threshold of 0.4 means that the breaker will be tripped if 40 out of every 100 requests fails.
	//
	// Tyk classic API definition: `version_data.versions..extended_paths.circuit_breakers[*].threshold_percent`.
	Threshold	float64	`bson:"threshold" json:"threshold"`
	// SampleSize is the size of the circuit breaker sampling window. Combining this with `threshold` gives the failure rate required to trip the circuit breaker.
	//
	// Tyk classic API definition: `version_data.versions..extended_paths.circuit_breakers[*].samples`.
	SampleSize	int	`bson:"sampleSize" json:"sampleSize"`
	// CoolDownPeriod is the period of time (in seconds) for which the circuit breaker will remain open before returning to service.
	//
	// Tyk classic API definition: `version_data.versions..extended_paths.circuit_breakers[*].return_to_service_after`.
	CoolDownPeriod	int	`bson:"coolDownPeriod" json:"coolDownPeriod"`
	// HalfOpenStateEnabled , if enabled, allows some requests to pass through the circuit breaker during the cool down period. If Tyk detects that the path is now working, the circuit breaker will be automatically reset and traffic will be resumed to the upstream.
	//
	// Tyk classic API definition: `version_data.versions..extended_paths.circuit_breakers[*].disable_half_open_state` (negated).
	HalfOpenStateEnabled	bool	`bson:"halfOpenStateEnabled" json:"halfOpenStateEnabled"`
}

ClientAuthData

ClientAuthData holds the client ID and secret for OAuth2 authentication.

Field name Field type Comment
ClientID

string

ClientID is the application's ID.

ClientSecret

string

ClientSecret is the application's secret.

type ClientAuthData struct {
	// ClientID is the application's ID.
	ClientID	string	`bson:"clientId" json:"clientId"`
	// ClientSecret is the application's secret.
	ClientSecret	string	`bson:"clientSecret,omitempty" json:"clientSecret,omitempty"`	// client secret is optional for password flow
}

ClientCertificates

ClientCertificates contains the configurations related to establishing static mutual TLS between the client and Tyk.

Field name Field type Comment
Enabled

bool

Enabled activates static mTLS for the API.

Tyk classic API definition: use_mutual_tls_auth.

Allowlist

[]string

Allowlist is the list of client certificates which are allowed.

Tyk classic API definition: client_certificates.

type ClientCertificates struct {
	// Enabled activates static mTLS for the API.
	//
	// Tyk classic API definition: `use_mutual_tls_auth`.
	Enabled	bool	`bson:"enabled" json:"enabled"`
	// Allowlist is the list of client certificates which are allowed.
	//
	// Tyk classic API definition: `client_certificates`.
	Allowlist	[]string	`bson:"allowlist" json:"allowlist"`
}

ClientCredentials

ClientCredentials holds the configuration for OAuth2 Client Credentials flow.

Field name Field type Comment

ClientAuthData

No comment on field.
Header

*AuthSource

Header holds the configuration for the custom header to be used for OAuth authentication.

TokenURL

string

TokenURL is the resource server's token endpoint URL. This is a constant specific to each server.

Scopes

[]string

Scopes specifies optional requested permissions.

ExtraMetadata

[]string

ExtraMetadata holds the keys that we want to extract from the token and pass to the upstream.

type ClientCredentials struct {
	ClientAuthData
	// Header holds the configuration for the custom header to be used for OAuth authentication.
	Header	*AuthSource	`bson:"header" json:"header"`
	// TokenURL is the resource server's token endpoint
	// URL. This is a constant specific to each server.
	TokenURL	string	`bson:"tokenUrl" json:"tokenUrl"`
	// Scopes specifies optional requested permissions.
	Scopes	[]string	`bson:"scopes,omitempty" json:"scopes,omitempty"`
	// ExtraMetadata holds the keys that we want to extract from the token and pass to the upstream.
	ExtraMetadata	[]string	`bson:"extraMetadata" json:"extraMetadata,omitempty"`
}

ClientToPolicy

ClientToPolicy contains a 1-1 mapping between Client ID and Policy ID.

Field name Field type Comment
ClientID

string

ClientID contains a Client ID.

Tyk classic API definition: Key in openid_options.providers[].client_ids map.

PolicyID

string

PolicyID contains a Policy ID.

Tyk classic API definition: Value in openid_options.providers[].client_ids map.

type ClientToPolicy struct {
	// ClientID contains a Client ID.
	//
	// Tyk classic API definition: Key in `openid_options.providers[].client_ids` map.
	ClientID	string	`bson:"clientId,omitempty" json:"clientId,omitempty"`

	// PolicyID contains a Policy ID.
	//
	// Tyk classic API definition: Value in `openid_options.providers[].client_ids` map.
	PolicyID	string	`bson:"policyId,omitempty" json:"policyId,omitempty"`
}

ContextVariables

ContextVariables holds the configuration related to Tyk context variables.

Field name Field type Comment
Enabled

bool

Enabled enables context variables to be passed to Tyk middlewares.

Tyk classic API definition: enable_context_vars.

type ContextVariables struct {
	// Enabled enables context variables to be passed to Tyk middlewares.
	//
	// Tyk classic API definition: `enable_context_vars`.
	Enabled bool `json:"enabled" bson:"enabled"`
}

CustomAnalyticsPlugins

CustomAnalyticsPlugins is a list of CustomPlugin objects for analytics.

Field name Field type Comment
type

[]CustomPlugin

No comment on field.
type CustomAnalyticsPlugins []CustomPlugin

CustomKeyLifetime

CustomKeyLifetime contains configuration for custom key retention.

Field name Field type Comment
Enabled

bool

Enabled enables custom maximum retention for keys for the API.

Value

ReadableDuration

Value configures the expiry interval for a Key. The value is a string that specifies the interval in a compact form, where hours, minutes and seconds are denoted by 'h', 'm' and 's' respectively. Multiple units can be combined to represent the duration.

Examples of valid shorthand notations:

  • "1h" : one hour
  • "20m" : twenty minutes
  • "30s" : thirty seconds
  • "1m29s": one minute and twenty-nine seconds
  • "1h30m" : one hour and thirty minutes

An empty value is interpreted as "0s"

Tyk classic API definition: session_lifetime.

RespectValidity

bool

RespectValidity ensures that Tyk respects the expiry configured in the key when the API level configuration grants a shorter lifetime. That is, Redis waits until the key has expired before deleting it.

Tyk classic API definition: session_lifetime_respects_key_expiration.

type CustomKeyLifetime struct {
	// Enabled enables custom maximum retention for keys for the API.
	Enabled	bool	`bson:"enabled,omitempty" json:"enabled,omitempty"`
	// Value configures the expiry interval for a Key.
	// The value is a string that specifies the interval in a compact form,
	// where hours, minutes and seconds are denoted by 'h', 'm' and 's' respectively.
	// Multiple units can be combined to represent the duration.
	//
	// Examples of valid shorthand notations:
	// - "1h"   : one hour
	// - "20m"  : twenty minutes
	// - "30s"  : thirty seconds
	// - "1m29s": one minute and twenty-nine seconds
	// - "1h30m" : one hour and thirty minutes
	//
	// An empty value is interpreted as "0s"
	//
	// Tyk classic API definition: `session_lifetime`.
	Value	ReadableDuration	`bson:"value" json:"value"`
	// RespectValidity ensures that Tyk respects the expiry configured in the key when the API level configuration grants a shorter lifetime.
	// That is, Redis waits until the key has expired before deleting it.
	//
	// Tyk classic API definition: `session_lifetime_respects_key_expiration`.
	RespectValidity	bool	`bson:"respectValidity,omitempty" json:"respectValidity,omitempty"`
}

CustomPlugin

CustomPlugin configures custom plugin.

Field name Field type Comment
Enabled

bool

Enabled activates the custom plugin.

Tyk classic API definition: custom_middleware.pre[].disabled, custom_middleware.post_key_auth[].disabled, custom_middleware.post[].disabled, custom_middleware.response[].disabled (negated).

FunctionName

string

FunctionName is the name of authentication method.

Tyk classic API definition: custom_middleware.pre[].name, custom_middleware.post_key_auth[].name, custom_middleware.post[].name, custom_middleware.response[].name.

Path

string

Path is the path to shared object file in case of goplugin mode or path to JS code in case of otto auth plugin.

Tyk classic API definition: custom_middleware.pre[].path, custom_middleware.post_key_auth[].path, custom_middleware.post[].path, custom_middleware.response[].path.

RawBodyOnly

bool

RawBodyOnly if set to true, do not fill body in request or response object.

Tyk classic API definition: custom_middleware.pre[].raw_body_only, custom_middleware.post_key_auth[].raw_body_only, custom_middleware.post[].raw_body_only, custom_middleware.response[].raw_body_only.

RequireSession

bool

RequireSession if set to true passes down the session information for plugins after authentication. RequireSession is used only with JSVM custom middleware.

Tyk classic API definition: custom_middleware.pre[].require_session, custom_middleware.post_key_auth[].require_session, custom_middleware.post[].require_session, custom_middleware.response[].require_session.

type CustomPlugin struct {
	// Enabled activates the custom plugin.
	//
	// Tyk classic API definition: `custom_middleware.pre[].disabled`, `custom_middleware.post_key_auth[].disabled`,
	// `custom_middleware.post[].disabled`, `custom_middleware.response[].disabled` (negated).
	Enabled	bool	`bson:"enabled" json:"enabled"`	// required.
	// FunctionName is the name of authentication method.
	//
	// Tyk classic API definition: `custom_middleware.pre[].name`, `custom_middleware.post_key_auth[].name`,
	// `custom_middleware.post[].name`, `custom_middleware.response[].name`.
	FunctionName	string	`bson:"functionName" json:"functionName"`	// required.
	// Path is the path to shared object file in case of goplugin mode or path to JS code in case of otto auth plugin.
	//
	// Tyk classic API definition: `custom_middleware.pre[].path`, `custom_middleware.post_key_auth[].path`,
	// `custom_middleware.post[].path`, `custom_middleware.response[].path`.
	Path	string	`bson:"path" json:"path"`
	// RawBodyOnly if set to true, do not fill body in request or response object.
	//
	// Tyk classic API definition: `custom_middleware.pre[].raw_body_only`, `custom_middleware.post_key_auth[].raw_body_only`,
	// `custom_middleware.post[].raw_body_only`, `custom_middleware.response[].raw_body_only`.
	RawBodyOnly	bool	`bson:"rawBodyOnly,omitempty" json:"rawBodyOnly,omitempty"`
	// RequireSession if set to true passes down the session information for plugins after authentication.
	// RequireSession is used only with JSVM custom middleware.
	//
	// Tyk classic API definition: `custom_middleware.pre[].require_session`, `custom_middleware.post_key_auth[].require_session`,
	// `custom_middleware.post[].require_session`, `custom_middleware.response[].require_session`.
	RequireSession	bool	`bson:"requireSession,omitempty" json:"requireSession,omitempty"`
}

CustomPluginAuthentication

CustomPluginAuthentication holds configuration for custom plugins.

Field name Field type Comment
Enabled

bool

Enabled activates the CustomPluginAuthentication authentication mode.

Tyk classic API definition: enable_coprocess_auth/use_go_plugin_auth.

Config

*AuthenticationPlugin

Config contains configuration related to custom authentication plugin.

Tyk classic API definition: custom_middleware.auth_check.

AuthSources

AuthSources contains authentication token sources (header, cookie, query). Valid only when driver is coprocess.

Tyk classic API definition: auth_configs["coprocess"].

type CustomPluginAuthentication struct {
	// Enabled activates the CustomPluginAuthentication authentication mode.
	//
	// Tyk classic API definition: `enable_coprocess_auth`/`use_go_plugin_auth`.
	Enabled	bool	`bson:"enabled" json:"enabled"`	// required

	// Config contains configuration related to custom authentication plugin.
	//
	// Tyk classic API definition: `custom_middleware.auth_check`.
	Config	*AuthenticationPlugin	`bson:"config,omitempty" json:"config,omitempty"`

	// AuthSources contains authentication token sources (header, cookie, query).
	// Valid only when driver is coprocess.
	//
	// Tyk classic API definition: `auth_configs["coprocess"]`.
	AuthSources	`bson:",inline" json:",inline"`
}

CustomPlugins

CustomPlugins is a list of CustomPlugin objects.

Field name Field type Comment
type

[]CustomPlugin

No comment on field.
type CustomPlugins []CustomPlugin

DetailedActivityLogs

DetailedActivityLogs holds the configuration related to recording detailed analytics.

Field name Field type Comment
Enabled

bool

Enabled activates detailed activity logs.

Tyk classic API definition: enable_detailed_recording

type DetailedActivityLogs struct {
	// Enabled activates detailed activity logs.
	//
	// Tyk classic API definition: `enable_detailed_recording`
	Enabled bool `bson:"enabled" json:"enabled"`
}

DetailedTracing

DetailedTracing holds the configuration of the detailed tracing.

Field name Field type Comment
Enabled

bool

Enabled activates detailed tracing.

Tyk classic API definition: detailed_tracing.

type DetailedTracing struct {
	// Enabled activates detailed tracing.
	//
	// Tyk classic API definition: `detailed_tracing`.
	Enabled bool `bson:"enabled" json:"enabled"`
}

Domain

Domain holds the configuration of the domain name the server should listen on.

Field name Field type Comment
Enabled

bool

Enabled allow/disallow the usage of the domain.

Tyk classic API definition: domain_disabled (negated).

Name

string

Name is the name of the domain.

Tyk classic API definition: domain.

Certificates

[]string

Certificates defines a field for specifying certificate IDs or file paths that the Gateway can utilise to dynamically load certificates for your custom domain.

Tyk classic API definition: certificates

type Domain struct {
	// Enabled allow/disallow the usage of the domain.
	//
	// Tyk classic API definition: `domain_disabled` (negated).
	Enabled	bool	`bson:"enabled" json:"enabled"`
	// Name is the name of the domain.
	//
	// Tyk classic API definition: `domain`.
	Name	string	`bson:"name" json:"name"`
	// Certificates defines a field for specifying certificate IDs or file paths
	// that the Gateway can utilise to dynamically load certificates for your custom domain.
	//
	// Tyk classic API definition: `certificates`
	Certificates	[]string	`bson:"certificates,omitempty" json:"certificates,omitempty"`
}

DomainToCertificate

DomainToCertificate holds a single mapping of domain name into a certificate.

Field name Field type Comment
Domain

string

Domain contains the domain name.

Certificate

string

Certificate contains the certificate mapped to the domain.

type DomainToCertificate struct {
	// Domain contains the domain name.
	Domain	string	`bson:"domain" json:"domain"`

	// Certificate contains the certificate mapped to the domain.
	Certificate	string	`bson:"certificate" json:"certificate"`
}

EndpointPostPlugin

EndpointPostPlugin contains endpoint level post plugin configuration.

Field name Field type Comment
Enabled

bool

Enabled activates post plugin.

Tyk classic API definition: version_data.versions..extended_paths.go_plugin.disabled(negated).

Name

string

Name is the name of plugin function to be executed. Deprecated: Use FunctionName instead.

FunctionName

string

FunctionName is the name of plugin function to be executed.

Tyk classic API definition: version_data.versions..extended_paths.go_plugin.symbol_name(negated).

Path

string

Path is the path to plugin.

Tyk classic API definition: version_data.versions..extended_paths.go_plugin.plugin_path(negated).

type EndpointPostPlugin struct {
	// Enabled activates post plugin.
	//
	// Tyk classic API definition: `version_data.versions..extended_paths.go_plugin.disabled`(negated).
	Enabled	bool	`bson:"enabled" json:"enabled"`	// required.
	// Name is the name of plugin function to be executed.
	// Deprecated: Use FunctionName instead.
	Name	string	`bson:"name,omitempty" json:"name,omitempty"`
	// FunctionName is the name of plugin function to be executed.
	//
	// Tyk classic API definition: `version_data.versions..extended_paths.go_plugin.symbol_name`(negated).
	FunctionName	string	`bson:"functionName" json:"functionName"`	// required.
	// Path is the path to plugin.
	//
	// Tyk classic API definition: `version_data.versions..extended_paths.go_plugin.plugin_path`(negated).
	Path	string	`bson:"path" json:"path"`	// required.
}

EndpointPostPlugins

EndpointPostPlugins is a list of EndpointPostPlugins. It's used where multiple plugins can be run.

Field name Field type Comment
type

[]EndpointPostPlugin

No comment on field.
type EndpointPostPlugins []EndpointPostPlugin

EnforceTimeout

EnforceTimeout holds the configuration for enforcing request timeouts.

Field name Field type Comment
Enabled

bool

Enabled is a boolean flag. If set to true, requests will enforce a configured timeout.

Tyk classic API definition: version_data.versions..extended_paths.hard_timeouts[].disabled (negated).

Value

int

Value is the configured timeout in seconds.

Tyk classic API definition: version_data.versions..extended_paths.hard_timeouts[].timeout.

type EnforceTimeout struct {
	// Enabled is a boolean flag. If set to `true`, requests will enforce a configured timeout.
	//
	// Tyk classic API definition: `version_data.versions..extended_paths.hard_timeouts[].disabled` (negated).
	Enabled	bool	`bson:"enabled" json:"enabled"`

	// Value is the configured timeout in seconds.
	//
	// Tyk classic API definition: `version_data.versions..extended_paths.hard_timeouts[].timeout`.
	Value	int	`bson:"value" json:"value"`
}

EventHandler

EventHandler holds information about individual event to be configured on the API.

Field name Field type Comment
Enabled

bool

Enabled enables the event handler.

Tyk classic API definition: event_handlers.events[].handler_meta.disabled (negated).

Trigger

event.Event

Trigger specifies the TykEvent that should trigger the event handler.

Tyk classic API definition: event_handlers.events key.

Kind

Kind

Kind specifies the action to be taken on the event trigger.

Tyk classic API definition: event_handlers.events[].handler.

ID

string

ID is the ID of event handler in storage.

Tyk classic API definition: event_handlers.events[].handler_meta.id.

Name

string

Name is the name of event handler.

Tyk classic API definition: event_handlers.events[].handler_meta.name.

Webhook

WebhookEvent

Webhook contains WebhookEvent configs. Encoding and decoding is handled by the custom marshaller.

JSVMEvent

JSVMEvent

JSVMEvent holds information about JavaScript VM events.

LogEvent

LogEvent

LogEvent represents the configuration for logging events tied to an event handler.

type EventHandler struct {
	// Enabled enables the event handler.
	//
	// Tyk classic API definition: `event_handlers.events[].handler_meta.disabled` (negated).
	Enabled	bool	`json:"enabled" bson:"enabled"`
	// Trigger specifies the TykEvent that should trigger the event handler.
	//
	// Tyk classic API definition: `event_handlers.events` key.
	Trigger	event.Event	`json:"trigger" bson:"trigger"`
	// Kind specifies the action to be taken on the event trigger.
	//
	// Tyk classic API definition: `event_handlers.events[].handler`.
	Kind	Kind	`json:"type" bson:"type"`	// json tag is changed as per contract
	// ID is the ID of event handler in storage.
	//
	// Tyk classic API definition: `event_handlers.events[].handler_meta.id`.
	ID	string	`json:"id,omitempty" bson:"id,omitempty"`
	// Name is the name of event handler.
	//
	// Tyk classic API definition: `event_handlers.events[].handler_meta.name`.
	Name	string	`json:"name,omitempty" bson:"name,omitempty"`

	// Webhook contains WebhookEvent configs. Encoding and decoding is handled by the custom marshaller.
	Webhook	WebhookEvent	`bson:"-" json:"-"`

	// JSVMEvent holds information about JavaScript VM events.
	JSVMEvent	JSVMEvent	`bson:"-" json:"-"`

	// LogEvent represents the configuration for logging events tied to an event handler.
	LogEvent	LogEvent	`bson:"-" json:"-"`
}

EventHandlers

EventHandlers holds the list of events to be processed for the API.

Field name Field type Comment
type

[]EventHandler

No comment on field.
type EventHandlers []EventHandler

ExternalOAuth

ExternalOAuth holds configuration for an external OAuth provider. Deprecated: ExternalOAuth support has been deprecated from 5.7.0. To avoid any disruptions, we recommend that you use JSON Web Token (JWT) instead, as explained in https://tyk.io/docs/basic-config-and-security/security/authentication-authorization/ext-oauth-middleware/.

Field name Field type Comment
Enabled

bool

Enabled activates external oauth functionality.

Tyk classic API definition: external_oauth.enabled.

AuthSources

AuthSources configures the source for the authentication token.

Providers

[]OAuthProvider

Providers is used to configure OAuth providers.

Tyk classic API definition: external_oauth.providers.

type ExternalOAuth struct {
	// Enabled activates external oauth functionality.
	//
	// Tyk classic API definition: `external_oauth.enabled`.
	Enabled	bool	`bson:"enabled" json:"enabled"`	// required

	// AuthSources configures the source for the authentication token.
	AuthSources	`bson:",inline" json:",inline"`

	// Providers is used to configure OAuth providers.
	//
	// Tyk classic API definition: `external_oauth.providers`.
	Providers	[]OAuthProvider	`bson:"providers" json:"providers"`	// required
}

ExtractCredentialsFromBody

ExtractCredentialsFromBody configures extracting credentials from the request body.

Field name Field type Comment
Enabled

bool

Enabled activates extracting credentials from body. Tyk classic API definition: basic_auth.extract_from_body

UserRegexp

string

UserRegexp is the regex for username e.g. <User>(.*)</User>. Tyk classic API definition: basic_auth.userRegexp

PasswordRegexp

string

PasswordRegexp is the regex for password e.g. <Password>(.*)</Password>. Tyk classic API definition: basic_auth.passwordRegexp

type ExtractCredentialsFromBody struct {
	// Enabled activates extracting credentials from body.
	// Tyk classic API definition: `basic_auth.extract_from_body`
	Enabled	bool	`bson:"enabled" json:"enabled"`	// required
	// UserRegexp is the regex for username e.g. `<User>(.*)</User>`.
	// Tyk classic API definition: `basic_auth.userRegexp`
	UserRegexp	string	`bson:"userRegexp,omitempty" json:"userRegexp,omitempty"`
	// PasswordRegexp is the regex for password e.g. `<Password>(.*)</Password>`.
	// Tyk classic API definition: `basic_auth.passwordRegexp`
	PasswordRegexp	string	`bson:"passwordRegexp,omitempty" json:"passwordRegexp,omitempty"`
}

FromOASExamples

FromOASExamples configures mock responses that should be returned from OAS example responses.

Field name Field type Comment
Enabled

bool

Enabled activates getting a mock response from OAS examples or schemas documented in OAS.

Code

int

Code is the default HTTP response code that the gateway reads from the path responses documented in OAS.

ContentType

string

ContentType is the default HTTP response body type that the gateway reads from the path responses documented in OAS.

ExampleName

string

ExampleName is the default example name among multiple path response examples documented in OAS.

type FromOASExamples struct {
	// Enabled activates getting a mock response from OAS examples or schemas documented in OAS.
	Enabled	bool	`bson:"enabled" json:"enabled"`
	// Code is the default HTTP response code that the gateway reads from the path responses documented in OAS.
	Code	int	`bson:"code,omitempty" json:"code,omitempty"`
	// ContentType is the default HTTP response body type that the gateway reads from the path responses documented in OAS.
	ContentType	string	`bson:"contentType,omitempty" json:"contentType,omitempty"`
	// ExampleName is the default example name among multiple path response examples documented in OAS.
	ExampleName	string	`bson:"exampleName,omitempty" json:"exampleName,omitempty"`
}

GatewayTags

GatewayTags holds a list of segment tags that should apply for a gateway.

Field name Field type Comment
Enabled

bool

Enabled activates use of segment tags.

Tyk classic API definition: tags_disabled (negated).

Tags

[]string

Tags contains a list of segment tags.

Tyk classic API definition: tags.

type GatewayTags struct {
	// Enabled activates use of segment tags.
	//
	// Tyk classic API definition: `tags_disabled` (negated).
	Enabled	bool	`bson:"enabled" json:"enabled"`
	// Tags contains a list of segment tags.
	//
	// Tyk classic API definition: `tags`.
	Tags	[]string	`bson:"tags" json:"tags"`
}

Global

Global contains configuration that affects the whole API (all endpoints).

Field name Field type Comment
PluginConfig

*PluginConfig

PluginConfig contains the common configuration for custom plugins.

CORS

*CORS

CORS contains the configuration related to Cross Origin Resource Sharing. Tyk classic API definition: CORS.

PrePlugin

*PrePlugin

PrePlugin contains configuration related to the custom plugin that is run before authentication. Deprecated: Use PrePlugins instead.

PrePlugins

CustomPlugins

PrePlugins contains configuration related to the custom plugin that is run before authentication. Tyk classic API definition: custom_middleware.pre.

PostAuthenticationPlugin

*PostAuthenticationPlugin

PostAuthenticationPlugin contains configuration related to the custom plugin that is run immediately after authentication. Deprecated: Use PostAuthenticationPlugins instead.

PostAuthenticationPlugins

CustomPlugins

PostAuthenticationPlugins contains configuration related to the custom plugin that is run immediately after authentication. Tyk classic API definition: custom_middleware.post_key_auth.

PostPlugin

*PostPlugin

PostPlugin contains configuration related to the custom plugin that is run immediately prior to proxying the request to the upstream. Deprecated: Use PostPlugins instead.

PostPlugins

CustomPlugins

PostPlugins contains configuration related to the custom plugin that is run immediately prior to proxying the request to the upstream. Tyk classic API definition: custom_middleware.post.

ResponsePlugin

*ResponsePlugin

ResponsePlugin contains configuration related to the custom plugin that is run during processing of the response from the upstream service. Deprecated: Use ResponsePlugins instead.

ResponsePlugins

CustomPlugins

ResponsePlugins contains configuration related to the custom plugin that is run during processing of the response from the upstream service.

Tyk classic API definition: custom_middleware.response.

Cache

*Cache

Cache contains the configurations related to caching. Tyk classic API definition: cache_options.

TransformRequestHeaders

*TransformHeaders

TransformRequestHeaders contains the configurations related to API level request header transformation. Tyk classic API definition: global_headers/global_headers_remove.

TransformResponseHeaders

*TransformHeaders

TransformResponseHeaders contains the configurations related to API level response header transformation. Tyk classic API definition: global_response_headers/global_response_headers_remove.

ContextVariables

*ContextVariables

ContextVariables contains the configuration related to Tyk context variables.

TrafficLogs

*TrafficLogs

TrafficLogs contains the configurations related to API level log analytics.

RequestSizeLimit

*GlobalRequestSizeLimit

RequestSizeLimit contains the configuration related to limiting the global request size.

IgnoreCase

*IgnoreCase

IgnoreCase contains the configuration to treat routes as case-insensitive.

SkipRateLimit

bool

SkipRateLimit determines whether the rate-limiting middleware logic should be skipped. Tyk classic API definition: disable_rate_limit.

SkipQuota

bool

SkipQuota determines whether quota enforcement should be bypassed. Tyk classic API definition: disable_quota.

SkipQuotaReset

bool

SkipQuotaReset indicates if quota limits should not be reset when creating or updating quotas for the API. Tyk classic API definition: dont_set_quota_on_create.

type Global struct {
	// PluginConfig contains the common configuration for custom plugins.
	PluginConfig	*PluginConfig	`bson:"pluginConfig,omitempty" json:"pluginConfig,omitempty"`

	// CORS contains the configuration related to Cross Origin Resource Sharing.
	// Tyk classic API definition: `CORS`.
	CORS	*CORS	`bson:"cors,omitempty" json:"cors,omitempty"`

	// PrePlugin contains configuration related to the custom plugin that is run before authentication.
	// Deprecated: Use PrePlugins instead.
	PrePlugin	*PrePlugin	`bson:"prePlugin,omitempty" json:"prePlugin,omitempty"`

	// PrePlugins contains configuration related to the custom plugin that is run before authentication.
	// Tyk classic API definition: `custom_middleware.pre`.
	PrePlugins	CustomPlugins	`bson:"prePlugins,omitempty" json:"prePlugins,omitempty"`

	// PostAuthenticationPlugin contains configuration related to the custom plugin that is run immediately after authentication.
	// Deprecated: Use PostAuthenticationPlugins instead.
	PostAuthenticationPlugin	*PostAuthenticationPlugin	`bson:"postAuthenticationPlugin,omitempty" json:"postAuthenticationPlugin,omitempty"`

	// PostAuthenticationPlugins contains configuration related to the custom plugin that is run immediately after authentication.
	// Tyk classic API definition: `custom_middleware.post_key_auth`.
	PostAuthenticationPlugins	CustomPlugins	`bson:"postAuthenticationPlugins,omitempty" json:"postAuthenticationPlugins,omitempty"`

	// PostPlugin contains configuration related to the custom plugin that is run immediately prior to proxying the request to the upstream.
	// Deprecated: Use PostPlugins instead.
	PostPlugin	*PostPlugin	`bson:"postPlugin,omitempty" json:"postPlugin,omitempty"`

	// PostPlugins contains configuration related to the custom plugin that is run immediately prior to proxying the request to the upstream.
	// Tyk classic API definition: `custom_middleware.post`.
	PostPlugins	CustomPlugins	`bson:"postPlugins,omitempty" json:"postPlugins,omitempty"`

	// ResponsePlugin contains configuration related to the custom plugin that is run during processing of the response from the upstream service.
	// Deprecated: Use ResponsePlugins instead.
	ResponsePlugin	*ResponsePlugin	`bson:"responsePlugin,omitempty" json:"responsePlugin,omitempty"`

	// ResponsePlugins contains configuration related to the custom plugin that is run during processing of the response from the upstream service.
	//
	// Tyk classic API definition: `custom_middleware.response`.
	ResponsePlugins	CustomPlugins	`bson:"responsePlugins,omitempty" json:"responsePlugins,omitempty"`

	// Cache contains the configurations related to caching.
	// Tyk classic API definition: `cache_options`.
	Cache	*Cache	`bson:"cache,omitempty" json:"cache,omitempty"`

	// TransformRequestHeaders contains the configurations related to API level request header transformation.
	// Tyk classic API definition: `global_headers`/`global_headers_remove`.
	TransformRequestHeaders	*TransformHeaders	`bson:"transformRequestHeaders,omitempty" json:"transformRequestHeaders,omitempty"`

	// TransformResponseHeaders contains the configurations related to API level response header transformation.
	// Tyk classic API definition: `global_response_headers`/`global_response_headers_remove`.
	TransformResponseHeaders	*TransformHeaders	`bson:"transformResponseHeaders,omitempty" json:"transformResponseHeaders,omitempty"`

	// ContextVariables contains the configuration related to Tyk context variables.
	ContextVariables	*ContextVariables	`bson:"contextVariables,omitempty" json:"contextVariables,omitempty"`

	// TrafficLogs contains the configurations related to API level log analytics.
	TrafficLogs	*TrafficLogs	`bson:"trafficLogs,omitempty" json:"trafficLogs,omitempty"`

	// RequestSizeLimit contains the configuration related to limiting the global request size.
	RequestSizeLimit	*GlobalRequestSizeLimit	`bson:"requestSizeLimit,omitempty" json:"requestSizeLimit,omitempty"`

	// IgnoreCase contains the configuration to treat routes as case-insensitive.
	IgnoreCase	*IgnoreCase	`bson:"ignoreCase,omitempty" json:"ignoreCase,omitempty"`

	// SkipRateLimit determines whether the rate-limiting middleware logic should be skipped.
	// Tyk classic API definition: `disable_rate_limit`.
	SkipRateLimit	bool	`bson:"skipRateLimit,omitempty" json:"skipRateLimit,omitempty"`

	// SkipQuota determines whether quota enforcement should be bypassed.
	// Tyk classic API definition: `disable_quota`.
	SkipQuota	bool	`bson:"skipQuota,omitempty" json:"skipQuota,omitempty"`

	// SkipQuotaReset indicates if quota limits should not be reset when creating or updating quotas for the API.
	// Tyk classic API definition: `dont_set_quota_on_create`.
	SkipQuotaReset	bool	`bson:"skipQuotaReset,omitempty" json:"skipQuotaReset,omitempty"`
}

GlobalRequestSizeLimit

GlobalRequestSizeLimit holds configuration about the global limits for request sizes.

Field name Field type Comment
Enabled

bool

Enabled activates the Request Size Limit.

Tyk classic API definition: version_data.versions..global_size_limit_disabled (negated).

Value

int64

Value contains the value of the request size limit.

Tyk classic API definition: version_data.versions..global_size_limit.

type GlobalRequestSizeLimit struct {
	// Enabled activates the Request Size Limit.
	//
	// Tyk classic API definition: `version_data.versions..global_size_limit_disabled` (negated).
	Enabled	bool	`bson:"enabled" json:"enabled"`
	// Value contains the value of the request size limit.
	//
	// Tyk classic API definition: `version_data.versions..global_size_limit`.
	Value	int64	`bson:"value" json:"value"`
}

HMAC

HMAC holds the configuration for the HMAC authentication mode.

Field name Field type Comment
Enabled

bool

Enabled activates the HMAC authentication mode.

Tyk classic API definition: enable_signature_checking.

AuthSources

AuthSources contains authentication token source configuration (header, cookie, query).

AllowedAlgorithms

[]string

AllowedAlgorithms is the array of HMAC algorithms which are allowed.

Tyk supports the following HMAC algorithms:

  • hmac-sha1
  • hmac-sha256
  • hmac-sha384
  • hmac-sha512

and reads the value from the algorithm header.

Tyk classic API definition: hmac_allowed_algorithms.

AllowedClockSkew

float64

AllowedClockSkew is the amount of milliseconds that will be tolerated for clock skew. It is used against replay attacks. The default value is 0, which deactivates clock skew checks.

Tyk classic API definition: hmac_allowed_clock_skew.

type HMAC struct {
	// Enabled activates the HMAC authentication mode.
	//
	// Tyk classic API definition: `enable_signature_checking`.
	Enabled	bool	`bson:"enabled" json:"enabled"`	// required

	// AuthSources contains authentication token source configuration (header, cookie, query).
	AuthSources	`bson:",inline" json:",inline"`

	// AllowedAlgorithms is the array of HMAC algorithms which are allowed.
	//
	// Tyk supports the following HMAC algorithms:
	//
	// - `hmac-sha1`
	// - `hmac-sha256`
	// - `hmac-sha384`
	// - `hmac-sha512`
	//
	// and reads the value from the algorithm header.
	//
	// Tyk classic API definition: `hmac_allowed_algorithms`.
	AllowedAlgorithms	[]string	`bson:"allowedAlgorithms,omitempty" json:"allowedAlgorithms,omitempty"`

	// AllowedClockSkew is the amount of milliseconds that will be tolerated for clock skew. It is used against replay attacks.
	// The default value is `0`, which deactivates clock skew checks.
	//
	// Tyk classic API definition: `hmac_allowed_clock_skew`.
	AllowedClockSkew	float64	`bson:"allowedClockSkew,omitempty" json:"allowedClockSkew,omitempty"`
}

Header holds a header name and value pair.

Field name Field type Comment
Name

string

Name is the name of the header.

Value

string

Value is the value of the header.

type Header struct {
	// Name is the name of the header.
	Name	string	`bson:"name" json:"name"`
	// Value is the value of the header.
	Value	string	`bson:"value" json:"value"`
}

Headers

Headers is an array of Header.

Field name Field type Comment
type

[]Header

No comment on field.
type Headers []Header

IDExtractor

IDExtractor configures ID Extractor.

Field name Field type Comment
Enabled

bool

Enabled activates ID extractor with coprocess authentication.

Tyk classic API definition: custom_middleware.id_extractor.disabled (negated).

Source

apidef.IdExtractorSource

Source is the source from which ID to be extracted from. Valid values are:

  • header - Extract ID from a header
  • form - Extract ID from a form parameter
  • body - Extract ID from the request body

Tyk classic API definition: custom_middleware.id_extractor.extract_from.

With

apidef.IdExtractorType

With is the type of ID extractor to be used. Valid values are:

  • value - Extract ID from a value
  • xpath - Extract ID using an XPath expression
  • regex - Extract ID using a regular expression

Tyk classic API definition: custom_middleware.id_extractor.extract_with.

Config

*IDExtractorConfig

Config holds the configuration specific to ID extractor type mentioned via With.

Tyk classic API definition: custom_middleware.id_extractor.extractor_config.

type IDExtractor struct {
	// Enabled activates ID extractor with coprocess authentication.
	//
	// Tyk classic API definition: `custom_middleware.id_extractor.disabled` (negated).
	Enabled	bool	`bson:"enabled" json:"enabled"`	// required
	// Source is the source from which ID to be extracted from.
	// Valid values are:
	// - `header` - Extract ID from a header
	// - `form` - Extract ID from a form parameter
	// - `body` - Extract ID from the request body
	//
	// Tyk classic API definition: `custom_middleware.id_extractor.extract_from`.
	Source	apidef.IdExtractorSource	`bson:"source" json:"source"`	// required
	// With is the type of ID extractor to be used.
	// Valid values are:
	// - `value` - Extract ID from a value
	// - `xpath` - Extract ID using an XPath expression
	// - `regex` - Extract ID using a regular expression
	//
	// Tyk classic API definition: `custom_middleware.id_extractor.extract_with`.
	With	apidef.IdExtractorType	`bson:"with" json:"with"`	// required
	// Config holds the configuration specific to ID extractor type mentioned via With.
	//
	// Tyk classic API definition: `custom_middleware.id_extractor.extractor_config`.
	Config	*IDExtractorConfig	`bson:"config" json:"config"`	// required
}

IDExtractorConfig

IDExtractorConfig specifies the configuration for ID extractor.

Field name Field type Comment
HeaderName

string

HeaderName is the header name to extract ID from. Used when Source is set to "header" and With is set to "value".

Tyk classic API definition: custom_middleware.id_extractor.extractor_config.header_name.

FormParamName

string

FormParamName is the form parameter name to extract ID from. Used when Source is set to "form" and With is set to "value".

Tyk classic API definition: custom_middleware.id_extractor.extractor_config.form_param_name.

Regexp

string

Regexp is the regular expression to match ID. Used when With is set to "regex".

Tyk classic API definition: custom_middleware.id_extractor.extractor_config.regex_expression.

RegexpMatchIndex

int

RegexpMatchIndex is the index from which ID to be extracted after a match. Default value is 0, ie if regexpMatchIndex is not provided ID is matched from index 0. Used when With is set to "regex".

Tyk classic API definition: custom_middleware.id_extractor.extractor_config.regex_match_index.

XPathExp

string

XPathExp is the xpath expression to match ID. Used when With is set to "xpath".

Tyk classic API definition: custom_middleware.id_extractor.extractor_config.xpath_expression.

type IDExtractorConfig struct {
	// HeaderName is the header name to extract ID from.
	// Used when Source is set to "header" and With is set to "value".
	//
	// Tyk classic API definition: `custom_middleware.id_extractor.extractor_config.header_name`.
	HeaderName	string	`bson:"headerName,omitempty" json:"headerName,omitempty"`
	// FormParamName is the form parameter name to extract ID from.
	// Used when Source is set to "form" and With is set to "value".
	//
	// Tyk classic API definition: `custom_middleware.id_extractor.extractor_config.form_param_name`.
	FormParamName	string	`bson:"formParamName,omitempty" json:"formParamName,omitempty"`
	// Regexp is the regular expression to match ID.
	// Used when With is set to "regex".
	//
	// Tyk classic API definition: `custom_middleware.id_extractor.extractor_config.regex_expression`.
	Regexp	string	`bson:"regexp,omitempty" json:"regexp,omitempty"`
	// RegexpMatchIndex is the index from which ID to be extracted after a match.
	// Default value is 0, ie if regexpMatchIndex is not provided ID is matched from index 0.
	// Used when With is set to "regex".
	//
	// Tyk classic API definition: `custom_middleware.id_extractor.extractor_config.regex_match_index`.
	RegexpMatchIndex	int	`bson:"regexpMatchIndex,omitempty" json:"regexpMatchIndex,omitempty"`
	// XPathExp is the xpath expression to match ID.
	// Used when With is set to "xpath".
	//
	// Tyk classic API definition: `custom_middleware.id_extractor.extractor_config.xpath_expression`.
	XPathExp	string	`bson:"xPathExp,omitempty" json:"xPathExp,omitempty"`
}

IPAccessControl

IPAccessControl represents IP access control configuration.

Field name Field type Comment
Enabled

bool

Enabled indicates whether IP access control is enabled.

Tyk classic API definition: ip_access_control_disabled (negated).

Allow

[]string

Allow is a list of allowed IP addresses or CIDR blocks (e.g. "192.168.1.0/24"). Note that if an IP address is present in both Allow and Block, the Block rule will take precedence.

Tyk classic API definition: allowed_ips.

Block

[]string

Block is a list of blocked IP addresses or CIDR blocks (e.g. "192.168.1.100/32"). If an IP address is present in both Allow and Block, the Block rule will take precedence.

Tyk classic API definition: blacklisted_ips.

type IPAccessControl struct {
	// Enabled indicates whether IP access control is enabled.
	//
	// Tyk classic API definition: `ip_access_control_disabled` (negated).
	Enabled	bool	`bson:"enabled" json:"enabled"`

	// Allow is a list of allowed IP addresses or CIDR blocks (e.g. "192.168.1.0/24").
	// Note that if an IP address is present in both Allow and Block, the Block rule will take precedence.
	//
	// Tyk classic API definition: `allowed_ips`.
	Allow	[]string	`bson:"allow,omitempty" json:"allow,omitempty"`

	// Block is a list of blocked IP addresses or CIDR blocks (e.g. "192.168.1.100/32").
	// If an IP address is present in both Allow and Block, the Block rule will take precedence.
	//
	// Tyk classic API definition: `blacklisted_ips`.
	Block	[]string	`bson:"block,omitempty" json:"block,omitempty"`
}

IgnoreCase

IgnoreCase will make route matching be case insensitive. This accepts request to /AAA or /aaa if set to true.

Field name Field type Comment
Enabled

bool

Enabled activates case insensitive route matching.

Tyk classic API definition: version_data.versions..ignore_endpoint_case.

type IgnoreCase struct {
	// Enabled activates case insensitive route matching.
	//
	// Tyk classic API definition: `version_data.versions..ignore_endpoint_case`.
	Enabled bool `json:"enabled" bson:"enabled"`
}

Info

Info contains the main metadata for the API definition.

Field name Field type Comment
ID

string

ID is the unique identifier of the API within Tyk. Tyk classic API definition: api_id

DBID

model.ObjectID

DBID is the unique identifier of the API within the Tyk database. Tyk classic API definition: id

OrgID

string

OrgID is the ID of the organisation which the API belongs to. Tyk classic API definition: org_id

Name

string

Name is the name of the API. Tyk classic API definition: name

Expiration

string

Expiration date. Tyk classic API definition: expiration

State

State

State holds configuration for API definition states (active, internal).

Versioning

*Versioning

Versioning holds configuration for API versioning.

type Info struct {
	// ID is the unique identifier of the API within Tyk.
	// Tyk classic API definition: `api_id`
	ID	string	`bson:"id" json:"id,omitempty"`
	// DBID is the unique identifier of the API within the Tyk database.
	// Tyk classic API definition: `id`
	DBID	model.ObjectID	`bson:"dbId" json:"dbId,omitempty"`
	// OrgID is the ID of the organisation which the API belongs to.
	// Tyk classic API definition: `org_id`
	OrgID	string	`bson:"orgId" json:"orgId,omitempty"`
	// Name is the name of the API.
	// Tyk classic API definition: `name`
	Name	string	`bson:"name" json:"name"`	// required
	// Expiration date.
	// Tyk classic API definition: `expiration`
	Expiration	string	`bson:"expiration,omitempty" json:"expiration,omitempty"`
	// State holds configuration for API definition states (active, internal).
	State	State	`bson:"state" json:"state"`	// required
	// Versioning holds configuration for API versioning.
	Versioning	*Versioning	`bson:"versioning,omitempty" json:"versioning,omitempty"`
}

Internal

Internal holds the endpoint configuration, configuring the endpoint for internal requests. Tyk classic API definition: version_data.versions...extended_paths.internal[*].

Field name Field type Comment
Enabled

bool

Enabled if set to true makes the endpoint available only for internal requests.

type Internal struct {
	// Enabled if set to true makes the endpoint available only for internal requests.
	Enabled bool `bson:"enabled" json:"enabled"`
}

Introspection

Introspection holds configuration for OAuth token introspection.

Field name Field type Comment
Enabled

bool

Enabled activates OAuth access token validation by introspection to a third party.

Tyk classic API definition: external_oauth.providers[].introspection.enabled.

URL

string

URL is the URL of the third party provider's introspection endpoint.

Tyk classic API definition: external_oauth.providers[].introspection.url.

ClientID

string

ClientID is the public identifier for the client, acquired from the third party.

Tyk classic API definition: external_oauth.providers[].introspection.client_id.

ClientSecret

string

ClientSecret is a secret known only to the client and the authorisation server, acquired from the third party.

Tyk classic API definition: external_oauth.providers[].introspection.client_secret.

IdentityBaseField

string

IdentityBaseField is the key showing where to find the user id in the claims. If it is empty, the sub key is looked at.

Tyk classic API definition: external_oauth.providers[].introspection.identity_base_field.

Cache

*IntrospectionCache

Cache is the caching mechanism for introspection responses.

Tyk classic API definition: external_oauth.providers[].introspection.cache.

type Introspection struct {
	// Enabled activates OAuth access token validation by introspection to a third party.
	//
	// Tyk classic API definition: `external_oauth.providers[].introspection.enabled`.
	Enabled	bool	`bson:"enabled" json:"enabled"`
	// URL is the URL of the third party provider's introspection endpoint.
	//
	// Tyk classic API definition: `external_oauth.providers[].introspection.url`.
	URL	string	`bson:"url" json:"url"`
	// ClientID is the public identifier for the client, acquired from the third party.
	//
	// Tyk classic API definition: `external_oauth.providers[].introspection.client_id`.
	ClientID	string	`bson:"clientId" json:"clientId"`
	// ClientSecret is a secret known only to the client and the authorisation server, acquired from the third party.
	//
	// Tyk classic API definition: `external_oauth.providers[].introspection.client_secret`.
	ClientSecret	string	`bson:"clientSecret" json:"clientSecret"`
	// IdentityBaseField is the key showing where to find the user id in the claims. If it is empty, the `sub` key is looked at.
	//
	// Tyk classic API definition: `external_oauth.providers[].introspection.identity_base_field`.
	IdentityBaseField	string	`bson:"identityBaseField,omitempty" json:"identityBaseField,omitempty"`
	// Cache is the caching mechanism for introspection responses.
	//
	// Tyk classic API definition: `external_oauth.providers[].introspection.cache`.
	Cache	*IntrospectionCache	`bson:"cache,omitempty" json:"cache,omitempty"`
}

IntrospectionCache

IntrospectionCache holds configuration for caching introspection requests.

Field name Field type Comment
Enabled

bool

Enabled activates the caching mechanism for introspection responses.

Tyk classic API definition: external_oauth.providers[].introspection.cache.enabled.

Timeout

int64

Timeout is the duration in seconds of how long the cached value stays. For introspection caching, it is suggested to use a short interval.

Tyk classic API definition: external_oauth.providers[].introspection.cache.timeout.

type IntrospectionCache struct {
	// Enabled activates the caching mechanism for introspection responses.
	//
	// Tyk classic API definition: `external_oauth.providers[].introspection.cache.enabled`.
	Enabled	bool	`bson:"enabled" json:"enabled"`
	// Timeout is the duration in seconds of how long the cached value stays.
	// For introspection caching, it is suggested to use a short interval.
	//
	// Tyk classic API definition: `external_oauth.providers[].introspection.cache.timeout`.
	Timeout	int64	`bson:"timeout" json:"timeout"`
}

JSVMEvent

JSVMEvent represents a JavaScript VM event configuration for event handlers.

Field name Field type Comment
FunctionName

string

FunctionName specifies the JavaScript function name to be executed.

Tyk classic API definition: event_handlers.events[].handler_meta.method_name.

Path

string

Path specifies the path to the JavaScript file containing the function.

Tyk classic API definition: event_handlers.events[].handler_meta.path.

type JSVMEvent struct {
	// FunctionName specifies the JavaScript function name to be executed.
	//
	// Tyk classic API definition: `event_handlers.events[].handler_meta.method_name`.
	FunctionName	string	`json:"functionName" bson:"functionName"`
	// Path specifies the path to the JavaScript file containing the function.
	//
	// Tyk classic API definition: `event_handlers.events[].handler_meta.path`.
	Path	string	`json:"path" bson:"path"`
}

JWT

JWT holds the configuration for the JWT middleware.

Field name Field type Comment
Enabled

bool

Enabled activates the basic authentication mode.

Tyk classic API definition: enable_jwt

AuthSources

AuthSources configures the source for the JWT.

Source

string

Source contains the source for the JWT.

Tyk classic API definition: jwt_source

JwksURIs

[]apidef.JWK

JwksURIs contains a list of whitelisted JWK endpoints.

Tyk classic API definition: jwt_jwks_uris

SigningMethod

string

SigningMethod contains the signing method to use for the JWT.

Tyk classic API definition: jwt_signing_method

IdentityBaseField

string

IdentityBaseField specifies the claim name uniquely identifying the subject of the JWT. The identity fields that are checked in order are: kid, IdentityBaseField, sub.

Tyk classic API definition: jwt_identity_base_field

SkipKid

bool

SkipKid controls skipping using the kid claim from a JWT (default behaviour). When this is true, the field configured in IdentityBaseField is checked first.

Tyk classic API definition: jwt_skip_kid

PolicyFieldName

string

PolicyFieldName is a configurable claim name from which a policy ID is extracted. The policy is applied to the session as a base policy.

Tyk classic API definition: jwt_policy_field_name

ClientBaseField

string

ClientBaseField is used when PolicyFieldName is not provided. It will get a session key and use the policies from that. The field ensures that requests use the same session.

Tyk classic API definition: jwt_client_base_field

Scopes

*Scopes

Scopes holds the scope to policy mappings for a claim name.

DefaultPolicies

[]string

DefaultPolicies is a list of policy IDs that apply to the session.

Tyk classic API definition: jwt_default_policies

IssuedAtValidationSkew

uint64

IssuedAtValidationSkew contains the duration in seconds for which token issuance can predate the current time during the request.

Tyk classic API definition: jwt_issued_at_validation_skew.

NotBeforeValidationSkew

uint64

NotBeforeValidationSkew contains the duration in seconds for which token validity can predate the current time during the request.

Tyk classic API definition: jwt_not_before_validation_skew.

ExpiresAtValidationSkew

uint64

ExpiresAtValidationSkew contains the duration in seconds for which the token can be expired before we consider it expired.

Tyk classic API definition: jwt_expires_at_validation_skew.

IDPClientIDMappingDisabled

bool

IDPClientIDMappingDisabled prevents Tyk from automatically detecting the use of certain IDPs based on standard claims that they include in the JWT: client_id, cid, clientId. Setting this flag to true disables the mapping and avoids accidentally misidentifying the use of one of these IDPs if one of their standard values is configured in your JWT.

Tyk classic API definition: idp_client_id_mapping_disabled.

type JWT struct {
	// Enabled activates the basic authentication mode.
	//
	// Tyk classic API definition: `enable_jwt`
	Enabled	bool	`bson:"enabled" json:"enabled"`	// required

	// AuthSources configures the source for the JWT.
	AuthSources	`bson:",inline" json:",inline"`

	// Source contains the source for the JWT.
	//
	// Tyk classic API definition: `jwt_source`
	Source	string	`bson:"source,omitempty" json:"source,omitempty"`

	// JwksURIs contains a list of whitelisted JWK endpoints.
	//
	// Tyk classic API definition: `jwt_jwks_uris`
	JwksURIs	[]apidef.JWK	`bson:"jwksURIs,omitempty" json:"jwksURIs,omitempty"`

	// SigningMethod contains the signing method to use for the JWT.
	//
	// Tyk classic API definition: `jwt_signing_method`
	SigningMethod	string	`bson:"signingMethod,omitempty" json:"signingMethod,omitempty"`

	// IdentityBaseField specifies the claim name uniquely identifying the subject of the JWT.
	// The identity fields that are checked in order are: `kid`, IdentityBaseField, `sub`.
	//
	// Tyk classic API definition: `jwt_identity_base_field`
	IdentityBaseField	string	`bson:"identityBaseField,omitempty" json:"identityBaseField,omitempty"`

	// SkipKid controls skipping using the `kid` claim from a JWT (default behaviour).
	// When this is true, the field configured in IdentityBaseField is checked first.
	//
	// Tyk classic API definition: `jwt_skip_kid`
	SkipKid	bool	`bson:"skipKid,omitempty" json:"skipKid,omitempty"`

	// PolicyFieldName is a configurable claim name from which a policy ID is extracted.
	// The policy is applied to the session as a base policy.
	//
	// Tyk classic API definition: `jwt_policy_field_name`
	PolicyFieldName	string	`bson:"policyFieldName,omitempty" json:"policyFieldName,omitempty"`

	// ClientBaseField is used when PolicyFieldName is not provided. It will get
	// a session key and use the policies from that. The field ensures that requests
	// use the same session.
	//
	// Tyk classic API definition: `jwt_client_base_field`
	ClientBaseField	string	`bson:"clientBaseField,omitempty" json:"clientBaseField,omitempty"`

	// Scopes holds the scope to policy mappings for a claim name.
	Scopes	*Scopes	`bson:"scopes,omitempty" json:"scopes,omitempty"`

	// DefaultPolicies is a list of policy IDs that apply to the session.
	//
	// Tyk classic API definition: `jwt_default_policies`
	DefaultPolicies	[]string	`bson:"defaultPolicies,omitempty" json:"defaultPolicies,omitempty"`

	// IssuedAtValidationSkew contains the duration in seconds for which token issuance can predate the current time during the request.
	//
	// Tyk classic API definition: `jwt_issued_at_validation_skew`.
	IssuedAtValidationSkew	uint64	`bson:"issuedAtValidationSkew,omitempty" json:"issuedAtValidationSkew,omitempty"`

	// NotBeforeValidationSkew contains the duration in seconds for which token validity can predate the current time during the request.
	//
	// Tyk classic API definition: `jwt_not_before_validation_skew`.
	NotBeforeValidationSkew	uint64	`bson:"notBeforeValidationSkew,omitempty" json:"notBeforeValidationSkew,omitempty"`

	// ExpiresAtValidationSkew contains the duration in seconds for which the token can be expired before we consider it expired.
	//
	// Tyk classic API definition: `jwt_expires_at_validation_skew`.
	ExpiresAtValidationSkew	uint64	`bson:"expiresAtValidationSkew,omitempty" json:"expiresAtValidationSkew,omitempty"`

	// IDPClientIDMappingDisabled prevents Tyk from automatically detecting the use of certain IDPs based on standard claims
	// that they include in the JWT: `client_id`, `cid`, `clientId`. Setting this flag to `true` disables the mapping and avoids
	// accidentally misidentifying the use of one of these IDPs if one of their standard values is configured in your JWT.
	//
	// Tyk classic API definition: `idp_client_id_mapping_disabled`.
	IDPClientIDMappingDisabled	bool	`bson:"idpClientIdMappingDisabled,omitempty" json:"idpClientIdMappingDisabled,omitempty"`
}

JWTValidation

JWTValidation holds configuration for validating access tokens by inspecing them against a third party API, usually one provided by the IDP.

Field name Field type Comment
Enabled

bool

Enabled activates OAuth access token validation.

Tyk classic API definition: external_oauth.providers[].jwt.enabled.

SigningMethod

string

SigningMethod to verify signing method used in jwt - allowed values HMAC/RSA/ECDSA.

Tyk classic API definition: external_oauth.providers[].jwt.signing_method.

Source

string

Source is the secret to verify signature. Valid values are:

  • a base64 encoded static secret,
  • a valid JWK URL in plain text,
  • a valid JWK URL in base64 encoded format.

Tyk classic API definition: external_oauth.providers[].jwt.source.

IdentityBaseField

string

IdentityBaseField is the identity claim name.

Tyk classic API definition: external_oauth.providers[].jwt.identity_base_field.

IssuedAtValidationSkew

uint64

IssuedAtValidationSkew is the clock skew to be considered while validating the iat claim.

Tyk classic API definition: external_oauth.providers[].jwt.issued_at_validation_skew.

NotBeforeValidationSkew

uint64

NotBeforeValidationSkew is the clock skew to be considered while validating the nbf claim.

Tyk classic API definition: external_oauth.providers[].jwt.not_before_validation_skew.

ExpiresAtValidationSkew

uint64

ExpiresAtValidationSkew is the clock skew to be considered while validating the exp claim.

Tyk classic API definition: external_oauth.providers[].jwt.expires_at_validation_skew.

type JWTValidation struct {
	// Enabled activates OAuth access token validation.
	//
	// Tyk classic API definition: `external_oauth.providers[].jwt.enabled`.
	Enabled	bool	`bson:"enabled" json:"enabled"`

	// SigningMethod to verify signing method used in jwt - allowed values HMAC/RSA/ECDSA.
	//
	// Tyk classic API definition: `external_oauth.providers[].jwt.signing_method`.
	SigningMethod	string	`bson:"signingMethod" json:"signingMethod"`

	// Source is the secret to verify signature. Valid values are:
	//
	// - a base64 encoded static secret,
	// - a valid JWK URL in plain text,
	// - a valid JWK URL in base64 encoded format.
	//
	// Tyk classic API definition: `external_oauth.providers[].jwt.source`.
	Source	string	`bson:"source" json:"source"`

	// IdentityBaseField is the identity claim name.
	//
	// Tyk classic API definition: `external_oauth.providers[].jwt.identity_base_field`.
	IdentityBaseField	string	`bson:"identityBaseField,omitempty" json:"identityBaseField,omitempty"`

	// IssuedAtValidationSkew is the clock skew to be considered while validating the iat claim.
	//
	// Tyk classic API definition: `external_oauth.providers[].jwt.issued_at_validation_skew`.
	IssuedAtValidationSkew	uint64	`bson:"issuedAtValidationSkew,omitempty" json:"issuedAtValidationSkew,omitempty"`

	// NotBeforeValidationSkew is the clock skew to be considered while validating the nbf claim.
	//
	// Tyk classic API definition: `external_oauth.providers[].jwt.not_before_validation_skew`.
	NotBeforeValidationSkew	uint64	`bson:"notBeforeValidationSkew,omitempty" json:"notBeforeValidationSkew,omitempty"`

	// ExpiresAtValidationSkew is the clock skew to be considered while validating the exp claim.
	//
	// Tyk classic API definition: `external_oauth.providers[].jwt.expires_at_validation_skew`.
	ExpiresAtValidationSkew	uint64	`bson:"expiresAtValidationSkew,omitempty" json:"expiresAtValidationSkew,omitempty"`
}

Kind

Kind is an alias maintained to be used in imports.

Field name Field type Comment
type

event.Kind

No comment on field.
type Kind = event.Kind

ListenPath

ListenPath is the base path on Tyk to which requests for this API should be sent. Tyk listens out for any requests coming into the host at this path, on the port that Tyk is configured to run on and processes these accordingly.

Field name Field type Comment
Value

string

Value is the value of the listen path e.g. /api/ or / or /httpbin/. Tyk classic API definition: proxy.listen_path

Strip

bool

Strip removes the inbound listen path (as accessed by the client) when generating the outbound request for the upstream service.

For example, consider the scenario where the Tyk base address is http://acme.com/', the listen path is example/and the upstream URL ishttp://httpbin.org/`:

  • If the client application sends a request to http://acme.com/example/get then the request will be proxied to http://httpbin.org/example/get
  • If stripListenPath is set to true, the example listen path is removed and the request would be proxied to http://httpbin.org/get.

Tyk classic API definition: proxy.strip_listen_path

type ListenPath struct {
	// Value is the value of the listen path e.g. `/api/` or `/` or `/httpbin/`.
	// Tyk classic API definition: `proxy.listen_path`
	Value	string	`bson:"value" json:"value"`	// required

	// Strip removes the inbound listen path (as accessed by the client) when generating the outbound request for the upstream service.
	//
	// For example, consider the scenario where the Tyk base address is `http://acme.com/', the listen path is `example/` and the upstream URL is `http://httpbin.org/`:
	//
	// - If the client application sends a request to `http://acme.com/example/get` then the request will be proxied to `http://httpbin.org/example/get`
	// - If stripListenPath is set to `true`, the `example` listen path is removed and the request would be proxied to `http://httpbin.org/get`.
	//
	// Tyk classic API definition: `proxy.strip_listen_path`
	Strip	bool	`bson:"strip,omitempty" json:"strip,omitempty"`
}

LoadBalancing

LoadBalancing represents the configuration for load balancing between multiple upstream targets.

Field name Field type Comment
Enabled

bool

Enabled determines if load balancing is active.

SkipUnavailableHosts

bool

SkipUnavailableHosts determines whether to skip unavailable hosts during load balancing based on uptime tests. Tyk classic field: proxy.check_host_against_uptime_tests

Targets

[]LoadBalancingTarget

Targets defines the list of targets with their respective weights for load balancing.

type LoadBalancing struct {
	// Enabled determines if load balancing is active.
	Enabled	bool	`json:"enabled" bson:"enabled"`	// required
	// SkipUnavailableHosts determines whether to skip unavailable hosts during load balancing based on uptime tests.
	// Tyk classic field: `proxy.check_host_against_uptime_tests`
	SkipUnavailableHosts	bool	`json:"skipUnavailableHosts,omitempty" bson:"skipUnavailableHosts,omitempty"`
	// Targets defines the list of targets with their respective weights for load balancing.
	Targets	[]LoadBalancingTarget	`json:"targets,omitempty" bson:"targets,omitempty"`
}

LoadBalancingTarget

LoadBalancingTarget represents a single upstream target for load balancing with a URL and an associated weight.

Field name Field type Comment
URL

string

URL specifies the upstream target URL for load balancing, represented as a string.

Weight

int

Weight specifies the relative distribution factor for load balancing, determining the importance of this target.

type LoadBalancingTarget struct {
	// URL specifies the upstream target URL for load balancing, represented as a string.
	URL	string	`json:"url" bson:"url"`	// required
	// Weight specifies the relative distribution factor for load balancing, determining the importance of this target.
	Weight	int	`json:"weight" bson:"weight"`	// required
}

LogEvent

LogEvent represents the configuration for logging events within an event handler.

Field name Field type Comment
LogPrefix

string

LogPrefix defines the prefix used for log messages in the logging event.

Tyk classic API definition: event_handlers.events[].handler_meta.prefix.

type LogEvent struct {
	// LogPrefix defines the prefix used for log messages in the logging event.
	//
	// Tyk classic API definition: `event_handlers.events[].handler_meta.prefix`.
	LogPrefix string `json:"logPrefix" bson:"logPrefix"`
}

Middleware

Middleware holds configuration for Tyk's native middleware.

Field name Field type Comment
Global

*Global

Global contains configuration for middleware that affects the whole API (all endpoints).

Operations

Operations

Operations contains configuration for middleware that can be applied to individual endpoints within the API (per-endpoint).

type Middleware struct {
	// Global contains configuration for middleware that affects the whole API (all endpoints).
	Global	*Global	`bson:"global,omitempty" json:"global,omitempty"`

	// Operations contains configuration for middleware that can be applied to individual endpoints within the API (per-endpoint).
	Operations	Operations	`bson:"operations,omitempty" json:"operations,omitempty"`
}

MockResponse

MockResponse configures the mock responses.

Field name Field type Comment
Enabled

bool

Enabled activates the mock response middleware.

Code

int

Code is the HTTP response code that will be returned.

Body

string

Body is the HTTP response body that will be returned.

Headers

Headers

Headers are the HTTP response headers that will be returned.

FromOASExamples

*FromOASExamples

FromOASExamples is the configuration to extract a mock response from OAS documentation.

type MockResponse struct {
	// Enabled activates the mock response middleware.
	Enabled	bool	`bson:"enabled" json:"enabled"`
	// Code is the HTTP response code that will be returned.
	Code	int	`bson:"code,omitempty" json:"code,omitempty"`
	// Body is the HTTP response body that will be returned.
	Body	string	`bson:"body,omitempty" json:"body,omitempty"`
	// Headers are the HTTP response headers that will be returned.
	Headers	Headers	`bson:"headers,omitempty" json:"headers,omitempty"`
	// FromOASExamples is the configuration to extract a mock response from OAS documentation.
	FromOASExamples	*FromOASExamples	`bson:"fromOASExamples,omitempty" json:"fromOASExamples,omitempty"`
}

MutualTLS

MutualTLS contains the configuration for establishing a mutual TLS connection between Tyk and the upstream server.

Field name Field type Comment
Enabled

bool

Enabled activates upstream mutual TLS for the API. Tyk classic API definition: upstream_certificates_disabled

DomainToCertificates

[]DomainToCertificate

DomainToCertificates maintains the mapping of domain to certificate. Tyk classic API definition: upstream_certificates

type MutualTLS struct {
	// Enabled activates upstream mutual TLS for the API.
	// Tyk classic API definition: `upstream_certificates_disabled`
	Enabled	bool	`bson:"enabled" json:"enabled"`

	// DomainToCertificates maintains the mapping of domain to certificate.
	// Tyk classic API definition: `upstream_certificates`
	DomainToCertificates	[]DomainToCertificate	`bson:"domainToCertificateMapping" json:"domainToCertificateMapping"`
}

Notifications

Notifications holds configuration for updates to keys.

Field name Field type Comment
SharedSecret

string

SharedSecret is the shared secret used in the notification request.

Tyk classic API definition: notifications.shared_secret.

OnKeyChangeURL

string

OnKeyChangeURL is the URL a request will be triggered against.

Tyk classic API definition: notifications.oauth_on_keychange_url.

type Notifications struct {
	// SharedSecret is the shared secret used in the notification request.
	//
	// Tyk classic API definition: `notifications.shared_secret`.
	SharedSecret	string	`bson:"sharedSecret,omitempty" json:"sharedSecret,omitempty"`
	// OnKeyChangeURL is the URL a request will be triggered against.
	//
	// Tyk classic API definition: `notifications.oauth_on_keychange_url`.
	OnKeyChangeURL	string	`bson:"onKeyChangeUrl,omitempty" json:"onKeyChangeUrl,omitempty"`
}

OAS

OAS holds the upstream OAS definition as well as adds functionality like custom JSON marshalling.

Field name Field type Comment

openapi3.T

No comment on field.
type OAS struct {
	openapi3.T
}

OAuth

OAuth configures the OAuth middleware.

Field name Field type Comment
Enabled

bool

Enabled activates the OAuth middleware.

Tyk classic API definition: use_oauth2.

AuthSources

AuthSources configures the sources for OAuth credentials.

AllowedAuthorizeTypes

[]osin.AuthorizeRequestType

AllowedAuthorizeTypes is an array of OAuth authorization types.

Tyk classic API definition: oauth_meta.allowed_authorize_types.

RefreshToken

bool

RefreshToken enables clients using a refresh token to get a new bearer access token.

Tyk classic API definition: oauth_meta.allowed_access_types (contains REFRESH_TOKEN).

AuthLoginRedirect

string

AuthLoginRedirect configures a URL to redirect to after a successful login.

Tyk classic API definition: oauth_meta.auth_login_redirect.

Notifications

*Notifications

Notifications configures a URL trigger on key changes.

Tyk classic API definition: notifications.

type OAuth struct {
	// Enabled activates the OAuth middleware.
	//
	// Tyk classic API definition: `use_oauth2`.
	Enabled	bool	`bson:"enabled" json:"enabled"`	// required

	// AuthSources configures the sources for OAuth credentials.
	AuthSources	`bson:",inline" json:",inline"`

	// AllowedAuthorizeTypes is an array of OAuth authorization types.
	//
	// Tyk classic API definition: `oauth_meta.allowed_authorize_types`.
	AllowedAuthorizeTypes	[]osin.AuthorizeRequestType	`bson:"allowedAuthorizeTypes,omitempty" json:"allowedAuthorizeTypes,omitempty"`

	// RefreshToken enables clients using a refresh token to get a new bearer access token.
	//
	// Tyk classic API definition: `oauth_meta.allowed_access_types` (contains REFRESH_TOKEN).
	RefreshToken	bool	`bson:"refreshToken,omitempty" json:"refreshToken,omitempty"`

	// AuthLoginRedirect configures a URL to redirect to after a successful login.
	//
	// Tyk classic API definition: `oauth_meta.auth_login_redirect`.
	AuthLoginRedirect	string	`bson:"authLoginRedirect,omitempty" json:"authLoginRedirect,omitempty"`

	// Notifications configures a URL trigger on key changes.
	//
	// Tyk classic API definition: `notifications`.
	Notifications	*Notifications	`bson:"notifications,omitempty" json:"notifications,omitempty"`
}

OAuthProvider

OAuthProvider holds the configuration for validation and introspection of OAuth tokens.

Field name Field type Comment
JWT

*JWTValidation

JWT configures JWT validation.

Tyk classic API definition: external_oauth.providers[].jwt.

Introspection

*Introspection

Introspection configures token introspection.

Tyk classic API definition: external_oauth.providers[].introspection.

type OAuthProvider struct {
	// JWT configures JWT validation.
	//
	// Tyk classic API definition: `external_oauth.providers[].jwt`.
	JWT	*JWTValidation	`bson:"jwt,omitempty" json:"jwt,omitempty"`
	// Introspection configures token introspection.
	//
	// Tyk classic API definition: `external_oauth.providers[].introspection`.
	Introspection	*Introspection	`bson:"introspection,omitempty" json:"introspection,omitempty"`
}

OIDC

OIDC contains configuration for the OIDC authentication mode. OIDC support will be deprecated starting from 5.7.0. To avoid any disruptions, we recommend that you use JSON Web Token (JWT) instead, as explained in https://tyk.io/docs/basic-config-and-security/security/authentication-authorization/openid-connect/.

Field name Field type Comment
Enabled

bool

Enabled activates the OIDC authentication mode.

Tyk classic API definition: use_openid

AuthSources

AuthSources contains authentication token source configuration (header, cookie, query).

SegregateByClientId

bool

SegregateByClientId is a boolean flag. If set to `true, the policies will be applied to a combination of Client ID and User ID.

Tyk classic API definition: openid_options.segregate_by_client.

Providers

[]Provider

Providers contains a list of authorized providers, their Client IDs and matched policies.

Tyk classic API definition: openid_options.providers.

Scopes

*Scopes

Scopes contains the defined scope claims.

type OIDC struct {
	// Enabled activates the OIDC authentication mode.
	//
	// Tyk classic API definition: `use_openid`
	Enabled	bool	`bson:"enabled" json:"enabled"`	// required

	// AuthSources contains authentication token source configuration (header, cookie, query).
	AuthSources	`bson:",inline" json:",inline"`

	// SegregateByClientId is a boolean flag. If set to `true, the policies will be applied to a combination of Client ID and User ID.
	//
	// Tyk classic API definition: `openid_options.segregate_by_client`.
	SegregateByClientId	bool	`bson:"segregateByClientId,omitempty" json:"segregateByClientId,omitempty"`

	// Providers contains a list of authorized providers, their Client IDs and matched policies.
	//
	// Tyk classic API definition: `openid_options.providers`.
	Providers	[]Provider	`bson:"providers,omitempty" json:"providers,omitempty"`

	// Scopes contains the defined scope claims.
	Scopes	*Scopes	`bson:"scopes,omitempty" json:"scopes,omitempty"`
}

OldOAS

OldOAS serves for data model migration/conversion purposes (gorm).

Field name Field type Comment

openapifork.T

No comment on field.
type OldOAS struct {
	openapifork.T
}

Operation

Operation holds a request operation configuration, allowances, tranformations, caching, timeouts and validation.

Field name Field type Comment
Allow

*Allowance

Allow request by allowance.

Block

*Allowance

Block request by allowance.

IgnoreAuthentication

*Allowance

IgnoreAuthentication ignores authentication on request by allowance.

Internal

*Internal

Internal makes the endpoint only respond to internal requests.

TransformRequestMethod

*TransformRequestMethod

TransformRequestMethod allows you to transform the method of a request.

TransformRequestBody

*TransformBody

TransformRequestBody allows you to transform request body. When both path and body are provided, body would take precedence.

TransformResponseBody

*TransformBody

TransformResponseBody allows you to transform response body. When both path and body are provided, body would take precedence.

TransformRequestHeaders

*TransformHeaders

TransformRequestHeaders allows you to transform request headers.

TransformResponseHeaders

*TransformHeaders

TransformResponseHeaders allows you to transform response headers.

URLRewrite

*URLRewrite

URLRewrite contains the URL rewriting configuration.

Cache

*CachePlugin

Cache contains the caching plugin configuration.

EnforceTimeout

*EnforceTimeout

EnforceTimeout contains the request timeout configuration.

ValidateRequest

*ValidateRequest

ValidateRequest contains the request validation configuration.

MockResponse

*MockResponse

MockResponse contains the mock response configuration.

VirtualEndpoint

*VirtualEndpoint

VirtualEndpoint contains virtual endpoint configuration.

PostPlugins

EndpointPostPlugins

PostPlugins contains endpoint level post plugins configuration.

CircuitBreaker

*CircuitBreaker

CircuitBreaker contains the configuration for the circuit breaker functionality.

TrackEndpoint

*TrackEndpoint

TrackEndpoint contains the configuration for enabling analytics and logs.

DoNotTrackEndpoint

*TrackEndpoint

DoNotTrackEndpoint contains the configuration for disabling analytics and logs.

RequestSizeLimit

*RequestSizeLimit

RequestSizeLimit limits the maximum allowed size of the request body in bytes.

RateLimit

*RateLimitEndpoint

RateLimit contains endpoint level rate limit configuration.

type Operation struct {
	// Allow request by allowance.
	Allow	*Allowance	`bson:"allow,omitempty" json:"allow,omitempty"`

	// Block request by allowance.
	Block	*Allowance	`bson:"block,omitempty" json:"block,omitempty"`

	// IgnoreAuthentication ignores authentication on request by allowance.
	IgnoreAuthentication	*Allowance	`bson:"ignoreAuthentication,omitempty" json:"ignoreAuthentication,omitempty"`

	// Internal makes the endpoint only respond to internal requests.
	Internal	*Internal	`bson:"internal,omitempty" json:"internal,omitempty"`

	// TransformRequestMethod allows you to transform the method of a request.
	TransformRequestMethod	*TransformRequestMethod	`bson:"transformRequestMethod,omitempty" json:"transformRequestMethod,omitempty"`

	// TransformRequestBody allows you to transform request body.
	// When both `path` and `body` are provided, body would take precedence.
	TransformRequestBody	*TransformBody	`bson:"transformRequestBody,omitempty" json:"transformRequestBody,omitempty"`

	// TransformResponseBody allows you to transform response body.
	// When both `path` and `body` are provided, body would take precedence.
	TransformResponseBody	*TransformBody	`bson:"transformResponseBody,omitempty" json:"transformResponseBody,omitempty"`

	// TransformRequestHeaders allows you to transform request headers.
	TransformRequestHeaders	*TransformHeaders	`bson:"transformRequestHeaders,omitempty" json:"transformRequestHeaders,omitempty"`

	// TransformResponseHeaders allows you to transform response headers.
	TransformResponseHeaders	*TransformHeaders	`bson:"transformResponseHeaders,omitempty" json:"transformResponseHeaders,omitempty"`

	// URLRewrite contains the URL rewriting configuration.
	URLRewrite	*URLRewrite	`bson:"urlRewrite,omitempty" json:"urlRewrite,omitempty"`

	// Cache contains the caching plugin configuration.
	Cache	*CachePlugin	`bson:"cache,omitempty" json:"cache,omitempty"`

	// EnforceTimeout contains the request timeout configuration.
	EnforceTimeout	*EnforceTimeout	`bson:"enforceTimeout,omitempty" json:"enforceTimeout,omitempty"`

	// ValidateRequest contains the request validation configuration.
	ValidateRequest	*ValidateRequest	`bson:"validateRequest,omitempty" json:"validateRequest,omitempty"`

	// MockResponse contains the mock response configuration.
	MockResponse	*MockResponse	`bson:"mockResponse,omitempty" json:"mockResponse,omitempty"`

	// VirtualEndpoint contains virtual endpoint configuration.
	VirtualEndpoint	*VirtualEndpoint	`bson:"virtualEndpoint,omitempty" json:"virtualEndpoint,omitempty"`

	// PostPlugins contains endpoint level post plugins configuration.
	PostPlugins	EndpointPostPlugins	`bson:"postPlugins,omitempty" json:"postPlugins,omitempty"`

	// CircuitBreaker contains the configuration for the circuit breaker functionality.
	CircuitBreaker	*CircuitBreaker	`bson:"circuitBreaker,omitempty" json:"circuitBreaker,omitempty"`

	// TrackEndpoint contains the configuration for enabling analytics and logs.
	TrackEndpoint	*TrackEndpoint	`bson:"trackEndpoint,omitempty" json:"trackEndpoint,omitempty"`

	// DoNotTrackEndpoint contains the configuration for disabling analytics and logs.
	DoNotTrackEndpoint	*TrackEndpoint	`bson:"doNotTrackEndpoint,omitempty" json:"doNotTrackEndpoint,omitempty"`

	// RequestSizeLimit limits the maximum allowed size of the request body in bytes.
	RequestSizeLimit	*RequestSizeLimit	`bson:"requestSizeLimit,omitempty" json:"requestSizeLimit,omitempty"`

	// RateLimit contains endpoint level rate limit configuration.
	RateLimit	*RateLimitEndpoint	`bson:"rateLimit,omitempty" json:"rateLimit,omitempty"`
}

Operations

Operations holds Operation definitions.

Field name Field type Comment
type

map[string]*Operation

No comment on field.
type Operations map[string]*Operation

PasswordAuthentication

PasswordAuthentication holds the configuration for upstream OAuth2 password authentication flow.

Field name Field type Comment

ClientAuthData

No comment on field.
Header

*AuthSource

Header holds the configuration for the custom header to be used for OAuth authentication.

Username

string

Username is the username to be used for upstream OAuth2 password authentication.

Password

string

Password is the password to be used for upstream OAuth2 password authentication.

TokenURL

string

TokenURL is the resource server's token endpoint URL. This is a constant specific to each server.

Scopes

[]string

Scopes specifies optional requested permissions.

ExtraMetadata

[]string

ExtraMetadata holds the keys that we want to extract from the token and pass to the upstream.

type PasswordAuthentication struct {
	ClientAuthData
	// Header holds the configuration for the custom header to be used for OAuth authentication.
	Header	*AuthSource	`bson:"header" json:"header"`
	// Username is the username to be used for upstream OAuth2 password authentication.
	Username	string	`bson:"username" json:"username"`
	// Password is the password to be used for upstream OAuth2 password authentication.
	Password	string	`bson:"password" json:"password"`
	// TokenURL is the resource server's token endpoint
	// URL. This is a constant specific to each server.
	TokenURL	string	`bson:"tokenUrl" json:"tokenUrl"`
	// Scopes specifies optional requested permissions.
	Scopes	[]string	`bson:"scopes" json:"scopes,omitempty"`
	// ExtraMetadata holds the keys that we want to extract from the token and pass to the upstream.
	ExtraMetadata	[]string	`bson:"extraMetadata" json:"extraMetadata,omitempty"`
}

Path

Path holds plugin configurations for HTTP method verbs.

Field name Field type Comment
Delete

*Plugins

Delete holds plugin configuration for DELETE requests.

Get

*Plugins

Get holds plugin configuration for GET requests.

Head

*Plugins

Head holds plugin configuration for HEAD requests.

Options

*Plugins

Options holds plugin configuration for OPTIONS requests.

Patch

*Plugins

Patch holds plugin configuration for PATCH requests.

Post

*Plugins

Post holds plugin configuration for POST requests.

Put

*Plugins

Put holds plugin configuration for PUT requests.

Trace

*Plugins

Trace holds plugin configuration for TRACE requests.

Connect

*Plugins

Connect holds plugin configuration for CONNECT requests.

type Path struct {
	// Delete holds plugin configuration for DELETE requests.
	Delete	*Plugins	`bson:"DELETE,omitempty" json:"DELETE,omitempty"`
	// Get holds plugin configuration for GET requests.
	Get	*Plugins	`bson:"GET,omitempty" json:"GET,omitempty"`
	// Head holds plugin configuration for HEAD requests.
	Head	*Plugins	`bson:"HEAD,omitempty" json:"HEAD,omitempty"`
	// Options holds plugin configuration for OPTIONS requests.
	Options	*Plugins	`bson:"OPTIONS,omitempty" json:"OPTIONS,omitempty"`
	// Patch holds plugin configuration for PATCH requests.
	Patch	*Plugins	`bson:"PATCH,omitempty" json:"PATCH,omitempty"`
	// Post holds plugin configuration for POST requests.
	Post	*Plugins	`bson:"POST,omitempty" json:"POST,omitempty"`
	// Put holds plugin configuration for PUT requests.
	Put	*Plugins	`bson:"PUT,omitempty" json:"PUT,omitempty"`
	// Trace holds plugin configuration for TRACE requests.
	Trace	*Plugins	`bson:"TRACE,omitempty" json:"TRACE,omitempty"`
	// Connect holds plugin configuration for CONNECT requests.
	Connect	*Plugins	`bson:"CONNECT,omitempty" json:"CONNECT,omitempty"`
}

Paths

Paths is a mapping of API endpoints to Path plugin configurations.

Field name Field type Comment
type

map[string]*Path

No comment on field.
type Paths map[string]*Path

PinnedPublicKey

PinnedPublicKey contains a mapping from the domain name into a list of public keys.

Field name Field type Comment
Domain

string

Domain contains the domain name.

PublicKeys

[]string

PublicKeys contains a list of the public keys pinned to the domain name.

type PinnedPublicKey struct {
	// Domain contains the domain name.
	Domain	string	`bson:"domain" json:"domain"`

	// PublicKeys contains a list of the public keys pinned to the domain name.
	PublicKeys	[]string	`bson:"publicKeys" json:"publicKeys"`
}

PinnedPublicKeys

PinnedPublicKeys is a list of domains and pinned public keys for them.

Field name Field type Comment
type

[]PinnedPublicKey

No comment on field.
type PinnedPublicKeys []PinnedPublicKey

PluginBundle

PluginBundle holds configuration for custom plugins.

Field name Field type Comment
Enabled

bool

Enabled activates the custom plugin bundles.

Tyk classic API definition: custom_middleware_bundle_disabled

Path

string

Path is the path suffix to construct the URL to fetch plugin bundle from. Path will be suffixed to bundle_base_url in gateway config.

type PluginBundle struct {
	// Enabled activates the custom plugin bundles.
	//
	// Tyk classic API definition: `custom_middleware_bundle_disabled`
	Enabled	bool	`bson:"enabled" json:"enabled"`	// required.
	// Path is the path suffix to construct the URL to fetch plugin bundle from.
	// Path will be suffixed to `bundle_base_url` in gateway config.
	Path	string	`bson:"path" json:"path"`	// required.
}

PluginConfig

PluginConfig holds configuration for custom plugins.

Field name Field type Comment
Driver

apidef.MiddlewareDriver

Driver configures which custom plugin driver to use. The value should be set to one of the following:

  • otto,
  • python,
  • lua,
  • grpc,
  • goplugin.

Tyk classic API definition: custom_middleware.driver.

Bundle

*PluginBundle

Bundle configures custom plugin bundles.

Data

*PluginConfigData

Data configures custom plugin data.

type PluginConfig struct {
	// Driver configures which custom plugin driver to use.
	// The value should be set to one of the following:
	//
	// - `otto`,
	// - `python`,
	// - `lua`,
	// - `grpc`,
	// - `goplugin`.
	//
	// Tyk classic API definition: `custom_middleware.driver`.
	Driver	apidef.MiddlewareDriver	`bson:"driver,omitempty" json:"driver,omitempty"`

	// Bundle configures custom plugin bundles.
	Bundle	*PluginBundle	`bson:"bundle,omitempty" json:"bundle,omitempty"`

	// Data configures custom plugin data.
	Data	*PluginConfigData	`bson:"data,omitempty" json:"data,omitempty"`
}

PluginConfigData

PluginConfigData configures config data for custom plugins.

Field name Field type Comment
Enabled

bool

Enabled activates custom plugin config data.

Tyk classic API definition: config_data_disabled (negated).

Value

map[string]any

Value is the value of custom plugin config data.

Tyk classic API definition: config_data.

type PluginConfigData struct {
	// Enabled activates custom plugin config data.
	//
	// Tyk classic API definition: `config_data_disabled` (negated).
	Enabled	bool	`bson:"enabled" json:"enabled"`	// required.

	// Value is the value of custom plugin config data.
	//
	// Tyk classic API definition: `config_data`.
	Value	map[string]interface{}	`bson:"value" json:"value"`	// required.
}

Plugins

Plugins configures common settings for each plugin, allowances, transforms, caching and timeouts.

Field name Field type Comment
Allow

*Allowance

Allow request by allowance.

Block

*Allowance

Block request by allowance.

IgnoreAuthentication

*Allowance

IgnoreAuthentication ignores authentication on request by allowance.

TransformRequestMethod

*TransformRequestMethod

TransformRequestMethod allows you to transform the method of a request.

Cache

*CachePlugin

Cache allows you to cache the server side response.

EnforceTimeout

*EnforceTimeout

EnforceTimeout allows you to configure a request timeout.

type Plugins struct {
	// Allow request by allowance.
	Allow	*Allowance	`bson:"allow,omitempty" json:"allow,omitempty"`

	// Block request by allowance.
	Block	*Allowance	`bson:"block,omitempty" json:"block,omitempty"`

	// IgnoreAuthentication ignores authentication on request by allowance.
	IgnoreAuthentication	*Allowance	`bson:"ignoreAuthentication,omitempty" json:"ignoreAuthentication,omitempty"`

	// TransformRequestMethod allows you to transform the method of a request.
	TransformRequestMethod	*TransformRequestMethod	`bson:"transformRequestMethod,omitempty" json:"transformRequestMethod,omitempty"`

	// Cache allows you to cache the server side response.
	Cache	*CachePlugin	`bson:"cache,omitempty" json:"cache,omitempty"`

	// EnforceTimeout allows you to configure a request timeout.
	EnforceTimeout	*EnforceTimeout	`bson:"enforcedTimeout,omitempty" json:"enforcedTimeout,omitempty"`
}

PostAuthenticationPlugin

PostAuthenticationPlugin configures post authentication plugins.

Field name Field type Comment
Plugins

CustomPlugins

Plugins configures custom plugins to be run on pre authentication stage. The plugins would be executed in the order of configuration in the list.

type PostAuthenticationPlugin struct {
	// Plugins configures custom plugins to be run on pre authentication stage.
	// The plugins would be executed in the order of configuration in the list.
	Plugins CustomPlugins `bson:"plugins,omitempty" json:"plugins,omitempty"`
}

PostPlugin

PostPlugin configures post plugins.

Field name Field type Comment
Plugins

CustomPlugins

Plugins configures custom plugins to be run on post stage. The plugins would be executed in the order of configuration in the list.

type PostPlugin struct {
	// Plugins configures custom plugins to be run on post stage.
	// The plugins would be executed in the order of configuration in the list.
	Plugins CustomPlugins `bson:"plugins,omitempty" json:"plugins,omitempty"`
}

PrePlugin

PrePlugin configures pre-request plugins.

Pre-request plugins are executed before the request is sent to the upstream target and before any authentication information is extracted from the header or parameter list of the request.

Field name Field type Comment
Plugins

CustomPlugins

Plugins configures custom plugins to be run on pre authentication stage. The plugins would be executed in the order of configuration in the list.

type PrePlugin struct {
	// Plugins configures custom plugins to be run on pre authentication stage.
	// The plugins would be executed in the order of configuration in the list.
	Plugins CustomPlugins `bson:"plugins,omitempty" json:"plugins,omitempty"`
}

PreserveHostHeader

PreserveHostHeader holds the configuration for preserving the host header.

Field name Field type Comment
Enabled

bool

Enabled activates preserving the host header.

type PreserveHostHeader struct {
	// Enabled activates preserving the host header.
	Enabled bool `json:"enabled" bson:"enabled"`
}

PreserveTrailingSlash

PreserveTrailingSlash holds the configuration for preserving the trailing slash when routed to upstream services.

The default behaviour of Tyk is to strip any trailing slash (/) from the target URL when proxying the request upstream. In some use cases the upstream might expect the trailing slash - or might consider /users/ to be a different endpoint from /users (for example).

Field name Field type Comment
Enabled

bool

Enabled activates preserving the trailing slash when routing requests.

type PreserveTrailingSlash struct {
	// Enabled activates preserving the trailing slash when routing requests.
	Enabled bool `json:"enabled" bson:"enabled"`	// required
}

Provider

Provider defines an issuer to validate and the Client ID to Policy ID mappings.

Field name Field type Comment
Issuer

string

Issuer contains a validation value for the issuer claim, usually a domain name e.g. accounts.google.com or similar.

Tyk classic API definition: openid_options.providers[].issuer.

ClientToPolicyMapping

[]ClientToPolicy

ClientToPolicyMapping contains mappings of Client IDs to Policy IDs.

Tyk classic API definition: openid_options.providers[].client_ids.

type Provider struct {
	// Issuer contains a validation value for the issuer claim, usually a domain name e.g. `accounts.google.com` or similar.
	//
	// Tyk classic API definition: `openid_options.providers[].issuer`.
	Issuer	string	`bson:"issuer,omitempty" json:"issuer,omitempty"`

	// ClientToPolicyMapping contains mappings of Client IDs to Policy IDs.
	//
	// Tyk classic API definition: `openid_options.providers[].client_ids`.
	ClientToPolicyMapping	[]ClientToPolicy	`bson:"clientToPolicyMapping,omitempty" json:"clientToPolicyMapping,omitempty"`
}

Proxy

Proxy contains the configuration for an internal proxy.

Tyk classic API definition: proxy.proxy_url

Field name Field type Comment
Enabled

bool

Enabled determines if the proxy is active.

URL

string

URL specifies the URL of the internal proxy.

type Proxy struct {
	// Enabled determines if the proxy is active.
	Enabled	bool	`bson:"enabled" json:"enabled"`

	// URL specifies the URL of the internal proxy.
	URL	string	`bson:"url" json:"url"`
}

RateLimit

RateLimit holds the configurations related to rate limit. The API-level rate limit applies a base-line limit on the frequency of requests to the upstream service for all endpoints. The frequency of requests is configured in two parts: the time interval and the number of requests that can be made during each interval. Tyk classic API definition: global_rate_limit.

Field name Field type Comment
Enabled

bool

Enabled activates API level rate limiting for this API.

Tyk classic API definition: !disable_rate_limit.

Rate

int

Rate specifies the number of requests that can be passed to the upstream in each time interval (per). This field sets the limit on the frequency of requests to ensure controlled resource access or to prevent abuse. The rate is defined as an integer value.

A higher value indicates a higher number of allowed requests in the given time frame. For instance, if Per is set to 1m (one minute), a Rate of 100 means up to 100 requests can be made per minute.

Tyk classic API definition: global_rate_limit.rate.

Per

ReadableDuration

Per defines the time interval for rate limiting using shorthand notation. The value of Per is a string that specifies the interval in a compact form, where hours, minutes and seconds are denoted by 'h', 'm' and 's' respectively. Multiple units can be combined to represent the duration.

Examples of valid shorthand notations:

  • "1h" : one hour
  • "20m" : twenty minutes
  • "30s" : thirty seconds
  • "1m29s": one minute and twenty-nine seconds
  • "1h30m" : one hour and thirty minutes

An empty value is interpreted as "0s", implying no rate limiting interval, which disables the API-level rate limit. It's important to format the string correctly, as invalid formats will be considered as 0s/empty.

Tyk classic API definition: global_rate_limit.per.

type RateLimit struct {
	// Enabled activates API level rate limiting for this API.
	//
	// Tyk classic API definition: `!disable_rate_limit`.
	Enabled	bool	`json:"enabled" bson:"enabled"`
	// Rate specifies the number of requests that can be passed to the upstream in each time interval (`per`).
	// This field sets the limit on the frequency of requests to ensure controlled
	// resource access or to prevent abuse. The rate is defined as an integer value.
	//
	// A higher value indicates a higher number of allowed requests in the given
	// time frame. For instance, if `Per` is set to `1m` (one minute), a Rate of `100`
	// means up to 100 requests can be made per minute.
	//
	// Tyk classic API definition: `global_rate_limit.rate`.
	Rate	int	`json:"rate" bson:"rate"`
	// Per defines the time interval for rate limiting using shorthand notation.
	// The value of Per is a string that specifies the interval in a compact form,
	// where hours, minutes and seconds are denoted by 'h', 'm' and 's' respectively.
	// Multiple units can be combined to represent the duration.
	//
	// Examples of valid shorthand notations:
	// - "1h"   : one hour
	// - "20m"  : twenty minutes
	// - "30s"  : thirty seconds
	// - "1m29s": one minute and twenty-nine seconds
	// - "1h30m" : one hour and thirty minutes
	//
	// An empty value is interpreted as "0s", implying no rate limiting interval, which disables the API-level rate limit.
	// It's important to format the string correctly, as invalid formats will
	// be considered as 0s/empty.
	//
	// Tyk classic API definition: `global_rate_limit.per`.
	Per	ReadableDuration	`json:"per" bson:"per"`
}

RateLimitEndpoint

RateLimitEndpoint carries same settings as RateLimit but for endpoints.

Field name Field type Comment
type

RateLimit

No comment on field.
type RateLimitEndpoint RateLimit

ReadableDuration

ReadableDuration is an alias maintained to be used in imports.

Field name Field type Comment
type

time.ReadableDuration

No comment on field.
type ReadableDuration = time.ReadableDuration

RequestSizeLimit

RequestSizeLimit limits the maximum allowed size of the request body in bytes.

Field name Field type Comment
Enabled

bool

Enabled activates the Request Size Limit functionality.

Tyk classic API definition: version_data.versions..extended_paths.size_limits[].disabled (negated).

Value

int64

Value is the maximum allowed size of the request body in bytes.

Tyk classic API definition: version_data.versions..extended_paths.size_limits[].size_limit.

type RequestSizeLimit struct {
	// Enabled activates the Request Size Limit functionality.
	//
	// Tyk classic API definition: `version_data.versions..extended_paths.size_limits[].disabled` (negated).
	Enabled	bool	`bson:"enabled" json:"enabled"`
	// Value is the maximum allowed size of the request body in bytes.
	//
	// Tyk classic API definition: `version_data.versions..extended_paths.size_limits[].size_limit`.
	Value	int64	`bson:"value" json:"value"`
}

ResponsePlugin

ResponsePlugin configures response plugins.

Field name Field type Comment
Plugins

CustomPlugins

Plugins configures custom plugins to be run on post stage. The plugins would be executed in the order of configuration in the list.

type ResponsePlugin struct {
	// Plugins configures custom plugins to be run on post stage.
	// The plugins would be executed in the order of configuration in the list.
	Plugins CustomPlugins `bson:"plugins,omitempty" json:"plugins,omitempty"`
}

ScopeToPolicy

ScopeToPolicy contains a single scope to policy ID mapping. This struct is used for both JWT and OIDC authentication.

Field name Field type Comment
Scope

string

Scope contains the scope name.

Tyk classic API definition:

  • For OIDC: Key in scopes.oidc.scope_to_policy map
  • For JWT: Key in scopes.jwt.scope_to_policy map.
PolicyID

string

PolicyID contains the Policy ID.

Tyk classic API definition:

  • For OIDC: Value in scopes.oidc.scope_to_policy map
  • For JWT: Value in scopes.jwt.scope_to_policy map.
type ScopeToPolicy struct {
	// Scope contains the scope name.
	//
	// Tyk classic API definition:
	// - For OIDC: Key in `scopes.oidc.scope_to_policy` map
	// - For JWT: Key in `scopes.jwt.scope_to_policy` map.
	Scope	string	`bson:"scope,omitempty" json:"scope,omitempty"`

	// PolicyID contains the Policy ID.
	//
	// Tyk classic API definition:
	// - For OIDC: Value in `scopes.oidc.scope_to_policy` map
	// - For JWT: Value in `scopes.jwt.scope_to_policy` map.
	PolicyID	string	`bson:"policyId,omitempty" json:"policyId,omitempty"`
}

Scopes

Scopes holds the scope to policy mappings for a claim name. This struct is used for both JWT and OIDC authentication.

Field name Field type Comment
ClaimName

string

ClaimName contains the claim name.

Tyk classic API definition:

  • For OIDC: scopes.oidc.scope_claim_name
  • For JWT: scopes.jwt.scope_claim_name
ScopeToPolicyMapping

[]ScopeToPolicy

ScopeToPolicyMapping contains the mappings of scopes to policy IDs.

Tyk classic API definition:

  • For OIDC: scopes.oidc.scope_to_policy
  • For JWT: scopes.jwt.scope_to_policy
type Scopes struct {
	// ClaimName contains the claim name.
	//
	// Tyk classic API definition:
	// - For OIDC: `scopes.oidc.scope_claim_name`
	// - For JWT: `scopes.jwt.scope_claim_name`
	ClaimName	string	`bson:"claimName,omitempty" json:"claimName,omitempty"`

	// ScopeToPolicyMapping contains the mappings of scopes to policy IDs.
	//
	// Tyk classic API definition:
	// - For OIDC: `scopes.oidc.scope_to_policy`
	// - For JWT: `scopes.jwt.scope_to_policy`
	ScopeToPolicyMapping	[]ScopeToPolicy	`bson:"scopeToPolicyMapping,omitempty" json:"scopeToPolicyMapping,omitempty"`
}

SecurityScheme

SecurityScheme defines an Importer interface for security schemes.

Field name Field type Comment
type

any

No comment on field.
type SecurityScheme interface {
	Import(nativeSS *openapi3.SecurityScheme, enable bool)
}

SecuritySchemes

SecuritySchemes holds security scheme values, filled with Import().

Field name Field type Comment
type

map[string]any

No comment on field.
type SecuritySchemes map[string]interface{}

Server

Server contains the configuration that sets Tyk up to receive requests from the client applications.

Field name Field type Comment
ListenPath

ListenPath

ListenPath is the base path on Tyk to which requests for this API should be sent. Tyk listens for any requests coming into the host at this path, on the port that Tyk is configured to run on and processes these accordingly.

Authentication

*Authentication

Authentication contains the configurations that manage how clients can authenticate with Tyk to access the API.

ClientCertificates

*ClientCertificates

ClientCertificates contains the configurations related to establishing static mutual TLS between the client and Tyk.

GatewayTags

*GatewayTags

GatewayTags contain segment tags to indicate which Gateways your upstream service is connected to (and hence where to deploy the API).

CustomDomain

*Domain

CustomDomain is the domain to bind this API to. This enforces domain matching for client requests.

Tyk classic API definition: domain

DetailedActivityLogs

*DetailedActivityLogs

DetailedActivityLogs configures detailed analytics recording.

DetailedTracing

*DetailedTracing

DetailedTracing enables OpenTelemetry's detailed tracing for this API.

Tyk classic API definition: detailed_tracing

EventHandlers

EventHandlers

EventHandlers contains the configuration related to Tyk Events.

Tyk classic API definition: event_handlers

IPAccessControl

*IPAccessControl

IPAccessControl configures IP access control for this API.

Tyk classic API definition: allowed_ips and blacklisted_ips.

BatchProcessing

*BatchProcessing

BatchProcessing contains configuration settings to enable or disable batch request support for the API.

Tyk classic API definition: enable_batch_request_support.

Protocol

string

Protocol configures the HTTP protocol used by the API. Possible values are:

  • "http": Standard HTTP/1.1 protocol
  • "http2": HTTP/2 protocol with TLS
  • "h2c": HTTP/2 protocol without TLS (cleartext).

Tyk classic API definition: protocol.

Port

int

Port Setting this value will change the port that Tyk listens on. Default: 8080.

Tyk classic API definition: listen_port.

type Server struct {
	// ListenPath is the base path on Tyk to which requests for this API should
	// be sent. Tyk listens for any requests coming into the host at this
	// path, on the port that Tyk is configured to run on and processes these
	// accordingly.
	ListenPath	ListenPath	`bson:"listenPath" json:"listenPath"`	// required

	// Authentication contains the configurations that manage how clients can authenticate with Tyk to access the API.
	Authentication	*Authentication	`bson:"authentication,omitempty" json:"authentication,omitempty"`

	// ClientCertificates contains the configurations related to establishing static mutual TLS between the client and Tyk.
	ClientCertificates	*ClientCertificates	`bson:"clientCertificates,omitempty" json:"clientCertificates,omitempty"`

	// GatewayTags contain segment tags to indicate which Gateways your upstream service is connected to (and hence where to deploy the API).
	GatewayTags	*GatewayTags	`bson:"gatewayTags,omitempty" json:"gatewayTags,omitempty"`

	// CustomDomain is the domain to bind this API to. This enforces domain matching for client requests.
	//
	// Tyk classic API definition: `domain`
	CustomDomain	*Domain	`bson:"customDomain,omitempty" json:"customDomain,omitempty"`

	// DetailedActivityLogs configures detailed analytics recording.
	DetailedActivityLogs	*DetailedActivityLogs	`bson:"detailedActivityLogs,omitempty" json:"detailedActivityLogs,omitempty"`

	// DetailedTracing enables OpenTelemetry's detailed tracing for this API.
	//
	// Tyk classic API definition: `detailed_tracing`
	DetailedTracing	*DetailedTracing	`bson:"detailedTracing,omitempty" json:"detailedTracing,omitempty"`

	// EventHandlers contains the configuration related to Tyk Events.
	//
	// Tyk classic API definition: `event_handlers`
	EventHandlers	EventHandlers	`bson:"eventHandlers,omitempty" json:"eventHandlers,omitempty"`

	// IPAccessControl configures IP access control for this API.
	//
	// Tyk classic API definition: `allowed_ips` and `blacklisted_ips`.
	IPAccessControl	*IPAccessControl	`bson:"ipAccessControl,omitempty" json:"ipAccessControl,omitempty"`

	// BatchProcessing contains configuration settings to enable or disable batch request support for the API.
	//
	// Tyk classic API definition: `enable_batch_request_support`.
	BatchProcessing	*BatchProcessing	`bson:"batchProcessing,omitempty" json:"batchProcessing,omitempty"`

	// Protocol configures the HTTP protocol used by the API.
	// Possible values are:
	// - "http": Standard HTTP/1.1 protocol
	// - "http2": HTTP/2 protocol with TLS
	// - "h2c": HTTP/2 protocol without TLS (cleartext).
	//
	// Tyk classic API definition: `protocol`.
	Protocol	string	`bson:"protocol,omitempty" json:"protocol,omitempty"`
	// Port Setting this value will change the port that Tyk listens on. Default: 8080.
	//
	// Tyk classic API definition: `listen_port`.
	Port	int	`bson:"port,omitempty" json:"port,omitempty"`
}

ServiceDiscovery

ServiceDiscovery holds configuration required for service discovery.

Field name Field type Comment
Enabled

bool

Enabled activates Service Discovery.

Tyk classic API definition: service_discovery.use_discovery_service

QueryEndpoint

string

QueryEndpoint is the endpoint to call, this would usually be Consul, etcd or Eureka K/V store. Tyk classic API definition: service_discovery.query_endpoint

DataPath

string

DataPath is the namespace of the data path - where exactly in your service response the namespace can be found. For example, if your service responds with:

{
 "action": "get",
 "node": {
   "key": "/services/single",
   "value": "http://httpbin.org:6000",
   "modifiedIndex": 6,
   "createdIndex": 6
 }
}

then your namespace would be node.value.

Tyk classic API definition: service_discovery.data_path

UseNestedQuery

bool

UseNestedQuery enables the use of a combination of dataPath and parentDataPath. It is necessary when the data lives within this string-encoded JSON object.

{
 "action": "get",
 "node": {
   "key": "/services/single",
   "value": "{"hostname": "http://httpbin.org", "port": "80"}",
   "modifiedIndex": 6,
   "createdIndex": 6
 }
}

Tyk classic API definition: service_discovery.use_nested_query

ParentDataPath

string

ParentDataPath is the namespace of the where to find the nested value if useNestedQuery is true. In the above example, it would be node.value. You would change the dataPath setting to be hostname, since this is where the host name data resides in the JSON string. Tyk automatically assumes that dataPath in this case is in a string-encoded JSON object and will try to deserialize it.

Tyk classic API definition: service_discovery.parent_data_path

PortDataPath

string

PortDataPath is the port of the data path. In the above nested example, we can see that there is a separate port value for the service in the nested JSON. In this case, you can set the portDataPath value and Tyk will treat dataPath as the hostname and zip them together (this assumes that the hostname element does not end in a slash or resource identifier such as /widgets/). In the above example, the portDataPath would be port.

Tyk classic API definition: service_discovery.port_data_path

UseTargetList

bool

UseTargetList should be set to true if you are using load balancing. Tyk will treat the data path as a list and inject it into the target list of your API definition.

Tyk classic API definition: service_discovery.use_target_list

CacheTimeout

int64

CacheTimeout is the timeout of a cache value when a new data is loaded from a discovery service. Setting it too low will cause Tyk to call the SD service too often, setting it too high could mean that failures are not recovered from quickly enough.

Deprecated: The field is deprecated. Use service_discovery to configure service discovery cache options.

Tyk classic API definition: service_discovery.cache_timeout

Cache

*ServiceDiscoveryCache

Cache holds cache related flags.

Tyk classic API definition:

  • service_discovery.cache_disabled
  • service_discovery.cache_timeout
TargetPath

string

TargetPath is used to set a target path that will be appended to the discovered endpoint, since many service discovery services only provide host and port data. It is important to be able to target a specific resource on that host. Setting this value will enable that.

Tyk classic API definition: service_discovery.target_path

EndpointReturnsList

bool

EndpointReturnsList is set true when the response type is a list instead of an object.

Tyk classic API definition: service_discovery.endpoint_returns_list

type ServiceDiscovery struct {
	// Enabled activates Service Discovery.
	//
	// Tyk classic API definition: `service_discovery.use_discovery_service`
	Enabled	bool	`bson:"enabled" json:"enabled"`	// required

	// QueryEndpoint is the endpoint to call, this would usually be Consul, etcd or Eureka K/V store.
	// Tyk classic API definition: `service_discovery.query_endpoint`
	QueryEndpoint	string	`bson:"queryEndpoint,omitempty" json:"queryEndpoint,omitempty"`

	// DataPath is the namespace of the data path - where exactly in your service response the namespace can be found.
	// For example, if your service responds with:
	//
	// ```
	// {
	//  "action": "get",
	//  "node": {
	//    "key": "/services/single",
	//    "value": "http://httpbin.org:6000",
	//    "modifiedIndex": 6,
	//    "createdIndex": 6
	//  }
	// }
	// ```
	//
	// then your namespace would be `node.value`.
	//
	// Tyk classic API definition: `service_discovery.data_path`
	DataPath	string	`bson:"dataPath,omitempty" json:"dataPath,omitempty"`

	// UseNestedQuery enables the use of a combination of `dataPath` and `parentDataPath`.
	// It is necessary when the data lives within this string-encoded JSON object.
	//
	// ```
	// {
	//  "action": "get",
	//  "node": {
	//    "key": "/services/single",
	//    "value": "{"hostname": "http://httpbin.org", "port": "80"}",
	//    "modifiedIndex": 6,
	//    "createdIndex": 6
	//  }
	// }
	// ```
	//
	// Tyk classic API definition: `service_discovery.use_nested_query`
	UseNestedQuery	bool	`bson:"useNestedQuery,omitempty" json:"useNestedQuery,omitempty"`

	// ParentDataPath is the namespace of the where to find the nested
	// value if `useNestedQuery` is `true`. In the above example, it
	// would be `node.value`. You would change the `dataPath` setting
	// to be `hostname`, since this is where the host name data
	// resides in the JSON string. Tyk automatically assumes that
	// `dataPath` in this case is in a string-encoded JSON object and
	// will try to deserialize it.
	//
	// Tyk classic API definition: `service_discovery.parent_data_path`
	ParentDataPath	string	`bson:"parentDataPath,omitempty" json:"parentDataPath,omitempty"`

	// PortDataPath is the port of the data path. In the above nested example, we can see that there is a separate `port` value
	// for the service in the nested JSON. In this case, you can set the `portDataPath` value and Tyk will treat `dataPath` as
	// the hostname and zip them together (this assumes that the hostname element does not end in a slash or resource identifier
	// such as `/widgets/`). In the above example, the `portDataPath` would be `port`.
	//
	// Tyk classic API definition: `service_discovery.port_data_path`
	PortDataPath	string	`bson:"portDataPath,omitempty" json:"portDataPath,omitempty"`

	// UseTargetList should be set to `true` if you are using load balancing. Tyk will treat the data path as a list and
	// inject it into the target list of your API definition.
	//
	// Tyk classic API definition: `service_discovery.use_target_list`
	UseTargetList	bool	`bson:"useTargetList,omitempty" json:"useTargetList,omitempty"`

	// CacheTimeout is the timeout of a cache value when a new data is loaded from a discovery service.
	// Setting it too low will cause Tyk to call the SD service too often, setting it too high could mean that
	// failures are not recovered from quickly enough.
	//
	// Deprecated: The field is deprecated. Use `service_discovery` to configure service discovery cache options.
	//
	// Tyk classic API definition: `service_discovery.cache_timeout`
	CacheTimeout	int64	`bson:"cacheTimeout,omitempty" json:"cacheTimeout,omitempty"`

	// Cache holds cache related flags.
	//
	// Tyk classic API definition:
	// - `service_discovery.cache_disabled`
	// - `service_discovery.cache_timeout`
	Cache	*ServiceDiscoveryCache	`bson:"cache,omitempty" json:"cache,omitempty"`

	// TargetPath is used to set a target path that will be appended to the
	// discovered endpoint, since many service discovery services only provide
	// host and port data. It is important to be able to target a specific
	// resource on that host. Setting this value will enable that.
	//
	// Tyk classic API definition: `service_discovery.target_path`
	TargetPath	string	`bson:"targetPath,omitempty" json:"targetPath,omitempty"`

	// EndpointReturnsList is set `true` when the response type is a list instead of an object.
	//
	// Tyk classic API definition: `service_discovery.endpoint_returns_list`
	EndpointReturnsList	bool	`bson:"endpointReturnsList,omitempty" json:"endpointReturnsList,omitempty"`
}

ServiceDiscoveryCache

ServiceDiscoveryCache holds configuration for caching ServiceDiscovery data.

Field name Field type Comment
Enabled

bool

Enabled turns service discovery cache on or off.

Tyk classic API definition: service_discovery.cache_disabled

Timeout

int64

Timeout is the TTL for a cached object in seconds.

Tyk classic API definition: service_discovery.cache_timeout

type ServiceDiscoveryCache struct {
	// Enabled turns service discovery cache on or off.
	//
	// Tyk classic API definition: `service_discovery.cache_disabled`
	Enabled	bool	`bson:"enabled" json:"enabled"`	// required

	// Timeout is the TTL for a cached object in seconds.
	//
	// Tyk classic API definition: `service_discovery.cache_timeout`
	Timeout	int64	`bson:"timeout,omitempty" json:"timeout,omitempty"`
}

Signature

Signature holds the configuration for signature validation.

Field name Field type Comment
Enabled

bool

Enabled activates signature validation.

Tyk classic API definition: auth_configs[X].validate_signature.

Algorithm

string

Algorithm is the signature method to use.

Tyk classic API definition: auth_configs[X].signature.algorithm.

Header

string

Header is the name of the header to consume.

Tyk classic API definition: auth_configs[X].signature.header.

Query

AuthSource

Query is the name of the query parameter to consume.

Tyk classic API definition: auth_configs[X].signature.use_param/param_name.

Secret

string

Secret is the signing secret used for signature validation.

Tyk classic API definition: auth_configs[X].signature.secret.

AllowedClockSkew

int64

AllowedClockSkew configures a grace period in seconds during which an expired token is still valid.

Tyk classic API definition: auth_configs[X].signature.allowed_clock_skew.

ErrorCode

int

ErrorCode configures the HTTP response code for a validation failure. If unconfigured, a HTTP 401 Unauthorized status code will be emitted.

Tyk classic API definition: auth_configs[X].signature.error_code.

ErrorMessage

string

ErrorMessage configures the error message that is emitted on validation failure. A default error message is emitted if unset.

Tyk classic API definition: auth_configs[X].signature.error_message.

type Signature struct {
	// Enabled activates signature validation.
	//
	// Tyk classic API definition: `auth_configs[X].validate_signature`.
	Enabled	bool	`bson:"enabled" json:"enabled"`	// required
	// Algorithm is the signature method to use.
	//
	// Tyk classic API definition: `auth_configs[X].signature.algorithm`.
	Algorithm	string	`bson:"algorithm,omitempty" json:"algorithm,omitempty"`
	// Header is the name of the header to consume.
	//
	// Tyk classic API definition: `auth_configs[X].signature.header`.
	Header	string	`bson:"header,omitempty" json:"header,omitempty"`
	// Query is the name of the query parameter to consume.
	//
	// Tyk classic API definition: `auth_configs[X].signature.use_param/param_name`.
	Query	AuthSource	`bson:"query,omitempty" json:"query,omitempty"`
	// Secret is the signing secret used for signature validation.
	//
	// Tyk classic API definition: `auth_configs[X].signature.secret`.
	Secret	string	`bson:"secret,omitempty" json:"secret,omitempty"`
	// AllowedClockSkew configures a grace period in seconds during which an expired token is still valid.
	//
	// Tyk classic API definition: `auth_configs[X].signature.allowed_clock_skew`.
	AllowedClockSkew	int64	`bson:"allowedClockSkew,omitempty" json:"allowedClockSkew,omitempty"`
	// ErrorCode configures the HTTP response code for a validation failure.
	// If unconfigured, a HTTP 401 Unauthorized status code will be emitted.
	//
	// Tyk classic API definition: `auth_configs[X].signature.error_code`.
	ErrorCode	int	`bson:"errorCode,omitempty" json:"errorCode,omitempty"`
	// ErrorMessage configures the error message that is emitted on validation failure.
	// A default error message is emitted if unset.
	//
	// Tyk classic API definition: `auth_configs[X].signature.error_message`.
	ErrorMessage	string	`bson:"errorMessage,omitempty" json:"errorMessage,omitempty"`
}

State

State holds configuration for the status of the API within Tyk - if it is currently active and if it is exposed externally.

Field name Field type Comment
Active

bool

Active enables the API so that Tyk will listen for and process requests made to the listenPath. Tyk classic API definition: active

Internal

bool

Internal makes the API accessible only internally. Tyk classic API definition: internal

type State struct {
	// Active enables the API so that Tyk will listen for and process requests made to the listenPath.
	// Tyk classic API definition: `active`
	Active	bool	`bson:"active" json:"active"`	// required
	// Internal makes the API accessible only internally.
	// Tyk classic API definition: `internal`
	Internal	bool	`bson:"internal,omitempty" json:"internal,omitempty"`
}

TLSTransport

TLSTransport contains the configuration for TLS transport settings. This struct allows you to specify a custom proxy and set the minimum TLS versions and any SSL ciphers.

Example:

{
  "proxy_url": "http(s)://proxy.url:1234",
  "minVersion": "1.0",
  "maxVersion": "1.0",
  "ciphers": [
    "TLS_RSA_WITH_AES_128_GCM_SHA256",
    "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA"
  ],
  "insecureSkipVerify": true,
  "forceCommonNameCheck": false
}

Tyk classic API definition: proxy.transport

Field name Field type Comment
InsecureSkipVerify

bool

InsecureSkipVerify controls whether a client verifies the server's certificate chain and host name. If InsecureSkipVerify is true, crypto/tls accepts any certificate presented by the server and any host name in that certificate. In this mode, TLS is susceptible to machine-in-the-middle attacks unless custom verification is used. This should be used only for testing or in combination with VerifyConnection or VerifyPeerCertificate.

Tyk classic API definition: proxy.transport.ssl_insecure_skip_verify

Ciphers

[]string

Ciphers is a list of SSL ciphers to be used. If unset, the default ciphers will be used.

Tyk classic API definition: proxy.transport.ssl_ciphers

MinVersion

string

MinVersion is the minimum SSL/TLS version that is acceptable. Tyk classic API definition: proxy.transport.ssl_min_version

MaxVersion

string

MaxVersion is the maximum SSL/TLS version that is acceptable.

ForceCommonNameCheck

bool

ForceCommonNameCheck forces the validation of the hostname against the certificate Common Name.

Tyk classic API definition: proxy.transport.ssl_force_common_name_check

type TLSTransport struct {
	// InsecureSkipVerify controls whether a client verifies the server's certificate chain and host name.
	// If InsecureSkipVerify is true, crypto/tls accepts any certificate presented by the server and any host name in that certificate.
	// In this mode, TLS is susceptible to machine-in-the-middle attacks unless custom verification is used.
	// This should be used only for testing or in combination with VerifyConnection or VerifyPeerCertificate.
	//
	// Tyk classic API definition: `proxy.transport.ssl_insecure_skip_verify`
	InsecureSkipVerify	bool	`bson:"insecureSkipVerify,omitempty" json:"insecureSkipVerify,omitempty"`

	// Ciphers is a list of SSL ciphers to be used. If unset, the default ciphers will be used.
	//
	// Tyk classic API definition: `proxy.transport.ssl_ciphers`
	Ciphers	[]string	`bson:"ciphers,omitempty" json:"ciphers,omitempty"`

	// MinVersion is the minimum SSL/TLS version that is acceptable.
	// Tyk classic API definition: `proxy.transport.ssl_min_version`
	MinVersion	string	`bson:"minVersion,omitempty" json:"minVersion,omitempty"`

	// MaxVersion is the maximum SSL/TLS version that is acceptable.
	MaxVersion	string	`bson:"maxVersion,omitempty" json:"maxVersion,omitempty"`

	// ForceCommonNameCheck forces the validation of the hostname against the certificate Common Name.
	//
	// Tyk classic API definition: `proxy.transport.ssl_force_common_name_check`
	ForceCommonNameCheck	bool	`bson:"forceCommonNameCheck,omitempty" json:"forceCommonNameCheck,omitempty"`
}

Token

Token holds the values related to authentication tokens.

Field name Field type Comment
Enabled

bool

Enabled activates the token based authentication mode.

Tyk classic API definition: auth_configs["authToken"].use_standard_auth

AuthSources

AuthSources contains the configuration for authentication sources.

EnableClientCertificate

bool

EnableClientCertificate allows to create dynamic keys based on certificates.

Tyk classic API definition: auth_configs["authToken"].use_certificate

Signature

*Signature

Signature holds the configuration for verifying the signature of the token.

Tyk classic API definition: auth_configs["authToken"].use_certificate

type Token struct {
	// Enabled activates the token based authentication mode.
	//
	// Tyk classic API definition: `auth_configs["authToken"].use_standard_auth`
	Enabled	bool	`bson:"enabled" json:"enabled"`	// required

	// AuthSources contains the configuration for authentication sources.
	AuthSources	`bson:",inline" json:",inline"`

	// EnableClientCertificate allows to create dynamic keys based on certificates.
	//
	// Tyk classic API definition: `auth_configs["authToken"].use_certificate`
	EnableClientCertificate	bool	`bson:"enableClientCertificate,omitempty" json:"enableClientCertificate,omitempty"`

	// Signature holds the configuration for verifying the signature of the token.
	//
	// Tyk classic API definition: `auth_configs["authToken"].use_certificate`
	Signature	*Signature	`bson:"signatureValidation,omitempty" json:"signatureValidation,omitempty"`
}

TrackEndpoint

TrackEndpoint configures Track or DoNotTrack behaviour for an endpoint. Tyk classic API definition: version_data.versions..extended_paths.track_endpoints, version_data.versions..extended_paths.do_not_track_endpoints.

Field name Field type Comment
Enabled

bool

Enabled if set to true enables or disables tracking for an endpoint depending if it's used in trackEndpoint or doNotTrackEndpoint.

type TrackEndpoint struct {
	// Enabled if set to true enables or disables tracking for an endpoint depending
	// if it's used in `trackEndpoint` or `doNotTrackEndpoint`.
	Enabled bool `bson:"enabled" json:"enabled"`
}

TrafficLogs

TrafficLogs holds configuration about API log analytics.

Field name Field type Comment
Enabled

bool

Enabled enables traffic log analytics for the API. Tyk classic API definition: do_not_track.

TagHeaders

[]string

TagHeaders is a string array of HTTP headers that can be extracted and transformed into analytics tags (statistics aggregated by tag, per hour).

CustomRetentionPeriod

ReadableDuration

CustomRetentionPeriod configures a custom value for how long the analytics is retained for, defaults to 100 years.

Plugins

CustomAnalyticsPlugins

Plugins configures custom plugins to allow for extensive modifications to analytics records The plugins would be executed in the order of configuration in the list.

type TrafficLogs struct {
	// Enabled enables traffic log analytics for the API.
	// Tyk classic API definition: `do_not_track`.
	Enabled	bool	`bson:"enabled" json:"enabled"`
	// TagHeaders is a string array of HTTP headers that can be extracted
	// and transformed into analytics tags (statistics aggregated by tag, per hour).
	TagHeaders	[]string	`bson:"tagHeaders" json:"tagHeaders,omitempty"`
	// CustomRetentionPeriod configures a custom value for how long the analytics is retained for,
	// defaults to 100 years.
	CustomRetentionPeriod	ReadableDuration	`bson:"customRetentionPeriod,omitempty" json:"customRetentionPeriod,omitempty"`
	// Plugins configures custom plugins to allow for extensive modifications to analytics records
	// The plugins would be executed in the order of configuration in the list.
	Plugins	CustomAnalyticsPlugins	`bson:"plugins,omitempty" json:"plugins,omitempty"`
}

TransformBody

TransformBody holds configuration about request/response body transformations.

Field name Field type Comment
Enabled

bool

Enabled activates transform request/request body middleware.

Tyk classic API definition: version_data.versions..extended_paths.transform[].disabled (negated).

Format

apidef.RequestInputType

Format of the request/response body, xml or json.

Tyk classic API definition: version_data.versions..extended_paths.transform[].template_data.input_type.

Path

string

Path file path for the template.

Tyk classic API definition: version_data.versions..extended_paths.transform[].template_data.template_source when template_data.template_mode is file.

Body

string

Body base64 encoded representation of the template.

Tyk classic API definition: version_data.versions..extended_paths.transform[].template_data.template_source when template_data.template_mode is blob.

type TransformBody struct {
	// Enabled activates transform request/request body middleware.
	//
	// Tyk classic API definition: `version_data.versions..extended_paths.transform[].disabled` (negated).
	Enabled	bool	`bson:"enabled" json:"enabled"`
	// Format of the request/response body, xml or json.
	//
	// Tyk classic API definition: `version_data.versions..extended_paths.transform[].template_data.input_type`.
	Format	apidef.RequestInputType	`bson:"format" json:"format"`
	// Path file path for the template.
	//
	// Tyk classic API definition: `version_data.versions..extended_paths.transform[].template_data.template_source` when `template_data.template_mode` is `file`.
	Path	string	`bson:"path,omitempty" json:"path,omitempty"`
	// Body base64 encoded representation of the template.
	//
	// Tyk classic API definition: `version_data.versions..extended_paths.transform[].template_data.template_source` when `template_data.template_mode` is `blob`.
	Body	string	`bson:"body,omitempty" json:"body,omitempty"`
}

TransformHeaders

TransformHeaders holds configuration about request/response header transformations.

Field name Field type Comment
Enabled

bool

Enabled activates Header Transform for the given path and method.

Tyk classic API definition: version_data.versions..extended_paths.transform_headers[].disabled (negated).

Remove

[]string

Remove specifies header names to be removed from the request/response.

Tyk classic API definition: version_data.versions..extended_paths.transform_headers[].delete_headers.

Add

Headers

Add specifies headers to be added to the request/response.

Tyk classic API definition: version_data.versions..extended_paths.transform_headers[].add_headers.

type TransformHeaders struct {
	// Enabled activates Header Transform for the given path and method.
	//
	// Tyk classic API definition: `version_data.versions..extended_paths.transform_headers[].disabled` (negated).
	Enabled	bool	`bson:"enabled" json:"enabled"`
	// Remove specifies header names to be removed from the request/response.
	//
	// Tyk classic API definition: `version_data.versions..extended_paths.transform_headers[].delete_headers`.
	Remove	[]string	`bson:"remove,omitempty" json:"remove,omitempty"`
	// Add specifies headers to be added to the request/response.
	//
	// Tyk classic API definition: `version_data.versions..extended_paths.transform_headers[].add_headers`.
	Add	Headers	`bson:"add,omitempty" json:"add,omitempty"`
}

TransformRequestMethod

TransformRequestMethod holds configuration for rewriting request methods.

Field name Field type Comment
Enabled

bool

Enabled activates Method Transform for the given path and method.

ToMethod

string

ToMethod is the http method value to which the method of an incoming request will be transformed.

type TransformRequestMethod struct {
	// Enabled activates Method Transform for the given path and method.
	Enabled	bool	`bson:"enabled" json:"enabled"`
	// ToMethod is the http method value to which the method of an incoming request will be transformed.
	ToMethod	string	`bson:"toMethod" json:"toMethod"`
}

TykExtensionConfigParams

TykExtensionConfigParams holds the essential configuration required for the Tyk Extension schema.

Field name Field type Comment
UpstreamURL

string

UpstreamURL configures the upstream URL.

ListenPath

string

ListenPath configures the listen path.

CustomDomain

string

CustomDomain configures the domain name.

ApiID

string

ApiID is the API ID.

Authentication

*bool

Authentication is true if the API configures authentication.

AllowList

*bool

AllowList is true if the API configures an allow list.

ValidateRequest

*bool

ValidateRequest is true if the API enables request validation.

MockResponse

*bool

MockResponse is true if a mocked response is configured.

pathItemHasParameters

bool

pathItemHasParameters is set to true when parameters are defined the same level as of operations within path.

type TykExtensionConfigParams struct {
	// UpstreamURL configures the upstream URL.
	UpstreamURL	string
	// ListenPath configures the listen path.
	ListenPath	string
	// CustomDomain configures the domain name.
	CustomDomain	string
	// ApiID is the API ID.
	ApiID	string

	// Authentication is true if the API configures authentication.
	Authentication	*bool
	// AllowList is true if the API configures an allow list.
	AllowList	*bool
	// ValidateRequest is true if the API enables request validation.
	ValidateRequest	*bool
	// MockResponse is true if a mocked response is configured.
	MockResponse	*bool

	// pathItemHasParameters is set to true when parameters are defined the same level as of operations within path.
	pathItemHasParameters	bool
}

URLRewrite

URLRewrite configures URL rewriting. Tyk classic API definition: version_data.versions..extended_paths.url_rewrite.

Field name Field type Comment
Enabled

bool

Enabled activates URL rewriting if set to true.

Pattern

string

Pattern is the regular expression against which the request URL is compared for the primary rewrite check. If this matches the defined pattern, the primary URL rewrite is triggered.

RewriteTo

string

RewriteTo specifies the URL to which the request shall be rewritten if the primary URL rewrite is triggered.

Triggers

[]*URLRewriteTrigger

Triggers contain advanced additional triggers for the URL rewrite. The triggers are processed only if the requested URL matches the pattern above.

type URLRewrite struct {
	// Enabled activates URL rewriting if set to true.
	Enabled	bool	`bson:"enabled" json:"enabled"`

	// Pattern is the regular expression against which the request URL is compared for the primary rewrite check.
	// If this matches the defined pattern, the primary URL rewrite is triggered.
	Pattern	string	`bson:"pattern,omitempty" json:"pattern,omitempty"`

	// RewriteTo specifies the URL to which the request shall be rewritten if the primary URL rewrite is triggered.
	RewriteTo	string	`bson:"rewriteTo,omitempty" json:"rewriteTo,omitempty"`

	// Triggers contain advanced additional triggers for the URL rewrite.
	// The triggers are processed only if the requested URL matches the pattern above.
	Triggers	[]*URLRewriteTrigger	`bson:"triggers,omitempty" json:"triggers,omitempty"`
}

URLRewriteCondition

URLRewriteCondition defines the matching mode for an URL rewrite rules. Tyk classic API definition: Matching condition in version_data.versions..extended_paths.url_rewrite[].triggers[].on.

  • Value any means any of the defined trigger rules may match.
  • Value all means all the defined trigger rules must match.

Field name Field type Comment
type

string

No comment on field.
type URLRewriteCondition string

URLRewriteInput

URLRewriteInput defines the input for an URL rewrite rule. Tyk classic API definition: Input source for URL rewrite rules in version_data.versions..extended_paths.url_rewrite[].triggers[].options.

The following values are valid:

  • url, match pattern against URL
  • query, match pattern against named query parameter value
  • path, match pattern against named path parameter value
  • header, match pattern against named header value
  • sessionMetadata, match pattern against session metadata
  • requestBody, match pattern against request body
  • requestContext, match pattern against request context

The default url is used as the input source.

Field name Field type Comment
type

string

No comment on field.
type URLRewriteInput string

URLRewriteRule

URLRewriteRule represents a rewrite matching rules. Tyk classic API definition: version_data.versions..extended_paths.url_rewrite[].triggers[].options.

Field name Field type Comment
In

URLRewriteInput

In specifies one of the valid inputs for URL rewriting.

Name

string

Name is the index in the value declared inside in.

Example: for in=query, name=q, the parameter q would be read from the request query parameters.

The value of name is unused when in is set to requestBody, as the request body is a single value and not a set of values.

Pattern

string

Pattern is the regular expression against which the in values are compared for this rule check. If the value matches the defined pattern, the URL rewrite is triggered for this rule.

Negate

bool

Negate is a boolean negation operator. Setting it to true inverts the matching behaviour such that the rewrite will be triggered if the value does not match the pattern for this rule.

type URLRewriteRule struct {
	// In specifies one of the valid inputs for URL rewriting.
	In	URLRewriteInput	`bson:"in" json:"in"`

	// Name is the index in the value declared inside `in`.
	//
	// Example: for `in=query`, `name=q`, the parameter `q` would
	// be read from the request query parameters.
	//
	// The value of name is unused when `in` is set to `requestBody`,
	// as the request body is a single value and not a set of values.
	Name	string	`bson:"name,omitempty" json:"name,omitempty"`

	// Pattern is the regular expression against which the `in` values are compared for this rule check.
	// If the value matches the defined `pattern`, the URL rewrite is triggered for this rule.
	Pattern	string	`bson:"pattern" json:"pattern"`

	// Negate is a boolean negation operator. Setting it to true inverts the matching behaviour
	// such that the rewrite will be triggered if the value does not match the `pattern` for this rule.
	Negate	bool	`bson:"negate,omitempty" json:"negate,omitempty"`
}

URLRewriteTrigger

URLRewriteTrigger represents a set of matching rules for a rewrite. Tyk classic API definition: version_data.versions..extended_paths.url_rewrite[].triggers.

Field name Field type Comment
Condition

URLRewriteCondition

Condition indicates the logical combination that will be applied to the rules for an advanced trigger.

Rules

[]*URLRewriteRule

Rules contain individual checks that are combined according to the condition to determine if the URL rewrite will be triggered. If empty, the trigger is ignored.

RewriteTo

string

RewriteTo specifies the URL to which the request shall be rewritten if indicated by the combination of condition and rules.

type URLRewriteTrigger struct {
	// Condition indicates the logical combination that will be applied to the rules for an advanced trigger.
	Condition	URLRewriteCondition	`bson:"condition" json:"condition"`

	// Rules contain individual checks that are combined according to the
	// `condition` to determine if the URL rewrite will be triggered.
	// If empty, the trigger is ignored.
	Rules	[]*URLRewriteRule	`bson:"rules,omitempty" json:"rules,omitempty"`

	// RewriteTo specifies the URL to which the request shall be rewritten
	// if indicated by the combination of `condition` and `rules`.
	RewriteTo	string	`bson:"rewriteTo" json:"rewriteTo"`
}

Upstream

Upstream holds configuration for the upstream server to which Tyk should proxy requests.

Field name Field type Comment
URL

string

URL defines the upstream address (or target URL) to which requests should be proxied. Tyk classic API definition: proxy.target_url

ServiceDiscovery

*ServiceDiscovery

ServiceDiscovery contains the configuration related to Service Discovery. Tyk classic API definition: proxy.service_discovery

UptimeTests

*UptimeTests

UptimeTests contains the configuration related to uptime tests. Tyk classic API definition: uptime_tests and check_host_against_uptime_tests.

MutualTLS

*MutualTLS

MutualTLS contains the configuration for establishing a mutual TLS connection between Tyk and the upstream server. Tyk classic API definition: upstream_certificates_disabled and upstream_certificates.

CertificatePinning

*CertificatePinning

CertificatePinning contains the configuration related to certificate pinning. Tyk classic API definition: certificate_pinning_disabled and pinned_public_keys.

RateLimit

*RateLimit

RateLimit contains the configuration related to API level rate limit. Tyk classic API definition: global_rate_limit.

Authentication

*UpstreamAuth

Authentication contains the configuration related to upstream authentication. Tyk classic API definition: upstream_auth.

LoadBalancing

*LoadBalancing

LoadBalancing contains configuration for load balancing between multiple upstream targets. Tyk classic API definition: proxy.enable_load_balancing and proxy.targets.

PreserveHostHeader

*PreserveHostHeader

PreserveHostHeader contains the configuration for preserving the host header. Tyk classic API definition: proxy.preserve_host_header.

PreserveTrailingSlash

*PreserveTrailingSlash

PreserveTrailingSlash controls whether Tyk preserves trailing slashes in URLs when proxying requests to upstream services. When enabled, URLs like "/users/" will retain the trailing slash. Tyk classic API definition: proxy.disable_strip_slash.

TLSTransport

*TLSTransport

TLSTransport contains the configuration for TLS transport settings. Tyk classic API definition: proxy.transport

Proxy

*Proxy

Proxy contains the configuration for an internal proxy. Tyk classic API definition: proxy.proxy_url

type Upstream struct {
	// URL defines the upstream address (or target URL) to which requests should be proxied.
	// Tyk classic API definition: `proxy.target_url`
	URL	string	`bson:"url" json:"url"`	// required

	// ServiceDiscovery contains the configuration related to Service Discovery.
	// Tyk classic API definition: `proxy.service_discovery`
	ServiceDiscovery	*ServiceDiscovery	`bson:"serviceDiscovery,omitempty" json:"serviceDiscovery,omitempty"`

	// UptimeTests contains the configuration related to uptime tests.
	// Tyk classic API definition: `uptime_tests` and `check_host_against_uptime_tests`.
	UptimeTests	*UptimeTests	`bson:"uptimeTests,omitempty" json:"uptimeTests,omitempty"`

	// MutualTLS contains the configuration for establishing a mutual TLS connection between Tyk and the upstream server.
	// Tyk classic API definition: `upstream_certificates_disabled` and `upstream_certificates`.
	MutualTLS	*MutualTLS	`bson:"mutualTLS,omitempty" json:"mutualTLS,omitempty"`

	// CertificatePinning contains the configuration related to certificate pinning.
	// Tyk classic API definition: `certificate_pinning_disabled` and `pinned_public_keys`.
	CertificatePinning	*CertificatePinning	`bson:"certificatePinning,omitempty" json:"certificatePinning,omitempty"`

	// RateLimit contains the configuration related to API level rate limit.
	// Tyk classic API definition: `global_rate_limit`.
	RateLimit	*RateLimit	`bson:"rateLimit,omitempty" json:"rateLimit,omitempty"`

	// Authentication contains the configuration related to upstream authentication.
	// Tyk classic API definition: `upstream_auth`.
	Authentication	*UpstreamAuth	`bson:"authentication,omitempty" json:"authentication,omitempty"`

	// LoadBalancing contains configuration for load balancing between multiple upstream targets.
	// Tyk classic API definition: `proxy.enable_load_balancing` and `proxy.targets`.
	LoadBalancing	*LoadBalancing	`bson:"loadBalancing,omitempty" json:"loadBalancing,omitempty"`

	// PreserveHostHeader contains the configuration for preserving the host header.
	// Tyk classic API definition: `proxy.preserve_host_header`.
	PreserveHostHeader	*PreserveHostHeader	`bson:"preserveHostHeader,omitempty" json:"preserveHostHeader,omitempty"`

	// PreserveTrailingSlash controls whether Tyk preserves trailing slashes in URLs when proxying
	// requests to upstream services. When enabled, URLs like "/users/" will retain the trailing slash.
	// Tyk classic API definition: `proxy.disable_strip_slash`.
	PreserveTrailingSlash	*PreserveTrailingSlash	`bson:"preserveTrailingSlash,omitempty" json:"preserveTrailingSlash,omitempty"`

	// TLSTransport contains the configuration for TLS transport settings.
	// Tyk classic API definition: `proxy.transport`
	TLSTransport	*TLSTransport	`bson:"tlsTransport,omitempty" json:"tlsTransport,omitempty"`

	// Proxy contains the configuration for an internal proxy.
	// Tyk classic API definition: `proxy.proxy_url`
	Proxy	*Proxy	`bson:"proxy,omitempty" json:"proxy,omitempty"`
}

UpstreamAuth

UpstreamAuth holds the configurations related to upstream API authentication.

Field name Field type Comment
Enabled

bool

Enabled enables upstream API authentication.

BasicAuth

*UpstreamBasicAuth

BasicAuth holds the basic authentication configuration for upstream API authentication.

OAuth

*UpstreamOAuth

OAuth contains the configuration for OAuth2 Client Credentials flow.

RequestSigning

*UpstreamRequestSigning

RequestSigning holds the configuration for generating signed requests to an upstream API.

type UpstreamAuth struct {
	// Enabled enables upstream API authentication.
	Enabled	bool	`bson:"enabled" json:"enabled"`
	// BasicAuth holds the basic authentication configuration for upstream API authentication.
	BasicAuth	*UpstreamBasicAuth	`bson:"basicAuth,omitempty" json:"basicAuth,omitempty"`
	// OAuth contains the configuration for OAuth2 Client Credentials flow.
	OAuth	*UpstreamOAuth	`bson:"oauth,omitempty" json:"oauth,omitempty"`
	// RequestSigning holds the configuration for generating signed requests to an upstream API.
	RequestSigning	*UpstreamRequestSigning	`bson:"requestSigning,omitempty" json:"requestSigning,omitempty"`
}

UpstreamBasicAuth

UpstreamBasicAuth holds upstream basic authentication configuration.

Field name Field type Comment
Enabled

bool

Enabled enables upstream basic authentication.

Header

*AuthSource

Header contains configurations for the header value.

Username

string

Username is the username to be used for upstream basic authentication.

Password

string

Password is the password to be used for upstream basic authentication.

type UpstreamBasicAuth struct {
	// Enabled enables upstream basic authentication.
	Enabled	bool	`bson:"enabled" json:"enabled"`
	// Header contains configurations for the header value.
	Header	*AuthSource	`bson:"header,omitempty" json:"header,omitempty"`
	// Username is the username to be used for upstream basic authentication.
	Username	string	`bson:"username" json:"username"`
	// Password is the password to be used for upstream basic authentication.
	Password	string	`bson:"password" json:"password"`
}

UpstreamOAuth

UpstreamOAuth holds the configuration for OAuth2 Client Credentials flow.

Field name Field type Comment
Enabled

bool

Enabled activates upstream OAuth2 authentication.

AllowedAuthorizeTypes

[]string

AllowedAuthorizeTypes specifies the allowed authorization types for upstream OAuth2 authentication.

ClientCredentials

*ClientCredentials

ClientCredentials holds the configuration for OAuth2 Client Credentials flow.

PasswordAuthentication

*PasswordAuthentication

PasswordAuthentication holds the configuration for upstream OAauth password authentication flow.

type UpstreamOAuth struct {
	// Enabled activates upstream OAuth2 authentication.
	Enabled	bool	`bson:"enabled" json:"enabled"`
	// AllowedAuthorizeTypes specifies the allowed authorization types for upstream OAuth2 authentication.
	AllowedAuthorizeTypes	[]string	`bson:"allowedAuthorizeTypes" json:"allowedAuthorizeTypes"`
	// ClientCredentials holds the configuration for OAuth2 Client Credentials flow.
	ClientCredentials	*ClientCredentials	`bson:"clientCredentials,omitempty" json:"clientCredentials,omitempty"`
	// PasswordAuthentication holds the configuration for upstream OAauth password authentication flow.
	PasswordAuthentication	*PasswordAuthentication	`bson:"password,omitempty" json:"password,omitempty"`
}

UpstreamRequestSigning

UpstreamRequestSigning represents configuration for generating signed requests to an upstream API. Tyk classic API definition: request_signing.

Field name Field type Comment
Enabled

bool

Enabled determines if request signing is enabled or disabled.

SignatureHeader

string

SignatureHeader specifies the HTTP header name for the signature.

Algorithm

string

Algorithm represents the signing algorithm used (e.g., HMAC-SHA256).

KeyID

string

KeyID identifies the key used for signing purposes.

Headers

[]string

Headers contains a list of headers included in the signature calculation.

Secret

string

Secret holds the secret used for signing when applicable.

CertificateID

string

CertificateID specifies the certificate ID used in signing operations.

type UpstreamRequestSigning struct {
	// Enabled determines if request signing is enabled or disabled.
	Enabled	bool	`bson:"enabled" json:"enabled"`	// required
	// SignatureHeader specifies the HTTP header name for the signature.
	SignatureHeader	string	`bson:"signatureHeader,omitempty" json:"signatureHeader,omitempty"`
	// Algorithm represents the signing algorithm used (e.g., HMAC-SHA256).
	Algorithm	string	`bson:"algorithm,omitempty" json:"algorithm,omitempty"`
	// KeyID identifies the key used for signing purposes.
	KeyID	string	`bson:"keyId,omitempty" json:"keyId,omitempty"`
	// Headers contains a list of headers included in the signature calculation.
	Headers	[]string	`bson:"headers,omitempty" json:"headers,omitempty"`
	// Secret holds the secret used for signing when applicable.
	Secret	string	`bson:"secret,omitempty" json:"secret,omitempty"`
	// CertificateID specifies the certificate ID used in signing operations.
	CertificateID	string	`bson:"certificateId,omitempty" json:"certificateId,omitempty"`
}

UptimeTest

UptimeTest configures an uptime test check.

Field name Field type Comment
CheckURL

string

CheckURL is the URL for a request. If service discovery is in use, the hostname will be resolved to a service host.

Examples:

  • http://database1.company.local
  • https://webcluster.service/health
  • tcp://127.0.0.1:6379 (for TCP checks).
Timeout

time.ReadableDuration

Timeout declares a timeout for the request. If the test exceeds this timeout, the check fails.

Method

string

Method allows you to customize the HTTP method for the test (GET, POST,...).

Headers

map[string]string

Headers contain any custom headers for the back end service.

Body

string

Body is the body of the test request.

Commands

[]UptimeTestCommand

Commands are used for TCP checks.

EnableProxyProtocol

bool

EnableProxyProtocol enables proxy protocol support when making request. The back end service needs to support this.

type UptimeTest struct {
	// CheckURL is the URL for a request. If service discovery is in use,
	// the hostname will be resolved to a service host.
	//
	// Examples:
	//
	// - `http://database1.company.local`
	// - `https://webcluster.service/health`
	// - `tcp://127.0.0.1:6379` (for TCP checks).
	CheckURL	string	`bson:"url" json:"url"`

	// Timeout declares a timeout for the request. If the test exceeds
	// this timeout, the check fails.
	Timeout	time.ReadableDuration	`bson:"timeout" json:"timeout,omitempty"`

	// Method allows you to customize the HTTP method for the test (`GET`, `POST`,...).
	Method	string	`bson:"method" json:"method"`

	// Headers contain any custom headers for the back end service.
	Headers	map[string]string	`bson:"headers" json:"headers,omitempty"`

	// Body is the body of the test request.
	Body	string	`bson:"body" json:"body,omitempty"`

	// Commands are used for TCP checks.
	Commands	[]UptimeTestCommand	`bson:"commands" json:"commands,omitempty"`

	// EnableProxyProtocol enables proxy protocol support when making request.
	// The back end service needs to support this.
	EnableProxyProtocol	bool	`bson:"enableProxyProtocol" json:"enableProxyProtocol"`
}

UptimeTestCommand

UptimeTestCommand handles additional checks for tcp connections.

Field name Field type Comment
Name

string

Name can be either send or expect, designating if the message should be sent, or read from the connection.

Message

string

Message contains the payload to send or expect.

type UptimeTestCommand struct {
	// Name can be either `send` or `expect`, designating if the
	// message should be sent, or read from the connection.
	Name	string	`bson:"name" json:"name"`

	// Message contains the payload to send or expect.
	Message	string	`bson:"message" json:"message"`
}

UptimeTests

UptimeTests configures uptime tests.

Field name Field type Comment
Enabled

bool

Enabled specifies whether the uptime tests are active or not. Tyk classic API definition: uptime_tests.disabled

ServiceDiscovery

*ServiceDiscovery

ServiceDiscovery contains the configuration related to test Service Discovery. Tyk classic API definition: proxy.service_discovery

Tests

[]UptimeTest

Tests contains individual connectivity tests defined for checking if a service is online.

HostDownRetestPeriod

time.ReadableDuration

HostDownRetestPeriod is the time to wait until rechecking a failed test. If undefined, the default testing interval (10s) is in use. Setting this to a lower value would result in quicker recovery on failed checks.

LogRetentionPeriod

time.ReadableDuration

LogRetentionPeriod holds a time to live for the uptime test results. If unset, a value of 100 years is the default.

type UptimeTests struct {
	// Enabled specifies whether the uptime tests are active or not.
	// Tyk classic API definition: `uptime_tests.disabled`
	Enabled	bool	`bson:"enabled" json:"enabled"`

	// ServiceDiscovery contains the configuration related to test Service Discovery.
	// Tyk classic API definition: `proxy.service_discovery`
	ServiceDiscovery	*ServiceDiscovery	`bson:"serviceDiscovery,omitempty" json:"serviceDiscovery,omitempty"`

	// Tests contains individual connectivity tests defined for checking if a service is online.
	Tests	[]UptimeTest	`bson:"tests,omitempty" json:"tests,omitempty"`

	// HostDownRetestPeriod is the time to wait until rechecking a failed test.
	// If undefined, the default testing interval (10s) is in use.
	// Setting this to a lower value would result in quicker recovery on failed checks.
	HostDownRetestPeriod	time.ReadableDuration	`bson:"hostDownRetestPeriod" json:"hostDownRetestPeriod,omitempty"`

	// LogRetentionPeriod holds a time to live for the uptime test results.
	// If unset, a value of 100 years is the default.
	LogRetentionPeriod	time.ReadableDuration	`bson:"logRetentionPeriod" json:"logRetentionPeriod,omitempty"`
}

ValidateRequest

ValidateRequest holds configuration required for validating requests.

Field name Field type Comment
Enabled

bool

Enabled is a boolean flag, if set to true, it enables request validation.

ErrorResponseCode

int

ErrorResponseCode is the error code emitted when the request fails validation. If unset or zero, the response will returned with http status 422 Unprocessable Entity.

type ValidateRequest struct {
	// Enabled is a boolean flag, if set to `true`, it enables request validation.
	Enabled	bool	`bson:"enabled" json:"enabled"`

	// ErrorResponseCode is the error code emitted when the request fails validation.
	// If unset or zero, the response will returned with http status 422 Unprocessable Entity.
	ErrorResponseCode	int	`bson:"errorResponseCode,omitempty" json:"errorResponseCode,omitempty"`
}

VersionToID

VersionToID contains a single mapping from a version name into an API ID. Tyk classic API definition: Entry in version_definition.versions map.

Field name Field type Comment
Name

string

Name contains the user chosen version name, e.g. v1 or similar.

ID

string

ID is the API ID for the version set in Name.

type VersionToID struct {
	// Name contains the user chosen version name, e.g. `v1` or similar.
	Name	string	`bson:"name" json:"name"`
	// ID is the API ID for the version set in Name.
	ID	string	`bson:"id" json:"id"`
}

Versioning

Versioning holds configuration for API versioning.

Tyk classic API definition: version_data.

Field name Field type Comment
Enabled

bool

Enabled is a boolean flag, if set to true it will enable versioning of the API.

Name

string

Name contains the name of the version as entered by the user ("v1" or similar).

Default

string

Default contains the default version name if a request is issued without a version.

Location

string

Location contains versioning location information. It can be one of the following:

  • header,
  • url-param,
  • url.
Key

string

Key contains the name of the key to check for versioning information.

Versions

[]VersionToID

Versions contains a list of versions that map to individual API IDs.

StripVersioningData

bool

StripVersioningData is a boolean flag, if set to true, the API responses will be stripped of versioning data.

UrlVersioningPattern

string

UrlVersioningPattern is a string that contains the pattern that if matched will remove the version from the URL.

FallbackToDefault

bool

FallbackToDefault controls the behaviour of Tyk when a versioned API is called with a nonexistent version name. If set to true then the default API version will be invoked; if set to false Tyk will return an HTTP 404 This API version does not seem to exist error in this scenario.

type Versioning struct {
	// Enabled is a boolean flag, if set to `true` it will enable versioning of the API.
	Enabled	bool	`bson:"enabled" json:"enabled"`	// required
	// Name contains the name of the version as entered by the user ("v1" or similar).
	Name	string	`bson:"name,omitempty" json:"name,omitempty"`
	// Default contains the default version name if a request is issued without a version.
	Default	string	`bson:"default" json:"default"`	// required
	// Location contains versioning location information. It can be one of the following:
	//
	// - `header`,
	// - `url-param`,
	// - `url`.
	Location	string	`bson:"location" json:"location"`	// required
	// Key contains the name of the key to check for versioning information.
	Key	string	`bson:"key" json:"key"`	// required
	// Versions contains a list of versions that map to individual API IDs.
	Versions	[]VersionToID	`bson:"versions" json:"versions"`	// required
	// StripVersioningData is a boolean flag, if set to `true`, the API responses will be stripped of versioning data.
	StripVersioningData	bool	`bson:"stripVersioningData,omitempty" json:"stripVersioningData,omitempty"`
	// UrlVersioningPattern is a string that contains the pattern that if matched will remove the version from the URL.
	UrlVersioningPattern	string	`bson:"urlVersioningPattern,omitempty" json:"urlVersioningPattern,omitempty"`
	// FallbackToDefault controls the behaviour of Tyk when a versioned API is called with a nonexistent version name.
	// If set to `true` then the default API version will be invoked; if set to `false` Tyk will return an HTTP 404
	// `This API version does not seem to exist` error in this scenario.
	FallbackToDefault	bool	`bson:"fallbackToDefault,omitempty" json:"fallbackToDefault,omitempty"`
}

VirtualEndpoint

VirtualEndpoint contains virtual endpoint configuration.

Field name Field type Comment
Enabled

bool

Enabled activates virtual endpoint.

Tyk classic API definition: virtual.disabled (negated).

Name

string

Name is the name of plugin function to be executed. Deprecated: Use FunctionName instead.

FunctionName

string

FunctionName is the name of plugin function to be executed.

Tyk classic API definition: virtual.response_function_name.

Path

string

Path is the path to JS file.

Tyk classic API definition: virtual.function_source_uri when virtual.function_source_type is file.

Body

string

Body is the JS function to execute encoded in base64 format.

Tyk classic API definition: virtual.function_source_uri when virtual.function_source_type is blob.

ProxyOnError

bool

ProxyOnError proxies if virtual endpoint errors out.

Tyk classic API definition: virtual.proxy_on_error.

RequireSession

bool

RequireSession if enabled passes session to virtual endpoint.

Tyk classic API definition: virtual.use_session.

type VirtualEndpoint struct {
	// Enabled activates virtual endpoint.
	//
	// Tyk classic API definition: `virtual.disabled` (negated).
	Enabled	bool	`bson:"enabled" json:"enabled"`	// required.
	// Name is the name of plugin function to be executed.
	// Deprecated: Use FunctionName instead.
	Name	string	`bson:"name,omitempty" json:"name,omitempty"`
	// FunctionName is the name of plugin function to be executed.
	//
	// Tyk classic API definition: `virtual.response_function_name`.
	FunctionName	string	`bson:"functionName" json:"functionName"`	// required.
	// Path is the path to JS file.
	//
	// Tyk classic API definition: `virtual.function_source_uri` when `virtual.function_source_type` is `file`.
	Path	string	`bson:"path,omitempty" json:"path,omitempty"`
	// Body is the JS function to execute encoded in base64 format.
	//
	// Tyk classic API definition: `virtual.function_source_uri` when `virtual.function_source_type` is `blob`.
	Body	string	`bson:"body,omitempty" json:"body,omitempty"`
	// ProxyOnError proxies if virtual endpoint errors out.
	//
	// Tyk classic API definition: `virtual.proxy_on_error`.
	ProxyOnError	bool	`bson:"proxyOnError,omitempty" json:"proxyOnError,omitempty"`
	// RequireSession if enabled passes session to virtual endpoint.
	//
	// Tyk classic API definition: `virtual.use_session`.
	RequireSession	bool	`bson:"requireSession,omitempty" json:"requireSession,omitempty"`
}

WebhookEvent

WebhookEvent stores the core information about a webhook event.

Field name Field type Comment
URL

string

URL is the target URL for the webhook.

Tyk classic API definition: event_handlers.events[].handler_meta.target_path.

Method

string

Method is the HTTP method for the webhook.

Tyk classic API definition: event_handlers.events[].handler_meta.method.

CoolDownPeriod

ReadableDuration

CoolDownPeriod defines cool-down for the event, so it does not trigger again. It uses shorthand notation. The value of CoolDownPeriod is a string that specifies the interval in a compact form, where hours, minutes and seconds are denoted by 'h', 'm' and 's' respectively. Multiple units can be combined to represent the duration.

Examples of valid shorthand notations:

  • "1h" : one hour
  • "20m" : twenty minutes
  • "30s" : thirty seconds
  • "1m29s": one minute and twenty-nine seconds
  • "1h30m" : one hour and thirty minutes

An empty value is interpreted as "0s", implying no cool-down. It's important to format the string correctly, as invalid formats will be considered as 0s/empty.

Tyk classic API definition: event_handlers.events[].handler_meta.event_timeout.

BodyTemplate

string

BodyTemplate is the template to be used for request payload.

Tyk classic API definition: event_handlers.events[].handler_meta.template_path.

Headers

Headers

Headers are the list of request headers to be used.

Tyk classic API definition: event_handlers.events[].handler_meta.header_map.

type WebhookEvent struct {
	// URL is the target URL for the webhook.
	//
	// Tyk classic API definition: `event_handlers.events[].handler_meta.target_path`.
	URL	string	`json:"url" bson:"url"`
	// Method is the HTTP method for the webhook.
	//
	// Tyk classic API definition: `event_handlers.events[].handler_meta.method`.
	Method	string	`json:"method" bson:"method"`
	// CoolDownPeriod defines cool-down for the event, so it does not trigger again.
	// It uses shorthand notation.
	// The value of CoolDownPeriod is a string that specifies the interval in a compact form,
	// where hours, minutes and seconds are denoted by 'h', 'm' and 's' respectively.
	// Multiple units can be combined to represent the duration.
	//
	// Examples of valid shorthand notations:
	// - "1h"   : one hour
	// - "20m"  : twenty minutes
	// - "30s"  : thirty seconds
	// - "1m29s": one minute and twenty-nine seconds
	// - "1h30m" : one hour and thirty minutes
	//
	// An empty value is interpreted as "0s", implying no cool-down.
	// It's important to format the string correctly, as invalid formats will
	// be considered as 0s/empty.
	//
	// Tyk classic API definition: `event_handlers.events[].handler_meta.event_timeout`.
	CoolDownPeriod	ReadableDuration	`json:"cooldownPeriod" bson:"cooldownPeriod"`
	// BodyTemplate is the template to be used for request payload.
	//
	// Tyk classic API definition: `event_handlers.events[].handler_meta.template_path`.
	BodyTemplate	string	`json:"bodyTemplate,omitempty" bson:"bodyTemplate,omitempty"`
	// Headers are the list of request headers to be used.
	//
	// Tyk classic API definition: `event_handlers.events[].handler_meta.header_map`.
	Headers	Headers	`json:"headers,omitempty" bson:"headers,omitempty"`
}

XTykAPIGateway

XTykAPIGateway contains custom Tyk API extensions for the OpenAPI definition. The values for the extensions are stored inside the OpenAPI document, under the key x-tyk-api-gateway.

Field name Field type Comment
Info

Info

Info contains the main metadata for the API definition.

Upstream

Upstream

Upstream contains the configurations related to the upstream.

Server

Server

Server contains the configurations related to the server.

Middleware

*Middleware

Middleware contains the configurations related to the Tyk middleware.

type XTykAPIGateway struct {
	// Info contains the main metadata for the API definition.
	Info	Info	`bson:"info" json:"info"`	// required
	// Upstream contains the configurations related to the upstream.
	Upstream	Upstream	`bson:"upstream" json:"upstream"`	// required
	// Server contains the configurations related to the server.
	Server	Server	`bson:"server" json:"server"`	// required
	// Middleware contains the configurations related to the Tyk middleware.
	Middleware	*Middleware	`bson:"middleware,omitempty" json:"middleware,omitempty"`
}

XTykStreaming

XTykStreaming represents the structure for Tyk streaming configurations.

Field name Field type Comment
Streams

map[string]any

Streams contains the configurations related to Tyk Streams.

type XTykStreaming struct {
	// Streams contains the configurations related to Tyk Streams.
	Streams map[string]interface{} `bson:"streams" json:"streams"`	// required
}

pathPart

This type doesn't have documentation.

Field name Field type Comment
name

string

No comment on field.
value

string

No comment on field.
isRegex

bool

No comment on field.
type pathPart struct {
	name	string
	value	string
	isRegex	bool
}

Functions

func ExampleExtractor

ExampleExtractor returns an example payload according to the openapi3.SchemaRef object.

func ExampleExtractor(schema *openapi3.SchemaRef) interface{} {
	val := schema.Value
	if val.Example != nil {
		return val.Example
	}

	switch {
	case val.Type == openapi3.TypeObject:
		obj := make(map[string]interface{})
		for name, prop := range schema.Value.Properties {
			obj[name] = ExampleExtractor(prop)
		}

		return obj
	case val.Type == openapi3.TypeArray:
		items := ExampleExtractor(val.Items)
		return []interface{}{items}
	default:
		if len(val.Enum) > 0 {
			return val.Enum[0]
		}
		return emptyExampleVal(val)
	}
}

Cognitive complexity: 15, Cyclomatic complexity: 7

Uses: openapi3.TypeArray, openapi3.TypeObject.

func FillOASFromClassicAPIDefinition

func FillOASFromClassicAPIDefinition(api *apidef.APIDefinition, oas *OAS) (*OAS, error) {
	api.IsOAS = true

	oas.Fill(*api)
	oas.setRequiredFields(api.Name, api.VersionName)
	clearClassicAPIForSomeFeatures(api)

	err := oas.Validate(context.Background(), []openapi3.ValidationOption{
		openapi3.DisableExamplesValidation(),
		openapi3.DisableSchemaDefaultsValidation(),
	}...)
	if err != nil {
		return nil, err
	}

	b, err := oas.MarshalJSON()
	if err != nil {
		return nil, err
	}

	return oas, ValidateOASObject(b, oas.OpenAPI)
}

Cognitive complexity: 5, Cyclomatic complexity: 3

Uses: context.Background, openapi3.DisableExamplesValidation, openapi3.DisableSchemaDefaultsValidation, openapi3.ValidationOption.

func GetOASSchema

GetOASSchema returns an oas schema for a particular version.

func GetOASSchema(version string) ([]byte, error) {
	if err := loadOASSchema(); err != nil {
		return nil, fmt.Errorf("loadOASSchema failed: %w", err)
	}

	if version == "" {
		return oasJSONSchemas[defaultVersion], nil
	}

	minorVersion, err := getMinorVersion(version)
	if err != nil {
		return nil, err
	}

	oasSchema, ok := oasJSONSchemas[minorVersion]
	if !ok {
		return nil, fmt.Errorf(oasSchemaVersionNotFoundFmt, version)
	}

	return oasSchema, nil
}

Cognitive complexity: 8, Cyclomatic complexity: 5

Uses: fmt.Errorf.

func GetTykExtensionConfigParams

GetTykExtensionConfigParams extracts a *TykExtensionConfigParams from a *http.Request.

func GetTykExtensionConfigParams(r *http.Request) *TykExtensionConfigParams {
	overRideValues := TykExtensionConfigParams{}

	queries := r.URL.Query()
	overRideValues.UpstreamURL = strings.TrimSpace(queries.Get("upstreamURL"))
	overRideValues.ListenPath = strings.TrimSpace(queries.Get("listenPath"))
	overRideValues.CustomDomain = strings.TrimSpace(queries.Get("customDomain"))
	overRideValues.ApiID = strings.TrimSpace(queries.Get("apiID"))

	overRideValues.Authentication = getQueryValPtr(strings.TrimSpace(queries.Get("authentication")))
	overRideValues.ValidateRequest = getQueryValPtr(strings.TrimSpace(queries.Get("validateRequest")))
	overRideValues.AllowList = getQueryValPtr(strings.TrimSpace(queries.Get("allowList")))
	overRideValues.MockResponse = getQueryValPtr(strings.TrimSpace(queries.Get("mockResponse")))

	if ShouldOmit(overRideValues) {
		return nil
	}

	return &overRideValues
}

Cognitive complexity: 3, Cyclomatic complexity: 2

Uses: strings.TrimSpace.

func GetValidationOptionsFromConfig

GetValidationOptionsFromConfig retrieves validation options based on the configuration settings.

func GetValidationOptionsFromConfig(oasConfig config.OASConfig) []openapi3.ValidationOption {
	var opts []openapi3.ValidationOption

	if !oasConfig.ValidateSchemaDefaults {
		opts = append(opts, openapi3.DisableSchemaDefaultsValidation())
	}

	if !oasConfig.ValidateExamples {
		opts = append(opts, openapi3.DisableExamplesValidation())
	}

	return opts
}

Cognitive complexity: 4, Cyclomatic complexity: 3

Uses: openapi3.DisableExamplesValidation, openapi3.DisableSchemaDefaultsValidation, openapi3.ValidationOption.

func MigrateAndFillOAS

MigrateAndFillOAS migrates classic APIs to OAS-compatible forms. Then, it fills an OAS with it. To be able to make it a valid OAS, it adds some required fields. It returns base API and its versions if any.

func MigrateAndFillOAS(api *apidef.APIDefinition) (APIDef, []APIDef, error) {
	baseAPIDef := APIDef{Classic: api}

	versions, err := api.Migrate()
	if err != nil {
		return baseAPIDef, nil, err
	}

	baseAPIDef.OAS, err = NewOASFromClassicAPIDefinition(api)
	if err != nil {
		return baseAPIDef, nil, fmt.Errorf("base API %s migrated OAS is not valid: %w", api.Name, err)
	}

	versionAPIDefs := make([]APIDef, len(versions))
	for i := 0; i < len(versions); i++ {
		versionOAS, err := NewOASFromClassicAPIDefinition(&versions[i])
		if err != nil {
			return baseAPIDef, nil, fmt.Errorf("version API %s migrated OAS is not valid: %w", versions[i].Name, err)
		}
		versionAPIDefs[i] = APIDef{versionOAS, &versions[i]}
	}

	return baseAPIDef, versionAPIDefs, err
}

Cognitive complexity: 10, Cyclomatic complexity: 5

Uses: fmt.Errorf.

func NewHeaders

NewHeaders creates Headers from in map.

func NewHeaders(in map[string]string) Headers {
	var headers = make(Headers, 0, len(in))

	for k, v := range in {
		headers = append(headers, Header{Name: k, Value: v})
	}

	sort.Slice(headers, func(i, j int) bool {
		return headers[i].Name < headers[j].Name
	})
	return headers
}

Cognitive complexity: 5, Cyclomatic complexity: 2

Uses: sort.Slice.

func NewOAS

NewOAS returns an allocated *OAS.

func NewOAS() *OAS {
	return &OAS{
		T: openapi3.T{},
	}
}

Cognitive complexity: 2, Cyclomatic complexity: 1

Uses: openapi3.T.

func NewOASFromClassicAPIDefinition

func NewOASFromClassicAPIDefinition(api *apidef.APIDefinition) (*OAS, error) {
	var oas OAS
	return FillOASFromClassicAPIDefinition(api, &oas)
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func RetainOldServerURL

RetainOldServerURL retains the first entry from old servers provided tyk adds a server URL to the start of oas.Servers to add the gw URL RetainOldServerURL can be used when API def is patched.

func RetainOldServerURL(oldServers, newServers openapi3.Servers) openapi3.Servers {
	if len(oldServers) > 0 && len(newServers) > 0 {
		if oldServers[0].URL == newServers[0].URL {
			return newServers
		}
		newServers = append(openapi3.Servers{oldServers[0]}, newServers...)
	}

	return newServers
}

Cognitive complexity: 5, Cyclomatic complexity: 4

Uses: openapi3.Servers.

func ValidateOASObject

ValidateOASObject validates an OAS document against a particular OAS version.

func ValidateOASObject(documentBody []byte, oasVersion string) error {
	oasSchema, err := GetOASSchema(oasVersion)
	if err != nil {
		return err
	}

	return validateJSON(oasSchema, documentBody)
}

Cognitive complexity: 2, Cyclomatic complexity: 2

func ValidateOASTemplate

ValidateOASTemplate checks a Tyk OAS API template for necessary fields, acknowledging that some standard Tyk OAS API fields are optional in templates.

func ValidateOASTemplate(documentBody []byte, oasVersion string) error {
	oasSchema, err := GetOASSchema(oasVersion)
	if err != nil {
		return err
	}

	oasSchema = jsonparser.Delete(oasSchema, keyProperties, ExtensionTykAPIGateway, keyRequired)

	definitions, _, _, err := jsonparser.Get(oasSchema, keyDefinitions)
	if err != nil {
		return err
	}

	unsetReqFieldsPaths := []string{
		"X-Tyk-Info",
		"X-Tyk-State",
		"X-Tyk-Server",
		"X-Tyk-ListenPath",
		"X-Tyk-Upstream",
	}

	for _, path := range unsetReqFieldsPaths {
		definitions = jsonparser.Delete(definitions, path, keyRequired)
	}

	unsetAnyOfFieldsPaths := []string{
		"X-Tyk-Upstream",
	}

	for _, path := range unsetAnyOfFieldsPaths {
		definitions = jsonparser.Delete(definitions, path, keyAnyOf)
	}

	oasSchema, err = jsonparser.Set(oasSchema, definitions, keyDefinitions)
	if err != nil {
		return err
	}

	return validateJSON(oasSchema, documentBody)
}

Cognitive complexity: 14, Cyclomatic complexity: 6

Uses: jsonparser.Delete, jsonparser.Get, jsonparser.Set.

func (*Allowance) ExtractTo

ExtractTo extracts the *Allowance into *apidef.EndPointMeta.

func (a *Allowance) ExtractTo(endpointMeta *apidef.EndPointMeta) {
	endpointMeta.Disabled = !a.Enabled
	endpointMeta.IgnoreCase = a.IgnoreCase
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*Allowance) Fill

Fill fills *Allowance from apidef.EndPointMeta.

func (a *Allowance) Fill(endpointMeta apidef.EndPointMeta) {
	a.Enabled = !endpointMeta.Disabled
	a.IgnoreCase = endpointMeta.IgnoreCase
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*Allowance) Import

Import enables an allowance based on the enabled argument.

func (a *Allowance) Import(enabled bool) {
	a.Enabled = enabled
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*AuthSource) ExtractTo

ExtractTo extracts *AuthSource into the function parameters.

func (as *AuthSource) ExtractTo(enabled *bool, name *string) {
	*enabled = as.Enabled
	*name = as.Name
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*AuthSource) Fill

Fill fills *AuthSource with values from the parameters.

func (as *AuthSource) Fill(enabled bool, name string) {
	as.Enabled = enabled
	as.Name = name
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*AuthSources) ExtractTo

ExtractTo extracts *AuthSources to *apidef.AuthConfig.

func (as *AuthSources) ExtractTo(authConfig *apidef.AuthConfig) {
	// Extract Header auth source.
	if as.Header != nil {
		var enabled bool
		as.Header.ExtractTo(&enabled, &authConfig.AuthHeaderName)
		authConfig.DisableHeader = !enabled
	} else {
		authConfig.DisableHeader = true
	}

	// Extract Query auth source.
	if as.Query != nil {
		as.Query.ExtractTo(&authConfig.UseParam, &authConfig.ParamName)
	}

	// Extract Cookie auth source.
	if as.Cookie != nil {
		as.Cookie.ExtractTo(&authConfig.UseCookie, &authConfig.CookieName)
	}
}

Cognitive complexity: 8, Cyclomatic complexity: 4

func (*AuthSources) Fill

Fill fills *AuthSources from apidef.AuthConfig.

func (as *AuthSources) Fill(authConfig apidef.AuthConfig) {
	// Allocate auth sources being filled.
	if as.Header == nil {
		as.Header = &AuthSource{}
	}
	if as.Cookie == nil {
		as.Cookie = &AuthSource{}
	}
	if as.Query == nil {
		as.Query = &AuthSource{}
	}

	// Fill the auth source structures.
	as.Header.Fill(!authConfig.DisableHeader, authConfig.AuthHeaderName)
	as.Query.Fill(authConfig.UseParam, authConfig.ParamName)
	as.Cookie.Fill(authConfig.UseCookie, authConfig.CookieName)

	// Check if auth sources should be omitted as they may be undefined.
	if ShouldOmit(as.Cookie) {
		as.Cookie = nil
	}
	if ShouldOmit(as.Header) {
		as.Header = nil
	}
	if ShouldOmit(as.Query) {
		as.Query = nil
	}
}

Cognitive complexity: 15, Cyclomatic complexity: 7

func (*AuthSources) Import

Import populates *AuthSources based on arguments.

func (as *AuthSources) Import(in string) {
	source := &AuthSource{Enabled: true}

	switch in {
	case header:
		as.Header = source
	case cookie:
		as.Cookie = source
	case query:
		as.Query = source
	}
}

Cognitive complexity: 6, Cyclomatic complexity: 5

func (*Authentication) ExtractTo

ExtractTo extracts *Authentication into *apidef.APIDefinition.

func (a *Authentication) ExtractTo(api *apidef.APIDefinition) {
	api.UseKeylessAccess = !a.Enabled
	api.StripAuthData = a.StripAuthorizationData
	api.BaseIdentityProvidedBy = a.BaseIdentityProvider

	if a.HMAC != nil {
		a.HMAC.ExtractTo(api)
	}

	if a.OIDC != nil {
		a.OIDC.ExtractTo(api)
	}

	if a.Custom == nil {
		a.Custom = &CustomPluginAuthentication{}
		defer func() {
			a.Custom = nil
		}()
	}

	a.Custom.ExtractTo(api)

	if a.CustomKeyLifetime == nil {
		a.CustomKeyLifetime = &CustomKeyLifetime{}
		defer func() {
			a.CustomKeyLifetime = nil
		}()
	}

	a.CustomKeyLifetime.ExtractTo(api)
}

Cognitive complexity: 12, Cyclomatic complexity: 5

func (*Authentication) Fill

Fill fills *Authentication from apidef.APIDefinition.

func (a *Authentication) Fill(api apidef.APIDefinition) {
	a.Enabled = !api.UseKeylessAccess
	a.StripAuthorizationData = api.StripAuthData
	a.BaseIdentityProvider = api.BaseIdentityProvidedBy

	if a.Custom == nil {
		a.Custom = &CustomPluginAuthentication{}
	}

	a.Custom.Fill(api)

	if ShouldOmit(a.Custom) {
		a.Custom = nil
	}

	if a.CustomKeyLifetime == nil {
		a.CustomKeyLifetime = &CustomKeyLifetime{}
	}

	a.CustomKeyLifetime.Fill(api)

	if ShouldOmit(a.CustomKeyLifetime) {
		a.CustomKeyLifetime = nil
	}

	if api.AuthConfigs == nil || len(api.AuthConfigs) == 0 {
		return
	}

	if _, ok := api.AuthConfigs[apidef.HMACType]; ok {
		if a.HMAC == nil {
			a.HMAC = &HMAC{}
		}

		a.HMAC.Fill(api)
	}

	if ShouldOmit(a.HMAC) {
		a.HMAC = nil
	}

	if _, ok := api.AuthConfigs[apidef.OIDCType]; ok {
		if a.OIDC == nil {
			a.OIDC = &OIDC{}
		}

		a.OIDC.Fill(api)
	}

	if ShouldOmit(a.OIDC) {
		a.OIDC = nil
	}
}

Cognitive complexity: 26, Cyclomatic complexity: 13

Uses: apidef.HMACType, apidef.OIDCType.

func (*AuthenticationPlugin) ExtractTo

func (ap *AuthenticationPlugin) ExtractTo(api *apidef.APIDefinition) {
	api.CustomMiddleware.AuthCheck.Disabled = !ap.Enabled
	api.CustomMiddleware.AuthCheck.Name = ap.FunctionName
	api.CustomMiddleware.AuthCheck.Path = ap.Path
	api.CustomMiddleware.AuthCheck.RawBodyOnly = ap.RawBodyOnly
	api.CustomMiddleware.AuthCheck.RequireSession = ap.RequireSession

	if ap.IDExtractor == nil {
		ap.IDExtractor = &IDExtractor{}
		defer func() {
			ap.IDExtractor = nil
		}()
	}

	ap.IDExtractor.ExtractTo(api)
}

Cognitive complexity: 4, Cyclomatic complexity: 2

func (*AuthenticationPlugin) Fill

func (ap *AuthenticationPlugin) Fill(api apidef.APIDefinition) {
	ap.FunctionName = api.CustomMiddleware.AuthCheck.Name
	ap.Path = api.CustomMiddleware.AuthCheck.Path
	ap.RawBodyOnly = api.CustomMiddleware.AuthCheck.RawBodyOnly
	ap.RequireSession = api.CustomMiddleware.AuthCheck.RequireSession
	ap.Enabled = !api.CustomMiddleware.AuthCheck.Disabled
	if ap.IDExtractor == nil {
		ap.IDExtractor = &IDExtractor{}
	}

	ap.IDExtractor.Fill(api)
	if ShouldOmit(ap.IDExtractor) {
		ap.IDExtractor = nil
	}
}

Cognitive complexity: 5, Cyclomatic complexity: 3

func (*Basic) Import

Import populates *Basic from it's arguments.

func (b *Basic) Import(enable bool) {
	b.Enabled = enable
	b.Header = &AuthSource{
		Enabled:	true,
		Name:		defaultAuthSourceName,
	}
}

Cognitive complexity: 1, Cyclomatic complexity: 1

func (*BatchProcessing) ExtractTo

ExtractTo copies the Enabled state of BatchProcessing into the EnableBatchRequestSupport field of the provided APIDefinition.

func (b *BatchProcessing) ExtractTo(api *apidef.APIDefinition) {
	api.EnableBatchRequestSupport = b.Enabled
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*BatchProcessing) Fill

Fill updates the BatchProcessing configuration based on the EnableBatchRequestSupport value from the given APIDefinition.

func (b *BatchProcessing) Fill(api apidef.APIDefinition) {
	b.Enabled = api.EnableBatchRequestSupport
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*CORS) ExtractTo

ExtractTo extracts *CORS into *apidef.CORSConfig.

func (c *CORS) ExtractTo(cors *apidef.CORSConfig) {
	cors.Enable = c.Enabled
	cors.MaxAge = c.MaxAge
	cors.AllowCredentials = c.AllowCredentials
	cors.ExposedHeaders = c.ExposedHeaders
	cors.AllowedHeaders = c.AllowedHeaders
	cors.OptionsPassthrough = c.OptionsPassthrough
	cors.Debug = c.Debug
	cors.AllowedOrigins = c.AllowedOrigins
	cors.AllowedMethods = c.AllowedMethods
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*CORS) Fill

Fill fills *CORS from apidef.CORSConfig.

func (c *CORS) Fill(cors apidef.CORSConfig) {
	c.Enabled = cors.Enable
	c.MaxAge = cors.MaxAge
	c.AllowCredentials = cors.AllowCredentials
	c.ExposedHeaders = cors.ExposedHeaders
	c.AllowedHeaders = cors.AllowedHeaders
	c.OptionsPassthrough = cors.OptionsPassthrough
	c.Debug = cors.Debug
	c.AllowedOrigins = cors.AllowedOrigins
	c.AllowedMethods = cors.AllowedMethods
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*Cache) ExtractTo

ExtractTo extracts *Cache into *apidef.CacheOptions.

func (c *Cache) ExtractTo(cache *apidef.CacheOptions) {
	cache.EnableCache = c.Enabled
	cache.CacheTimeout = c.Timeout
	cache.CacheAllSafeRequests = c.CacheAllSafeRequests
	cache.CacheOnlyResponseCodes = c.CacheResponseCodes
	cache.CacheByHeaders = c.CacheByHeaders
	cache.EnableUpstreamCacheControl = c.EnableUpstreamCacheControl
	cache.CacheControlTTLHeader = c.ControlTTLHeaderName
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*Cache) Fill

Fill fills *Cache from apidef.CacheOptions.

func (c *Cache) Fill(cache apidef.CacheOptions) {
	c.Enabled = cache.EnableCache
	c.Timeout = cache.CacheTimeout
	c.CacheAllSafeRequests = cache.CacheAllSafeRequests
	c.CacheResponseCodes = cache.CacheOnlyResponseCodes
	c.CacheByHeaders = cache.CacheByHeaders
	c.EnableUpstreamCacheControl = cache.EnableUpstreamCacheControl
	c.ControlTTLHeaderName = cache.CacheControlTTLHeader
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*CachePlugin) ExtractTo

ExtractTo extracts *CachePlugin values to *apidef.CacheMeta.

func (a *CachePlugin) ExtractTo(cm *apidef.CacheMeta) {
	cm.Disabled = !a.Enabled
	cm.CacheKeyRegex = a.CacheByRegex
	cm.CacheOnlyResponseCodes = a.CacheResponseCodes
	cm.Timeout = a.Timeout
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*CachePlugin) Fill

Fill fills *CachePlugin from apidef.CacheMeta.

func (a *CachePlugin) Fill(cm apidef.CacheMeta) {
	a.Enabled = !cm.Disabled
	a.CacheByRegex = cm.CacheKeyRegex
	a.CacheResponseCodes = cm.CacheOnlyResponseCodes
	a.Timeout = cm.Timeout

	//TT-14102: Default cache timeout in seconds if none is specified but caching is enabled
	if a.Enabled && a.Timeout == 0 {
		a.Timeout = apidef.DefaultCacheTimeout
	}
}

Cognitive complexity: 2, Cyclomatic complexity: 3

Uses: apidef.DefaultCacheTimeout.

func (*CertificatePinning) ExtractTo

ExtractTo extracts *CertficiatePinning into *apidef.APIDefinition.

func (cp *CertificatePinning) ExtractTo(api *apidef.APIDefinition) {
	api.CertificatePinningDisabled = !cp.Enabled

	if len(cp.DomainToPublicKeysMapping) > 0 {
		api.PinnedPublicKeys = make(map[string]string)
		cp.DomainToPublicKeysMapping.ExtractTo(api.PinnedPublicKeys)
	} else {
		api.PinnedPublicKeys = nil
	}
}

Cognitive complexity: 4, Cyclomatic complexity: 2

func (*CertificatePinning) Fill

Fill fills *CertificatePinning from apidef.APIDefinition.

func (cp *CertificatePinning) Fill(api apidef.APIDefinition) {
	cp.Enabled = !api.CertificatePinningDisabled

	if cp.DomainToPublicKeysMapping == nil {
		cp.DomainToPublicKeysMapping = make(PinnedPublicKeys, len(api.PinnedPublicKeys))
	}

	cp.DomainToPublicKeysMapping.Fill(api.PinnedPublicKeys)

	if ShouldOmit(cp.DomainToPublicKeysMapping) {
		cp.DomainToPublicKeysMapping = nil
	}
}

Cognitive complexity: 4, Cyclomatic complexity: 3

func (*CircuitBreaker) ExtractTo

ExtractTo extracts *CircuitBreaker into *apidef.CircuitBreakerMeta.

func (cb *CircuitBreaker) ExtractTo(circuitBreaker *apidef.CircuitBreakerMeta) {
	circuitBreaker.Disabled = !cb.Enabled
	circuitBreaker.ThresholdPercent = cb.Threshold
	circuitBreaker.Samples = int64(cb.SampleSize)
	circuitBreaker.ReturnToServiceAfter = cb.CoolDownPeriod
	circuitBreaker.DisableHalfOpenState = !cb.HalfOpenStateEnabled
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*CircuitBreaker) Fill

Fill fills *CircuitBreaker from apidef.CircuitBreakerMeta.

func (cb *CircuitBreaker) Fill(circuitBreaker apidef.CircuitBreakerMeta) {
	cb.Enabled = !circuitBreaker.Disabled
	cb.Threshold = circuitBreaker.ThresholdPercent
	cb.SampleSize = int(circuitBreaker.Samples)
	cb.CoolDownPeriod = circuitBreaker.ReturnToServiceAfter
	cb.HalfOpenStateEnabled = !circuitBreaker.DisableHalfOpenState
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*ClientCertificates) ExtractTo

ExtractTo extracts *ClientCertificates into *apidef.APIDefinition.

func (cc *ClientCertificates) ExtractTo(api *apidef.APIDefinition) {
	api.UseMutualTLSAuth = cc.Enabled
	api.ClientCertificates = cc.Allowlist
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*ClientCertificates) Fill

Fill fills *ClientCertificates from apidef.APIDefinition.

func (cc *ClientCertificates) Fill(api apidef.APIDefinition) {
	cc.Enabled = api.UseMutualTLSAuth
	cc.Allowlist = api.ClientCertificates
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*ClientCredentials) ExtractTo

func (c *ClientCredentials) ExtractTo(api *apidef.ClientCredentials) {
	api.ClientID = c.ClientID
	api.ClientSecret = c.ClientSecret
	api.TokenURL = c.TokenURL
	api.Scopes = c.Scopes
	api.ExtraMetadata = c.ExtraMetadata

	if c.Header == nil {
		c.Header = &AuthSource{}
		defer func() {
			c.Header = nil
		}()
	}
	c.Header.ExtractTo(&api.Header.Enabled, &api.Header.Name)
}

Cognitive complexity: 4, Cyclomatic complexity: 2

func (*ClientCredentials) Fill

func (c *ClientCredentials) Fill(api apidef.ClientCredentials) {
	c.ClientID = api.ClientID
	c.ClientSecret = api.ClientSecret
	c.TokenURL = api.TokenURL
	c.Scopes = api.Scopes
	c.ExtraMetadata = api.ExtraMetadata

	if c.Header == nil {
		c.Header = &AuthSource{}
	}
	c.Header.Fill(api.Header.Enabled, api.Header.Name)
	if ShouldOmit(c.Header) {
		c.Header = nil
	}
}

Cognitive complexity: 5, Cyclomatic complexity: 3

func (*ContextVariables) ExtractTo

ExtractTo extracts *ContextVariables into *apidef.APIDefinition.

func (c *ContextVariables) ExtractTo(api *apidef.APIDefinition) {
	api.EnableContextVars = c.Enabled
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*ContextVariables) Fill

Fill fills *ContextVariables from apidef.APIDefinition.

func (c *ContextVariables) Fill(api apidef.APIDefinition) {
	c.Enabled = api.EnableContextVars
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*CustomAnalyticsPlugins) ExtractTo

ExtractTo extracts CustomAnalyticsPlugins into AnalyticsPlugin of supplied api.

func (c *CustomAnalyticsPlugins) ExtractTo(api *apidef.APIDefinition) {
	if len(*c) > 0 {
		// extract the first item in the customAnalyticsPlugin into apidef
		plugin := (*c)[0]
		api.AnalyticsPlugin.Enabled = plugin.Enabled
		api.AnalyticsPlugin.FuncName = plugin.FunctionName
		api.AnalyticsPlugin.PluginPath = plugin.Path
	}
}

Cognitive complexity: 2, Cyclomatic complexity: 2

func (*CustomAnalyticsPlugins) Fill

Fill fills CustomAnalyticsPlugins from AnalyticsPlugin in the supplied api.

func (c *CustomAnalyticsPlugins) Fill(api apidef.APIDefinition) {
	if api.AnalyticsPlugin.Enabled {
		customPlugins := []CustomPlugin{
			{
				Enabled:	api.AnalyticsPlugin.Enabled,
				FunctionName:	api.AnalyticsPlugin.FuncName,
				Path:		api.AnalyticsPlugin.PluginPath,
			},
		}
		*c = customPlugins
	}
}

Cognitive complexity: 4, Cyclomatic complexity: 2

func (*CustomKeyLifetime) ExtractTo

ExtractTo extracts *Authentication into *apidef.APIDefinition.

func (k *CustomKeyLifetime) ExtractTo(api *apidef.APIDefinition) {
	api.SessionLifetimeRespectsKeyExpiration = k.RespectValidity

	if k.Enabled {
		api.SessionLifetime = int64(k.Value.Seconds())
	} else {
		api.SessionLifetime = 0
	}
}

Cognitive complexity: 4, Cyclomatic complexity: 2

func (*CustomKeyLifetime) Fill

Fill fills *CustomKeyLifetime from apidef.APIDefinition.

func (k *CustomKeyLifetime) Fill(api apidef.APIDefinition) {
	k.RespectValidity = api.SessionLifetimeRespectsKeyExpiration

	if api.SessionLifetime == 0 {
		k.Enabled = false
	} else {
		k.Enabled = true
		k.Value = ReadableDuration(time.Duration(api.SessionLifetime) * time.Second)
	}
}

Cognitive complexity: 4, Cyclomatic complexity: 2

Uses: time.Duration, time.Second.

func (*CustomPluginAuthentication) ExtractTo

ExtractTo extracts *CustomPluginAuthentication to *apidef.APIDefinition.

func (c *CustomPluginAuthentication) ExtractTo(api *apidef.APIDefinition) {
	api.CustomPluginAuthEnabled = c.Enabled

	if c.Config == nil {
		c.Config = &AuthenticationPlugin{}
		defer func() {
			c.Config = nil
		}()
	}

	c.Config.ExtractTo(api)

	authConfig := apidef.AuthConfig{}
	c.AuthSources.ExtractTo(&authConfig)

	if reflect.DeepEqual(authConfig, apidef.AuthConfig{DisableHeader: true}) {
		return
	}

	if api.AuthConfigs == nil {
		api.AuthConfigs = make(map[string]apidef.AuthConfig)
	}

	api.AuthConfigs[apidef.CoprocessType] = authConfig
}

Cognitive complexity: 10, Cyclomatic complexity: 4

Uses: apidef.AuthConfig, apidef.CoprocessType, reflect.DeepEqual.

func (*CustomPluginAuthentication) Fill

Fill fills *CustomPluginAuthentication from apidef.AuthConfig.

func (c *CustomPluginAuthentication) Fill(api apidef.APIDefinition) {
	c.Enabled = api.CustomPluginAuthEnabled

	if c.Config == nil {
		c.Config = &AuthenticationPlugin{}
	}

	c.Config.Fill(api)
	if ShouldOmit(c.Config) {
		c.Config = nil
	}

	if ShouldOmit(api.AuthConfigs[apidef.CoprocessType]) {
		return
	}

	c.AuthSources.Fill(api.AuthConfigs[apidef.CoprocessType])
}

Cognitive complexity: 7, Cyclomatic complexity: 4

Uses: apidef.CoprocessType.

func (*CustomPlugins) ExtractTo

ExtractTo extracts CustomPlugins into supplied Middleware definitions.

func (c *CustomPlugins) ExtractTo(mwDefs []apidef.MiddlewareDefinition) {
	if c == nil {
		return
	}

	for i, plugin := range *c {
		mwDefs[i] = apidef.MiddlewareDefinition{
			Disabled:	!plugin.Enabled,
			Name:		plugin.FunctionName,
			Path:		plugin.Path,
			RawBodyOnly:	plugin.RawBodyOnly,
			RequireSession:	plugin.RequireSession,
		}
	}
}

Cognitive complexity: 6, Cyclomatic complexity: 3

Uses: apidef.MiddlewareDefinition.

func (*CustomPlugins) Fill

Fill fills CustomPlugins from supplied Middleware definitions.

func (c *CustomPlugins) Fill(mwDefs []apidef.MiddlewareDefinition) {
	if len(mwDefs) == 0 {
		return
	}

	customPlugins := make(CustomPlugins, len(mwDefs))
	for i, mwDef := range mwDefs {
		customPlugins[i] = CustomPlugin{
			Enabled:	!mwDef.Disabled,
			Path:		mwDef.Path,
			FunctionName:	mwDef.Name,
			RawBodyOnly:	mwDef.RawBodyOnly,
			RequireSession:	mwDef.RequireSession,
		}
	}

	*c = customPlugins
}

Cognitive complexity: 6, Cyclomatic complexity: 3

func (*DetailedActivityLogs) ExtractTo

ExtractTo extracts *DetailedActivityLogs into *apidef.APIDefinition.

func (d *DetailedActivityLogs) ExtractTo(api *apidef.APIDefinition) {
	api.EnableDetailedRecording = d.Enabled
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*DetailedActivityLogs) Fill

Fill fills *DetailedActivityLogs from apidef.APIDefinition.

func (d *DetailedActivityLogs) Fill(api apidef.APIDefinition) {
	d.Enabled = api.EnableDetailedRecording
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*DetailedTracing) ExtractTo

ExtractTo extracts *DetailedTracing into *apidef.APIDefinition.

func (dt *DetailedTracing) ExtractTo(api *apidef.APIDefinition) {
	api.DetailedTracing = dt.Enabled
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*DetailedTracing) Fill

Fill fills *DetailedTracing from apidef.APIDefinition.

func (dt *DetailedTracing) Fill(api apidef.APIDefinition) {
	dt.Enabled = api.DetailedTracing
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*Domain) ExtractTo

ExtractTo extracts *Domain into *apidef.APIDefinition.

func (cd *Domain) ExtractTo(api *apidef.APIDefinition) {
	api.DomainDisabled = !cd.Enabled
	api.Domain = cd.Name
	api.Certificates = cd.Certificates
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*Domain) Fill

Fill fills *Domain from apidef.APIDefinition.

func (cd *Domain) Fill(api apidef.APIDefinition) {
	cd.Enabled = !api.DomainDisabled
	cd.Name = api.Domain
	cd.Certificates = api.Certificates
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*EndpointPostPlugin) MarshalJSON

MarshalJSON is a custom JSON marshaler for the EndpointPostPlugin struct. It is implemented to facilitate a smooth migration from deprecated fields that were previously used to represent the same data.

func (ep *EndpointPostPlugin) MarshalJSON() ([]byte, error) {
	if ep == nil {
		return nil, nil
	}

	// to prevent infinite recursion
	type Alias EndpointPostPlugin

	payload := Alias(*ep)
	if payload.FunctionName == "" && payload.Name != "" {
		payload.FunctionName = payload.Name
		payload.Name = ""
	}

	return json.Marshal(payload)
}

Cognitive complexity: 4, Cyclomatic complexity: 4

Uses: json.Marshal.

func (*EnforceTimeout) ExtractTo

ExtractTo extracts *EnforceTimeout to *apidef.HardTimeoutMeta.

func (et *EnforceTimeout) ExtractTo(meta *apidef.HardTimeoutMeta) {
	meta.Disabled = !et.Enabled
	meta.TimeOut = et.Value
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*EnforceTimeout) Fill

Fill fills *EnforceTimeout from apidef.HardTimeoutMeta.

func (et *EnforceTimeout) Fill(meta apidef.HardTimeoutMeta) {
	et.Enabled = !meta.Disabled
	et.Value = meta.TimeOut
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*EventHandler) GetJSVMEventHandlerConf

GetJSVMEventHandlerConf generates the JavaScript VM event handler configuration using the current EventHandler instance.

func (e *EventHandler) GetJSVMEventHandlerConf() apidef.JSVMEventHandlerConf {
	return apidef.JSVMEventHandlerConf{
		Disabled:	!e.Enabled,
		ID:		e.ID,
		MethodName:	e.JSVMEvent.FunctionName,
		Path:		e.JSVMEvent.Path,
	}
}

Cognitive complexity: 1, Cyclomatic complexity: 1

Uses: apidef.JSVMEventHandlerConf.

func (*EventHandler) GetLogEventHandlerConf

GetLogEventHandlerConf creates and returns a LogEventHandlerConf based on the current EventHandler configuration.

func (e *EventHandler) GetLogEventHandlerConf() apidef.LogEventHandlerConf {
	return apidef.LogEventHandlerConf{
		Disabled:	!e.Enabled,
		Prefix:		e.LogEvent.LogPrefix,
	}
}

Cognitive complexity: 1, Cyclomatic complexity: 1

Uses: apidef.LogEventHandlerConf.

func (*EventHandler) GetWebhookConf

GetWebhookConf converts EventHandler.WebhookEvent apidef.WebHookHandlerConf.

func (e *EventHandler) GetWebhookConf() apidef.WebHookHandlerConf {
	return apidef.WebHookHandlerConf{
		Disabled:	!e.Enabled,
		ID:		e.ID,
		Name:		e.Name,
		Method:		e.Webhook.Method,
		TargetPath:	e.Webhook.URL,
		HeaderList:	e.Webhook.Headers.Map(),
		EventTimeout:	int64(e.Webhook.CoolDownPeriod.Seconds()),
		TemplatePath:	e.Webhook.BodyTemplate,
	}
}

Cognitive complexity: 1, Cyclomatic complexity: 1

Uses: apidef.WebHookHandlerConf.

func (*EventHandler) UnmarshalJSON

UnmarshalJSON unmarshal EventHandler as per Tyk OAS API definition contract.

func (e *EventHandler) UnmarshalJSON(in []byte) error {
	type helperEventHandler EventHandler
	helper := helperEventHandler{}
	if err := json.Unmarshal(in, &helper); err != nil {
		return err
	}

	switch helper.Kind {
	case WebhookKind:
		if err := json.Unmarshal(in, &helper.Webhook); err != nil {
			return err
		}
	case JSVMKind:
		if err := json.Unmarshal(in, &helper.JSVMEvent); err != nil {
			return err
		}
	case LogKind:
		if err := json.Unmarshal(in, &helper.LogEvent); err != nil {
			return err
		}
	}

	*e = EventHandler(helper)
	return nil
}

Cognitive complexity: 14, Cyclomatic complexity: 9

Uses: json.Unmarshal.

func (*EventHandlers) ExtractTo

ExtractTo EventHandlers events to apidef.APIDefinition.

func (e *EventHandlers) ExtractTo(api *apidef.APIDefinition) {
	if api.EventHandlers.Events == nil {
		api.EventHandlers.Events = make(map[apidef.TykEvent][]apidef.EventHandlerTriggerConfig)
	}

	resetOASSupportedEventHandlers(api)

	if e == nil {
		return
	}

	if len(*e) == 0 {
		return
	}

	for _, ev := range *e {
		var (
			handler		event.HandlerName
			handlerMeta	*map[string]any
			err		error
		)

		switch ev.Kind {
		case WebhookKind:
			handler = event.WebHookHandler
			whConf := ev.GetWebhookConf()
			handlerMeta, err = reflect.Cast[map[string]any](whConf)
		case JSVMKind:
			handler = event.JSVMHandler
			jsvmConf := ev.GetJSVMEventHandlerConf()
			handlerMeta, err = reflect.Cast[map[string]any](jsvmConf)
		case LogKind:
			handler = event.LogHandler
			logConf := ev.GetLogEventHandlerConf()
			handlerMeta, err = reflect.Cast[map[string]any](logConf)
		default:
			continue
		}

		if err != nil {
			log.WithError(err).Error("error converting event to map")
			continue
		}

		eventHandlerTriggerConfig := apidef.EventHandlerTriggerConfig{
			Handler:	handler,
			HandlerMeta:	*handlerMeta,
		}

		if val, ok := api.EventHandlers.Events[ev.Trigger]; ok {
			api.EventHandlers.Events[ev.Trigger] = append(val, eventHandlerTriggerConfig)
			continue
		}

		api.EventHandlers.Events[ev.Trigger] = []apidef.EventHandlerTriggerConfig{eventHandlerTriggerConfig}
	}
}

Cognitive complexity: 20, Cyclomatic complexity: 11

Uses: apidef.EventHandlerTriggerConfig, apidef.TykEvent, event.HandlerName, event.JSVMHandler, event.LogHandler, event.WebHookHandler, reflect.Cast.

func (*EventHandlers) Fill

Fill fills EventHandlers from classic API definition. Currently only webhook and jsvm events are supported.

func (e *EventHandlers) Fill(api apidef.APIDefinition) {
	events := EventHandlers{}
	if len(api.EventHandlers.Events) == 0 {
		*e = events
		return
	}

	for gwEvent, ehs := range api.EventHandlers.Events {
		for _, eh := range ehs {
			switch eh.Handler {
			case event.WebHookHandler:
				whConf := apidef.WebHookHandlerConf{}
				err := whConf.Scan(eh.HandlerMeta)
				if err != nil {
					continue
				}

				ev := EventHandler{
					Enabled:	!whConf.Disabled,
					Trigger:	gwEvent,
					Kind:		WebhookKind,
					ID:		whConf.ID,
					Name:		whConf.Name,
					Webhook: WebhookEvent{
						URL:		whConf.TargetPath,
						Method:		whConf.Method,
						Headers:	NewHeaders(whConf.HeaderList),
						BodyTemplate:	whConf.TemplatePath,
						CoolDownPeriod:	ReadableDuration(time.Duration(whConf.EventTimeout) * time.Second),
					},
				}

				events = append(events, ev)
			case event.JSVMHandler:
				jsvmHandlerConf := apidef.JSVMEventHandlerConf{}
				err := jsvmHandlerConf.Scan(eh.HandlerMeta)
				if err != nil {
					continue
				}

				ev := EventHandler{
					Enabled:	!jsvmHandlerConf.Disabled,
					Trigger:	gwEvent,
					Kind:		JSVMKind,
					ID:		jsvmHandlerConf.ID,
					Name:		jsvmHandlerConf.MethodName,	// jsvm events don't have human-readable names, let's reuse the methodName
					JSVMEvent: JSVMEvent{
						FunctionName:	jsvmHandlerConf.MethodName,
						Path:		jsvmHandlerConf.Path,
					},
				}

				events = append(events, ev)
			case event.LogHandler:
				logHandlerConf := apidef.LogEventHandlerConf{}
				err := logHandlerConf.Scan(eh.HandlerMeta)
				if err != nil {
					continue
				}

				ev := EventHandler{
					Enabled:	!logHandlerConf.Disabled,
					Trigger:	gwEvent,
					Kind:		LogKind,
					Name:		logHandlerConf.Prefix,	// log events don't have human-readable names, let's reuse the prefix
					LogEvent: LogEvent{
						LogPrefix: logHandlerConf.Prefix,
					},
				}

				events = append(events, ev)
			default:
				continue
			}
		}
	}

	*e = events
}

Cognitive complexity: 29, Cyclomatic complexity: 11

Uses: apidef.JSVMEventHandlerConf, apidef.LogEventHandlerConf, apidef.WebHookHandlerConf, event.JSVMHandler, event.LogHandler, event.WebHookHandler, time.Duration, time.Second.

func (*ExtractCredentialsFromBody) ExtractTo

ExtractTo extracts *ExtractCredentialsFromBody and populates *apidef.APIDefinition.

func (e *ExtractCredentialsFromBody) ExtractTo(api *apidef.APIDefinition) {
	api.BasicAuth.ExtractFromBody = e.Enabled
	api.BasicAuth.BodyUserRegexp = e.UserRegexp
	api.BasicAuth.BodyPasswordRegexp = e.PasswordRegexp
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*ExtractCredentialsFromBody) Fill

Fill fills *ExtractCredentialsFromBody from apidef.APIDefinition.

func (e *ExtractCredentialsFromBody) Fill(api apidef.APIDefinition) {
	e.Enabled = api.BasicAuth.ExtractFromBody
	e.UserRegexp = api.BasicAuth.BodyUserRegexp
	e.PasswordRegexp = api.BasicAuth.BodyPasswordRegexp
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*GatewayTags) ExtractTo

ExtractTo extracts *GatewayTags into *apidef.APIDefinition.

func (gt *GatewayTags) ExtractTo(api *apidef.APIDefinition) {
	api.TagsDisabled = !gt.Enabled
	api.Tags = gt.Tags
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*GatewayTags) Fill

Fill fills *GatewayTags from apidef.APIDefinition.

func (gt *GatewayTags) Fill(api apidef.APIDefinition) {
	gt.Enabled = !api.TagsDisabled
	gt.Tags = api.Tags
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*Global) ExtractTo

ExtractTo extracts *Global into *apidef.APIDefinition.

func (g *Global) ExtractTo(api *apidef.APIDefinition) {
	if g.PluginConfig == nil {
		g.PluginConfig = &PluginConfig{}
		defer func() {
			g.PluginConfig = nil
		}()
	}

	g.PluginConfig.ExtractTo(api)

	if g.CORS == nil {
		g.CORS = &CORS{}
		defer func() {
			g.CORS = nil
		}()
	}

	g.CORS.ExtractTo(&api.CORS)

	g.extractPrePluginsTo(api)

	g.extractPostAuthenticationPluginsTo(api)

	g.extractPostPluginsTo(api)

	if g.Cache == nil {
		g.Cache = &Cache{}
		defer func() {
			g.Cache = nil
		}()
	}

	g.Cache.ExtractTo(&api.CacheOptions)

	g.extractResponsePluginsTo(api)

	g.extractIgnoreCase(api)

	g.extractContextVariablesTo(api)

	g.extractTrafficLogsTo(api)

	if g.TransformRequestHeaders == nil {
		g.TransformRequestHeaders = &TransformHeaders{}
		defer func() {
			g.TransformRequestHeaders = nil
		}()
	}

	var headerMeta apidef.HeaderInjectionMeta
	g.TransformRequestHeaders.ExtractTo(&headerMeta)

	if g.TransformResponseHeaders == nil {
		g.TransformResponseHeaders = &TransformHeaders{}
		defer func() {
			g.TransformResponseHeaders = nil
		}()
	}

	var resHeaderMeta apidef.HeaderInjectionMeta
	g.TransformResponseHeaders.ExtractTo(&resHeaderMeta)

	requireMainVersion(api)
	vInfo := api.VersionData.Versions[Main]
	vInfo.GlobalHeadersDisabled = headerMeta.Disabled
	vInfo.GlobalHeaders = headerMeta.AddHeaders
	vInfo.GlobalHeadersRemove = headerMeta.DeleteHeaders

	vInfo.GlobalResponseHeadersDisabled = resHeaderMeta.Disabled
	vInfo.GlobalResponseHeaders = resHeaderMeta.AddHeaders
	vInfo.GlobalResponseHeadersRemove = resHeaderMeta.DeleteHeaders
	updateMainVersion(api, vInfo)

	g.extractRequestSizeLimitTo(api)

	g.extractSkipsTo(api)
}

Cognitive complexity: 20, Cyclomatic complexity: 6

Uses: apidef.HeaderInjectionMeta.

func (*Global) Fill

Fill fills *Global from apidef.APIDefinition.

func (g *Global) Fill(api apidef.APIDefinition) {
	if g.PluginConfig == nil {
		g.PluginConfig = &PluginConfig{}
	}

	g.PluginConfig.Fill(api)
	if ShouldOmit(g.PluginConfig) {
		g.PluginConfig = nil
	}

	if g.CORS == nil {
		g.CORS = &CORS{}
	}

	g.CORS.Fill(api.CORS)
	if ShouldOmit(g.CORS) {
		g.CORS = nil
	}

	g.PrePlugins.Fill(api.CustomMiddleware.Pre)
	g.PrePlugin = nil

	if ShouldOmit(g.PrePlugins) {
		g.PrePlugins = nil
	}

	g.PostAuthenticationPlugins.Fill(api.CustomMiddleware.PostKeyAuth)
	g.PostAuthenticationPlugin = nil

	if ShouldOmit(g.PostAuthenticationPlugins) {
		g.PostAuthenticationPlugins = nil
	}

	g.PostPlugins.Fill(api.CustomMiddleware.Post)
	g.PostPlugin = nil

	if ShouldOmit(g.PostPlugins) {
		g.PostPlugins = nil
	}

	if g.Cache == nil {
		g.Cache = &Cache{}
	}

	g.Cache.Fill(api.CacheOptions)
	if ShouldOmit(g.Cache) {
		g.Cache = nil
	}

	g.ResponsePlugins.Fill(api.CustomMiddleware.Response)
	g.ResponsePlugin = nil

	if ShouldOmit(g.ResponsePlugins) {
		g.ResponsePlugins = nil
	}

	if g.TransformRequestHeaders == nil {
		g.TransformRequestHeaders = &TransformHeaders{}
	}

	vInfo := api.VersionData.Versions[Main]
	g.TransformRequestHeaders.Fill(apidef.HeaderInjectionMeta{
		Disabled:	vInfo.GlobalHeadersDisabled,
		AddHeaders:	vInfo.GlobalHeaders,
		DeleteHeaders:	vInfo.GlobalHeadersRemove,
	})
	if ShouldOmit(g.TransformRequestHeaders) {
		g.TransformRequestHeaders = nil
	}

	if g.TransformResponseHeaders == nil {
		g.TransformResponseHeaders = &TransformHeaders{}
	}

	g.TransformResponseHeaders.Fill(apidef.HeaderInjectionMeta{
		Disabled:	vInfo.GlobalResponseHeadersDisabled,
		AddHeaders:	vInfo.GlobalResponseHeaders,
		DeleteHeaders:	vInfo.GlobalResponseHeadersRemove,
	})
	if ShouldOmit(g.TransformResponseHeaders) {
		g.TransformResponseHeaders = nil
	}

	g.fillIgnoreCase(api)

	g.fillContextVariables(api)

	g.fillTrafficLogs(api)

	g.fillRequestSizeLimit(api)

	g.fillSkips(api)
}

Cognitive complexity: 35, Cyclomatic complexity: 15

Uses: apidef.HeaderInjectionMeta.

func (*Global) MarshalJSON

MarshalJSON is a custom JSON marshaller for the Global struct. It is implemented to facilitate a smooth migration from deprecated fields that were previously used to represent the same data. This custom marshaller ensures backwards compatibility and proper handling of the deprecated fields during the migration process.

func (g *Global) MarshalJSON() ([]byte, error) {
	if g == nil {
		return nil, nil
	}

	type Alias Global

	var payload = Alias(*g)

	if payload.PrePlugin != nil {
		payload.PrePlugins = payload.PrePlugin.Plugins
		payload.PrePlugin = nil
	}

	if payload.PostAuthenticationPlugin != nil {
		payload.PostAuthenticationPlugins = payload.PostAuthenticationPlugin.Plugins
		payload.PostAuthenticationPlugin = nil
	}

	if payload.PostPlugin != nil {
		payload.PostPlugins = payload.PostPlugin.Plugins
		payload.PostPlugin = nil
	}

	if payload.ResponsePlugin != nil {
		payload.ResponsePlugins = payload.ResponsePlugin.Plugins
		payload.ResponsePlugin = nil
	}

	// to prevent infinite recursion
	return json.Marshal(payload)
}

Cognitive complexity: 10, Cyclomatic complexity: 6

Uses: json.Marshal.

func (*GlobalRequestSizeLimit) ExtractTo

ExtractTo extracts *GlobalRequestSizeLimit into *apidef.APIDefinition.

func (g *GlobalRequestSizeLimit) ExtractTo(api *apidef.APIDefinition) {
	mainVersion := requireMainVersion(api)
	defer func() {
		updateMainVersion(api, mainVersion)
	}()

	if g.Value == 0 {
		mainVersion.GlobalSizeLimit = 0
		mainVersion.GlobalSizeLimitDisabled = true
		return
	}

	mainVersion.GlobalSizeLimitDisabled = !g.Enabled
	mainVersion.GlobalSizeLimit = g.Value
}

Cognitive complexity: 3, Cyclomatic complexity: 2

func (*GlobalRequestSizeLimit) Fill

Fill fills *GlobalRequestSizeLimit from apidef.APIDefinition.

func (g *GlobalRequestSizeLimit) Fill(api apidef.APIDefinition) {
	ok := false
	if api.VersionData.Versions != nil {
		_, ok = api.VersionData.Versions[Main]
	}
	if !ok || api.VersionData.Versions[Main].GlobalSizeLimit == 0 {
		g.Enabled = false
		g.Value = 0
		return
	}

	g.Enabled = !api.VersionData.Versions[Main].GlobalSizeLimitDisabled
	g.Value = api.VersionData.Versions[Main].GlobalSizeLimit
}

Cognitive complexity: 4, Cyclomatic complexity: 4

func (*HMAC) ExtractTo

ExtractTo extracts *HMAC to *apidef.APIDefinition.

func (h *HMAC) ExtractTo(api *apidef.APIDefinition) {
	api.EnableSignatureChecking = h.Enabled

	authConfig := apidef.AuthConfig{}
	h.AuthSources.ExtractTo(&authConfig)

	if api.AuthConfigs == nil {
		api.AuthConfigs = make(map[string]apidef.AuthConfig)
	}

	api.AuthConfigs["hmac"] = authConfig

	api.HmacAllowedAlgorithms = h.AllowedAlgorithms
	api.HmacAllowedClockSkew = h.AllowedClockSkew
}

Cognitive complexity: 3, Cyclomatic complexity: 2

Uses: apidef.AuthConfig.

func (*HMAC) Fill

Fill fills *HMAC from apidef.APIDefinition.

func (h *HMAC) Fill(api apidef.APIDefinition) {
	h.Enabled = api.EnableSignatureChecking

	h.AuthSources.Fill(api.AuthConfigs["hmac"])

	h.AllowedAlgorithms = api.HmacAllowedAlgorithms
	h.AllowedClockSkew = api.HmacAllowedClockSkew
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*IDExtractor) ExtractTo

ExtractTo extracts IDExtractor into supplied classic API definition.

func (id *IDExtractor) ExtractTo(api *apidef.APIDefinition) {
	api.CustomMiddleware.IdExtractor.Disabled = !id.Enabled
	api.CustomMiddleware.IdExtractor.ExtractFrom = id.Source
	api.CustomMiddleware.IdExtractor.ExtractWith = id.With

	if id.Config == nil {
		id.Config = &IDExtractorConfig{}
		defer func() {
			id.Config = nil
		}()
	}

	id.Config.ExtractTo(api)
}

Cognitive complexity: 4, Cyclomatic complexity: 2

func (*IDExtractor) Fill

Fill fills IDExtractor from supplied classic APIDefinition.

func (id *IDExtractor) Fill(api apidef.APIDefinition) {
	id.Enabled = !api.CustomMiddleware.IdExtractor.Disabled
	id.Source = api.CustomMiddleware.IdExtractor.ExtractFrom
	id.With = api.CustomMiddleware.IdExtractor.ExtractWith

	if id.Config == nil {
		id.Config = &IDExtractorConfig{}
	}

	id.Config.Fill(api)
	if ShouldOmit(id.Config) {
		id.Config = nil
	}
}

Cognitive complexity: 5, Cyclomatic complexity: 3

func (*IDExtractorConfig) ExtractTo

ExtractTo extracts IDExtractorConfig into supplied classic API definition.

func (id *IDExtractorConfig) ExtractTo(api *apidef.APIDefinition) {
	classicIDExtractorConfig := apidef.IDExtractorConfig{
		HeaderName:		id.HeaderName,
		FormParamName:		id.FormParamName,
		RegexExpression:	id.Regexp,
		RegexMatchIndex:	id.RegexpMatchIndex,
		XPathExpression:	id.XPathExp,
	}

	configData, err := json.Marshal(&classicIDExtractorConfig)
	if err != nil {
		log.WithError(err).Error("error while marshalling IDExtractorConfig")
		return
	}
	var extractorConfigMap map[string]interface{}
	err = json.Unmarshal(configData, &extractorConfigMap)
	if err != nil {
		log.WithError(err).Error("error while encoding IDExtractorConfig")
		return
	}

	if len(extractorConfigMap) == 0 {
		extractorConfigMap = nil
	}

	api.CustomMiddleware.IdExtractor.ExtractorConfig = extractorConfigMap
}

Cognitive complexity: 8, Cyclomatic complexity: 4

Uses: apidef.IDExtractorConfig, json.Marshal, json.Unmarshal.

func (*IDExtractorConfig) Fill

Fill fills IDExtractorConfig from supplied classic APIDefinition.

func (id *IDExtractorConfig) Fill(api apidef.APIDefinition) {
	var classicIDExtractorConfig apidef.IDExtractorConfig
	err := mapstructure.Decode(api.CustomMiddleware.IdExtractor.ExtractorConfig, &classicIDExtractorConfig)
	if err != nil {
		log.WithError(err).Error("error while decoding IDExtractorConfig")
		return
	}

	*id = IDExtractorConfig{
		HeaderName:		classicIDExtractorConfig.HeaderName,
		FormParamName:		classicIDExtractorConfig.FormParamName,
		Regexp:			classicIDExtractorConfig.RegexExpression,
		RegexpMatchIndex:	classicIDExtractorConfig.RegexMatchIndex,
		XPathExp:		classicIDExtractorConfig.XPathExpression,
	}
}

Cognitive complexity: 3, Cyclomatic complexity: 2

Uses: apidef.IDExtractorConfig, mapstructure.Decode.

func (*IPAccessControl) ExtractTo

ExtractTo extracts *IPAccessControl into *apidef.APIDefinition.

func (i *IPAccessControl) ExtractTo(api *apidef.APIDefinition) {
	api.IPAccessControlDisabled = !i.Enabled
	api.BlacklistedIPs = i.Block
	api.AllowedIPs = i.Allow
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*IPAccessControl) Fill

Fill fills *IPAccessControl from apidef.APIDefinition.

func (i *IPAccessControl) Fill(api apidef.APIDefinition) {
	i.Enabled = !api.IPAccessControlDisabled
	i.Block = api.BlacklistedIPs
	i.Allow = api.AllowedIPs
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*IgnoreCase) ExtractTo

ExtractTo extracts *IgnoreCase into *apidef.APIDefinition.

func (p *IgnoreCase) ExtractTo(api *apidef.APIDefinition) {
	mainVersion := requireMainVersion(api)
	defer func() {
		updateMainVersion(api, mainVersion)
	}()

	mainVersion.IgnoreEndpointCase = p.Enabled
}

Cognitive complexity: 1, Cyclomatic complexity: 1

func (*IgnoreCase) Fill

Fill fills *IgnoreCase from apidef.APIDefinition.

func (p *IgnoreCase) Fill(api apidef.APIDefinition) {
	ok := false
	if api.VersionData.Versions != nil {
		_, ok = api.VersionData.Versions[Main]
	}
	if !ok {
		p.Enabled = false
		return
	}

	p.Enabled = api.VersionData.Versions[Main].IgnoreEndpointCase
}

Cognitive complexity: 4, Cyclomatic complexity: 3

func (*Info) ExtractTo

ExtractTo extracts *Info into an *apidef.APIDefinition.

func (i *Info) ExtractTo(api *apidef.APIDefinition) {
	api.APIID = i.ID
	api.Id = i.DBID
	api.OrgID = i.OrgID
	api.Name = i.Name
	api.Expiration = i.Expiration
	i.State.ExtractTo(api)

	if i.Versioning == nil {
		i.Versioning = &Versioning{}
		defer func() {
			i.Versioning = nil
		}()
	}

	i.Versioning.ExtractTo(api)

	// everytime
	api.VersionData.NotVersioned = true
	api.VersionData.DefaultVersion = ""
	if len(api.VersionData.Versions) == 0 {
		api.VersionData.Versions = map[string]apidef.VersionInfo{
			"": {},
		}
	}
}

Cognitive complexity: 8, Cyclomatic complexity: 3

Uses: apidef.VersionInfo.

func (*Info) Fill

Fill fills *Info from apidef.APIDefinition.

func (i *Info) Fill(api apidef.APIDefinition) {
	i.ID = api.APIID
	i.DBID = api.Id
	i.OrgID = api.OrgID
	i.Name = api.Name
	i.Expiration = api.Expiration
	i.State.Fill(api)

	if i.Versioning == nil {
		i.Versioning = &Versioning{}
	}

	i.Versioning.Fill(api)
	if ShouldOmit(i.Versioning) {
		i.Versioning = nil
	}
}

Cognitive complexity: 5, Cyclomatic complexity: 3

func (*Internal) ExtractTo

ExtractTo fills *apidef.InternalMeta from *Internal.

func (i *Internal) ExtractTo(meta *apidef.InternalMeta) {
	meta.Disabled = !i.Enabled
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*Internal) Fill

Fill fills *Internal receiver with data from apidef.InternalMeta.

func (i *Internal) Fill(meta apidef.InternalMeta) {
	i.Enabled = !meta.Disabled
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*Introspection) ExtractTo

func (i *Introspection) ExtractTo(intros *apidef.Introspection) {
	intros.Enabled = i.Enabled
	intros.URL = i.URL
	intros.ClientID = i.ClientID
	intros.ClientSecret = i.ClientSecret
	intros.IdentityBaseField = i.IdentityBaseField

	if i.Cache != nil {
		i.Cache.ExtractTo(&intros.Cache)
	}
}

Cognitive complexity: 2, Cyclomatic complexity: 2

func (*Introspection) Fill

func (i *Introspection) Fill(intros apidef.Introspection) {
	i.Enabled = intros.Enabled
	i.URL = intros.URL
	i.ClientID = intros.ClientID
	i.ClientSecret = intros.ClientSecret
	i.IdentityBaseField = intros.IdentityBaseField

	if i.Cache == nil {
		i.Cache = &IntrospectionCache{}
	}

	i.Cache.Fill(intros.Cache)
	if ShouldOmit(i.Cache) {
		i.Cache = nil
	}
}

Cognitive complexity: 5, Cyclomatic complexity: 3

func (*IntrospectionCache) ExtractTo

func (c *IntrospectionCache) ExtractTo(cache *apidef.IntrospectionCache) {
	cache.Enabled = c.Enabled
	cache.Timeout = c.Timeout
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*IntrospectionCache) Fill

func (c *IntrospectionCache) Fill(cache apidef.IntrospectionCache) {
	c.Enabled = cache.Enabled
	c.Timeout = cache.Timeout
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*JWT) Import

Import populates *JWT based on arguments.

func (j *JWT) Import(enable bool) {
	j.Enabled = enable
	j.Header = &AuthSource{
		Enabled:	true,
		Name:		defaultAuthSourceName,
	}
}

Cognitive complexity: 1, Cyclomatic complexity: 1

func (*JWTValidation) ExtractTo

func (j *JWTValidation) ExtractTo(jwt *apidef.JWTValidation) {
	jwt.Enabled = j.Enabled
	jwt.SigningMethod = j.SigningMethod
	jwt.Source = j.Source
	jwt.IdentityBaseField = j.IdentityBaseField
	jwt.IssuedAtValidationSkew = j.IssuedAtValidationSkew
	jwt.NotBeforeValidationSkew = j.NotBeforeValidationSkew
	jwt.ExpiresAtValidationSkew = j.ExpiresAtValidationSkew
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*JWTValidation) Fill

func (j *JWTValidation) Fill(jwt apidef.JWTValidation) {
	j.Enabled = jwt.Enabled
	j.SigningMethod = jwt.SigningMethod
	j.Source = jwt.Source
	j.IdentityBaseField = jwt.IdentityBaseField
	j.IssuedAtValidationSkew = jwt.IssuedAtValidationSkew
	j.NotBeforeValidationSkew = jwt.NotBeforeValidationSkew
	j.ExpiresAtValidationSkew = jwt.ExpiresAtValidationSkew
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*ListenPath) ExtractTo

ExtractTo extracts *ListenPath into *apidef.APIDefinition.

func (lp *ListenPath) ExtractTo(api *apidef.APIDefinition) {
	api.Proxy.ListenPath = lp.Value
	api.Proxy.StripListenPath = lp.Strip
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*ListenPath) Fill

Fill fills *ListenPath from apidef.APIDefinition.

func (lp *ListenPath) Fill(api apidef.APIDefinition) {
	lp.Value = api.Proxy.ListenPath
	lp.Strip = api.Proxy.StripListenPath
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*LoadBalancing) ExtractTo

ExtractTo populates an APIDefinition's proxy load balancing configuration with data from the LoadBalancing instance.

func (l *LoadBalancing) ExtractTo(api *apidef.APIDefinition) {
	if len(l.Targets) == 0 {
		api.Proxy.EnableLoadBalancing = false
		api.Proxy.CheckHostAgainstUptimeTests = false
		api.Proxy.Targets = nil
		return
	}

	proxyConfTargets := make([]string, 0, len(l.Targets))
	api.Proxy.EnableLoadBalancing = l.Enabled
	api.Proxy.CheckHostAgainstUptimeTests = l.SkipUnavailableHosts
	for _, target := range l.Targets {
		for i := 0; i < target.Weight; i++ {
			proxyConfTargets = append(proxyConfTargets, target.URL)
		}
	}

	api.Proxy.Targets = proxyConfTargets
}

Cognitive complexity: 7, Cyclomatic complexity: 4

func (*LoadBalancing) Fill

Fill populates the LoadBalancing structure based on the provided APIDefinition, including targets and their weights.

func (l *LoadBalancing) Fill(api apidef.APIDefinition) {
	if len(api.Proxy.Targets) == 0 {
		api.Proxy.EnableLoadBalancing = false
		api.Proxy.CheckHostAgainstUptimeTests = false
		api.Proxy.Targets = nil
		return
	}

	l.Enabled = api.Proxy.EnableLoadBalancing
	l.SkipUnavailableHosts = api.Proxy.CheckHostAgainstUptimeTests

	targetCounter := make(map[string]*LoadBalancingTarget)
	for _, target := range api.Proxy.Targets {
		if _, ok := targetCounter[target]; !ok {
			targetCounter[target] = &LoadBalancingTarget{
				URL:	target,
				Weight:	0,
			}
		}
		targetCounter[target].Weight++
	}

	targets := make([]LoadBalancingTarget, len(targetCounter))
	i := 0
	for _, target := range targetCounter {
		targets[i] = *target
		i++
	}

	targetsSorter := func(i, j int) bool {
		return targets[i].URL < targets[j].URL
	}

	sort.Slice(targets, targetsSorter)
	l.Targets = targets
}

Cognitive complexity: 12, Cyclomatic complexity: 5

Uses: sort.Slice.

func (*Middleware) ExtractTo

ExtractTo extracts *Middleware into *apidef.APIDefinition.

func (m *Middleware) ExtractTo(api *apidef.APIDefinition) {
	if m.Global == nil {
		m.Global = &Global{}
		defer func() {
			m.Global = nil
		}()
	}

	m.Global.ExtractTo(api)
}

Cognitive complexity: 4, Cyclomatic complexity: 2

func (*Middleware) Fill

Fill fills *Middleware from apidef.APIDefinition.

func (m *Middleware) Fill(api apidef.APIDefinition) {
	if m.Global == nil {
		m.Global = &Global{}
	}

	m.Global.Fill(api)
	if ShouldOmit(m.Global) {
		m.Global = nil
	}
}

Cognitive complexity: 5, Cyclomatic complexity: 3

func (*MockResponse) ExtractTo

func (m *MockResponse) ExtractTo(meta *apidef.MockResponseMeta) {
	meta.Disabled = !m.Enabled
	meta.Code = m.Code
	meta.Body = m.Body

	// Initialize headers map even when empty
	meta.Headers = make(map[string]string)

	for _, h := range m.Headers {
		meta.Headers[h.Name] = h.Value
	}

	if len(meta.Headers) == 0 {
		meta.Headers = nil
	}
}

Cognitive complexity: 5, Cyclomatic complexity: 3

func (*MockResponse) Fill

Fill populates the MockResponse fields from a classic API MockResponseMeta.

func (m *MockResponse) Fill(op apidef.MockResponseMeta) {
	headers := make([]Header, 0)
	for k, v := range op.Headers {
		headers = append(headers, Header{
			Name:	http.CanonicalHeaderKey(k),
			Value:	v,
		})
	}

	// Sort headers by name so that the order is deterministic
	sort.Slice(headers, func(i, j int) bool {
		return headers[i].Name < headers[j].Name
	})

	m.Enabled = !op.Disabled
	m.Code = op.Code
	m.Body = op.Body
	m.Headers = headers
}

Cognitive complexity: 5, Cyclomatic complexity: 2

Uses: http.CanonicalHeaderKey, sort.Slice.

func (*MockResponse) Import

Import populates *MockResponse with enabled argument for FromOASExamples.

func (m *MockResponse) Import(enabled bool) {
	m.Enabled = enabled
	m.FromOASExamples = &FromOASExamples{
		Enabled: enabled,
	}
}

Cognitive complexity: 1, Cyclomatic complexity: 1

func (*MutualTLS) ExtractTo

ExtractTo extracts *MutualTLS into *apidef.APIDefinition.

func (m *MutualTLS) ExtractTo(api *apidef.APIDefinition) {
	api.UpstreamCertificatesDisabled = !m.Enabled

	if len(m.DomainToCertificates) > 0 {
		api.UpstreamCertificates = make(map[string]string)
	} else {
		api.UpstreamCertificates = nil
	}

	for _, domainToCert := range m.DomainToCertificates {
		api.UpstreamCertificates[domainToCert.Domain] = domainToCert.Certificate
	}
}

Cognitive complexity: 7, Cyclomatic complexity: 3

func (*MutualTLS) Fill

Fill fills *MutualTLS from apidef.APIDefinition.

func (m *MutualTLS) Fill(api apidef.APIDefinition) {
	m.Enabled = !api.UpstreamCertificatesDisabled
	m.DomainToCertificates = make([]DomainToCertificate, len(api.UpstreamCertificates))

	i := 0
	for domain, cert := range api.UpstreamCertificates {
		m.DomainToCertificates[i] = DomainToCertificate{Domain: domain, Certificate: cert}
		i++
	}

	if ShouldOmit(m.DomainToCertificates) {
		api.UpstreamCertificates = nil
	}
}

Cognitive complexity: 6, Cyclomatic complexity: 3

func (*Notifications) ExtractTo

ExtractTo extracts *Notifications into *apidef.NotificationsManager.

func (n *Notifications) ExtractTo(nm *apidef.NotificationsManager) {
	nm.SharedSecret = n.SharedSecret
	nm.OAuthKeyChangeURL = n.OnKeyChangeURL
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*Notifications) Fill

Fill fills *Notifications from apidef.NotificationsManager.

func (n *Notifications) Fill(nm apidef.NotificationsManager) {
	n.SharedSecret = nm.SharedSecret
	n.OnKeyChangeURL = nm.OAuthKeyChangeURL
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*OAS) AddServers

AddServers adds a server into the servers definition if not already present.

func (s *OAS) AddServers(apiURLs ...string) {
	apiURLSet := make(map[string]struct{})
	newServers := openapi3.Servers{}
	for _, apiURL := range apiURLs {
		if strings.Contains(apiURL, "{") && strings.Contains(apiURL, "}") {
			continue
		}

		newServers = append(newServers, &openapi3.Server{
			URL: apiURL,
		})
		apiURLSet[apiURL] = struct{}{}
	}

	if len(newServers) == 0 {
		return
	}

	if len(s.Servers) == 0 {
		s.Servers = newServers
		return
	}

	// check if apiURL already exists in servers object
	for i := 0; i < len(s.Servers); i++ {
		if _, ok := apiURLSet[s.Servers[i].URL]; ok {
			continue
		}

		newServers = append(newServers, s.Servers[i])
	}

	s.Servers = newServers
}

Cognitive complexity: 18, Cyclomatic complexity: 8

Uses: openapi3.Server, openapi3.Servers, strings.Contains.

func (*OAS) BuildDefaultTykExtension

BuildDefaultTykExtension builds a default tyk extension in *OAS based on function arguments.

func (s *OAS) BuildDefaultTykExtension(overRideValues TykExtensionConfigParams, isImport bool) error {
	xTykAPIGateway := s.GetTykExtension()

	if xTykAPIGateway == nil {
		xTykAPIGateway = &XTykAPIGateway{}
		s.SetTykExtension(xTykAPIGateway)
	}

	if isImport {
		xTykAPIGateway.Info.State.Active = true
		xTykAPIGateway.Info.State.Internal = false
		xTykAPIGateway.Server.ListenPath.Strip = true
		xTykAPIGateway.enableContextVariablesIfEmpty()
		xTykAPIGateway.enableTrafficLogsIfEmpty()
	}

	if xTykAPIGateway.Info.Name == "" {
		xTykAPIGateway.Info.Name = s.Info.Title
	}

	if overRideValues.ApiID != "" {
		xTykAPIGateway.Info.ID = overRideValues.ApiID
	}

	if overRideValues.ListenPath != "" {
		xTykAPIGateway.Server.ListenPath.Value = overRideValues.ListenPath
	} else if xTykAPIGateway.Server.ListenPath.Value == "" {
		xTykAPIGateway.Server.ListenPath.Value = "/"
	}

	if overRideValues.CustomDomain != "" {
		if xTykAPIGateway.Server.CustomDomain == nil {
			xTykAPIGateway.Server.CustomDomain = &Domain{Enabled: true}
		}
		xTykAPIGateway.Server.CustomDomain.Name = overRideValues.CustomDomain
	}

	var upstreamURL string

	if overRideValues.UpstreamURL != "" {
		upstreamURL = overRideValues.UpstreamURL
	} else if xTykAPIGateway.Upstream.URL == "" {
		if len(s.Servers) == 0 {
			return errEmptyServersObject
		}

		upstreamURL = s.Servers[0].URL
		if isURLParametrized(upstreamURL) {
			var err error
			upstreamURL, err = generateUrlUsingDefaultVariableValues(s, upstreamURL)
			if err != nil {
				return err
			}
		}
	}

	if upstreamURL != "" {
		if err := getURLFormatErr(overRideValues.UpstreamURL != "", upstreamURL); err != nil {
			return err
		}

		xTykAPIGateway.Upstream.URL = upstreamURL
	}

	if overRideValues.Authentication != nil {
		err := s.importAuthentication(*overRideValues.Authentication)
		if err != nil {
			return err
		}
	}

	s.importMiddlewares(overRideValues)

	return nil
}

Cognitive complexity: 36, Cyclomatic complexity: 18

func (*OAS) Clone

Clone creates a deep copy of the OAS object and returns a new instance.

func (s *OAS) Clone() (*OAS, error) {
	return reflect.Clone(s), nil
}

Cognitive complexity: 0, Cyclomatic complexity: 1

Uses: reflect.Clone.

func (*OAS) ExtractTo

ExtractTo extracts *OAS into *apidef.APIDefinition.

func (s *OAS) ExtractTo(api *apidef.APIDefinition) {
	if s.GetTykExtension() == nil {
		s.SetTykExtension(&XTykAPIGateway{})
		defer func() {
			delete(s.Extensions, ExtensionTykAPIGateway)
		}()
	}

	s.GetTykExtension().ExtractTo(api)

	s.extractSecurityTo(api)

	vInfo := api.VersionData.Versions[Main]
	vInfo.UseExtendedPaths = true
	s.extractPathsAndOperations(&vInfo.ExtendedPaths)
	api.VersionData.Versions[Main] = vInfo
}

Cognitive complexity: 4, Cyclomatic complexity: 2

func (*OAS) Fill

Fill fills *OAS definition from apidef.APIDefinition.

func (s *OAS) Fill(api apidef.APIDefinition) {
	xTykAPIGateway := s.GetTykExtension()
	if xTykAPIGateway == nil {
		xTykAPIGateway = &XTykAPIGateway{}
		s.SetTykExtension(xTykAPIGateway)
	}

	xTykAPIGateway.Fill(api)
	s.fillPathsAndOperations(api.VersionData.Versions[Main].ExtendedPaths)
	s.fillSecurity(api)

	if ShouldOmit(xTykAPIGateway) {
		delete(s.Extensions, ExtensionTykAPIGateway)
	}

	if ShouldOmit(s.Extensions) {
		s.Extensions = nil
	}

	// set external docs to nil if populated with default values
	if ShouldOmit(s.ExternalDocs) {
		s.ExternalDocs = nil
	}
}

Cognitive complexity: 9, Cyclomatic complexity: 5

func (*OAS) GetTykExtension

GetTykExtension returns our OAS schema extension from inside *OAS.

func (s *OAS) GetTykExtension() *XTykAPIGateway {
	if s.Extensions == nil {
		return nil
	}

	if ext := s.Extensions[ExtensionTykAPIGateway]; ext != nil {
		rawTykAPIGateway, ok := ext.(json.RawMessage)
		if ok {
			var xTykAPIGateway XTykAPIGateway
			_ = json.Unmarshal(rawTykAPIGateway, &xTykAPIGateway)
			s.Extensions[ExtensionTykAPIGateway] = &xTykAPIGateway
			return &xTykAPIGateway
		}

		mapTykAPIGateway, ok := ext.(map[string]interface{})
		if ok {
			var xTykAPIGateway XTykAPIGateway
			dbByte, _ := json.Marshal(mapTykAPIGateway)
			_ = json.Unmarshal(dbByte, &xTykAPIGateway)
			s.Extensions[ExtensionTykAPIGateway] = &xTykAPIGateway
			return &xTykAPIGateway
		}

		return ext.(*XTykAPIGateway)
	}

	return nil
}

Cognitive complexity: 9, Cyclomatic complexity: 5

Uses: json.Marshal, json.RawMessage, json.Unmarshal.

func (*OAS) GetTykMiddleware

GetTykMiddleware returns middleware section from XTykAPIGateway.

func (s *OAS) GetTykMiddleware() (middleware *Middleware) {
	if s.GetTykExtension() != nil {
		middleware = s.GetTykExtension().Middleware
	}

	return
}

Cognitive complexity: 2, Cyclomatic complexity: 2

func (*OAS) GetTykStreamingExtension

func (s *OAS) GetTykStreamingExtension() *XTykStreaming {
	if s.Extensions == nil {
		return nil
	}

	if ext := s.Extensions[ExtensionTykStreaming]; ext != nil {
		rawTykStreaming, ok := ext.(json.RawMessage)
		if ok {
			var xTykStreaming XTykStreaming
			_ = json.Unmarshal(rawTykStreaming, &xTykStreaming)
			s.Extensions[ExtensionTykStreaming] = &xTykStreaming
			return &xTykStreaming
		}

		mapTykAPIGateway, ok := ext.(map[string]interface{})
		if ok {
			var xTykStreaming XTykStreaming
			dbByte, _ := json.Marshal(mapTykAPIGateway)
			_ = json.Unmarshal(dbByte, &xTykStreaming)
			s.Extensions[ExtensionTykStreaming] = &xTykStreaming
			return &xTykStreaming
		}

		return ext.(*XTykStreaming)
	}

	return nil
}

Cognitive complexity: 9, Cyclomatic complexity: 5

Uses: json.Marshal, json.RawMessage, json.Unmarshal.

func (*OAS) MarshalJSON

MarshalJSON implements json.Marshaller.

func (s *OAS) MarshalJSON() ([]byte, error) {
	if ShouldOmit(s.ExternalDocs) {	// for sql case
		s.ExternalDocs = nil
	}

	if s.Info != nil && ShouldOmit(s.Info.License) {	// for sql case
		s.Info.License = nil
	}

	// when OAS object is unmarshalled, the extension values are marshalled as plain []byte by kin/openapi
	// this causes json marshaller to base64 encode the values - https://pkg.go.dev/encoding/json#Marshal.
	// this block converts the extensions to json.RawMessage so that it's correctly marshalled.
	for k := range s.Extensions {
		if k == ExtensionTykAPIGateway {
			continue
		}

		if byteV, ok := s.Extensions[k].([]byte); ok {
			s.Extensions[k] = json.RawMessage(byteV)
		}
	}

	type Alias OAS

	// to prevent infinite recursion
	return json.Marshal(&struct {
		*Alias
	}{
		Alias: (*Alias)(s),
	})
}

Cognitive complexity: 13, Cyclomatic complexity: 7

Uses: json.Marshal, json.RawMessage.

func (*OAS) RemoveTykExtension

RemoveTykExtension clears the Tyk extensions from *OAS.

func (s *OAS) RemoveTykExtension() {
	if s.Extensions == nil {
		return
	}

	delete(s.Extensions, ExtensionTykAPIGateway)
}

Cognitive complexity: 2, Cyclomatic complexity: 2

func (*OAS) RemoveTykStreamingExtension

func (s *OAS) RemoveTykStreamingExtension() {
	if s.Extensions == nil {
		return
	}

	delete(s.Extensions, ExtensionTykStreaming)
}

Cognitive complexity: 2, Cyclomatic complexity: 2

func (*OAS) ReplaceServers

ReplaceServers replaces OAS servers entry having oldAPIURLs with new apiURLs .

func (s *OAS) ReplaceServers(apiURLs, oldAPIURLs []string) {
	if len(s.Servers) == 0 && len(apiURLs) == 1 {
		s.Servers = openapi3.Servers{
			{
				URL: apiURLs[0],
			},
		}
		return
	}

	oldAPIURLSet := make(map[string]struct{})
	for _, apiURL := range oldAPIURLs {
		oldAPIURLSet[apiURL] = struct{}{}
	}

	newServers := openapi3.Servers{}
	for _, apiURL := range apiURLs {
		newServers = append(newServers, &openapi3.Server{URL: apiURL})
	}

	userAddedServers := openapi3.Servers{}
	for _, server := range s.Servers {
		if _, ok := oldAPIURLSet[server.URL]; ok {
			continue
		}
		userAddedServers = append(userAddedServers, server)
	}

	s.Servers = append(newServers, userAddedServers...)
}

Cognitive complexity: 21, Cyclomatic complexity: 7

Uses: openapi3.Server, openapi3.Servers.

func (*OAS) SetTykExtension

SetTykExtension populates our OAS schema extension inside *OAS.

func (s *OAS) SetTykExtension(xTykAPIGateway *XTykAPIGateway) {
	if s.Extensions == nil {
		s.Extensions = make(map[string]interface{})
	}

	s.Extensions[ExtensionTykAPIGateway] = xTykAPIGateway
}

Cognitive complexity: 3, Cyclomatic complexity: 2

func (*OAS) SetTykStreamingExtension

func (s *OAS) SetTykStreamingExtension(xTykStreaming *XTykStreaming) {
	if s.Extensions == nil {
		s.Extensions = make(map[string]interface{})
	}

	s.Extensions[ExtensionTykStreaming] = xTykStreaming
}

Cognitive complexity: 3, Cyclomatic complexity: 2

func (*OAS) UpdateServers

UpdateServers sets or updates the first servers URL if it matches oldAPIURL.

func (s *OAS) UpdateServers(apiURL, oldAPIURL string) {
	apiURLContainsNamedRegex := strings.Contains(apiURL, "{") && strings.Contains(apiURL, "}")
	serverAddedByTyk := len(s.Servers) > 0 && s.Servers[0].URL == oldAPIURL

	if apiURLContainsNamedRegex && serverAddedByTyk {
		s.Servers = s.Servers[1:]
		return
	}

	if serverAddedByTyk {
		s.Servers[0].URL = apiURL
	}

	if len(s.Servers) == 0 {
		s.Servers = openapi3.Servers{
			{
				URL: apiURL,
			},
		}
		return
	}
}

Cognitive complexity: 8, Cyclomatic complexity: 7

Uses: openapi3.Servers, strings.Contains.

func (*OAS) Validate

Validate validates OAS document by calling openapi3.T.Validate() function. In addition, it validates Security Requirement section and it's requirements by calling OAS.validateSecurity() function.

func (s *OAS) Validate(ctx context.Context, opts ...openapi3.ValidationOption) error {
	validationErr := s.T.Validate(ctx, opts...)
	securityErr := s.validateSecurity()

	return errors.Join(validationErr, securityErr)
}

Cognitive complexity: 0, Cyclomatic complexity: 1

Uses: errors.Join.

func (*OAuth) Import

Import populates *OAuth from it's arguments.

func (o *OAuth) Import(enable bool) {
	o.Enabled = enable
	o.Header = &AuthSource{
		Enabled:	true,
		Name:		defaultAuthSourceName,
	}
}

Cognitive complexity: 1, Cyclomatic complexity: 1

func (*OIDC) ExtractTo

ExtractTo extracts *OIDC to *apidef.APIDefinition.

func (o *OIDC) ExtractTo(api *apidef.APIDefinition) {
	api.UseOpenID = o.Enabled

	authConfig := apidef.AuthConfig{}
	o.AuthSources.ExtractTo(&authConfig)

	if api.AuthConfigs == nil {
		api.AuthConfigs = make(map[string]apidef.AuthConfig)
	}

	api.AuthConfigs["oidc"] = authConfig

	api.OpenIDOptions.SegregateByClient = o.SegregateByClientId

	api.OpenIDOptions.Providers = []apidef.OIDProviderConfig{}
	for _, p := range o.Providers {
		clientIDs := make(map[string]string)
		for _, mapping := range p.ClientToPolicyMapping {
			clientIDs[mapping.ClientID] = mapping.PolicyID
		}

		api.OpenIDOptions.Providers = append(api.OpenIDOptions.Providers, apidef.OIDProviderConfig{Issuer: p.Issuer, ClientIDs: clientIDs})
	}

	if o.Scopes != nil {
		o.Scopes.ExtractTo(&api.Scopes.OIDC)
	}
}

Cognitive complexity: 13, Cyclomatic complexity: 5

Uses: apidef.AuthConfig, apidef.OIDProviderConfig.

func (*OIDC) Fill

Fill fills *OIDC from apidef.APIDefinition.

func (o *OIDC) Fill(api apidef.APIDefinition) {
	o.Enabled = api.UseOpenID

	o.AuthSources.Fill(api.AuthConfigs["oidc"])

	o.SegregateByClientId = api.OpenIDOptions.SegregateByClient

	o.Providers = []Provider{}
	for _, v := range api.OpenIDOptions.Providers {
		var mapping []ClientToPolicy
		for clientID, polID := range v.ClientIDs {
			mapping = append(mapping, ClientToPolicy{ClientID: clientID, PolicyID: polID})
		}

		if len(mapping) == 0 {
			mapping = nil
		}

		sort.Slice(mapping, func(i, j int) bool {
			return mapping[i].ClientID < mapping[j].ClientID
		})

		o.Providers = append(o.Providers, Provider{Issuer: v.Issuer, ClientToPolicyMapping: mapping})
	}

	if len(o.Providers) == 0 {
		o.Providers = nil
	}

	if o.Scopes == nil {
		o.Scopes = &Scopes{}
	}

	o.Scopes.Fill(&api.Scopes.OIDC)
	if ShouldOmit(o.Scopes) {
		o.Scopes = nil
	}
}

Cognitive complexity: 19, Cyclomatic complexity: 7

Uses: sort.Slice.

func (*OldOAS) ConvertToNewerOAS

ConvertToNewerOAS converts a deprecated OldOAS object to the newer OAS representation.

func (o *OldOAS) ConvertToNewerOAS() (*OAS, error) {
	outBytes, err := o.MarshalJSON()
	if err != nil {
		return nil, err
	}

	loader := openapi3.NewLoader()
	t, err := loader.LoadFromData(outBytes)
	if err != nil {
		return nil, err
	}

	return &OAS{T: *t}, nil
}

Cognitive complexity: 5, Cyclomatic complexity: 3

Uses: openapi3.NewLoader.

func (*Operation) Import

Import takes the arguments and populates the receiver *Operation values.

func (o *Operation) Import(oasOperation *openapi3.Operation, overRideValues TykExtensionConfigParams) {
	if overRideValues.AllowList != nil {
		allow := o.Allow
		if allow == nil {
			allow = &Allowance{}
		}

		allow.Import(*overRideValues.AllowList)

		if block := o.Block; block != nil && block.Enabled && *overRideValues.AllowList {
			block.Enabled = false
		}

		o.Allow = allow
	}

	if overRideValues.ValidateRequest != nil {
		validate := o.ValidateRequest
		if validate == nil {
			validate = &ValidateRequest{}
		}

		if ok := validate.shouldImport(oasOperation); ok || overRideValues.pathItemHasParameters {
			validate.Import(*overRideValues.ValidateRequest)
			o.ValidateRequest = validate
		}
	}

	if overRideValues.MockResponse != nil {
		mock := o.MockResponse
		if mock == nil {
			mock = &MockResponse{}
		}

		if ok := mock.shouldImport(oasOperation); ok {
			mock.Import(*overRideValues.MockResponse)
			o.MockResponse = mock
		}
	}
}

Cognitive complexity: 21, Cyclomatic complexity: 13

func (*PasswordAuthentication) ExtractTo

func (p *PasswordAuthentication) ExtractTo(api *apidef.PasswordAuthentication) {
	api.ClientID = p.ClientID
	api.ClientSecret = p.ClientSecret
	api.Username = p.Username
	api.Password = p.Password
	api.TokenURL = p.TokenURL
	api.Scopes = p.Scopes
	api.ExtraMetadata = p.ExtraMetadata

	if p.Header == nil {
		p.Header = &AuthSource{}
		defer func() {
			p.Header = nil
		}()
	}
	p.Header.ExtractTo(&api.Header.Enabled, &api.Header.Name)
}

Cognitive complexity: 4, Cyclomatic complexity: 2

func (*PasswordAuthentication) Fill

func (p *PasswordAuthentication) Fill(api apidef.PasswordAuthentication) {
	p.ClientID = api.ClientID
	p.ClientSecret = api.ClientSecret
	p.Username = api.Username
	p.Password = api.Password
	p.TokenURL = api.TokenURL
	p.Scopes = api.Scopes
	p.ExtraMetadata = api.ExtraMetadata
	if p.Header == nil {
		p.Header = &AuthSource{}
	}
	p.Header.Fill(api.Header.Enabled, api.Header.Name)
	if ShouldOmit(p.Header) {
		p.Header = nil
	}
}

Cognitive complexity: 5, Cyclomatic complexity: 3

func (*Path) ExtractTo

ExtractTo extracts *Path into *apidef.ExtendedPathSet.

func (p *Path) ExtractTo(ep *apidef.ExtendedPathsSet, path string) {
	if p.Get != nil {
		p.Get.ExtractTo(ep, path, http.MethodGet)
	}

	if p.Post != nil {
		p.Post.ExtractTo(ep, path, http.MethodPost)
	}

	if p.Put != nil {
		p.Put.ExtractTo(ep, path, http.MethodPut)
	}

	if p.Delete != nil {
		p.Delete.ExtractTo(ep, path, http.MethodDelete)
	}

	if p.Head != nil {
		p.Head.ExtractTo(ep, path, http.MethodHead)
	}

	if p.Options != nil {
		p.Options.ExtractTo(ep, path, http.MethodOptions)
	}

	if p.Trace != nil {
		p.Trace.ExtractTo(ep, path, http.MethodTrace)
	}

	if p.Patch != nil {
		p.Patch.ExtractTo(ep, path, http.MethodPatch)
	}

	if p.Connect != nil {
		p.Connect.ExtractTo(ep, path, http.MethodConnect)
	}
}

Cognitive complexity: 18, Cyclomatic complexity: 10

Uses: http.MethodConnect, http.MethodDelete, http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodPatch, http.MethodPost, http.MethodPut, http.MethodTrace.

func (*PluginBundle) ExtractTo

ExtractTo extracts *PluginBundle into *apidef.

func (p *PluginBundle) ExtractTo(api *apidef.APIDefinition) {
	api.CustomMiddlewareBundleDisabled = !p.Enabled
	api.CustomMiddlewareBundle = p.Path
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*PluginBundle) Fill

Fill fills PluginBundle from apidef.

func (p *PluginBundle) Fill(api apidef.APIDefinition) {
	p.Enabled = !api.CustomMiddlewareBundleDisabled
	p.Path = api.CustomMiddlewareBundle
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*PluginConfig) ExtractTo

ExtractTo extracts *PluginConfig into *apidef.

func (p *PluginConfig) ExtractTo(api *apidef.APIDefinition) {
	api.CustomMiddleware.Driver = p.Driver

	if p.Bundle == nil {
		p.Bundle = &PluginBundle{}
		defer func() {
			p.Bundle = nil
		}()
	}

	p.Bundle.ExtractTo(api)

	if p.Data == nil {
		p.Data = &PluginConfigData{}
		defer func() {
			p.Data = nil
		}()
	}

	p.Data.ExtractTo(api)
}

Cognitive complexity: 8, Cyclomatic complexity: 3

func (*PluginConfig) Fill

Fill fills PluginConfig from apidef.

func (p *PluginConfig) Fill(api apidef.APIDefinition) {
	p.Driver = api.CustomMiddleware.Driver

	if p.Bundle == nil {
		p.Bundle = &PluginBundle{}
	}

	p.Bundle.Fill(api)
	if ShouldOmit(p.Bundle) {
		p.Bundle = nil
	}

	if p.Data == nil {
		p.Data = &PluginConfigData{}
	}

	p.Data.Fill(api)
	if ShouldOmit(p.Data) {
		p.Data = nil
	}
}

Cognitive complexity: 10, Cyclomatic complexity: 5

func (*PluginConfigData) ExtractTo

ExtractTo extracts *PluginConfigData into *apidef.

func (p *PluginConfigData) ExtractTo(api *apidef.APIDefinition) {
	api.ConfigDataDisabled = !p.Enabled
	api.ConfigData = p.Value
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*PluginConfigData) Fill

Fill fills PluginConfigData from apidef.

func (p *PluginConfigData) Fill(api apidef.APIDefinition) {
	p.Enabled = !api.ConfigDataDisabled
	p.Value = api.ConfigData
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*Plugins) ExtractTo

ExtractTo extracts *Plugins into *apidef.ExtendedPathsSet.

func (p *Plugins) ExtractTo(ep *apidef.ExtendedPathsSet, path string, method string) {
	p.extractAllowanceTo(ep, path, method, allow)
	p.extractAllowanceTo(ep, path, method, block)
	p.extractAllowanceTo(ep, path, method, ignoreAuthentication)
	p.extractTransformRequestMethodTo(ep, path, method)
	p.extractCacheTo(ep, path, method)
	p.extractEnforcedTimeoutTo(ep, path, method)
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*PostAuthenticationPlugin) ExtractTo

ExtractTo extracts PostAuthenticationPlugin into Tyk classic api definition.

func (p *PostAuthenticationPlugin) ExtractTo(api *apidef.APIDefinition) {
	if len(p.Plugins) == 0 {
		api.CustomMiddleware.PostKeyAuth = nil
		return
	}

	api.CustomMiddleware.PostKeyAuth = make([]apidef.MiddlewareDefinition, len(p.Plugins))
	p.Plugins.ExtractTo(api.CustomMiddleware.PostKeyAuth)
}

Cognitive complexity: 2, Cyclomatic complexity: 2

Uses: apidef.MiddlewareDefinition.

func (*PostAuthenticationPlugin) Fill

Fill fills PostAuthenticationPlugin from supplied Tyk classic api definition.

func (p *PostAuthenticationPlugin) Fill(api apidef.APIDefinition) {
	if len(api.CustomMiddleware.PostKeyAuth) == 0 {
		p.Plugins = nil
		return
	}

	p.Plugins = make(CustomPlugins, len(api.CustomMiddleware.PostKeyAuth))
	p.Plugins.Fill(api.CustomMiddleware.PostKeyAuth)
}

Cognitive complexity: 2, Cyclomatic complexity: 2

func (*PostPlugin) ExtractTo

ExtractTo extracts PostPlugin into Tyk classic api definition.

func (p *PostPlugin) ExtractTo(api *apidef.APIDefinition) {
	if len(p.Plugins) == 0 {
		api.CustomMiddleware.Post = nil
		return
	}

	api.CustomMiddleware.Post = make([]apidef.MiddlewareDefinition, len(p.Plugins))
	p.Plugins.ExtractTo(api.CustomMiddleware.Post)
}

Cognitive complexity: 2, Cyclomatic complexity: 2

Uses: apidef.MiddlewareDefinition.

func (*PostPlugin) Fill

Fill fills PostPlugin from supplied Tyk classic api definition.

func (p *PostPlugin) Fill(api apidef.APIDefinition) {
	if len(api.CustomMiddleware.Post) == 0 {
		p.Plugins = nil
		return
	}

	p.Plugins = make(CustomPlugins, len(api.CustomMiddleware.Post))
	p.Plugins.Fill(api.CustomMiddleware.Post)
}

Cognitive complexity: 2, Cyclomatic complexity: 2

func (*PrePlugin) ExtractTo

ExtractTo extracts PrePlugin into Tyk classic api definition.

func (p *PrePlugin) ExtractTo(api *apidef.APIDefinition) {
	if len(p.Plugins) == 0 {
		api.CustomMiddleware.Pre = nil
		return
	}

	api.CustomMiddleware.Pre = make([]apidef.MiddlewareDefinition, len(p.Plugins))
	p.Plugins.ExtractTo(api.CustomMiddleware.Pre)
}

Cognitive complexity: 2, Cyclomatic complexity: 2

Uses: apidef.MiddlewareDefinition.

func (*PrePlugin) Fill

Fill fills PrePlugin from supplied Tyk classic api definition.

func (p *PrePlugin) Fill(api apidef.APIDefinition) {
	if len(api.CustomMiddleware.Pre) == 0 {
		p.Plugins = nil
		return
	}

	p.Plugins = make(CustomPlugins, len(api.CustomMiddleware.Pre))
	p.Plugins.Fill(api.CustomMiddleware.Pre)
}

Cognitive complexity: 2, Cyclomatic complexity: 2

func (*PreserveHostHeader) ExtractTo

ExtractTo extracts *PreserveHostHeader into *apidef.APIDefinition.

func (p *PreserveHostHeader) ExtractTo(api *apidef.APIDefinition) {
	api.Proxy.PreserveHostHeader = p.Enabled
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*PreserveHostHeader) Fill

Fill fills *PreserveHostHeader from apidef.APIDefinition.

func (p *PreserveHostHeader) Fill(api apidef.APIDefinition) {
	p.Enabled = api.Proxy.PreserveHostHeader
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*PreserveTrailingSlash) ExtractTo

ExtractTo extracts *PreserveTrailingSlash into *apidef.APIDefinition.

func (p *PreserveTrailingSlash) ExtractTo(api *apidef.APIDefinition) {
	api.Proxy.DisableStripSlash = p.Enabled
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*PreserveTrailingSlash) Fill

Fill fills *PreserveTrailingSlash from apidef.APIDefinition.

func (p *PreserveTrailingSlash) Fill(api apidef.APIDefinition) {
	p.Enabled = api.Proxy.DisableStripSlash
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*Proxy) ExtractTo

ExtractTo extracts *Proxy into *apidef.ServiceDiscoveryConfiguration.

func (p *Proxy) ExtractTo(api *apidef.APIDefinition) {
	api.Proxy.Transport.ProxyURL = p.URL
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*Proxy) Fill

Fill fills *Proxy from apidef.ServiceDiscoveryConfiguration.

func (p *Proxy) Fill(api apidef.APIDefinition) {
	p.URL = api.Proxy.Transport.ProxyURL
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*RateLimit) ExtractTo

ExtractTo extracts *Ratelimit into *apidef.APIDefinition.

func (r *RateLimit) ExtractTo(api *apidef.APIDefinition) {
	api.GlobalRateLimit.Disabled = !r.Enabled
	api.GlobalRateLimit.Rate = float64(r.Rate)
	api.GlobalRateLimit.Per = r.Per.Seconds()
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*RateLimit) Fill

Fill fills *RateLimit from apidef.APIDefinition.

func (r *RateLimit) Fill(api apidef.APIDefinition) {
	r.Enabled = !api.GlobalRateLimit.Disabled
	r.Rate = int(api.GlobalRateLimit.Rate)
	r.Per = ReadableDuration(time.Duration(api.GlobalRateLimit.Per) * time.Second)
}

Cognitive complexity: 0, Cyclomatic complexity: 1

Uses: time.Duration, time.Second.

func (*RateLimitEndpoint) ExtractTo

ExtractTo extracts *Ratelimit into *apidef.RateLimitMeta.

func (r *RateLimitEndpoint) ExtractTo(meta *apidef.RateLimitMeta) {
	meta.Disabled = !r.Enabled
	meta.Rate = float64(r.Rate)
	meta.Per = r.Per.Seconds()
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*RateLimitEndpoint) Fill

Fill fills *RateLimit from apidef.RateLimitMeta.

func (r *RateLimitEndpoint) Fill(api apidef.RateLimitMeta) {
	r.Enabled = !api.Disabled
	r.Rate = int(api.Rate)
	r.Per = ReadableDuration(time.Duration(api.Per) * time.Second)
}

Cognitive complexity: 0, Cyclomatic complexity: 1

Uses: time.Duration, time.Second.

func (*RequestSizeLimit) ExtractTo

ExtractTo extracts *RequestSizeLimiter into *apidef.RequestSizeMeta.

func (r *RequestSizeLimit) ExtractTo(meta *apidef.RequestSizeMeta) {
	meta.Disabled = !r.Enabled
	meta.SizeLimit = r.Value
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*RequestSizeLimit) Fill

Fill fills *RequestSizeLimit from apidef.RequestSizeMeta.

func (r *RequestSizeLimit) Fill(meta apidef.RequestSizeMeta) {
	r.Enabled = !meta.Disabled
	r.Value = meta.SizeLimit
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*ResponsePlugin) ExtractTo

ExtractTo extracts PostPlugin into Tyk classic api definition.

func (p *ResponsePlugin) ExtractTo(api *apidef.APIDefinition) {
	if len(p.Plugins) == 0 {
		api.CustomMiddleware.Response = nil
		return
	}

	api.CustomMiddleware.Response = make([]apidef.MiddlewareDefinition, len(p.Plugins))
	p.Plugins.ExtractTo(api.CustomMiddleware.Response)
}

Cognitive complexity: 2, Cyclomatic complexity: 2

Uses: apidef.MiddlewareDefinition.

func (*ResponsePlugin) Fill

Fill fills ResponsePlugin from supplied Tyk classic api definition.

func (p *ResponsePlugin) Fill(api apidef.APIDefinition) {
	if len(api.CustomMiddleware.Response) == 0 {
		p.Plugins = nil
		return
	}

	p.Plugins = make(CustomPlugins, len(api.CustomMiddleware.Response))
	p.Plugins.Fill(api.CustomMiddleware.Response)
}

Cognitive complexity: 2, Cyclomatic complexity: 2

func (*Scopes) ExtractTo

ExtractTo extracts *Scopes to *apidef.ScopeClaim.

func (s *Scopes) ExtractTo(scopeClaim *apidef.ScopeClaim) {
	scopeClaim.ScopeClaimName = s.ClaimName

	scopeClaim.ScopeToPolicy = map[string]string{}
	for _, v := range s.ScopeToPolicyMapping {
		scopeClaim.ScopeToPolicy[v.Scope] = v.PolicyID
	}
}

Cognitive complexity: 4, Cyclomatic complexity: 2

func (*Scopes) Fill

Fill fills *Scopes from *apidef.ScopeClaim.

func (s *Scopes) Fill(scopeClaim *apidef.ScopeClaim) {
	s.ClaimName = scopeClaim.ScopeClaimName

	s.ScopeToPolicyMapping = []ScopeToPolicy{}

	for scope, policyID := range scopeClaim.ScopeToPolicy {
		s.ScopeToPolicyMapping = append(s.ScopeToPolicyMapping, ScopeToPolicy{Scope: scope, PolicyID: policyID})
	}

	sort.Slice(s.ScopeToPolicyMapping, func(i, j int) bool {
		return s.ScopeToPolicyMapping[i].Scope < s.ScopeToPolicyMapping[j].Scope
	})

	if len(s.ScopeToPolicyMapping) == 0 {
		s.ScopeToPolicyMapping = nil
	}
}

Cognitive complexity: 8, Cyclomatic complexity: 3

Uses: sort.Slice.

func (*Server) ExtractTo

ExtractTo extracts *Server into *apidef.APIDefinition.

func (s *Server) ExtractTo(api *apidef.APIDefinition) {
	api.Protocol = s.Protocol
	api.ListenPort = s.Port
	s.ListenPath.ExtractTo(api)

	if s.ClientCertificates == nil {
		s.ClientCertificates = &ClientCertificates{}
		defer func() {
			s.ClientCertificates = nil
		}()
	}

	s.ClientCertificates.ExtractTo(api)

	if s.GatewayTags == nil {
		s.GatewayTags = &GatewayTags{}
		defer func() {
			s.GatewayTags = nil
		}()
	}

	s.GatewayTags.ExtractTo(api)

	if s.CustomDomain == nil {
		s.CustomDomain = &Domain{}
		defer func() {
			s.CustomDomain = nil
		}()
	}

	s.CustomDomain.ExtractTo(api)

	if s.DetailedActivityLogs == nil {
		s.DetailedActivityLogs = &DetailedActivityLogs{}
		defer func() {
			s.DetailedActivityLogs = nil
		}()
	}

	s.DetailedActivityLogs.ExtractTo(api)

	if s.DetailedTracing == nil {
		s.DetailedTracing = &DetailedTracing{}
		defer func() {
			s.DetailedTracing = nil
		}()
	}

	s.DetailedTracing.ExtractTo(api)

	if s.EventHandlers == nil {
		s.EventHandlers = EventHandlers{}
		defer func() {
			s.EventHandlers = nil
		}()
	}

	s.EventHandlers.ExtractTo(api)

	s.extractIPAccessControlTo(api)
	s.extractBatchProcessingTo(api)
}

Cognitive complexity: 24, Cyclomatic complexity: 7

func (*Server) Fill

Fill fills *Server from apidef.APIDefinition.

func (s *Server) Fill(api apidef.APIDefinition) {
	s.Protocol = api.Protocol
	s.Port = api.ListenPort

	s.ListenPath.Fill(api)

	if s.ClientCertificates == nil {
		s.ClientCertificates = &ClientCertificates{}
	}

	s.ClientCertificates.Fill(api)
	if ShouldOmit(s.ClientCertificates) {
		s.ClientCertificates = nil
	}

	if s.GatewayTags == nil {
		s.GatewayTags = &GatewayTags{}
	}
	s.GatewayTags.Fill(api)
	if ShouldOmit(s.GatewayTags) {
		s.GatewayTags = nil
	}

	if s.CustomDomain == nil {
		s.CustomDomain = &Domain{}
	}

	s.CustomDomain.Fill(api)
	if ShouldOmit(s.CustomDomain) {
		s.CustomDomain = nil
	}

	if s.DetailedActivityLogs == nil {
		s.DetailedActivityLogs = &DetailedActivityLogs{}
	}

	s.DetailedActivityLogs.Fill(api)
	if ShouldOmit(s.DetailedActivityLogs) {
		s.DetailedActivityLogs = nil
	}

	if s.DetailedTracing == nil {
		s.DetailedTracing = &DetailedTracing{}
	}
	s.DetailedTracing.Fill(api)
	if ShouldOmit(s.DetailedTracing) {
		s.DetailedTracing = nil
	}

	if s.EventHandlers == nil {
		s.EventHandlers = EventHandlers{}
	}
	s.EventHandlers.Fill(api)
	if ShouldOmit(s.EventHandlers) {
		s.EventHandlers = nil
	}

	s.fillIPAccessControl(api)
	s.fillBatchProcessing(api)
}

Cognitive complexity: 30, Cyclomatic complexity: 13

func (*ServiceDiscovery) CacheOptions

CacheOptions returns the timeout value in effect and a bool if cache is enabled.

func (sd *ServiceDiscovery) CacheOptions() (int64, bool) {
	if sd.Cache != nil {
		return sd.Cache.Timeout, sd.Cache.Enabled
	}

	return sd.CacheTimeout, sd.CacheTimeout > 0
}

Cognitive complexity: 2, Cyclomatic complexity: 2

func (*ServiceDiscovery) ExtractTo

ExtractTo extracts *ServiceDiscovery into *apidef.ServiceDiscoveryConfiguration.

func (sd *ServiceDiscovery) ExtractTo(serviceDiscovery *apidef.ServiceDiscoveryConfiguration) {
	serviceDiscovery.UseDiscoveryService = sd.Enabled
	serviceDiscovery.EndpointReturnsList = sd.EndpointReturnsList
	serviceDiscovery.ParentDataPath = sd.ParentDataPath
	serviceDiscovery.QueryEndpoint = sd.QueryEndpoint
	serviceDiscovery.TargetPath = sd.TargetPath
	serviceDiscovery.UseTargetList = sd.UseTargetList
	serviceDiscovery.UseNestedQuery = sd.UseNestedQuery
	serviceDiscovery.DataPath = sd.DataPath
	serviceDiscovery.PortDataPath = sd.PortDataPath

	timeout, enabled := sd.CacheOptions()
	serviceDiscovery.CacheDisabled = !enabled
	serviceDiscovery.CacheTimeout = timeout
	if !sd.Enabled {
		serviceDiscovery.CacheDisabled = true
	}
}

Cognitive complexity: 2, Cyclomatic complexity: 2

func (*ServiceDiscovery) Fill

Fill fills *ServiceDiscovery from apidef.ServiceDiscoveryConfiguration.

func (sd *ServiceDiscovery) Fill(serviceDiscovery apidef.ServiceDiscoveryConfiguration) {
	sd.Enabled = serviceDiscovery.UseDiscoveryService
	sd.EndpointReturnsList = serviceDiscovery.EndpointReturnsList
	sd.ParentDataPath = serviceDiscovery.ParentDataPath
	sd.QueryEndpoint = serviceDiscovery.QueryEndpoint
	sd.TargetPath = serviceDiscovery.TargetPath
	sd.UseTargetList = serviceDiscovery.UseTargetList
	sd.UseNestedQuery = serviceDiscovery.UseNestedQuery
	sd.DataPath = serviceDiscovery.DataPath
	sd.PortDataPath = serviceDiscovery.PortDataPath

	timeout, enabled := serviceDiscovery.CacheOptions()
	sd.Cache = &ServiceDiscoveryCache{
		Enabled:	enabled && sd.Enabled,
		Timeout:	timeout,
	}

	if !sd.Cache.Enabled {
		sd.Cache = nil
	}

	sd.CacheTimeout = 0
}

Cognitive complexity: 3, Cyclomatic complexity: 3

func (*Signature) ExtractTo

ExtractTo extracts *Signature to *apidef.AuthConfig.

func (s *Signature) ExtractTo(authConfig *apidef.AuthConfig) {
	authConfig.ValidateSignature = s.Enabled

	authConfig.Signature.Algorithm = s.Algorithm
	authConfig.Signature.Header = s.Header
	s.Query.ExtractTo(&authConfig.Signature.UseParam, &authConfig.Signature.ParamName)
	authConfig.Signature.Secret = s.Secret
	authConfig.Signature.AllowedClockSkew = s.AllowedClockSkew
	authConfig.Signature.ErrorCode = s.ErrorCode
	authConfig.Signature.ErrorMessage = s.ErrorMessage
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*Signature) Fill

Fill fills *Signature from apidef.AuthConfig.

func (s *Signature) Fill(authConfig apidef.AuthConfig) {
	signature := authConfig.Signature

	s.Enabled = authConfig.ValidateSignature
	s.Algorithm = signature.Algorithm
	s.Header = signature.Header
	s.Query.Fill(signature.UseParam, signature.ParamName)
	s.Secret = signature.Secret
	s.AllowedClockSkew = signature.AllowedClockSkew
	s.ErrorCode = signature.ErrorCode
	s.ErrorMessage = signature.ErrorMessage
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*State) ExtractTo

ExtractTo extracts *State to *apidef.APIDefinition.

func (s *State) ExtractTo(api *apidef.APIDefinition) {
	api.Active = s.Active
	api.Internal = s.Internal
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*State) Fill

Fill fills *State from apidef.APIDefinition.

func (s *State) Fill(api apidef.APIDefinition) {
	s.Active = api.Active
	s.Internal = api.Internal
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*TLSTransport) ExtractTo

ExtractTo extracts *TLSTransport into *apidef.ServiceDiscoveryConfiguration.

func (t *TLSTransport) ExtractTo(api *apidef.APIDefinition) {
	api.Proxy.Transport.SSLForceCommonNameCheck = t.ForceCommonNameCheck
	api.Proxy.Transport.SSLCipherSuites = t.Ciphers
	api.Proxy.Transport.SSLMaxVersion = t.tlsVersionFromString(t.MaxVersion)
	api.Proxy.Transport.SSLMinVersion = t.tlsVersionFromString(t.MinVersion)
	api.Proxy.Transport.SSLInsecureSkipVerify = t.InsecureSkipVerify
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*TLSTransport) Fill

Fill fills *TLSTransport from apidef.ServiceDiscoveryConfiguration.

func (t *TLSTransport) Fill(api apidef.APIDefinition) {
	t.ForceCommonNameCheck = api.Proxy.Transport.SSLForceCommonNameCheck
	t.Ciphers = api.Proxy.Transport.SSLCipherSuites
	t.MaxVersion = t.tlsVersionToString(api.Proxy.Transport.SSLMaxVersion)
	t.MinVersion = t.tlsVersionToString(api.Proxy.Transport.SSLMinVersion)
	t.InsecureSkipVerify = api.Proxy.Transport.SSLInsecureSkipVerify
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*Token) Import

Import populates *Token from argument values.

func (t *Token) Import(nativeSS *openapi3.SecurityScheme, enable bool) {
	t.Enabled = enable
	t.AuthSources.Import(nativeSS.In)
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*TrackEndpoint) ExtractTo

ExtractTo fills *apidef.TrackEndpointMeta from *TrackEndpoint.

func (i *TrackEndpoint) ExtractTo(meta *apidef.TrackEndpointMeta) {
	meta.Disabled = !i.Enabled
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*TrackEndpoint) Fill

Fill fills *TrackEndpoint receiver with data from apidef.TrackEndpointMeta.

func (i *TrackEndpoint) Fill(meta apidef.TrackEndpointMeta) {
	i.Enabled = !meta.Disabled
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*TrafficLogs) ExtractTo

ExtractTo extracts *TrafficLogs into *apidef.APIDefinition.

func (t *TrafficLogs) ExtractTo(api *apidef.APIDefinition) {
	api.DoNotTrack = !t.Enabled
	api.TagHeaders = t.TagHeaders
	api.ExpireAnalyticsAfter = int64(t.CustomRetentionPeriod.Seconds())

	if t.Plugins == nil {
		t.Plugins = make(CustomAnalyticsPlugins, 0)
		defer func() {
			t.Plugins = nil
		}()
	}
	t.Plugins.ExtractTo(api)
}

Cognitive complexity: 3, Cyclomatic complexity: 2

func (*TrafficLogs) Fill

Fill fills *TrafficLogs from apidef.APIDefinition.

func (t *TrafficLogs) Fill(api apidef.APIDefinition) {
	t.Enabled = !api.DoNotTrack
	t.TagHeaders = api.TagHeaders
	t.CustomRetentionPeriod = ReadableDuration(time.Duration(api.ExpireAnalyticsAfter) * time.Second)

	if t.Plugins == nil {
		t.Plugins = make(CustomAnalyticsPlugins, 0)
	}
	t.Plugins.Fill(api)
	if ShouldOmit(t.Plugins) {
		t.Plugins = nil
	}
}

Cognitive complexity: 4, Cyclomatic complexity: 3

Uses: time.Duration, time.Second.

func (*TransformBody) ExtractTo

ExtractTo extracts data from *TransformBody into *apidef.TemplateMeta.

func (tr *TransformBody) ExtractTo(meta *apidef.TemplateMeta) {
	meta.Disabled = !tr.Enabled
	meta.TemplateData.Input = tr.Format
	meta.TemplateData.EnableSession = true
	if tr.Body != "" {
		meta.TemplateData.Mode = apidef.UseBlob
		meta.TemplateData.TemplateSource = tr.Body
	} else {
		meta.TemplateData.Mode = apidef.UseFile
		meta.TemplateData.TemplateSource = tr.Path
	}
}

Cognitive complexity: 4, Cyclomatic complexity: 2

Uses: apidef.UseBlob, apidef.UseFile.

func (*TransformBody) Fill

Fill fills *TransformBody from apidef.TemplateMeta.

func (tr *TransformBody) Fill(meta apidef.TemplateMeta) {
	tr.Enabled = !meta.Disabled
	tr.Format = meta.TemplateData.Input
	if meta.TemplateData.Mode == apidef.UseBlob {
		tr.Body = meta.TemplateData.TemplateSource
	} else {
		tr.Path = meta.TemplateData.TemplateSource
	}
}

Cognitive complexity: 4, Cyclomatic complexity: 2

Uses: apidef.UseBlob.

func (*TransformHeaders) ExtractTo

ExtractTo extracts *TransformHeaders into *apidef.HeaderInjectionMeta.

func (th *TransformHeaders) ExtractTo(meta *apidef.HeaderInjectionMeta) {
	meta.Disabled = !th.Enabled
	meta.DeleteHeaders = th.Remove

	meta.AddHeaders = make(map[string]string, len(th.Remove))
	for _, header := range th.Add {
		meta.AddHeaders[header.Name] = header.Value
	}
}

Cognitive complexity: 3, Cyclomatic complexity: 2

func (*TransformHeaders) Fill

Fill fills *TransformHeaders from apidef.HeaderInjectionMeta.

func (th *TransformHeaders) Fill(meta apidef.HeaderInjectionMeta) {
	th.Enabled = !meta.Disabled
	th.Remove = meta.DeleteHeaders
	th.Add = NewHeaders(meta.AddHeaders)

	if len(th.Add) == 0 {
		th.Add = nil
	}
}

Cognitive complexity: 2, Cyclomatic complexity: 2

func (*TransformRequestMethod) ExtractTo

ExtractTo extracts *TransformRequestMethod into *apidef.MethodTransformMeta.

func (tm *TransformRequestMethod) ExtractTo(meta *apidef.MethodTransformMeta) {
	meta.Disabled = !tm.Enabled
	meta.ToMethod = tm.ToMethod
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*TransformRequestMethod) Fill

Fill fills *TransformRequestMethod from apidef.MethodTransformMeta.

func (tm *TransformRequestMethod) Fill(meta apidef.MethodTransformMeta) {
	tm.Enabled = !meta.Disabled
	tm.ToMethod = meta.ToMethod
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*URLRewrite) ExtractTo

ExtractTo fills *apidef.URLRewriteMeta from *URLRewrite.

func (v *URLRewrite) ExtractTo(dest *apidef.URLRewriteMeta) {
	dest.Disabled = !v.Enabled
	dest.MatchPattern = v.Pattern
	dest.RewriteTo = v.RewriteTo
	dest.Triggers = v.extractTriggers()
	if len(dest.Triggers) == 0 {
		dest.Triggers = nil
	}
}

Cognitive complexity: 2, Cyclomatic complexity: 2

func (*URLRewrite) Fill

Fill fills *URLRewrite receiver from apidef.URLRewriteMeta.

func (v *URLRewrite) Fill(meta apidef.URLRewriteMeta) {
	v.Enabled = !meta.Disabled
	v.Pattern = meta.MatchPattern
	v.RewriteTo = meta.RewriteTo

	v.Triggers = v.fillTriggers(meta.Triggers)

	if len(v.Triggers) == 0 {
		v.Triggers = nil
	}

	v.Sort()
}

Cognitive complexity: 2, Cyclomatic complexity: 2

func (*URLRewrite) Sort

Sort reorders the internal trigger rules.

func (v *URLRewrite) Sort() {
	for _, t := range v.Triggers {
		rules := t.Rules

		sort.Slice(rules, func(i, j int) bool {
			return rules[i].In.Index() < rules[j].In.Index()
		})
	}
}

Cognitive complexity: 4, Cyclomatic complexity: 2

Uses: sort.Slice.

func (*Upstream) ExtractTo

ExtractTo extracts *Upstream into *apidef.APIDefinition.

func (u *Upstream) ExtractTo(api *apidef.APIDefinition) {
	api.Proxy.TargetURL = u.URL

	if u.ServiceDiscovery == nil {
		u.ServiceDiscovery = &ServiceDiscovery{}
		defer func() {
			u.ServiceDiscovery = nil
		}()
	}

	u.ServiceDiscovery.ExtractTo(&api.Proxy.ServiceDiscovery)

	if u.UptimeTests == nil {
		u.UptimeTests = &UptimeTests{}
		defer func() {
			u.UptimeTests = nil
		}()
	}

	u.UptimeTests.ExtractTo(&api.UptimeTests)

	if u.MutualTLS == nil {
		u.MutualTLS = &MutualTLS{}
		defer func() {
			u.MutualTLS = nil
		}()
	}

	u.MutualTLS.ExtractTo(api)

	if u.CertificatePinning == nil {
		u.CertificatePinning = &CertificatePinning{}
		defer func() {
			u.CertificatePinning = nil
		}()
	}

	u.CertificatePinning.ExtractTo(api)

	if u.RateLimit == nil {
		u.RateLimit = &RateLimit{}
		defer func() {
			u.RateLimit = nil
		}()
	}

	u.RateLimit.ExtractTo(api)

	if u.Authentication == nil {
		u.Authentication = &UpstreamAuth{}
		defer func() {
			u.Authentication = nil
		}()
	}

	u.Authentication.ExtractTo(api)

	u.loadBalancingExtractTo(api)

	if u.TLSTransport == nil {
		u.TLSTransport = &TLSTransport{}
		defer func() {
			u.TLSTransport = nil
		}()
	}
	u.TLSTransport.ExtractTo(api)

	if u.Proxy == nil {
		u.Proxy = &Proxy{}
		defer func() {
			u.Proxy = nil
		}()
	}
	u.Proxy.ExtractTo(api)

	u.preserveHostHeaderExtractTo(api)
	u.preserveTrailingSlashExtractTo(api)
}

Cognitive complexity: 32, Cyclomatic complexity: 9

func (*Upstream) Fill

Fill fills *Upstream from apidef.APIDefinition.

func (u *Upstream) Fill(api apidef.APIDefinition) {
	u.URL = api.Proxy.TargetURL

	if u.ServiceDiscovery == nil {
		u.ServiceDiscovery = &ServiceDiscovery{}
	}

	u.ServiceDiscovery.Fill(api.Proxy.ServiceDiscovery)
	if ShouldOmit(u.ServiceDiscovery) {
		u.ServiceDiscovery = nil
	}

	if u.UptimeTests == nil {
		u.UptimeTests = &UptimeTests{}
	}

	u.UptimeTests.Fill(api.UptimeTests)
	if ShouldOmit(u.UptimeTests) {
		u.UptimeTests = nil
	}

	if u.MutualTLS == nil {
		u.MutualTLS = &MutualTLS{}
	}

	u.MutualTLS.Fill(api)
	if ShouldOmit(u.MutualTLS) {
		u.MutualTLS = nil
	}

	if u.CertificatePinning == nil {
		u.CertificatePinning = &CertificatePinning{}
	}

	u.CertificatePinning.Fill(api)
	if ShouldOmit(u.CertificatePinning) {
		u.CertificatePinning = nil
	}

	if u.RateLimit == nil {
		u.RateLimit = &RateLimit{}
	}

	u.RateLimit.Fill(api)
	if ShouldOmit(u.RateLimit) {
		u.RateLimit = nil
	}

	if u.Authentication == nil {
		u.Authentication = &UpstreamAuth{}
	}

	u.Authentication.Fill(api)
	if ShouldOmit(u.Authentication) {
		u.Authentication = nil
	}

	if u.TLSTransport == nil {
		u.TLSTransport = &TLSTransport{}
	}
	u.TLSTransport.Fill(api)
	if ShouldOmit(u.TLSTransport) {
		u.TLSTransport = nil
	}

	if u.Proxy == nil {
		u.Proxy = &Proxy{}
	}
	u.Proxy.Fill(api)
	if ShouldOmit(u.Proxy) {
		u.Proxy = nil
	}

	u.fillLoadBalancing(api)
	u.fillPreserveHostHeader(api)
	u.fillPreserveTrailingSlash(api)
}

Cognitive complexity: 40, Cyclomatic complexity: 17

func (*UpstreamAuth) ExtractTo

ExtractTo extracts *UpstreamAuth into *apidef.APIDefinition.

func (u *UpstreamAuth) ExtractTo(api *apidef.APIDefinition) {
	api.UpstreamAuth.Enabled = u.Enabled

	if u.BasicAuth == nil {
		u.BasicAuth = &UpstreamBasicAuth{}
		defer func() {
			u.BasicAuth = nil
		}()
	}
	u.BasicAuth.ExtractTo(&api.UpstreamAuth.BasicAuth)

	if u.OAuth == nil {
		u.OAuth = &UpstreamOAuth{}
		defer func() {
			u.OAuth = nil
		}()
	}
	u.OAuth.ExtractTo(&api.UpstreamAuth.OAuth)

	u.requestSigningExtractTo(api)
}

Cognitive complexity: 8, Cyclomatic complexity: 3

func (*UpstreamAuth) Fill

Fill fills *UpstreamAuth from apidef.APIDefinition.

func (u *UpstreamAuth) Fill(api apidef.APIDefinition) {
	u.Enabled = api.UpstreamAuth.Enabled

	if u.BasicAuth == nil {
		u.BasicAuth = &UpstreamBasicAuth{}
	}
	u.BasicAuth.Fill(api.UpstreamAuth.BasicAuth)
	if ShouldOmit(u.BasicAuth) {
		u.BasicAuth = nil
	}

	if u.OAuth == nil {
		u.OAuth = &UpstreamOAuth{}
	}
	u.OAuth.Fill(api.UpstreamAuth.OAuth)
	if ShouldOmit(u.OAuth) {
		u.OAuth = nil
	}

	u.fillRequestSigning(api)
}

Cognitive complexity: 10, Cyclomatic complexity: 5

func (*UpstreamBasicAuth) ExtractTo

ExtractTo extracts *UpstreamBasicAuth into *apidef.UpstreamBasicAuth.

func (u *UpstreamBasicAuth) ExtractTo(api *apidef.UpstreamBasicAuth) {
	api.Enabled = u.Enabled
	api.Enabled = u.Enabled
	api.Username = u.Username
	api.Password = u.Password

	if u.Header == nil {
		u.Header = &AuthSource{}
		defer func() {
			u.Header = nil
		}()
	}
	u.Header.ExtractTo(&api.Header.Enabled, &api.Header.Name)
}

Cognitive complexity: 4, Cyclomatic complexity: 2

func (*UpstreamBasicAuth) Fill

Fill fills *UpstreamBasicAuth from apidef.UpstreamBasicAuth.

func (u *UpstreamBasicAuth) Fill(api apidef.UpstreamBasicAuth) {
	u.Enabled = api.Enabled
	u.Username = api.Username
	u.Password = api.Password

	if u.Header == nil {
		u.Header = &AuthSource{}
	}
	u.Header.Fill(api.Header.Enabled, api.Header.Name)
	if ShouldOmit(u.Header) {
		u.Header = nil
	}
}

Cognitive complexity: 5, Cyclomatic complexity: 3

func (*UpstreamOAuth) ExtractTo

func (u *UpstreamOAuth) ExtractTo(api *apidef.UpstreamOAuth) {
	api.Enabled = u.Enabled
	api.AllowedAuthorizeTypes = u.AllowedAuthorizeTypes
	if u.ClientCredentials == nil {
		u.ClientCredentials = &ClientCredentials{}
		defer func() {
			u.ClientCredentials = nil
		}()
	}
	u.ClientCredentials.ExtractTo(&api.ClientCredentials)

	if u.PasswordAuthentication == nil {
		u.PasswordAuthentication = &PasswordAuthentication{}
		defer func() {
			u.PasswordAuthentication = nil
		}()
	}
	u.PasswordAuthentication.ExtractTo(&api.PasswordAuthentication)
}

Cognitive complexity: 8, Cyclomatic complexity: 3

func (*UpstreamOAuth) Fill

func (u *UpstreamOAuth) Fill(api apidef.UpstreamOAuth) {
	u.Enabled = api.Enabled
	u.AllowedAuthorizeTypes = api.AllowedAuthorizeTypes

	if u.ClientCredentials == nil {
		u.ClientCredentials = &ClientCredentials{}
	}
	u.ClientCredentials.Fill(api.ClientCredentials)
	if ShouldOmit(u.ClientCredentials) {
		u.ClientCredentials = nil
	}

	if u.PasswordAuthentication == nil {
		u.PasswordAuthentication = &PasswordAuthentication{}
	}
	u.PasswordAuthentication.Fill(api.PasswordAuthentication)
	if ShouldOmit(u.PasswordAuthentication) {
		u.PasswordAuthentication = nil
	}
}

Cognitive complexity: 10, Cyclomatic complexity: 5

func (*UpstreamRequestSigning) ExtractTo

ExtractTo populates the given apidef.APIDefinition RequestSigning fields with values from the UpstreamRequestSigning.

func (l *UpstreamRequestSigning) ExtractTo(api *apidef.APIDefinition) {
	api.RequestSigning.IsEnabled = l.Enabled
	api.RequestSigning.SignatureHeader = l.SignatureHeader
	api.RequestSigning.Algorithm = l.Algorithm
	api.RequestSigning.KeyId = l.KeyID
	api.RequestSigning.HeaderList = l.Headers
	api.RequestSigning.Secret = l.Secret
	api.RequestSigning.CertificateId = l.CertificateID
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*UpstreamRequestSigning) Fill

Fill populates the UpstreamRequestSigning fields from the given apidef.APIDefinition configuration.

func (l *UpstreamRequestSigning) Fill(api apidef.APIDefinition) {
	l.Enabled = api.RequestSigning.IsEnabled
	l.SignatureHeader = api.RequestSigning.SignatureHeader
	l.Algorithm = api.RequestSigning.Algorithm
	l.KeyID = api.RequestSigning.KeyId
	l.Headers = api.RequestSigning.HeaderList
	l.Secret = api.RequestSigning.Secret
	l.CertificateID = api.RequestSigning.CertificateId
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*UptimeTest) AddCommand

AddCommand will append a new command to the test.

func (t *UptimeTest) AddCommand(name, message string) {
	command := UptimeTestCommand{
		Name:		name,
		Message:	message,
	}

	t.Commands = append(t.Commands, command)
}

Cognitive complexity: 1, Cyclomatic complexity: 1

func (*UptimeTests) ExtractTo

ExtractTo extracts *UptimeTests into *apidef.UptimeTests.

func (u *UptimeTests) ExtractTo(uptimeTests *apidef.UptimeTests) {
	uptimeTests.Disabled = !u.Enabled

	if u.ServiceDiscovery == nil {
		u.ServiceDiscovery = &ServiceDiscovery{}
		defer func() {
			u.ServiceDiscovery = nil
		}()
	}

	u.ServiceDiscovery.ExtractTo(&uptimeTests.Config.ServiceDiscovery)

	uptimeTests.Config.ExpireUptimeAnalyticsAfter = int64(u.LogRetentionPeriod.Seconds())
	uptimeTests.Config.RecheckWait = int(u.HostDownRetestPeriod.Seconds())

	uptimeTests.CheckList = nil

	result := []apidef.HostCheckObject{}
	for _, v := range u.Tests {
		classicProtocol, classicCheckURL := u.extractToProtocolAndCheckURL(v.CheckURL)
		check := apidef.HostCheckObject{
			CheckURL:		classicCheckURL,
			Protocol:		classicProtocol,
			Timeout:		time.Duration(v.Timeout),
			Method:			v.Method,
			Headers:		v.Headers,
			Body:			v.Body,
			EnableProxyProtocol:	v.EnableProxyProtocol,
		}
		for _, command := range v.Commands {
			check.AddCommand(command.Name, command.Message)
		}

		result = append(result, check)
	}

	if len(result) > 0 {
		uptimeTests.CheckList = result
	}
}

Cognitive complexity: 14, Cyclomatic complexity: 5

Uses: apidef.HostCheckObject, time.Duration.

func (*UptimeTests) Fill

Fill fills *UptimeTests from apidef.UptimeTests.

func (u *UptimeTests) Fill(uptimeTests apidef.UptimeTests) {
	if u.ServiceDiscovery == nil {
		u.ServiceDiscovery = &ServiceDiscovery{}
	}

	u.ServiceDiscovery.Fill(uptimeTests.Config.ServiceDiscovery)

	if ShouldOmit(u.ServiceDiscovery) {
		u.ServiceDiscovery = nil
	}

	u.LogRetentionPeriod = ReadableDuration(time.Duration(uptimeTests.Config.ExpireUptimeAnalyticsAfter) * time.Second)
	u.HostDownRetestPeriod = ReadableDuration(time.Duration(uptimeTests.Config.RecheckWait) * time.Second)

	u.Tests = nil
	for _, v := range uptimeTests.CheckList {
		check := UptimeTest{
			CheckURL:		u.fillCheckURL(v.Protocol, v.CheckURL),
			Timeout:		ReadableDuration(v.Timeout),
			Method:			v.Method,
			Headers:		v.Headers,
			Body:			v.Body,
			EnableProxyProtocol:	v.EnableProxyProtocol,
		}
		for _, command := range v.Commands {
			check.AddCommand(command.Name, command.Message)
		}
		u.Tests = append(u.Tests, check)
	}

	u.Enabled = len(u.Tests) > 0 && !uptimeTests.Disabled
}

Cognitive complexity: 12, Cyclomatic complexity: 6

Uses: time.Duration, time.Second.

func (*ValidateRequest) Fill

Fill fills *ValidateRequest receiver from apidef.ValidateRequestMeta.

func (v *ValidateRequest) Fill(meta apidef.ValidatePathMeta) {
	v.Enabled = !meta.Disabled
	v.ErrorResponseCode = meta.ErrorResponseCode
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*ValidateRequest) Import

Import populates *ValidateRequest with enabled argument and a default error response code.

func (v *ValidateRequest) Import(enabled bool) {
	v.Enabled = enabled
	v.ErrorResponseCode = http.StatusUnprocessableEntity
}

Cognitive complexity: 0, Cyclomatic complexity: 1

Uses: http.StatusUnprocessableEntity.

func (*Versioning) ExtractTo

ExtractTo extracts *Versioning into *apidef.APIDefinition.

func (v *Versioning) ExtractTo(api *apidef.APIDefinition) {
	api.VersionDefinition.Enabled = v.Enabled
	api.VersionDefinition.Name = v.Name
	api.VersionDefinition.Default = v.Default
	api.VersionDefinition.Location = v.Location
	api.VersionDefinition.Key = v.Key

	if len(v.Versions) > 0 {
		api.VersionDefinition.Versions = make(map[string]string)
		for _, val := range v.Versions {
			api.VersionDefinition.Versions[val.Name] = val.ID
		}
	} else {
		api.VersionDefinition.Versions = nil
	}

	api.VersionDefinition.StripVersioningData = v.StripVersioningData
	api.VersionDefinition.UrlVersioningPattern = v.UrlVersioningPattern
	api.VersionDefinition.FallbackToDefault = v.FallbackToDefault
}

Cognitive complexity: 7, Cyclomatic complexity: 3

func (*Versioning) Fill

Fill fills *Versioning from apidef.APIDefinition.

func (v *Versioning) Fill(api apidef.APIDefinition) {
	v.Enabled = api.VersionDefinition.Enabled
	v.Name = api.VersionDefinition.Name
	v.Default = api.VersionDefinition.Default
	v.Location = api.VersionDefinition.Location
	v.Key = api.VersionDefinition.Key
	v.Versions = []VersionToID{}
	for vName, apiID := range api.VersionDefinition.Versions {
		v.Versions = append(v.Versions, VersionToID{vName, apiID})
	}

	sort.Slice(v.Versions, func(i, j int) bool {
		return v.Versions[i].Name < v.Versions[j].Name
	})

	if ShouldOmit(v.Versions) {
		v.Versions = nil
	}

	v.StripVersioningData = api.VersionDefinition.StripVersioningData
	v.FallbackToDefault = api.VersionDefinition.FallbackToDefault
	v.UrlVersioningPattern = api.VersionDefinition.UrlVersioningPattern
}

Cognitive complexity: 8, Cyclomatic complexity: 3

Uses: sort.Slice.

func (*VirtualEndpoint) ExtractTo

ExtractTo extracts *VirtualEndpoint to *apidef.VirtualMeta.

func (v *VirtualEndpoint) ExtractTo(meta *apidef.VirtualMeta) {
	meta.Disabled = !v.Enabled
	if v.FunctionName != "" {
		meta.ResponseFunctionName = v.FunctionName
		v.Name = ""
	} else {
		meta.ResponseFunctionName = v.Name
	}

	meta.UseSession = v.RequireSession
	meta.ProxyOnError = v.ProxyOnError
	if v.Body != "" {
		meta.FunctionSourceType = apidef.UseBlob
		meta.FunctionSourceURI = v.Body
	} else {
		meta.FunctionSourceType = apidef.UseFile
		meta.FunctionSourceURI = v.Path
	}
}

Cognitive complexity: 8, Cyclomatic complexity: 3

Uses: apidef.UseBlob, apidef.UseFile.

func (*VirtualEndpoint) Fill

Fill fills *VirtualEndpoint from apidef.VirtualMeta.

func (v *VirtualEndpoint) Fill(meta apidef.VirtualMeta) {
	v.Enabled = !meta.Disabled
	v.FunctionName = meta.ResponseFunctionName
	v.Name = ""
	v.RequireSession = meta.UseSession
	v.ProxyOnError = meta.ProxyOnError
	if meta.FunctionSourceType == apidef.UseBlob {
		v.Body = meta.FunctionSourceURI
	} else {
		v.Path = meta.FunctionSourceURI
	}
}

Cognitive complexity: 4, Cyclomatic complexity: 2

Uses: apidef.UseBlob.

func (*VirtualEndpoint) MarshalJSON

MarshalJSON is a custom JSON marshaler for the VirtualEndpoint struct. It is implemented to facilitate a smooth migration from deprecated fields that were previously used to represent the same data.

func (v *VirtualEndpoint) MarshalJSON() ([]byte, error) {
	if v == nil {
		return nil, nil
	}

	type Alias VirtualEndpoint

	var payload = Alias(*v)

	if payload.FunctionName == "" && payload.Name != "" {
		payload.FunctionName = payload.Name
		payload.Name = ""
	}

	// to prevent infinite recursion
	return json.Marshal(payload)
}

Cognitive complexity: 4, Cyclomatic complexity: 4

Uses: json.Marshal.

func (*XTykAPIGateway) ExtractTo

ExtractTo extracts *XTykAPIGateway into *apidef.APIDefinition.

func (x *XTykAPIGateway) ExtractTo(api *apidef.APIDefinition) {
	api.SetDisabledFlags()

	x.Info.ExtractTo(api)
	x.Upstream.ExtractTo(api)
	x.Server.ExtractTo(api)

	if x.Middleware == nil {
		x.Middleware = &Middleware{}
		defer func() {
			x.Middleware = nil
		}()
	}

	x.Middleware.ExtractTo(api)
}

Cognitive complexity: 4, Cyclomatic complexity: 2

func (*XTykAPIGateway) Fill

Fill fills *XTykAPIGateway from apidef.APIDefinition.

func (x *XTykAPIGateway) Fill(api apidef.APIDefinition) {
	x.Info.Fill(api)
	x.Upstream.Fill(api)
	x.Server.Fill(api)

	if x.Middleware == nil {
		x.Middleware = &Middleware{}
	}

	x.Middleware.Fill(api)
	if ShouldOmit(x.Middleware) {
		x.Middleware = nil
	}
}

Cognitive complexity: 5, Cyclomatic complexity: 3

func (EndpointPostPlugins) ExtractTo

ExtractTo extracts *EndpointPostPlugin to *apidef.GoPluginMeta.

func (e EndpointPostPlugins) ExtractTo(meta *apidef.GoPluginMeta) {
	if len(e) == 0 {
		return
	}

	meta.Disabled = !e[0].Enabled
	meta.PluginPath = e[0].Path
	if e[0].FunctionName != "" {
		meta.SymbolName = e[0].FunctionName
	} else {
		meta.SymbolName = e[0].Name
	}
}

Cognitive complexity: 6, Cyclomatic complexity: 3

func (EndpointPostPlugins) Fill

Fill fills *EndpointPostPlugin from apidef.GoPluginMeta.

func (e EndpointPostPlugins) Fill(meta apidef.GoPluginMeta) {
	if len(e) == 0 {
		return
	}

	e[0] = EndpointPostPlugin{
		Enabled:	!meta.Disabled,
		FunctionName:	meta.SymbolName,
		Path:		meta.PluginPath,
	}
}

Cognitive complexity: 3, Cyclomatic complexity: 2

func (EventHandler) MarshalJSON

MarshalJSON marshals EventHandler as per Tyk OAS API definition contract.

func (e EventHandler) MarshalJSON() ([]byte, error) {
	type helperEventHandler EventHandler
	helper := helperEventHandler(e)

	outMap, err := reflect.Cast[map[string]any](helper)
	if err != nil {
		return nil, err
	}

	outMapVal := *outMap

	switch helper.Kind {
	case WebhookKind:
		webhookMap, err := reflect.Cast[map[string]any](helper.Webhook)
		if err != nil {
			return nil, err
		}
		maps.Insert(outMapVal, maps.All(*webhookMap))
	case JSVMKind:
		jsvmMap, err := reflect.Cast[map[string]any](helper.JSVMEvent)
		if err != nil {
			return nil, err
		}
		maps.Insert(outMapVal, maps.All(*jsvmMap))
	case LogKind:
		logMap, err := reflect.Cast[map[string]any](helper.LogEvent)
		if err != nil {
			return nil, err
		}
		maps.Insert(outMapVal, maps.All(*logMap))
	}

	return json.Marshal(outMapVal)
}

Cognitive complexity: 13, Cyclomatic complexity: 9

Uses: json.Marshal, maps.All, maps.Insert, reflect.Cast.

func (Headers) Map

Map transforms Headers into a map.

func (hs Headers) Map() map[string]string {
	var headersMap = make(map[string]string, len(hs))
	for _, h := range hs {
		headersMap[h.Name] = h.Value
	}

	return headersMap
}

Cognitive complexity: 3, Cyclomatic complexity: 2

func (Paths) ExtractTo

ExtractTo extracts Paths into *apidef.ExtendedPathsSet.

func (ps Paths) ExtractTo(ep *apidef.ExtendedPathsSet) {
	var paths []string
	for path := range ps {
		paths = append(paths, path)
	}

	sort.Strings(paths)

	for _, path := range paths {
		ps[path].ExtractTo(ep, path)
	}
}

Cognitive complexity: 6, Cyclomatic complexity: 3

Uses: sort.Strings.

func (Paths) Fill

Fill fills *Paths (map) from apidef.ExtendedPathSet.

func (ps Paths) Fill(ep apidef.ExtendedPathsSet) {
	ps.fillAllowance(ep.WhiteList, allow)
	ps.fillAllowance(ep.BlackList, block)
	ps.fillAllowance(ep.Ignored, ignoreAuthentication)
	ps.fillTransformRequestMethod(ep.MethodTransforms)
	ps.fillCache(ep.AdvanceCacheConfig)
	ps.fillEnforceTimeout(ep.HardTimeouts)
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (PinnedPublicKeys) ExtractTo

ExtractTo extracts PinnedPublicKeys values into the publicKeys map.

func (ppk PinnedPublicKeys) ExtractTo(publicKeys map[string]string) {
	for _, publicKey := range ppk {
		publicKeys[publicKey.Domain] = strings.Join(publicKey.PublicKeys, ",")
	}
}

Cognitive complexity: 3, Cyclomatic complexity: 2

Uses: strings.Join.

func (PinnedPublicKeys) Fill

Fill fills *PinnerPublicKeys (slice) from publicKeys argument.

func (ppk PinnedPublicKeys) Fill(publicKeys map[string]string) {
	domains := make([]string, len(publicKeys))

	i := 0
	for domain := range publicKeys {
		domains[i] = domain
		i++
	}

	sort.Slice(domains, func(i, j int) bool {
		return domains[i] < domains[j]
	})

	i = 0
	for _, domain := range domains {
		ppk[i] = PinnedPublicKey{Domain: domain, PublicKeys: strings.Split(strings.ReplaceAll(publicKeys[domain], " ", ""), ",")}
		i++
	}
}

Cognitive complexity: 8, Cyclomatic complexity: 3

Uses: sort.Slice, strings.ReplaceAll, strings.Split.

func (SecuritySchemes) GetBaseIdentityProvider

GetBaseIdentityProvider returns the identity provider by precedence from SecuritySchemes.

func (ss SecuritySchemes) GetBaseIdentityProvider() (res apidef.AuthTypeEnum) {
	if len(ss) < 2 {
		return
	}

	resBaseIdentityProvider := baseIdentityProviderPrecedence(apidef.AuthTypeNone)
	res = apidef.OAuthKey

	for _, scheme := range ss {
		if _, ok := scheme.(*Token); ok {
			return apidef.AuthToken
		}

		if _, ok := scheme.(*JWT); ok {
			if baseIdentityProviderPrecedence(apidef.JWTClaim) < resBaseIdentityProvider {
				resBaseIdentityProvider = baseIdentityProviderPrecedence(apidef.JWTClaim)
				res = apidef.JWTClaim
			}
		}
	}

	return
}

Cognitive complexity: 11, Cyclomatic complexity: 6

Uses: apidef.AuthToken, apidef.AuthTypeNone, apidef.JWTClaim, apidef.OAuthKey.

func (SecuritySchemes) Import

Import takes the openapi3.SecurityScheme as argument and applies it to the receiver. The SecuritySchemes receiver is a map, so modification of the receiver is enabled, regardless of the fact that the receiver isn't a pointer type. The map is a pointer type itself.

func (ss SecuritySchemes) Import(name string, nativeSS *openapi3.SecurityScheme, enable bool) error {
	switch {
	case nativeSS.Type == typeAPIKey:
		token := &Token{}
		if ss[name] == nil {
			ss[name] = token
		} else {
			if tokenVal, ok := ss[name].(*Token); ok {
				token = tokenVal
			} else {
				toStructIfMap(ss[name], token)
			}
		}

		token.Import(nativeSS, enable)
	case nativeSS.Type == typeHTTP && nativeSS.Scheme == schemeBearer && nativeSS.BearerFormat == bearerFormatJWT:
		jwt := &JWT{}
		if ss[name] == nil {
			ss[name] = jwt
		} else {
			if jwtVal, ok := ss[name].(*JWT); ok {
				jwt = jwtVal
			} else {
				toStructIfMap(ss[name], jwt)
			}
		}

		jwt.Import(enable)
	case nativeSS.Type == typeHTTP && nativeSS.Scheme == schemeBasic:
		basic := &Basic{}
		if ss[name] == nil {
			ss[name] = basic
		} else {
			if basicVal, ok := ss[name].(*Basic); ok {
				basic = basicVal
			} else {
				toStructIfMap(ss[name], basic)
			}
		}

		basic.Import(enable)
	case nativeSS.Type == typeOAuth2:
		oauth := &OAuth{}
		if ss[name] == nil {
			ss[name] = oauth
		} else {
			if oauthVal, ok := ss[name].(*OAuth); ok {
				oauth = oauthVal
			} else {
				toStructIfMap(ss[name], oauth)
			}
		}

		oauth.Import(enable)
	default:
		return fmt.Errorf(unsupportedSecuritySchemeFmt, name)
	}

	return nil
}

Cognitive complexity: 42, Cyclomatic complexity: 17

Uses: fmt.Errorf.

func (URLRewriteInput) Err

Err returns an error if the type value is invalid, nil otherwise.

func (i URLRewriteInput) Err() error {
	if !i.Valid() {
		return fmt.Errorf("Invalid value for URL rewrite input: %s", i)
	}
	return nil
}

Cognitive complexity: 2, Cyclomatic complexity: 2

Uses: fmt.Errorf.

func (URLRewriteInput) Index

Index returns the cardinal order for the value. Used for sorting.

func (i URLRewriteInput) Index() int {
	for k, v := range URLRewriteInputs {
		if v == i {
			return k
		}
	}
	return -1
}

Cognitive complexity: 5, Cyclomatic complexity: 3

func (URLRewriteInput) Valid

Valid returns true if the type value matches valid values, false otherwise.

func (i URLRewriteInput) Valid() bool {
	switch i {
	case InputQuery, InputPath, InputHeader, InputSessionMetadata, InputRequestBody, InputRequestContext:
		return true
	}
	return false
}

Cognitive complexity: 3, Cyclomatic complexity: 3

func (pathPart) String

func (p pathPart) String() string {
	if p.isRegex {
		return "{" + p.name + "}"
	}

	return p.value
}

Cognitive complexity: 2, Cyclomatic complexity: 2

Private functions

func baseIdentityProviderPrecedence

baseIdentityProviderPrecedence (authType apidef.AuthTypeEnum) int
References: apidef.AuthToken, apidef.BasicAuthUser, apidef.JWTClaim, apidef.OAuthKey.

func buildPath

buildPath converts the URL paths with regex to named parameters e.g. ["a", ".*"] becomes /a/{customRegex1}.

buildPath (parts []pathPart, appendSlash bool) string

func clearClassicAPIForSomeFeatures

clearClassicAPIForSomeFeatures clears some features that will be OAS-only. For example, the new validate request will just be valid for OAS APIs so after migrating from classic API definition the existing feature should be cleared to prevent ValidateJSON middleware interference.

clearClassicAPIForSomeFeatures (api *apidef.APIDefinition)

func convertSchema

convertSchema (mapSchema map[string]interface{}) (*openapi3.Schema, error)
References: json.Marshal, openapi3.NewSchema.

func detectMockResponseContentType

detectMockResponseContentType determines the Content-Type of the mock response. It first checks the headers for an explicit Content-Type, then attempts to detect the type from the body content. Returns "text/plain" if no specific type can be determined.

detectMockResponseContentType (mock apidef.MockResponseMeta) string
References: http.CanonicalHeaderKey, json.RawMessage, json.Unmarshal.

func emptyExampleVal

emptyExampleVal (schema *openapi3.Schema) interface{}
References: openapi3.TypeBoolean, openapi3.TypeInteger, openapi3.TypeNumber, openapi3.TypeString.

func findDefaultVersion

findDefaultVersion (rawVersions []string) string
References: pkgver.Collection, pkgver.NewVersion, pkgver.Version, sort.Sort.

func generateUrlUsingDefaultVariableValues

generateUrlUsingDefaultVariableValues (s *OAS, upstreamURL string) (string, error)
References: errors.New, fmt.Errorf, strings.Contains.

func getMinorVersion

getMinorVersion (version string) (string, error)
References: fmt.Sprintf, pkgver.NewVersion.

func getQueryValPtr

getQueryValPtr (val string) *bool
References: strconv.ParseBool.

func getURLFormatErr

getURLFormatErr (fromParam bool, upstreamURL string) error
References: fmt.Errorf, fmt.Sprintf, url.Parse.

func hasMockResponse

hasMockResponse returns true if any method action has a Reply action type. This is used to determine if an endpoint should be treated as a mock response.

hasMockResponse (methodActions map[string]apidef.EndpointMethodMeta) bool
References: apidef.Reply.

func isIdentifier

isIdentifier (value string) bool
References: regexp.MatchString.

func isRegex

isRegex checks if value has expected regular expression patterns.

isRegex (value string) bool
References: strings.Contains.

func isURLParametrized

isURLParametrized (url string) bool
References: strings.Contains.

func loadOASSchema

loadOASSchema () error
References: filepath.Join, fmt.Errorf, fmt.Sprintf, jsonparser.Delete, jsonparser.ObjectEach, jsonparser.Set, jsonparser.ValueType, strings.HasSuffix, strings.TrimSuffix.

func newAllowance

newAllowance (prev **Allowance) *Allowance

func parseMuxTemplate

parseMuxTemplate parses a segment that is a mux template and extracts the name or assigns a custom regex name.

parseMuxTemplate (segment string, regexCount int) (pathPart, int, bool)
References: fmt.Sprintf, strings.Cut, strings.Trim.

func parsePathSegment

parsePathSegment parses a single path segment and determines if it contains a regex pattern.

parsePathSegment (segment string, regexCount int, hasRegex bool) (pathPart, int, bool)
References: fmt.Sprintf, strings.HasPrefix, strings.HasSuffix.

func replaceParameterWithValue

replaceParameterWithValue (url string, name string, value string) string
References: strings.ReplaceAll.

func requireMainVersion

requireMainVersion (api *apidef.APIDefinition) apidef.VersionInfo
References: apidef.VersionInfo.

func resetOASSupportedEventHandlers

resetOASSupportedEventHandlers (api *apidef.APIDefinition)
References: apidef.EventHandlerTriggerConfig, apidef.TykEvent, event.JSVMHandler, event.LogHandler, event.WebHookHandler.

func resetSecuritySchemes

resetSecuritySchemes (api *apidef.APIDefinition)
References: apidef.ExternalOAuth, apidef.MiddlewareDefinition, apidef.MiddlewareIdExtractor, apidef.NotificationsManager, apidef.OpenIDOptions, apidef.ScopeClaim.

func setAuthorizationURLIfEmpty

setAuthorizationURLIfEmpty (flow *openapi3.OAuthFlow)

func setDefaultVersion

setDefaultVersion ()

func setScopesIfEmpty

setScopesIfEmpty (flow *openapi3.OAuthFlow)

func setTokenURLIfEmpty

setTokenURLIfEmpty (flow *openapi3.OAuthFlow)

func sortMockResponseAllowList

sortMockResponseAllowList sorts the mock response paths by path, method, and response code. This ensures a deterministic order of mock responses.

sortMockResponseAllowList (ep *apidef.ExtendedPathsSet)
References: sort.Slice.

func splitPath

splitPath splits URL into folder parts, detecting regex patterns.

splitPath (inPath string) ([]pathPart, bool)
References: strings.Split, strings.Trim.

func toStructIfMap

toStructIfMap (input interface{}, val interface{}) bool
References: json.Marshal, json.Unmarshal.

func updateMainVersion

updateMainVersion (api *apidef.APIDefinition, updatedMainVersion apidef.VersionInfo)

func validateJSON

validateJSON (schema,document []byte) error
References: errors.New, gojsonschema.NewBytesLoader, gojsonschema.Validate, multierror.Append, multierror.Error, tykerrors.Formatter.

func extractContextVariablesTo

extractContextVariablesTo (api *apidef.APIDefinition)

func extractIgnoreCase

extractIgnoreCase (api *apidef.APIDefinition)

func extractPostAuthenticationPluginsTo

extractPostAuthenticationPluginsTo (api *apidef.APIDefinition)
References: apidef.MiddlewareDefinition.

func extractPostPluginsTo

extractPostPluginsTo (api *apidef.APIDefinition)
References: apidef.MiddlewareDefinition.

func extractPrePluginsTo

extractPrePluginsTo (api *apidef.APIDefinition)
References: apidef.MiddlewareDefinition.

func extractRequestSizeLimitTo

extractRequestSizeLimitTo (api *apidef.APIDefinition)

func extractResponsePluginsTo

extractResponsePluginsTo (api *apidef.APIDefinition)
References: apidef.MiddlewareDefinition.

func extractSkipsTo

extractSkipsTo (api *apidef.APIDefinition)

func extractTrafficLogsTo

extractTrafficLogsTo (api *apidef.APIDefinition)

func fillContextVariables

fillContextVariables (api apidef.APIDefinition)

func fillIgnoreCase

fillIgnoreCase (api apidef.APIDefinition)

func fillRequestSizeLimit

fillRequestSizeLimit (api apidef.APIDefinition)

func fillSkips

fillSkips (api apidef.APIDefinition)

func fillTrafficLogs

fillTrafficLogs (api apidef.APIDefinition)

func shouldImport

shouldImport (operation *openapi3.Operation) bool

func appendSecurity

appendSecurity (name string)
References: openapi3.NewSecurityRequirement.

func deleteTykOperationIfEmpty

deleteTykOperationIfEmpty (tykOperation *Operation, method,path string)
References: reflect.DeepEqual.

func extractAPIKeySchemeTo

extractAPIKeySchemeTo (ac *apidef.AuthConfig, name string)

func extractBasicTo

extractBasicTo (api *apidef.APIDefinition, name string)
References: apidef.AuthConfig, apidef.BasicType.

func extractExternalOAuthTo

extractExternalOAuthTo (api *apidef.APIDefinition, name string)
References: apidef.AuthConfig, apidef.ExternalOAuthType, apidef.Provider.

func extractJWTTo

extractJWTTo (api *apidef.APIDefinition, name string)
References: apidef.AuthConfig, apidef.JWTType.

func extractOAuthSchemeTo

extractOAuthSchemeTo (api *apidef.APIDefinition, name string)
References: osin.AUTHORIZATION_CODE, osin.CLIENT_CREDENTIALS, osin.IMPLICIT, osin.PASSWORD.

func extractOAuthTo

extractOAuthTo (api *apidef.APIDefinition, name string)
References: apidef.AuthConfig, apidef.OAuthType, osin.AccessRequestType, osin.REFRESH_TOKEN.

func extractPathsAndOperations

extractPathsAndOperations (ep *apidef.ExtendedPathsSet)
References: oasutil.SortByPathLength.

func extractSecurityTo

extractSecurityTo (api *apidef.APIDefinition)
References: apidef.AuthConfig.

func extractTokenTo

extractTokenTo (api *apidef.APIDefinition, name string)
References: apidef.AuthConfig, apidef.AuthTokenType.

func fillAPIKeyScheme

fillAPIKeyScheme (ac *apidef.AuthConfig)
References: openapi3.NewSecurityScheme, openapi3.SecuritySchemeRef.

func fillAllowance

fillAllowance (endpointMetas []apidef.EndPointMeta, typ AllowanceType)

func fillBasic

fillBasic (api apidef.APIDefinition)
References: apidef.BasicType, openapi3.NewSecurityScheme, openapi3.SecuritySchemeRef.

func fillCache

fillCache (metas []apidef.CacheMeta)

func fillCircuitBreaker

fillCircuitBreaker (metas []apidef.CircuitBreakerMeta)

func fillDoNotTrackEndpoint

fillDoNotTrackEndpoint (metas []apidef.TrackEndpointMeta)

func fillEndpointPostPlugins

fillEndpointPostPlugins (endpointMetas []apidef.GoPluginMeta)

func fillEnforceTimeout

fillEnforceTimeout (metas []apidef.HardTimeoutMeta)

func fillExternalOAuth

fillExternalOAuth (api apidef.APIDefinition)
References: apidef.AuthConfig, apidef.ExternalOAuthType.

func fillInternal

fillInternal (metas []apidef.InternalMeta)

func fillJWT

fillJWT (api apidef.APIDefinition)
References: apidef.JWTType, openapi3.NewSecurityScheme, openapi3.SecuritySchemeRef.

func fillMockResponsePaths

fillMockResponsePaths converts classic API mock responses to OAS format. This method only handles direct mock response conversions, as other middleware configurations (like allow lists, block lists, etc.) are converted to classic API mock responses in an earlier step of the process.

For each mock response, it:

  1. Creates an OAS operation with a unique ID (if it doesn't exist)
  2. Sets up the mock response with content type detection and example values
  3. Configures the operation to ignore authentication for this endpoint

The content type is determined by:

  • Checking the Content-Type header if present
  • Attempting to parse the body as JSON
  • Defaulting to text/plain if neither above applies

fillMockResponsePaths (paths openapi3.Paths, ep apidef.ExtendedPathsSet)
References: openapi3.NewResponses, openapi3.Operation, openapi3.Response, openapi3.ResponseRef, strconv.Itoa.

func fillOASValidateRequest

fillOASValidateRequest (metas []apidef.ValidatePathMeta)
References: openapi3.NewRequestBody, openapi3.RequestBodyRef.

func fillOAuth

fillOAuth (api apidef.APIDefinition)
References: apidef.OAuthType, osin.REFRESH_TOKEN.

func fillOAuthScheme

fillOAuthScheme (accessTypes []osin.AccessRequestType, name string)
References: openapi3.NewSecurityScheme, openapi3.OAuthFlow, openapi3.OAuthFlows, openapi3.SecuritySchemeRef, osin.AUTHORIZATION_CODE, osin.CLIENT_CREDENTIALS, osin.IMPLICIT, osin.PASSWORD.

func fillOAuthSchemeForExternal

fillOAuthSchemeForExternal (name string)
References: openapi3.NewSecurityScheme, openapi3.OAuthFlow, openapi3.OAuthFlows, openapi3.SecuritySchemeRef.

func fillPathsAndOperations

fillPathsAndOperations (ep apidef.ExtendedPathsSet)
References: openapi3.Paths.

func fillRateLimitEndpoints

fillRateLimitEndpoints (endpointMetas []apidef.RateLimitMeta)

func fillRequestSizeLimit

fillRequestSizeLimit (metas []apidef.RequestSizeMeta)

func fillSecurity

fillSecurity (api apidef.APIDefinition)
References: openapi3.Components.

func fillToken

fillToken (api apidef.APIDefinition)
References: apidef.AuthTokenType.

func fillTrackEndpoint

fillTrackEndpoint (metas []apidef.TrackEndpointMeta)

func fillTransformRequestBody

fillTransformRequestBody (metas []apidef.TemplateMeta)

func fillTransformRequestHeaders

fillTransformRequestHeaders (metas []apidef.HeaderInjectionMeta)

func fillTransformRequestMethod

fillTransformRequestMethod (metas []apidef.MethodTransformMeta)

func fillTransformResponseBody

fillTransformResponseBody (metas []apidef.TemplateMeta)

func fillTransformResponseHeaders

fillTransformResponseHeaders (metas []apidef.HeaderInjectionMeta)

func fillURLRewrite

fillURLRewrite (metas []apidef.URLRewriteMeta)

func fillVirtualEndpoint

fillVirtualEndpoint (endpointMetas []apidef.VirtualMeta)

func getOperationID

getOperationID (inPath,method string) string
References: openapi3.NewResponses, openapi3.Operation, openapi3.Parameter, openapi3.ParameterRef, openapi3.PathItem, openapi3.Schema, openapi3.SchemaRef, strings.HasSuffix, strings.TrimPrefix.

func getTykAuthentication

getTykAuthentication () *Authentication

func getTykBasicAuth

getTykBasicAuth (name string) *Basic

func getTykExternalOAuthAuth

getTykExternalOAuthAuth (name string) *ExternalOAuth

func getTykJWTAuth

getTykJWTAuth (name string) *JWT

func getTykOAuthAuth

getTykOAuthAuth (name string) *OAuth

func getTykOperation

getTykOperation (method,path string) *Operation

func getTykOperations

getTykOperations () Operations

func getTykSecurityScheme

getTykSecurityScheme (name string) interface{}

func getTykSecuritySchemes

getTykSecuritySchemes () SecuritySchemes

func getTykTokenAuth

getTykTokenAuth (name string) *Token

func importAuthentication

importAuthentication (enable bool) error

func importMiddlewares

importMiddlewares (overRideValues TykExtensionConfigParams)

func setRequiredFields

setRequiredFields sets some required fields to make OAS object a valid one.

setRequiredFields (name string, versionName string)
References: openapi3.Info.

func validateSecurity

validateSecurity verifies that existing Security Requirement Objects has Security Schemes declared in the Security Schemes under the Components Object. This function closes gap in validation provided by OAS.Validate func.

validateSecurity () error
References: errors.New, fmt.Sprintf.

func extractAllowanceTo

extractAllowanceTo (ep *apidef.ExtendedPathsSet, path string, method string, typ AllowanceType)
References: apidef.EndPointMeta.

func extractCacheTo

extractCacheTo (ep *apidef.ExtendedPathsSet, path string, method string)
References: apidef.CacheMeta.

func extractCircuitBreakerTo

extractCircuitBreakerTo (ep *apidef.ExtendedPathsSet, path string, method string)
References: apidef.CircuitBreakerMeta.

func extractDoNotTrackEndpointTo

extractDoNotTrackEndpointTo (ep *apidef.ExtendedPathsSet, path string, method string)
References: apidef.TrackEndpointMeta.

func extractEndpointPostPluginTo

extractEndpointPostPluginTo (ep *apidef.ExtendedPathsSet, path string, method string)
References: apidef.GoPluginMeta.

func extractEnforceTimeoutTo

extractEnforceTimeoutTo (ep *apidef.ExtendedPathsSet, path string, method string)
References: apidef.HardTimeoutMeta.

func extractInternalTo

extractInternalTo (ep *apidef.ExtendedPathsSet, path string, method string)
References: apidef.InternalMeta.

func extractRateLimitEndpointTo

extractRateLimitEndpointTo (ep *apidef.ExtendedPathsSet, path string, method string)
References: apidef.RateLimitMeta.

func extractRequestSizeLimitTo

extractRequestSizeLimitTo (ep *apidef.ExtendedPathsSet, path string, method string)
References: apidef.RequestSizeMeta.

func extractTrackEndpointTo

extractTrackEndpointTo (ep *apidef.ExtendedPathsSet, path string, method string)
References: apidef.TrackEndpointMeta.

func extractTransformRequestBodyTo

extractTransformRequestBodyTo (ep *apidef.ExtendedPathsSet, path string, method string)
References: apidef.TemplateMeta.

func extractTransformRequestHeadersTo

extractTransformRequestHeadersTo (ep *apidef.ExtendedPathsSet, path string, method string)
References: apidef.HeaderInjectionMeta.

func extractTransformRequestMethodTo

extractTransformRequestMethodTo (ep *apidef.ExtendedPathsSet, path string, method string)
References: apidef.MethodTransformMeta.

func extractTransformResponseBodyTo

extractTransformResponseBodyTo (ep *apidef.ExtendedPathsSet, path string, method string)
References: apidef.TemplateMeta.

func extractTransformResponseHeadersTo

extractTransformResponseHeadersTo (ep *apidef.ExtendedPathsSet, path string, method string)
References: apidef.HeaderInjectionMeta.

func extractURLRewriteTo

extractURLRewriteTo (ep *apidef.ExtendedPathsSet, path string, method string)
References: apidef.URLRewriteMeta.

func extractVirtualEndpointTo

extractVirtualEndpointTo (ep *apidef.ExtendedPathsSet, path string, method string)
References: apidef.VirtualMeta.

func getMethod

getMethod (name string) *Plugins
References: http.MethodConnect, http.MethodDelete, http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodPatch, http.MethodPost, http.MethodPut, http.MethodTrace, strings.EqualFold.

func extractAllowanceTo

extractAllowanceTo (ep *apidef.ExtendedPathsSet, path string, method string, typ AllowanceType)
References: apidef.EndPointMeta.

func extractCacheTo

extractCacheTo (ep *apidef.ExtendedPathsSet, path string, method string)
References: apidef.CacheMeta.

func extractEnforcedTimeoutTo

extractEnforcedTimeoutTo (ep *apidef.ExtendedPathsSet, path string, method string)
References: apidef.HardTimeoutMeta.

func extractTransformRequestMethodTo

extractTransformRequestMethodTo (ep *apidef.ExtendedPathsSet, path string, method string)
References: apidef.MethodTransformMeta.

func extractBatchProcessingTo

extractBatchProcessingTo (api *apidef.APIDefinition)

func extractIPAccessControlTo

extractIPAccessControlTo (api *apidef.APIDefinition)

func fillBatchProcessing

fillBatchProcessing (api apidef.APIDefinition)

func fillIPAccessControl

fillIPAccessControl (api apidef.APIDefinition)

func tlsVersionFromString

tlsVersionFromString converts v in the form of 1.2/1.3 to the version int

tlsVersionFromString (v string) uint16
References: tls.VersionTLS10, tls.VersionTLS11, tls.VersionTLS12, tls.VersionTLS13.

func tlsVersionToString

tlsVersionFromString converts v from version into to the form 1.0/1.1

tlsVersionToString (v uint16) string
References: tls.VersionTLS10, tls.VersionTLS11, tls.VersionTLS12, tls.VersionTLS13.

func appendRules

appendRules (rules *[]*URLRewriteRule, from map[string]apidef.StringRegexMap, in URLRewriteInput)

func extractTriggerOptions

extractTriggerOptions (rules []*URLRewriteRule) apidef.RoutingTriggerOptions
References: apidef.NewRoutingTriggerOptions, apidef.StringRegexMap.

func extractTriggers

extractTriggers () []apidef.RoutingTrigger
References: apidef.RoutingTrigger, apidef.RoutingTriggerOnType.

func fillRules

fillRules (from apidef.RoutingTriggerOptions) []*URLRewriteRule
References: apidef.StringRegexMap.

func fillTriggers

fillTriggers (from []apidef.RoutingTrigger) []*URLRewriteTrigger

func fillLoadBalancing

fillLoadBalancing (api apidef.APIDefinition)

func fillPreserveHostHeader

fillPreserveHostHeader (api apidef.APIDefinition)

func fillPreserveTrailingSlash

fillPreserveTrailingSlash (api apidef.APIDefinition)

func loadBalancingExtractTo

loadBalancingExtractTo (api *apidef.APIDefinition)

func preserveHostHeaderExtractTo

preserveHostHeaderExtractTo (api *apidef.APIDefinition)

func preserveTrailingSlashExtractTo

preserveTrailingSlashExtractTo (api *apidef.APIDefinition)

func fillRequestSigning

fillRequestSigning (api apidef.APIDefinition)

func requestSigningExtractTo

requestSigningExtractTo (api *apidef.APIDefinition)

func extractToProtocolAndCheckURL

extractToProtocolAndCheckURL splits a URL into its protocol and the remaining part of the URL, returning both as strings. Classic has a special field for protocol while OAS only has checkURL. The protocol should remain inside checkURL.

extractToProtocolAndCheckURL (checkURL string) string
References: strings.Split.

func fillCheckURL

fillCheckURL constructs a valid URL by appending the protocol to the provided URL, removing any existing protocol. This needs to be done because classic can have invalid protocol and checkURL combinations, e.g. protocol=tcp, checkURL=https://myservice.fake

fillCheckURL (protocol string, checkURL string) string
References: fmt.Sprintf, strings.Split.

func shouldImport

shouldImport (operation *openapi3.Operation) bool

func enableContextVariablesIfEmpty

enableContextVariablesIfEmpty enables context variables in middleware.global.contextVariables. Context variables will be set only if it is not set, if it is already set to false, it won't be enabled.

enableContextVariablesIfEmpty ()

func enableTrafficLogsIfEmpty

enableTrafficLogsIfEmpty enables traffic logs in middleware.global.trafficLogs. Traffic logs will be set only if it is not set. If it is already set to false, it won't be enabled.

enableTrafficLogsIfEmpty ()

func getOperation

getOperation (operationID string) *Operation

func fillAllowance

fillAllowance (endpointMetas []apidef.EndPointMeta, typ AllowanceType)

func fillCache

fillCache (cacheMetas []apidef.CacheMeta)

func fillEnforceTimeout

fillEnforceTimeout (metas []apidef.HardTimeoutMeta)

func fillTransformRequestMethod

fillTransformRequestMethod (metas []apidef.MethodTransformMeta)


Tests

Files: 18. Third party imports: 4. Imports from organisation: 2. Tests: 133. Benchmarks: 1.

Vars

Map HTTP methods to their corresponding PathItem field setters

var methodSetters = map[string]func(*openapi3.PathItem, *openapi3.Operation){
	"GET":		func(p *openapi3.PathItem, op *openapi3.Operation) { p.Get = op },
	"POST":		func(p *openapi3.PathItem, op *openapi3.Operation) { p.Post = op },
	"PUT":		func(p *openapi3.PathItem, op *openapi3.Operation) { p.Put = op },
	"PATCH":	func(p *openapi3.PathItem, op *openapi3.Operation) { p.Patch = op },
	"DELETE":	func(p *openapi3.PathItem, op *openapi3.Operation) { p.Delete = op },
	"HEAD":		func(p *openapi3.PathItem, op *openapi3.Operation) { p.Head = op },
	"OPTIONS":	func(p *openapi3.PathItem, op *openapi3.Operation) { p.Options = op },
}
var oasTemplateFS embed.FS
var urlRewriteFS embed.FS
var urlSortingFS embed.FS

Types

subStruct

This type doesn't have documentation.

Field name Field type Comment
SubMap

map[string]string

No comment on field.
type subStruct struct {
	SubMap map[string]string
}

testStruct

This type doesn't have documentation.

Field name Field type Comment
Bool

bool

No comment on field.
Array

[]string

No comment on field.
Map

map[string]string

No comment on field.
SubStruct

*subStruct

No comment on field.
type testStruct struct {
	Bool		bool
	Array		[]string
	Map		map[string]string
	SubStruct	*subStruct
}

Test functions

TestAPIContext_getValidationOptionsFromConfig

References: assert.Len, assert.Nil, config.New, testing.T.

TestAuthSource

References: apidef.AuthConfig, assert.Equal, testing.T.

TestAuthSources

References: apidef.AuthConfig, assert.Equal.

TestAuthSources_Import

References: assert.Equal, testing.T.

TestAuthentication

References: apidef.APIDefinition, assert.Equal.

TestAuthenticationPlugin

References: apidef.APIDefinition, assert.Equal, testing.T.

TestBasic_Import

References: assert.Equal.

TestBatchProcessing

References: apidef.APIDefinition, assert.Equal, testing.T.

TestCORS

References: apidef.CORSConfig, assert.Equal.

TestCache

References: apidef.CacheOptions, assert.Equal.

TestCacheOptions

References: assert.Equal, testing.T.

TestCachePlugin_Fill

References: apidef.CacheMeta, apidef.DefaultCacheTimeout, assert.Empty, assert.Equal, assert.False, assert.Nil, assert.True, testing.T.

TestCertificatePinning

References: apidef.APIDefinition, assert.ElementsMatch, assert.Equal, testing.T.

TestCircuitBreaker

References: apidef.CircuitBreakerMeta, assert.Equal, testing.T.

TestClientCertificates

References: apidef.APIDefinition, assert.Equal.

TestContextVariables

References: apidef.APIDefinition, assert.Equal, testing.T.

TestCustomDomain

References: apidef.APIDefinition, assert.Equal, assert.Equalf, testing.T.

TestCustomPlugin

References: apidef.APIDefinition, assert.Empty, assert.Equal, assert.NotEmpty, testing.T.

TestCustomPlugins

References: apidef.MiddlewareDefinition, assert.Equal, assert.False, assert.Nil, assert.True, testing.T.

TestEndpointPostPlugins

References: apidef.GoPluginMeta, assert.Contains, assert.Equal, assert.NoError, assert.NotContains, json.Marshal, testing.T.

TestEventHandler_MarshalJSON

References: assert.EqualValues, assert.NoError, event.JSVMKind, event.LogKind, event.QuotaExceeded, event.WebhookKind, http.MethodPost, json.Marshal, json.Unmarshal, testing.T, time.Second.

TestEventHandler_UnmarshalJSON

References: assert.EqualValues, assert.NoError, event.JSVMKind, event.LogKind, event.QuotaExceeded, event.WebhookKind, http.MethodPost, json.Marshal, json.Unmarshal, testing.T, time.Second.

TestEventHandlers

References: apidef.APIDefinition, apidef.EventHandlerMetaConfig, apidef.EventHandlerTriggerConfig, apidef.TykEvent, assert.ElementsMatch, assert.Equal, event.BreakerTriggered, event.Event, event.JSVMHandler, event.JSVMKind, event.Kind, event.LogHandler, event.LogKind, event.QuotaExceeded, event.RateLimitExceeded, event.WebHookHandler, event.WebhookKind, http.MethodPost, testing.T, time.Second.

TestExportDetailedTracing

References: apidef.APIDefinition, assert.Equal, testing.T.

TestExtendedPaths

References: apidef.ExtendedPathsSet, assert.Equal, testing.T.

TestFillDetailedTracing

References: apidef.APIDefinition, assert.Equal, testing.T.

TestGatewayTags

References: apidef.APIDefinition, assert.Equal, assert.Nil, fmt.Sprintf, testing.T.

TestGetOASSchema

References: assert.Equal, assert.NoError, assert.NotEmpty, fmt.Errorf, testing.T.

TestGetOperationID

References: openapi3.Parameter, openapi3.ParameterRef, openapi3.PathItem, openapi3.Paths, openapi3.Schema, openapi3.SchemaRef, openapi3.T, testing.T.

TestGetTykExtensionConfigParams

References: assert.Equal, assert.Nil, assert.NoError, http.MethodPatch, http.NewRequest, testing.T, url.Parse.

TestGlobal

References: apidef.APIDefinition, assert.Equal, assert.Nil, assert.NoError, assert.NotNil, json.Marshal, json.Unmarshal, testing.T.

TestGlobalRequestSizeLimit

References: apidef.APIDefinition, apidef.VersionData, apidef.VersionInfo, assert.Equal, testing.T.

TestHMAC

References: apidef.APIDefinition, assert.Equal.

TestHeaders_Map

References: assert.Equal.

TestIDExtractor

References: apidef.APIDefinition, apidef.HeaderSource, apidef.ValueExtractor, assert.Equal, testing.T.

TestIDExtractorConfig

References: apidef.APIDefinition, assert.Equal, testing.T.

TestIPAccessControl

References: apidef.APIDefinition, assert.Equal, assert.False, testing.T.

TestInfo

References: apidef.APIDefinition, assert.Equal.

TestInternal_ExtractTo

References: apidef.InternalMeta, assert.Equal.

TestInternal_Fill

References: apidef.InternalMeta, assert.Equal.

TestJWT_Import

References: assert.Equal.

TestKeyRetentionPeriod

References: apidef.APIDefinition, assert.Equal, assert.True, testing.T, time.Minute.

TestListenPath

References: apidef.APIDefinition, assert.Equal.

TestLoadBalancing

References: apidef.APIDefinition, apidef.ProxyConfig, assert.Equal, testing.T.

TestMiddleware

References: apidef.APIDefinition, assert.Equal, testing.T.

TestMigrateAndFillOAS

References: apidef.APIDefinition, apidef.DefaultAPIVersionKey, apidef.EndPointMeta, apidef.EndpointMethodMeta, apidef.ErrMigrationNewVersioningEnabled, apidef.ExtendedPathsSet, apidef.HeaderLocation, apidef.VersionInfo, assert.Equal, assert.ErrorContains, assert.ErrorIs, assert.Len, assert.NoError, assert.True, context.Background, http.MethodGet, testing.T.

TestMigrateAndFillOAS_CustomPluginAuth

References: apidef.APIDefinition, apidef.AuthConfig, apidef.CoprocessType, apidef.GoPluginDriver, apidef.MiddlewareDefinition, apidef.MiddlewareIdExtractor, apidef.MiddlewareSection, apidef.ProxyConfig, apidef.PythonDriver, apidef.VersionData, apidef.VersionInfo, assert.Equal, assert.NoError, testing.T.

TestMigrateAndFillOAS_CustomPlugins

References: apidef.APIDefinition, apidef.GoPluginDriver, apidef.MiddlewareDefinition, apidef.MiddlewareSection, apidef.ProxyConfig, apidef.VersionData, apidef.VersionInfo, assert.Equal, assert.Nil, assert.NoError, testing.T.

TestMigrateAndFillOAS_DropEmpties

References: apidef.APIDefinition, apidef.DefaultAPIVersionKey, apidef.HeaderLocation, apidef.VersionInfo, assert.Equal, assert.Nil, assert.NoError, testing.T.

TestMigrateAndFillOAS_PluginConfigData

References: apidef.APIDefinition, apidef.GoPluginDriver, apidef.MiddlewareSection, apidef.ProxyConfig, apidef.VersionData, apidef.VersionInfo, assert.Equal, assert.NoError.

TestMigrateAndFillOAS_ValidateRequest

References: apidef.APIDefinition, apidef.ExtendedPathsSet, apidef.ProxyConfig, apidef.ValidatePathMeta, apidef.VersionData, apidef.VersionInfo, assert.Equal, assert.Error, assert.Nil, assert.NoError, assert.NotNil, http.MethodPost, http.StatusTeapot, testing.T.

TestNewHeaders

References: assert.Equal.

TestOAS

References: apidef.APIDefinition, apidef.AuthConfig, apidef.AuthTokenType, assert.Equal, openapi3.Components, openapi3.NewResponses, openapi3.Operation, openapi3.Paths, testing.T.

TestOAS_AddServers

References: assert.ElementsMatch, assert.Empty, openapi3.Servers, openapi3.T, testing.T.

TestOAS_ApiKeyScheme

References: apidef.AuthConfig, assert.Equal, openapi3.Components, openapi3.SecurityRequirements, openapi3.SecurityScheme, openapi3.SecuritySchemeRef, openapi3.SecuritySchemes, testing.T.

TestOAS_AppendSecurity

References: assert.Contains, assert.Len, openapi3.SecurityRequirement, openapi3.SecurityRequirements, testing.T.

TestOAS_Basic

References: apidef.APIDefinition, apidef.AuthConfig, assert.Equal, openapi3.Components, openapi3.SecurityRequirements, openapi3.SecurityScheme, openapi3.SecuritySchemes.

TestOAS_BuildDefaultTykExtension

References: apidef.AuthToken, assert.Contains, assert.Equal, assert.EqualValues, assert.ErrorIs, assert.Nil, assert.NoError, assert.NotNil, http.MethodPost, http.StatusUnprocessableEntity, openapi3.Components, openapi3.Content, openapi3.Example, openapi3.ExampleRef, openapi3.Examples, openapi3.Info, openapi3.MediaType, openapi3.NewContentWithSchema, openapi3.NewRequestBody, openapi3.NewSchema, openapi3.NewSecurityScheme, openapi3.Operation, openapi3.Parameter, openapi3.Parameters, openapi3.Paths, openapi3.RequestBodyRef, openapi3.Response, openapi3.ResponseRef, openapi3.Responses, openapi3.Schema, openapi3.SchemaRef, openapi3.Schemas, openapi3.SecurityRequirements, openapi3.SecuritySchemeRef, openapi3.SecuritySchemes, openapi3.ServerVariable, openapi3.Servers, openapi3.T, openapi3.TypeBoolean, testing.T.

TestOAS_Clone

References: assert.Equal, assert.NoError, assert.NotEqual, assert.True, testing.T.

TestOAS_CustomPlugin

References: apidef.APIDefinition, apidef.AuthConfig, assert.Equal.

TestOAS_ExternalOAuth

References: apidef.APIDefinition, apidef.ExternalOAuthType, assert.Equal, openapi3.Components, openapi3.OAuthFlow, openapi3.OAuthFlows, openapi3.Paths, openapi3.SecurityRequirements, openapi3.SecurityScheme, openapi3.SecuritySchemes, testing.T.

TestOAS_ExtractTo_DontTouchExistingClassicFields

References: apidef.APIDefinition, apidef.ExtendedPathsSet, apidef.PersistGraphQLMeta, apidef.VersionInfo, assert.Len.

TestOAS_ExtractTo_ResetAPIDefinition

References: apidef.APIDefinition, apidef.AuthConfig, apidef.EventHandlerTriggerConfig, apidef.TykEvent, apidef.VersionInfo, assert.Empty, assert.Equal, event.JSVMHandler, event.LogHandler, event.QuotaExceeded, event.WebHookHandler.

TestOAS_GetSecuritySchemes

References: assert.Equal, assert.NoError, json.Marshal, json.Unmarshal.

TestOAS_JWT

References: apidef.APIDefinition, apidef.AuthConfig, assert.Equal, openapi3.Components, openapi3.SecurityRequirements, openapi3.SecurityScheme, openapi3.SecuritySchemes.

TestOAS_MarshalJSON

References: assert.Contains, assert.NoError, assert.NotContains, json.Marshal, openapi3.ExternalDocs, openapi3.Info, openapi3.License, openapi3.T, testing.T.

TestOAS_MockResponse_extractPathsAndOperations

References: apidef.ExtendedPathsSet, assert.Empty, openapi3.Operation, openapi3.Paths, openapi3.T, require.Len, testing.T.

TestOAS_MockResponse_fillMockResponsePaths

References: apidef.ExtendedPathsSet, apidef.MockResponseMeta, assert.Empty, assert.Len, openapi3.Info, openapi3.NewResponses, openapi3.Operation, openapi3.PathItem, openapi3.Paths, openapi3.Response, openapi3.ResponseRef, openapi3.T, require.Empty, require.Equal, require.Len, require.Nil, require.NotNil, strconv.Itoa, testing.T.

TestOAS_OAuth

References: apidef.APIDefinition, assert.Equal, openapi3.Components, openapi3.OAuthFlow, openapi3.OAuthFlows, openapi3.Paths, openapi3.SecurityRequirements, openapi3.SecurityScheme, openapi3.SecuritySchemes.

TestOAS_OIDC

References: apidef.APIDefinition, apidef.AuthConfig, assert.Equal, sort.Slice.

TestOAS_PathsAndOperations

References: apidef.ExtendedPathsSet, assert.Equal, assert.NoError, context.Background, openapi3.NewResponses, openapi3.Operation, openapi3.Paths, testing.T, time.Minute.

TestOAS_PathsAndOperationsRegex

References: assert.Equal, openapi3.NewResponses, openapi3.Operation, openapi3.Parameter, openapi3.ParameterRef, openapi3.PathItem, openapi3.Paths, openapi3.Schema, openapi3.SchemaRef.

TestOAS_PathsAndOperations_sorting

References: apidef.APIDefinition, assert.Equal.

TestOAS_RegexOperationIDs

References: assert.Equalf, openapi3.Operation, openapi3.Paths.

TestOAS_RegexPaths

References: assert.Equalf, assert.Lenf, assert.NotNilf, assert.True, assert.Truef, openapi3.Paths, strings.HasPrefix, strings.ReplaceAll.

TestOAS_ReplaceServers

References: assert.Equal, openapi3.Servers, openapi3.T, testing.T.

TestOAS_Security

References: apidef.APIDefinition, apidef.AuthConfig, apidef.AuthTokenType, assert.Equal.

TestOAS_Token

References: apidef.APIDefinition, apidef.AuthConfig, assert.Equal, openapi3.Components, openapi3.SecurityRequirements, openapi3.SecurityScheme, openapi3.SecuritySchemes.

TestOAS_Token_MultipleSecuritySchemes

References: apidef.APIDefinition, assert.Contains, assert.Len, openapi3.Components, openapi3.SecurityRequirements, openapi3.SecurityScheme, openapi3.SecuritySchemes.

TestOAS_TykAuthentication_NoOASSecurity

References: apidef.APIDefinition, assert.Equal, openapi3.Components, openapi3.Paths.

TestOAS_UpdateServers

References: assert.Equal, openapi3.Servers, openapi3.T, testing.T.

TestOAS_ValidateSecurity

References: assert.Contains, assert.Error, assert.NoError, context.Background, fmt.Sprintf, openapi3.Components, openapi3.Info, openapi3.NewJWTSecurityScheme, openapi3.NewSecurityRequirement, openapi3.Paths, openapi3.SecurityRequirements, openapi3.SecuritySchemeRef, openapi3.SecuritySchemes, openapi3.T, testing.T.

TestOAS_fillAllowance

References: apidef.EndPointMeta, apidef.EndpointMethodMeta, apidef.NoAction, apidef.Reply, assert.Empty, assert.False, assert.Nil, assert.NotNil, assert.True, http.MethodGet, openapi3.Paths, openapi3.T, testing.T.

TestOAS_importAuthentication

References: apidef.AuthToken, apidef.AuthTypeNone, assert.Equal, assert.ErrorIs, assert.Nil, assert.NoError, assert.True, openapi3.Components, openapi3.NewSecurityScheme, openapi3.SecurityRequirements, openapi3.SecuritySchemeRef, openapi3.SecuritySchemes, testing.T.

TestOAuth_Import

References: assert.Equal.

TestOIDC

References: apidef.APIDefinition, apidef.OIDProviderConfig, assert.Equal, assert.Len, testing.T.

TestPinnedPublicKeys

References: assert.Equal.

TestPluginBundle

References: apidef.APIDefinition, assert.Equal, assert.False, testing.T.

TestPluginConfig

References: apidef.APIDefinition, apidef.GoPluginDriver, apidef.GrpcDriver, apidef.LuaDriver, apidef.MiddlewareDriver, apidef.OttoDriver, apidef.PythonDriver, assert.Equal, assert.False, testing.T.

TestPluginConfigData

References: apidef.APIDefinition, assert.Equal, testing.T.

TestPostAuthenticationPlugin

References: apidef.APIDefinition, assert.Equal, testing.T.

TestPostPlugin

References: apidef.APIDefinition, assert.Equal, testing.T.

TestPrePlugin

References: apidef.APIDefinition, assert.Equal, testing.T.

TestPreserveHostHeader

References: apidef.APIDefinition, apidef.ProxyConfig, assert.Equal, testing.T.

TestResponsePlugin

References: apidef.APIDefinition, assert.Equal, testing.T.

TestRetainOldServerURL

References: assert.EqualValues, openapi3.Servers, testing.T.

TestScopes

References: apidef.ScopeClaim, assert.Equal.

TestSecuritySchemes_GetBaseIdentityProvider

References: apidef.AuthToken, apidef.AuthTypeNone, apidef.JWTClaim, apidef.OAuthKey, assert.Equal, testing.T.

TestSecuritySchemes_Import

References: assert.Equal, assert.Error, assert.NoError, fmt.Sprintf, openapi3.SecurityScheme, testing.T.

TestServer

References: apidef.APIDefinition, assert.Equal, testing.T.

TestServiceDiscovery

References: apidef.ServiceDiscoveryConfiguration, assert.Equal.

TestShouldOmit

References: assert.False, assert.True.

TestSignature

References: apidef.AuthConfig, assert.Equal.

TestSplitPath

References: assert.Equal, testing.T.

TestState

References: apidef.APIDefinition, assert.Equal.

TestTLSTransportProxy

References: apidef.APIDefinition, assert.Equal, testing.T, tls.VersionTLS12, tls.VersionTLS13.

TestTagsExportServer

References: apidef.APIDefinition, assert.Equal, testing.T.

TestToken_Import

References: assert.Equal, openapi3.SecurityScheme.

TestTrackEndpoint_ExtractTo

References: apidef.TrackEndpointMeta, assert.Equal.

TestTrackEndpoint_Fill

References: apidef.TrackEndpointMeta, assert.Equal.

TestTrafficLogs

References: apidef.APIDefinition, assert.Empty, assert.Equal, assert.False, testing.T, time.Millisecond, time.Minute.

TestTransformBody

References: apidef.RequestJSON, apidef.TemplateData, apidef.TemplateMeta, apidef.UseBlob, apidef.UseFile, assert.Equal, testing.T.

TestTransformHeaders

References: apidef.HeaderInjectionMeta, assert.Equal.

TestURLRewrite_ExtractTo

References: apidef.URLRewriteMeta, assert.Equal.

TestURLRewrite_Fill

References: apidef.URLRewriteMeta, assert.Equal.

TestUpstream

References: apidef.APIDefinition, assert.Equal, testing.T, time.Hour, time.Minute, time.Second.

TestUpstreamMutualTLS

References: apidef.APIDefinition, assert.ElementsMatch, assert.Equal, testing.T.

TestUpstreamRequestSigning

References: apidef.APIDefinition, apidef.RequestSigningMeta, assert.Equal, testing.T.

TestUptimeTests

References: apidef.HostCheckObject, apidef.UptimeTests, assert.Equal, assert.Len, assert.Nil, assert.NotContains, assert.True, http.MethodGet, json.Marshal, json.Unmarshal, reflect.DeepEqual, testing.T, time.Millisecond.

TestValidateOASObject

References: assert.ElementsMatch, assert.Equal, assert.Nil, fmt.Errorf, fmt.Sprintf, openapi3.Info, openapi3.Operation, openapi3.PathItem, openapi3.Response, openapi3.ResponseRef, openapi3.Responses, openapi3.T, strings.Split, testing.T.

TestValidateOASTemplate

References: assert.NoError, require.NoError, testing.T.

TestVersioning

References: apidef.APIDefinition, assert.Equal.

TestVirtualEndpoint

References: apidef.UseBlob, apidef.UseFile, apidef.VirtualMeta, assert.Contains, assert.Equal, assert.NoError, assert.NotContains, json.Marshal, testing.T.

TestXTykAPIGateway

References: apidef.APIDefinition, assert.Equal, assert.NoError, json.MarshalIndent, openapi3.Components, openapi3.SecurityRequirements, openapi3.SecurityScheme, openapi3.SecuritySchemes, testing.T.

TestXTykAPIGateway_EnableContextVariables

References: assert.EqualExportedValues, testing.T.

TestXTykAPIGateway_enableTrafficLogsIfEmpty

References: assert.EqualExportedValues, testing.T.

TestXTykGateway_Lint

References: assert.NoError, bytes.Buffer, bytes.NewReader, event.QuotaExceeded, event.WebhookKind, gojsonschema.NewBytesLoader, gojsonschema.NewGoLoader, gojsonschema.Validate, http.MethodPost, json.NewDecoder, json.NewEncoder, require.NoError, time.Millisecond, time.Minute, time.Second.

TestYaml

References: assert.Equal, assert.NoError, assert.True, json.Marshal, model.NewObjectID, openapi3.NewLoader, yaml.JSONToYAML.

Test_exampleExtractor

References: assert.Equal, assert.NoError, context.Background, openapi3.SchemaRef, testing.T.

Test_findDefaultVersion

References: assert.Equal, testing.T.

Test_loadOASSchema

References: assert.Nil, assert.NoError, assert.NotNil, jsonparser.Get, testing.T.

Test_setDefaultVersion

References: assert.Equal, assert.NoError.

Test_toStructIfMap

References: assert.Equal, json.Marshal, json.Unmarshal.

Benchmark functions

BenchmarkOAS_Clone

References: assert.NoError, openapi3.Info, openapi3.Operation, openapi3.PathItem, openapi3.Response, openapi3.ResponseRef, openapi3.Responses, openapi3.T.