Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Start Generating Swagger generation from the code. #6123

Open
wants to merge 107 commits into
base: master
Choose a base branch
from

Conversation

yurisasuke
Copy link
Member

@yurisasuke yurisasuke commented Mar 7, 2024

User description

Type

enhancement


Description

  • Introduced functionality to generate OpenAPI Specification (OAS) for classic API endpoints.
  • Implemented main function in swagger/cmd/main.go to generate and write the OpenAPI 3.0.3 spec to open.yaml.
  • Added necessary dependencies for OpenAPI spec generation.
  • Generated detailed OpenAPI 3.0.3 specification for the Tyk Gateway API, including paths, components, and schemas.

Changes walkthrough

Relevant files
Enhancement
classic_api.go
Add OpenAPI Spec Generation for Classic API                           

swagger/classic_api.go

  • Introduced APIS and GetClassicApiRequest functions for generating
    OpenAPI Specification (OAS) for classic API endpoints.
  • Utilizes openapi3.Reflector to define API operations.
  • +27/-0   
    main.go
    Implement Main Function for OAS Generation                             

    swagger/cmd/main.go

  • Implemented main function to generate OpenAPI 3.0.3 YAML
    specification.
  • Configures openapi3.Reflector with Tyk Gateway API information and
    writes the generated spec to open.yaml.
  • +46/-0   
    Dependencies
    go.mod
    Update Dependencies for OpenAPI Spec Generation                   

    go.mod

  • Added dependencies for jsonschema-go, openapi-go, and refl to support
    OpenAPI spec generation.
  • +3/-0     
    go.sum
    Update go.sum with New Dependencies                                           

    go.sum

    • Updated go.sum with new dependencies for OpenAPI spec generation.
    +7/-0     
    Documentation
    open.yaml
    Generate OpenAPI 3.0.3 Specification for Tyk Gateway API 

    swagger/cmd/open.yaml

  • Generated OpenAPI 3.0.3 specification YAML for the Tyk Gateway API.
  • Includes detailed API paths, components, and schemas definitions.
  • +1473/-0

    PR-Agent usage:
    Comment /help on the PR to get a list of all available PR-Agent tools and their descriptions


    PR Type

    Enhancement, Documentation


    Description

    • Introduced comprehensive OpenAPI 3.0.3 support for API documentation and schema generation.
    • Added OAuth API operations for managing clients and tokens, including creation, updates, and token revocation.
    • Implemented key management functionalities such as creation, deletion, updates, and hashed key support.
    • Enhanced support for managing APIs in OpenAPI Specification (OAS) format, including export and import capabilities.
    • Improved error handling, logging, and documentation annotations across various modules.

    Changes walkthrough 📝

    Relevant files
    Enhancement
    6 files
    shared.go
    Add OpenAPI 3.0.3 schema and parameter utilities.               

    swagger/shared.go

  • Introduced utility functions for OpenAPI 3.0.3 schema and parameter
    handling.
  • Added support for reusable examples, parameters, and schemas in
    OpenAPI specifications.
  • Defined structures and methods for managing API operations with
    examples and responses.
  • +970/-0 
    oauth.go
    Implement OAuth API operations and token management.         

    swagger/oauth.go

  • Added OAuth API operations for managing clients and tokens.
  • Introduced endpoints for creating, updating, and deleting OAuth
    clients.
  • Implemented token revocation and OAuth client rotation
    functionalities.
  • +475/-0 
    keys.go
    Add key management operations and endpoints.                         

    swagger/keys.go

  • Added key management operations including creation, deletion, and
    updates.
  • Introduced endpoints for listing and previewing keys.
  • Enhanced support for hashed keys and custom key creation.
  • +461/-0 
    oas_api.go
    Add OAS API management and export/import functionalities.

    swagger/oas_api.go

  • Added operations for managing APIs in OpenAPI Specification (OAS)
    format.
  • Implemented endpoints for listing, creating, updating, and deleting
    OAS APIs.
  • Introduced support for exporting and importing OAS API definitions.
  • +551/-0 
    api.go
    Enhance API operations with improved error handling and documentation.

    gateway/api.go

  • Enhanced error handling and logging for API operations.
  • Added example annotations to API-related structures for better
    documentation.
  • Improved file handling and response formatting for API operations.
  • +35/-42 
    manager.go
    Improve certificate management and documentation.               

    certs/manager.go

  • Added example annotations to certificate metadata for better
    documentation.
  • Refactored constant definitions for improved readability.
  • Enhanced certificate management functionalities.
  • +7/-11   
    Additional files (token-limit)
    29 files
    api_definitions.go
    ...                                                                                                           

    apidef/api_definitions.go

    ...

    +49/-44 
    policies.go
    ...                                                                                                           

    swagger/policies.go

    ...

    +336/-0 
    classic_api.go
    ...                                                                                                           

    swagger/classic_api.go

    ...

    +316/-0 
    certs.go
    ...                                                                                                           

    swagger/certs.go

    ...

    +245/-0 
    session.go
    ...                                                                                                           

    user/session.go

    ...

    +37/-36 
    orgs.go
    ...                                                                                                           

    swagger/orgs.go

    ...

    +189/-0 
    server.go
    ...                                                                                                           

    gateway/server.go

    ...

    +16/-13 
    policy.go
    ...                                                                                                           

    user/policy.go

    ...

    +23/-24 
    main.go
    ...                                                                                                           

    swagger/cmd/main.go

    ...

    +130/-0 
    reload.go
    ...                                                                                                           

    swagger/reload.go

    ...

    +70/-0   
    debug.go
    ...                                                                                                           

    swagger/debug.go

    ...

    +60/-0   
    model.go
    ...                                                                                                           

    swagger/model.go

    ...

    +62/-0   
    cert.go
    ...                                                                                                           

    gateway/cert.go

    ...

    +4/-5     
    hello.go
    ...                                                                                                           

    swagger/hello.go

    ...

    +51/-0   
    cache.go
    ...                                                                                                           

    swagger/cache.go

    ...

    +48/-0   
    schema.go
    ...                                                                                                           

    swagger/schema.go

    ...

    +45/-0   
    auth_manager.go
    ...                                                                                                           

    gateway/auth_manager.go

    ...

    +4/-3     
    constants.go
    ...                                                                                                           

    swagger/constants.go

    ...

    +26/-0   
    coprocess_helpers.go
    ...                                                                                                           

    gateway/coprocess_helpers.go

    ...

    +1/-2     
    health_check.go
    ...                                                                                                           

    apidef/health_check.go

    ...

    +2/-2     
    diff_result.html
    ...                                                                                                           

    swagger/cmd/diff_result.html

    ...

    +8127/-1
    swagger.yml
    ...                                                                                                           

    swagger/cmd/swagger.yml

    ...

    +7857/-1
    master_swagger.yml
    ...                                                                                                           

    swagger/cmd/master_swagger.yml

    ...

    +4014/-1
    .redocly.lint-ignore.yaml
    ...                                                                                                           

    swagger/cmd/.redocly.lint-ignore.yaml

    ...

    +41/-0   
    go.sum
    ...                                                                                                           

    go.sum

    ...

    +4/-0     
    redocly.yml
    ...                                                                                                           

    swagger/cmd/redocly.yml

    ...

    +56/-0   
    oas.yml
    ...                                                                                                           

    oas.yml

    ...

    +64/-0   
    go.mod
    ...                                                                                                           

    go.mod

    ...

    +2/-0     
    Makefile
    ...                                                                                                           

    swagger/cmd/Makefile

    ...

    +6/-0     

    💡 PR-Agent usage: Comment /help "your question" on any pull request to receive relevant information

    @yurisasuke yurisasuke marked this pull request as draft March 7, 2024 21:37
    Copy link
    Contributor

    github-actions bot commented Mar 7, 2024

    API Changes

    --- prev.txt	2024-09-17 12:37:13.109581916 +0000
    +++ current.txt	2024-09-17 12:37:09.721564698 +0000
    @@ -1027,7 +1027,7 @@
     
     	// Gateway segment tags
     	TagsDisabled bool     `bson:"tags_disabled" json:"tags_disabled,omitempty"`
    -	Tags         []string `bson:"tags" json:"tags"`
    +	Tags         []string `bson:"tags" json:"tags" example:"[\"Default\",\"v1\"]"`
     
     	// IsOAS is set to true when API has an OAS definition (created in OAS or migrated to OAS)
     	IsOAS       bool   `bson:"is_oas" json:"is_oas,omitempty"`
    @@ -1082,7 +1082,7 @@
     	UseCookie         bool            `mapstructure:"use_cookie" bson:"use_cookie" json:"use_cookie"`
     	CookieName        string          `mapstructure:"cookie_name" bson:"cookie_name" json:"cookie_name"`
     	DisableHeader     bool            `mapstructure:"disable_header" bson:"disable_header" json:"disable_header"`
    -	AuthHeaderName    string          `mapstructure:"auth_header_name" bson:"auth_header_name" json:"auth_header_name"`
    +	AuthHeaderName    string          `mapstructure:"auth_header_name" bson:"auth_header_name" json:"auth_header_name" example:"Authorization"`
     	UseCertificate    bool            `mapstructure:"use_certificate" bson:"use_certificate" json:"use_certificate"`
     	ValidateSignature bool            `mapstructure:"validate_signature" bson:"validate_signature" json:"validate_signature"`
     	Signature         SignatureConfig `mapstructure:"signature" bson:"signature" json:"signature,omitempty"`
    @@ -1106,15 +1106,15 @@
     }
     
     type CORSConfig struct {
    -	Enable             bool     `bson:"enable" json:"enable"`
    -	AllowedOrigins     []string `bson:"allowed_origins" json:"allowed_origins"`
    -	AllowedMethods     []string `bson:"allowed_methods" json:"allowed_methods"`
    -	AllowedHeaders     []string `bson:"allowed_headers" json:"allowed_headers"`
    -	ExposedHeaders     []string `bson:"exposed_headers" json:"exposed_headers"`
    -	AllowCredentials   bool     `bson:"allow_credentials" json:"allow_credentials"`
    -	MaxAge             int      `bson:"max_age" json:"max_age"`
    -	OptionsPassthrough bool     `bson:"options_passthrough" json:"options_passthrough"`
    -	Debug              bool     `bson:"debug" json:"debug"`
    +	Enable             bool     `bson:"enable" json:"enable" example:"false"`
    +	AllowedOrigins     []string `bson:"allowed_origins" json:"allowed_origins" example:"[\"https://*.foo.com\"]"`
    +	AllowedMethods     []string `bson:"allowed_methods" json:"allowed_methods" example:"[\"GET\",\"HEAD\",\"POST\"]"`
    +	AllowedHeaders     []string `bson:"allowed_headers" json:"allowed_headers" example:"[\"Origin\",\"Accept\",\"Content-Type\",\"Authorization\"]"`
    +	ExposedHeaders     []string `bson:"exposed_headers" json:"exposed_headers" example:"[\"Accept\",\"Content-Type\"]"`
    +	AllowCredentials   bool     `bson:"allow_credentials" json:"allow_credentials" example:"false"`
    +	MaxAge             int      `bson:"max_age" json:"max_age" example:"24"`
    +	OptionsPassthrough bool     `bson:"options_passthrough" json:"options_passthrough" example:"false"`
    +	Debug              bool     `bson:"debug" json:"debug" example:"true"`
     }
     
     type CacheMeta struct {
    @@ -1123,15 +1123,15 @@
     	Path                   string `bson:"path" json:"path"`
     	CacheKeyRegex          string `bson:"cache_key_regex" json:"cache_key_regex"`
     	CacheOnlyResponseCodes []int  `bson:"cache_response_codes" json:"cache_response_codes"`
    -	Timeout                int64  `bson:"timeout" json:"timeout"`
    +	Timeout                int64  `bson:"timeout" json:"timeout" format:"int64"`
     }
     
     type CacheOptions struct {
    -	CacheTimeout               int64    `bson:"cache_timeout" json:"cache_timeout"`
    -	EnableCache                bool     `bson:"enable_cache" json:"enable_cache"`
    -	CacheAllSafeRequests       bool     `bson:"cache_all_safe_requests" json:"cache_all_safe_requests"`
    +	CacheTimeout               int64    `bson:"cache_timeout" json:"cache_timeout" example:"60" format:"int64"`
    +	EnableCache                bool     `bson:"enable_cache" json:"enable_cache" example:"true"`
    +	CacheAllSafeRequests       bool     `bson:"cache_all_safe_requests" json:"cache_all_safe_requests" example:"false"`
     	CacheOnlyResponseCodes     []int    `bson:"cache_response_codes" json:"cache_response_codes"`
    -	EnableUpstreamCacheControl bool     `bson:"enable_upstream_cache_control" json:"enable_upstream_cache_control"`
    +	EnableUpstreamCacheControl bool     `bson:"enable_upstream_cache_control" json:"enable_upstream_cache_control" example:"false"`
     	CacheControlTTLHeader      string   `bson:"cache_control_ttl_header" json:"cache_control_ttl_header"`
     	CacheByHeaders             []string `bson:"cache_by_headers" json:"cache_by_headers"`
     }
    @@ -1146,7 +1146,7 @@
     	Path                 string  `bson:"path" json:"path"`
     	Method               string  `bson:"method" json:"method"`
     	ThresholdPercent     float64 `bson:"threshold_percent" json:"threshold_percent"`
    -	Samples              int64   `bson:"samples" json:"samples"`
    +	Samples              int64   `bson:"samples" json:"samples" format:"int64"`
     	ReturnToServiceAfter int     `bson:"return_to_service_after" json:"return_to_service_after"`
     	DisableHalfOpenState bool    `bson:"disable_half_open_state" json:"disable_half_open_state"`
     }
    @@ -1169,7 +1169,7 @@
     type EndpointMethodAction string
     
     type EndpointMethodMeta struct {
    -	Action  EndpointMethodAction `bson:"action" json:"action"`
    +	Action  EndpointMethodAction `bson:"action" json:"action" enum:"no_action,reply"`
     	Code    int                  `bson:"code" json:"code"`
     	Data    string               `bson:"data" json:"data"`
     	Headers map[string]string    `bson:"headers" json:"headers"`
    @@ -1244,9 +1244,9 @@
     	// Enabled indicates if GraphQL should be enabled.
     	Enabled bool `bson:"enabled" json:"enabled"`
     	// ExecutionMode is the mode to define how an api behaves.
    -	ExecutionMode GraphQLExecutionMode `bson:"execution_mode" json:"execution_mode"`
    +	ExecutionMode GraphQLExecutionMode `bson:"execution_mode" json:"execution_mode" enum:"proxyOnly,executionEngine,subgraph,supergraph"`
     	// Version defines the version of the GraphQL config and engine to be used.
    -	Version GraphQLConfigVersion `bson:"version" json:"version"`
    +	Version GraphQLConfigVersion `bson:"version" json:"version" enum:"',1,2"`
     	// Schema is the GraphQL Schema exposed by the GraphQL API/Upstream/Engine.
     	Schema string `bson:"schema" json:"schema"`
     	// LastSchemaUpdate contains the date and time of the last triggered schema update to the upstream.
    @@ -1401,7 +1401,7 @@
     	UpdatedAt            *time.Time              `bson:"updated_at" json:"updated_at,omitempty"`
     	Subgraphs            []GraphQLSubgraphEntity `bson:"subgraphs" json:"subgraphs"`
     	MergedSDL            string                  `bson:"merged_sdl" json:"merged_sdl"`
    -	GlobalHeaders        map[string]string       `bson:"global_headers" json:"global_headers"`
    +	GlobalHeaders        map[string]string       `bson:"global_headers" json:"global_headers" jsonschema:"example={'header1':'value1','header2':'value2'}"`
     	DisableQueryBatching bool                    `bson:"disable_query_batching" json:"disable_query_batching"`
     }
     
    @@ -1443,7 +1443,7 @@
     type HealthCheckComponentType string
     
     type HealthCheckItem struct {
    -	Status        HealthCheckStatus `json:"status"`
    +	Status        HealthCheckStatus `json:"status" enum:"pass,fail,warn"`
     	Output        string            `json:"output,omitempty"`
     	ComponentType string            `json:"componentType,omitempty"`
     	ComponentID   string            `json:"componentId,omitempty"`
    @@ -1451,7 +1451,7 @@
     }
     
     type HealthCheckResponse struct {
    -	Status      HealthCheckStatus          `json:"status"`
    +	Status      HealthCheckStatus          `json:"status" enum:"pass,fail,warn"`
     	Version     string                     `json:"version,omitempty"`
     	Output      string                     `json:"output,omitempty"`
     	Description string                     `json:"description,omitempty"`
    @@ -1533,7 +1533,7 @@
     
     type IntrospectionCache struct {
     	Enabled bool  `bson:"enabled" json:"enabled"`
    -	Timeout int64 `bson:"timeout" json:"timeout"`
    +	Timeout int64 `bson:"timeout" json:"timeout" format:"int64"`
     }
     
     type JWTValidation struct {
    @@ -1560,10 +1560,10 @@
     
     type MiddlewareDefinition struct {
     	Disabled       bool   `bson:"disabled" json:"disabled"`
    -	Name           string `bson:"name" json:"name"`
    +	Name           string `bson:"name" json:"name" example:"PreMiddlewareFunction"`
     	Path           string `bson:"path" json:"path"`
    -	RequireSession bool   `bson:"require_session" json:"require_session"`
    -	RawBodyOnly    bool   `bson:"raw_body_only" json:"raw_body_only"`
    +	RequireSession bool   `bson:"require_session" json:"require_session" example:"false"`
    +	RawBodyOnly    bool   `bson:"raw_body_only" json:"raw_body_only" example:"false"`
     }
     
     type MiddlewareDriver string
    @@ -1643,10 +1643,10 @@
     
     type ProxyConfig struct {
     	PreserveHostHeader          bool                          `bson:"preserve_host_header" json:"preserve_host_header"`
    -	ListenPath                  string                        `bson:"listen_path" json:"listen_path"`
    -	TargetURL                   string                        `bson:"target_url" json:"target_url"`
    +	ListenPath                  string                        `bson:"listen_path" json:"listen_path" example:"/relative-path-examples/"`
    +	TargetURL                   string                        `bson:"target_url" json:"target_url" example:"https://httpbin.org/"`
     	DisableStripSlash           bool                          `bson:"disable_strip_slash" json:"disable_strip_slash"`
    -	StripListenPath             bool                          `bson:"strip_listen_path" json:"strip_listen_path"`
    +	StripListenPath             bool                          `bson:"strip_listen_path" json:"strip_listen_path" example:"true"`
     	EnableLoadBalancing         bool                          `bson:"enable_load_balancing" json:"enable_load_balancing"`
     	Targets                     []string                      `bson:"target_list" json:"target_list"`
     	StructuredTargetList        *HostList                     `bson:"-" json:"-"`
    @@ -1798,7 +1798,7 @@
     	Disabled  bool   `bson:"disabled" json:"disabled"`
     	Path      string `bson:"path" json:"path"`
     	Method    string `bson:"method" json:"method"`
    -	SizeLimit int64  `bson:"size_limit" json:"size_limit"`
    +	SizeLimit int64  `bson:"size_limit" json:"size_limit" format:"int64"`
     }
     
     type ResponseProcessor struct {
    @@ -1807,7 +1807,7 @@
     }
     
     type RoutingTrigger struct {
    -	On        RoutingTriggerOnType  `bson:"on" json:"on"`
    +	On        RoutingTriggerOnType  `bson:"on" json:"on" enum:"all,any"`
     	Options   RoutingTriggerOptions `bson:"options" json:"options"`
     	RewriteTo string                `bson:"rewrite_to" json:"rewrite_to"`
     }
    @@ -1913,8 +1913,8 @@
     type SubscriptionType string
     
     type TemplateData struct {
    -	Input          RequestInputType `bson:"input_type" json:"input_type"`
    -	Mode           SourceMode       `bson:"template_mode" json:"template_mode"`
    +	Input          RequestInputType `bson:"input_type" json:"input_type" enum:"json,xml"`
    +	Mode           SourceMode       `bson:"template_mode" json:"template_mode" enum:"blob,file"`
     	EnableSession  bool             `bson:"enable_session" json:"enable_session"`
     	TemplateSource string           `bson:"template_source" json:"template_source"`
     }
    @@ -2031,10 +2031,10 @@
     	Default string `bson:"default" json:"default"`
     
     	// Location is the location in the request where the version information can be found.
    -	Location string `bson:"location" json:"location"`
    +	Location string `bson:"location" json:"location" json:"location" example:"header"`
     
     	// Key is the key to use to extract the version information from the specified location.
    -	Key string `bson:"key" json:"key"`
    +	Key string `bson:"key" json:"key" example:"x-api-version"`
     
     	// StripPath is a deprecated field. Use StripVersioningData instead.
     	StripPath bool `bson:"strip_path" json:"strip_path"` // Deprecated. Use StripVersioningData instead.
    @@ -2066,7 +2066,7 @@
     		WhiteList []string `bson:"white_list" json:"white_list"`
     		BlackList []string `bson:"black_list" json:"black_list"`
     	} `bson:"paths" json:"paths"`
    -	UseExtendedPaths              bool              `bson:"use_extended_paths" json:"use_extended_paths"`
    +	UseExtendedPaths              bool              `bson:"use_extended_paths" json:"use_extended_paths" example:"true"`
     	ExtendedPaths                 ExtendedPathsSet  `bson:"extended_paths" json:"extended_paths"`
     	GlobalHeaders                 map[string]string `bson:"global_headers" json:"global_headers"`
     	GlobalHeadersRemove           []string          `bson:"global_headers_remove" json:"global_headers_remove"`
    @@ -2075,7 +2075,7 @@
     	GlobalResponseHeadersRemove   []string          `bson:"global_response_headers_remove" json:"global_response_headers_remove"`
     	GlobalResponseHeadersDisabled bool              `bson:"global_response_headers_disabled" json:"global_response_headers_disabled"`
     	IgnoreEndpointCase            bool              `bson:"ignore_endpoint_case" json:"ignore_endpoint_case"`
    -	GlobalSizeLimit               int64             `bson:"global_size_limit" json:"global_size_limit"`
    +	GlobalSizeLimit               int64             `bson:"global_size_limit" json:"global_size_limit" format:"int64"`
     	OverrideTarget                string            `bson:"override_target" json:"override_target"`
     }
     
    @@ -2097,7 +2097,7 @@
     type VirtualMeta struct {
     	Disabled             bool       `bson:"disabled" json:"disabled"`
     	ResponseFunctionName string     `bson:"response_function_name" json:"response_function_name"`
    -	FunctionSourceType   SourceMode `bson:"function_source_type" json:"function_source_type"`
    +	FunctionSourceType   SourceMode `bson:"function_source_type" json:"function_source_type" enum:"blob,file"`
     	FunctionSourceURI    string     `bson:"function_source_uri" json:"function_source_uri"`
     	Path                 string     `bson:"path" json:"path"`
     	Method               string     `bson:"method" json:"method"`
    @@ -4844,9 +4844,7 @@
     	GenServerCertificate = tykcrypto.GenServerCertificate
     	HexSHA256            = tykcrypto.HexSHA256
     )
    -var (
    -	CertManagerLogPrefix = "cert_storage"
    -)
    +var CertManagerLogPrefix = "cert_storage"
     
     FUNCTIONS
     
    @@ -4884,14 +4882,14 @@
     }
     
     type CertificateMeta struct {
    -	ID            string    `json:"id"`
    -	Fingerprint   string    `json:"fingerprint"`
    -	HasPrivateKey bool      `json:"has_private"`
    +	ID            string    `json:"id" example:"5e9d9544a1dcd60001d0ed207c440d66ebb0a4629d21329808dce9091acf5f2fde328067a6e60e5347271d90"`
    +	Fingerprint   string    `json:"fingerprint" example:"7c440d66ebb0a4629d21329808dce9091acf5f2fde328067a6e60e5347271d90"`
    +	HasPrivateKey bool      `json:"has_private" example:"false"`
     	Issuer        pkix.Name `json:"issuer,omitempty"`
     	Subject       pkix.Name `json:"subject,omitempty"`
    -	NotBefore     time.Time `json:"not_before,omitempty"`
    -	NotAfter      time.Time `json:"not_after,omitempty"`
    -	DNSNames      []string  `json:"dns_names,omitempty"`
    +	NotBefore     time.Time `json:"not_before,omitempty" example:"2024-03-25T08:46:37Z"`
    +	NotAfter      time.Time `json:"not_after,omitempty" example:"2034-03-26T08:46:37Z"`
    +	DNSNames      []string  `json:"dns_names,omitempty" example:"[.*tyk.io]"`
     	IsCA          bool      `json:"is_ca"`
     }
     
    @@ -7685,9 +7683,7 @@
     var (
     	ErrPoliciesFetchFailed = errors.New("fetch policies request login failure")
     )
    -var (
    -	ErrRequestMalformed = errors.New("request malformed")
    -)
    +var ErrRequestMalformed = errors.New("request malformed")
     var GatewayFireSystemEvent func(name apidef.TykEvent, meta interface{})
         GatewayFireSystemEvent declared as global variable, set during gw start
     
    @@ -7808,9 +7804,9 @@
     }
     
     type APICertificateStatusMessage struct {
    -	CertID  string `json:"id"`
    -	Status  string `json:"status"`
    -	Message string `json:"message"`
    +	CertID  string `json:"id" example:"5e9d9544a1dcd60001d0ed207c440d66ebb0a4629d21329808dce9091acf5f2fde328067a6e60e5347271d90"`
    +	Status  string `json:"status" example:"ok"`
    +	Message string `json:"message" example:"Certificate added"`
     }
     
     type APIDefinitionLoader struct {
    @@ -8331,7 +8327,8 @@
     func (b *DefaultSessionManager) Store() storage.Handler
     
     func (b *DefaultSessionManager) UpdateSession(keyName string, session *user.SessionState,
    -	resetTTLTo int64, hashed bool) error
    +	resetTTLTo int64, hashed bool,
    +) error
         UpdateSession updates the session state in the storage engine
     
     type DummyProxyHandler struct {
    @@ -9296,13 +9293,13 @@
     func (m *MultiTargetProxy) ServeHTTPForCache(w http.ResponseWriter, r *http.Request) ProxyResponse
     
     type NewClientRequest struct {
    -	ClientID          string      `json:"client_id"`
    -	ClientRedirectURI string      `json:"redirect_uri"`
    -	APIID             string      `json:"api_id,omitempty"`
    +	ClientID          string      `json:"client_id" example:"2a06b398c17f46908de3dffcb71ef87b"`
    +	ClientRedirectURI string      `json:"redirect_uri" example:"https://httpbin.org/ip"`
    +	APIID             string      `json:"api_id,omitempty" example:"keyless"`
     	PolicyID          string      `json:"policy_id,omitempty"`
    -	ClientSecret      string      `json:"secret"`
    +	ClientSecret      string      `json:"secret" example:"MmQwNTI5NGQtYjU0YS00NjMyLWIwZjktNTZjY2M1ZjhjYWY0"`
     	MetaData          interface{} `json:"meta_data"`
    -	Description       string      `json:"description"`
    +	Description       string      `json:"description" example:"google client login"`
     }
         NewClientRequest is an outward facing JSON object translated from osin
         OAuthClients
    @@ -10723,16 +10720,16 @@
         system, return an error to have the chain fail
     
     type VersionMeta struct {
    -	ID               string `json:"id"`
    -	Name             string `json:"name"`
    -	VersionName      string `json:"versionName"`
    -	Internal         bool   `json:"internal"`
    -	ExpirationDate   string `json:"expirationDate"`
    -	IsDefaultVersion bool   `json:"isDefaultVersion"`
    +	ID               string `json:"id" example:"keyless"`
    +	Name             string `json:"name" example:"Tyk Test Keyless API"`
    +	VersionName      string `json:"versionName" example:"v2"`
    +	Internal         bool   `json:"internal" example:"false"`
    +	ExpirationDate   string `json:"expirationDate" example:"2026-03-26 09:00"`
    +	IsDefaultVersion bool   `json:"isDefaultVersion" example:"true"`
     }
     
     type VersionMetas struct {
    -	Status string        `json:"status"`
    +	Status string        `json:"status" example:"success"`
     	Metas  []VersionMeta `json:"apis"`
     }
     
    @@ -11882,6 +11879,299 @@
     
     func (v *Vault) Get(key string) (string, error)
     
    +# Package: ./swagger
    +
    +package swagger // import "github.com/TykTechnologies/tyk/swagger"
    +
    +
    +CONSTANTS
    +
    +const (
    +	CacheTag     = "Cache Invalidation"
    +	CacheTagDesc = `Sometimes a cache might contain stale data, or it may just need to be cleared because of an invalid configuration. This call will purge all keys associated with a cache on an API-by-API basis.
    +`
    +)
    +const (
    +	CertsTag = "Certs"
    +)
    +const (
    +	APIsTag    = "APIs"
    +	ApiTagDesc = `**Note: Applies only to Tyk Gateway Community Edition** <br/>
    +
    +API management is very simple using the Tyk Rest API: each update only affects the underlying file, and this endpoint will only work with disk based installations, not database-backed ones.<br/>
    +
    +APIs that are added this way are flushed to to disk into the app_path folder using the format: *{api-id}.json*. Updating existing APIs that use a different naming convention will cause those APIs to be added, which could subsequently lead to a loading error and crash if they use the same listen_path. <br/>
    +
    +These methods only work on a single API node. If updating a cluster, it is important to ensure that all nodes are updated before initiating a reload.<br/>
    +`
    +)
    +const (
    +	KeysTag     = "Keys"
    +	KeyTagsDesc = `All keys that are used to access services via Tyk correspond to a session object that informs Tyk about the context of this particular token, like access rules and rate/quota allowance.
    +`
    +)
    +const (
    +	OASTag = "Tyk OAS APIs"
    +
    +	OASTagDesc = `**Note: Applies only to Tyk Gateway Community Edition** <br/>
    +
    +`
    +)
    +const (
    +	OAuthTag     = "OAuth"
    +	OAuthTagDesc = `Manage OAuth clients, and manage their tokens
    +`
    +)
    +const (
    +	OrgTag     = "Organisation Quotas"
    +	OrgTagDesc = `It is possible to force API quota and rate limit across all keys that belong to a specific organisation ID. Rate limiting at an organisation level is useful for creating tiered access levels and trial accounts.<br />
    +
    +The Organisation rate limiting middleware works with both Quotas and Rate Limiters. In order to manage this functionality, a simple API has been put in place to manage these sessions. <br />
    +
    +Although the Organisation session-limiter uses the same session object, all other security keys are optional as they are not used. <br />
    +
    +<h3>Managing active status</h3> <br />
    +
    +To disallow access to an entire group of keys without rate limiting the organisation, create a session object with the "is_inactive" key set to true. This will block access before any other middleware is executed. It is useful when managing subscriptions for an organisation group and access needs to be blocked because of non-payment. <br />
    +`
    +)
    +const (
    +	PolicyTag     = "Policies"
    +	PolicyTagDesc = `A Tyk security policy incorporates several security options that can be applied to an API key. It acts as a template that can override individual sections of an API key (or identity) in Tyk.
    +`
    +)
    +const (
    +	UpstreamURL     = "UpstreamURL"
    +	ListenPath      = "ListenPath"
    +	CustomDomain    = "CustomDomain"
    +	AllowList       = "AllowList"
    +	ValidateRequest = "ValidateRequest"
    +	MockResponse    = "MockResponse"
    +	Authentication  = "Authentication"
    +	TemplateID      = "TemplateID"
    +	SearchText      = "SearchText"
    +	AccessType      = "AccessType"
    +)
    +const TykDesc = `The Tyk Gateway API is the primary means for integrating your application with the Tyk API Gateway system. This API is very small, and has no granular permissions system. It is intended to be used purely for internal automation and integration.
    +
    +**Warning: Under no circumstances should outside parties be granted access to this API.**
    +
    +The Tyk Gateway API is capable of:
    +
    +* Managing session objects (key generation).
    +* Managing and listing policies.
    +* Managing and listing API Definitions (only when not using the Tyk Dashboard).
    +* Hot reloads / reloading a cluster configuration.
    +* OAuth client creation (only when not using the Tyk Dashboard).
    +
    +In order to use the Gateway API, you'll need to set the **secret** parameter in your tyk.conf file.
    +
    +The shared secret you set should then be sent along as a header with each Gateway API Request in order for it to be successful:
    +
    +**x-tyk-authorization: <your-secret>***
    +<br/>
    +
    +<b>The Tyk Gateway API is subsumed by the Tyk Dashboard API in Pro installations.</b>
    +
    +`
    +
    +VARIABLES
    +
    +var ErrOperationExposer = errors.New("object is not of type openapi3.OperationExposer")
    +var Tags []openapi3.Tag
    +
    +FUNCTIONS
    +
    +func APIS(r *openapi3.Reflector) error
    +func AddRefComponent(r *openapi3.Reflector)
    +func Certs(r *openapi3.Reflector) error
    +func DebugApi(r *openapi3.Reflector) error
    +func HealthEndpoint(r *openapi3.Reflector) error
    +    Done
    +
    +func InvalidateCache(r *openapi3.Reflector) error
    +func Keys(r *openapi3.Reflector) error
    +func OAuthApi(r *openapi3.Reflector) error
    +func OasAPIS(r *openapi3.Reflector) error
    +func OasNoXTykSample() string
    +func OasSampleString() string
    +func OrgsApi(r *openapi3.Reflector) error
    +func PointerValue[T any](value T) *T
    +func PoliciesApis(r *openapi3.Reflector) error
    +func RefExamples(r *openapi3.Reflector)
    +func RefParameters(r *openapi3.Reflector)
    +func ReloadApi(r *openapi3.Reflector) error
    +func SchemaAPi(r *openapi3.Reflector) error
    +func StringPointerValue(value string) *string
    +func UpdateOrgKey(r *openapi3.Reflector) error
    +
    +TYPES
    +
    +type AllOfOneOf int
    +
    +const (
    +	OneOf AllOfOneOf = iota
    +	AllOff
    +)
    +type BinaryExample string
    +
    +func (b BinaryExample) MarshalJSON() ([]byte, error)
    +
    +type BinaryFormat struct {
    +	// Has unexported fields.
    +}
    +
    +type BinarySchema struct {
    +	Name string `json:"name"`
    +}
    +
    +type ExampleObject struct {
    +	// Has unexported fields.
    +}
    +
    +type ExampleType int
    +
    +const (
    +	Inline ExampleType = iota
    +	External
    +	Component
    +)
    +type ExternalRef struct {
    +	Ref string
    +
    +	// Has unexported fields.
    +}
    +
    +type File struct {
    +	File multipart.File ` json:"file" formData:"file" required:"true" `
    +}
    +
    +type HeaderCr struct {
    +	Key         string              `json:"key"`
    +	Description string              `json:"description"`
    +	Type        openapi3.SchemaType `json:"type"`
    +}
    +
    +type ItemType int
    +
    +const (
    +	InlineType ItemType = iota
    +	ExternalType
    +	ComponentType
    +)
    +type OperationWithExample struct {
    +	// Has unexported fields.
    +}
    +
    +func NewOperationWithExamples(r *openapi3.Reflector, method, pathPattern, operationID, tag string) (*OperationWithExample, error)
    +
    +func NewOperationWithSafeExample(r *openapi3.Reflector, operation SafeOperation) (*OperationWithExample, error)
    +
    +func (op *OperationWithExample) AddBinaryFormatResp(format BinaryFormat)
    +
    +func (op *OperationWithExample) AddGenericErrorResponse(httpStatus int, message string, options ...openapi.ContentOption)
    +
    +func (op *OperationWithExample) AddGenericStatusOk(message string, options ...openapi.ContentOption)
    +
    +func (op *OperationWithExample) AddOneOfAllOfRespWithExamples(itemType AllOfOneOf, httpStatus int, items []multipleExamplesValues, options ...openapi.ContentOption)
    +
    +func (op *OperationWithExample) AddOperation() error
    +
    +func (op *OperationWithExample) AddPageQueryParameter()
    +
    +func (op *OperationWithExample) AddParameter(name, description string, In openapi3.ParameterIn, optionalPams OptionalParameterValues)
    +
    +func (op *OperationWithExample) AddPathParameter(name, description string, optionalPams OptionalParameterValues)
    +
    +func (op *OperationWithExample) AddQueryParameter(name, description string, optionalPams OptionalParameterValues)
    +
    +func (op *OperationWithExample) AddRefParameters(name string)
    +
    +func (op *OperationWithExample) AddReqOneOfAllOfWithExamples(itemType AllOfOneOf, items []ReqOneOfAllOf)
    +
    +func (op *OperationWithExample) AddReqWithExample(object interface{}, options ...openapi.ContentOption)
    +
    +func (op *OperationWithExample) AddReqWithExternalRef(ref ExternalRef)
    +
    +func (op *OperationWithExample) AddReqWithSeparateExample(object interface{}, example interface{})
    +
    +func (op *OperationWithExample) AddResp(object interface{}, httpStatus int, options ...openapi.ContentOption)
    +
    +func (op *OperationWithExample) AddRespWithExample(object interface{}, httpStatus int, options ...openapi.ContentOption)
    +
    +func (op *OperationWithExample) AddRespWithRefExamples(httpStatus int, object interface{}, values []multipleExamplesValues, options ...openapi.ContentOption)
    +
    +func (op *OperationWithExample) AddResponseHeaders(header ResponseHeader)
    +
    +func (op *OperationWithExample) AddResponseWithSeparateExample(object interface{}, httpStatus int, example interface{}, options ...openapi.ContentOption)
    +
    +func (op *OperationWithExample) SetDescription(summary string)
    +
    +func (op *OperationWithExample) SetSummary(summary string)
    +
    +func (op *OperationWithExample) StatusBadRequest(message string, options ...openapi.ContentOption)
    +
    +func (op *OperationWithExample) StatusForbidden(options ...openapi.ContentOption)
    +
    +func (op *OperationWithExample) StatusInternalServerError(message string)
    +
    +func (op *OperationWithExample) StatusNotFound(message string, options ...openapi.ContentOption)
    +
    +func (op *OperationWithExample) StatusUnauthorized()
    +
    +type OptionalParameterValues struct {
    +	Required         *bool
    +	Example          *interface{}
    +	Type             openapi3.SchemaType
    +	Enum             []interface{}
    +	Deprecated       *bool `json:"deprecated,omitempty"`
    +	Default          *interface{}
    +	MultipleExamples []multipleExamplesValues
    +	AllowEmptyValue  bool
    +}
    +
    +type ParameterValues struct {
    +	Name        string
    +	Description string
    +	Type        openapi3.SchemaType
    +	Example     interface{}
    +	Required    bool
    +	In          openapi3.ParameterIn
    +}
    +
    +type ReqOneOfAllOf struct {
    +	Ref string
    +
    +	AllOfOneOf AllOfOneOf
    +	// Has unexported fields.
    +}
    +
    +type ResponseHeader struct {
    +	Name        string
    +	Description *string
    +	Type        *openapi3.SchemaType
    +}
    +
    +type Revoke struct {
    +	Token         string `json:"token" formData:"token" description:"token to be revoked" required:"true"`
    +	TokenTypeHint string `json:"token_type_hint" formData:"token_type_hint" description:"type of token to be revoked, if sent then the accepted values are access_token and refresh_token. String value and optional, of not provided then it will attempt to remove access and refresh tokens that matches"`
    +	ClientID      string `json:"client_id" formData:"client_id" description:"id of oauth client" required:"true"`
    +	OrgID         string `json:"org_id" formData:"org_id"`
    +}
    +
    +type SafeOperation struct {
    +	Method, PathPattern, OperationID, Tag string
    +}
    +
    +type URLVals struct {
    +	Host     string `json:"Host"`
    +	BasePath string `json:"BasePath"`
    +	APIURL   string `json:"ApiURL"`
    +}
    +
    +# Package: ./swagger/cmd
    +
    +
     # Package: ./tcp
     
     package tcp // import "github.com/TykTechnologies/tyk/tcp"
    @@ -12462,17 +12752,17 @@
         IsEmpty checks if APILimit is empty.
     
     type AccessDefinition struct {
    -	APIName              string                  `json:"api_name" msg:"api_name"`
    -	APIID                string                  `json:"api_id" msg:"api_id"`
    -	Versions             []string                `json:"versions" msg:"versions"`
    +	APIName              string                  `json:"api_name" msg:"api_name" example:"Rate Limit Proxy API"`
    +	APIID                string                  `json:"api_id" msg:"api_id" example:"d1dfc6a927a046c54c0ed470f19757cc"`
    +	Versions             []string                `json:"versions" msg:"versions" example:"[\"Default\",\"v2\"]"`
     	AllowedURLs          []AccessSpec            `bson:"allowed_urls" json:"allowed_urls" msg:"allowed_urls"` // mapped string MUST be a valid regex
     	RestrictedTypes      []graphql.Type          `json:"restricted_types" msg:"restricted_types"`
     	AllowedTypes         []graphql.Type          `json:"allowed_types" msg:"allowed_types"`
     	Limit                APILimit                `json:"limit" msg:"limit"`
     	FieldAccessRights    []FieldAccessDefinition `json:"field_access_rights" msg:"field_access_rights"`
    -	DisableIntrospection bool                    `json:"disable_introspection" msg:"disable_introspection"`
    +	DisableIntrospection bool                    `json:"disable_introspection" msg:"disable_introspection" example:"false"`
     
    -	AllowanceScope string `json:"allowance_scope" msg:"allowance_scope"`
    +	AllowanceScope string `json:"allowance_scope" msg:"allowance_scope" example:"d371b83b249845a2497ab9a947fd6210"`
     
     	Endpoints Endpoints `json:"endpoints,omitempty" msg:"endpoints,omitempty"`
     }
    @@ -12481,8 +12771,8 @@
         the gateway/policy.go:19 TODO: is it possible to share fields?
     
     type AccessSpec struct {
    -	URL     string   `json:"url" msg:"url"`
    -	Methods []string `json:"methods" msg:"methods"`
    +	URL     string   `json:"url" msg:"url" example:"anything/rate-limit-1-per-5"`
    +	Methods []string `json:"methods" msg:"methods" example:"[\"GET\",\"POST\",\"DELETE\",\"PUT\"]"`
     }
         AccessSpecs define what URLS a user has access to an what methods are
         enabled
    @@ -12562,8 +12852,7 @@
     	MaxQueryDepth int `json:"max_query_depth" msg:"max_query_depth"`
     }
     
    -type GraphAccessDefinition struct {
    -}
    +type GraphAccessDefinition struct{}
     
     type HashType string
     
    @@ -12572,30 +12861,30 @@
     }
     
     type Monitor struct {
    -	TriggerLimits []float64 `json:"trigger_limits" msg:"trigger_limits"`
    +	TriggerLimits []float64 `json:"trigger_limits" msg:"trigger_limits" example:"[80, 60, 50]"`
     }
     
     type Policy struct {
    -	MID                           model.ObjectID                   `bson:"_id,omitempty" json:"_id" gorm:"primaryKey;column:_id"`
    -	ID                            string                           `bson:"id,omitempty" json:"id"`
    -	Name                          string                           `bson:"name" json:"name"`
    -	OrgID                         string                           `bson:"org_id" json:"org_id"`
    -	Rate                          float64                          `bson:"rate" json:"rate"`
    -	Per                           float64                          `bson:"per" json:"per"`
    -	QuotaMax                      int64                            `bson:"quota_max" json:"quota_max"`
    -	QuotaRenewalRate              int64                            `bson:"quota_renewal_rate" json:"quota_renewal_rate"`
    -	ThrottleInterval              float64                          `bson:"throttle_interval" json:"throttle_interval"`
    -	ThrottleRetryLimit            int                              `bson:"throttle_retry_limit" json:"throttle_retry_limit"`
    -	MaxQueryDepth                 int                              `bson:"max_query_depth" json:"max_query_depth"`
    +	MID                           model.ObjectID                   `bson:"_id,omitempty" json:"_id" gorm:"primaryKey;column:_id" example:"5ead7120575961000181867e"`
    +	ID                            string                           `bson:"id,omitempty" json:"id" example:"5ead7120575961000181867e"`
    +	Name                          string                           `bson:"name" json:"name" example:"Swagger Petstore Policy"`
    +	OrgID                         string                           `bson:"org_id" json:"org_id" example:"5e9d9544a1dcd60001d0ed20"`
    +	Rate                          float64                          `bson:"rate" json:"rate" format:"double" example:"1000"`
    +	Per                           float64                          `bson:"per" json:"per" format:"double" example:"60"`
    +	QuotaMax                      int64                            `bson:"quota_max" json:"quota_max" example:"-1" format:"int64"`
    +	QuotaRenewalRate              int64                            `bson:"quota_renewal_rate" json:"quota_renewal_rate" format:"int64" example:"3600"`
    +	ThrottleInterval              float64                          `bson:"throttle_interval" json:"throttle_interval" format:"double" example:"-1"`
    +	ThrottleRetryLimit            int                              `bson:"throttle_retry_limit" json:"throttle_retry_limit" example:"-1"`
    +	MaxQueryDepth                 int                              `bson:"max_query_depth" json:"max_query_depth" example:"-1"`
     	AccessRights                  map[string]AccessDefinition      `bson:"access_rights" json:"access_rights"`
    -	HMACEnabled                   bool                             `bson:"hmac_enabled" json:"hmac_enabled"`
    -	EnableHTTPSignatureValidation bool                             `json:"enable_http_signature_validation" msg:"enable_http_signature_validation"`
    -	Active                        bool                             `bson:"active" json:"active"`
    -	IsInactive                    bool                             `bson:"is_inactive" json:"is_inactive"`
    +	HMACEnabled                   bool                             `bson:"hmac_enabled" json:"hmac_enabled" example:"false"`
    +	EnableHTTPSignatureValidation bool                             `json:"enable_http_signature_validation" msg:"enable_http_signature_validation" example:"false"`
    +	Active                        bool                             `bson:"active" json:"active" example:"true"`
    +	IsInactive                    bool                             `bson:"is_inactive" json:"is_inactive" example:"false"`
     	Tags                          []string                         `bson:"tags" json:"tags"`
    -	KeyExpiresIn                  int64                            `bson:"key_expires_in" json:"key_expires_in"`
    +	KeyExpiresIn                  int64                            `bson:"key_expires_in" json:"key_expires_in" example:"0" format:"int64"`
     	Partitions                    PolicyPartitions                 `bson:"partitions" json:"partitions"`
    -	LastUpdated                   string                           `bson:"last_updated" json:"last_updated"`
    +	LastUpdated                   string                           `bson:"last_updated" json:"last_updated" example:"1655965189"`
     	MetaData                      map[string]interface{}           `bson:"meta_data" json:"meta_data"`
     	GraphQL                       map[string]GraphAccessDefinition `bson:"graphql_access_rights" json:"graphql_access_rights"`
     
    @@ -12607,11 +12896,11 @@
     func (p *Policy) APILimit() APILimit
     
     type PolicyPartitions struct {
    -	Quota      bool `bson:"quota" json:"quota"`
    -	RateLimit  bool `bson:"rate_limit" json:"rate_limit"`
    -	Complexity bool `bson:"complexity" json:"complexity"`
    -	Acl        bool `bson:"acl" json:"acl"`
    -	PerAPI     bool `bson:"per_api" json:"per_api"`
    +	Quota      bool `bson:"quota" json:"quota" example:"true"`
    +	RateLimit  bool `bson:"rate_limit" json:"rate_limit" example:"true"`
    +	Complexity bool `bson:"complexity" json:"complexity" example:"false"`
    +	Acl        bool `bson:"acl" json:"acl" example:"true"`
    +	PerAPI     bool `bson:"per_api" json:"per_api" example:"false"`
     }
     
     func (p PolicyPartitions) Enabled() bool
    @@ -12633,45 +12922,45 @@
         It's used to decide which rate limit has a bigger allowance.
     
     type SessionState struct {
    -	LastCheck                     int64                       `json:"last_check" msg:"last_check"`
    -	Allowance                     float64                     `json:"allowance" msg:"allowance"`
    -	Rate                          float64                     `json:"rate" msg:"rate"`
    -	Per                           float64                     `json:"per" msg:"per"`
    -	ThrottleInterval              float64                     `json:"throttle_interval" msg:"throttle_interval"`
    -	ThrottleRetryLimit            int                         `json:"throttle_retry_limit" msg:"throttle_retry_limit"`
    -	MaxQueryDepth                 int                         `json:"max_query_depth" msg:"max_query_depth"`
    -	DateCreated                   time.Time                   `json:"date_created" msg:"date_created"`
    -	Expires                       int64                       `json:"expires" msg:"expires"`
    -	QuotaMax                      int64                       `json:"quota_max" msg:"quota_max"`
    -	QuotaRenews                   int64                       `json:"quota_renews" msg:"quota_renews"`
    -	QuotaRemaining                int64                       `json:"quota_remaining" msg:"quota_remaining"`
    -	QuotaRenewalRate              int64                       `json:"quota_renewal_rate" msg:"quota_renewal_rate"`
    +	LastCheck                     int64                       `json:"last_check" msg:"last_check" format:"int64" example:"0"`
    +	Allowance                     float64                     `json:"allowance" msg:"allowance" example:"1000" format:"double"`
    +	Rate                          float64                     `json:"rate" msg:"rate" format:"double" example:"1"`
    +	Per                           float64                     `json:"per" msg:"per" format:"double" example:"5"`
    +	ThrottleInterval              float64                     `json:"throttle_interval" msg:"throttle_interval" format:"double" example:"10"`
    +	ThrottleRetryLimit            int                         `json:"throttle_retry_limit" msg:"throttle_retry_limit" example:"1000"`
    +	MaxQueryDepth                 int                         `json:"max_query_depth" msg:"max_query_depth" example:"-1"`
    +	DateCreated                   time.Time                   `json:"date_created" msg:"date_created" example:"2024-03-13T03:56:46.568042549Z"`
    +	Expires                       int64                       `json:"expires" msg:"expires" example:"1712895619" format:"int64"`
    +	QuotaMax                      int64                       `json:"quota_max" msg:"quota_max" format:"int64" example:"20000"`
    +	QuotaRenews                   int64                       `json:"quota_renews" msg:"quota_renews" example:"1710302205" format:"int64"`
    +	QuotaRemaining                int64                       `json:"quota_remaining" msg:"quota_remaining" format:"int64" example:"20000"`
    +	QuotaRenewalRate              int64                       `json:"quota_renewal_rate" msg:"quota_renewal_rate" format:"int64" example:"31556952"`
     	AccessRights                  map[string]AccessDefinition `json:"access_rights" msg:"access_rights"`
    -	OrgID                         string                      `json:"org_id" msg:"org_id"`
    +	OrgID                         string                      `json:"org_id" msg:"org_id" example:"5e9d9544a1dcd60001d0ed20"`
     	OauthClientID                 string                      `json:"oauth_client_id" msg:"oauth_client_id"`
     	OauthKeys                     map[string]string           `json:"oauth_keys" msg:"oauth_keys"`
     	Certificate                   string                      `json:"certificate" msg:"certificate"`
     	BasicAuthData                 BasicAuthData               `json:"basic_auth_data" msg:"basic_auth_data"`
     	JWTData                       JWTData                     `json:"jwt_data" msg:"jwt_data"`
    -	HMACEnabled                   bool                        `json:"hmac_enabled" msg:"hmac_enabled"`
    -	EnableHTTPSignatureValidation bool                        `json:"enable_http_signature_validation" msg:"enable_http_signature_validation"`
    +	HMACEnabled                   bool                        `json:"hmac_enabled" msg:"hmac_enabled" example:"false"`
    +	EnableHTTPSignatureValidation bool                        `json:"enable_http_signature_validation" msg:"enable_http_signature_validation" example:"false"`
     	HmacSecret                    string                      `json:"hmac_string" msg:"hmac_string"`
     	RSACertificateId              string                      `json:"rsa_certificate_id" msg:"rsa_certificate_id"`
    -	IsInactive                    bool                        `json:"is_inactive" msg:"is_inactive"`
    -	ApplyPolicyID                 string                      `json:"apply_policy_id" msg:"apply_policy_id"`
    -	ApplyPolicies                 []string                    `json:"apply_policies" msg:"apply_policies"`
    -	DataExpires                   int64                       `json:"data_expires" msg:"data_expires"`
    +	IsInactive                    bool                        `json:"is_inactive" msg:"is_inactive" example:"false"`
    +	ApplyPolicyID                 string                      `json:"apply_policy_id" msg:"apply_policy_id" example:"641c15dd0fffb800010197bf" deprecated:"true" description:"deprecated use apply_policies going forward instead to send a list of policies ids"`
    +	ApplyPolicies                 []string                    `json:"apply_policies" msg:"apply_policies" example:"[\"641c15dd0fffb800010197bf\"]"`
    +	DataExpires                   int64                       `json:"data_expires" msg:"data_expires" format:"int64" example:"0"`
     	Monitor                       Monitor                     `json:"monitor" msg:"monitor"`
     	// Deprecated: EnableDetailRecording is deprecated. Use EnableDetailedRecording
     	// going forward instead
    -	EnableDetailRecording   bool                   `json:"enable_detail_recording" msg:"enable_detail_recording"`
    -	EnableDetailedRecording bool                   `json:"enable_detailed_recording" msg:"enable_detailed_recording"`
    -	MetaData                map[string]interface{} `json:"meta_data" msg:"meta_data"`
    -	Tags                    []string               `json:"tags" msg:"tags"`
    -	Alias                   string                 `json:"alias" msg:"alias"`
    -	LastUpdated             string                 `json:"last_updated" msg:"last_updated"`
    -	IdExtractorDeadline     int64                  `json:"id_extractor_deadline" msg:"id_extractor_deadline"`
    -	SessionLifetime         int64                  `bson:"session_lifetime" json:"session_lifetime"`
    +	EnableDetailRecording   bool                   `json:"enable_detail_recording" msg:"enable_detail_recording" example:"false" deprecated:"true" description:"deprecated use enable_detailed_recording going forward instead"`
    +	EnableDetailedRecording bool                   `json:"enable_detailed_recording" msg:"enable_detailed_recording" example:"true"`
    +	MetaData                map[string]interface{} `json:"meta_data" msg:"meta_data" example:"{\"tyk_developer_id\": \"62b3fb9a1d5e4f00017226f5\"}"`
    +	Tags                    []string               `json:"tags" msg:"tags" example:"[edge,edge-eu]"`
    +	Alias                   string                 `json:"alias" msg:"alias" example:"[email protected]"`
    +	LastUpdated             string                 `json:"last_updated" msg:"last_updated" example:"1710302206"`
    +	IdExtractorDeadline     int64                  `json:"id_extractor_deadline" msg:"id_extractor_deadline" format:"int64"`
    +	SessionLifetime         int64                  `bson:"session_lifetime" json:"session_lifetime" format:"int64" example:"0"`
     
     	KeyID string `json:"-"`
     

    Copy link
    Contributor

    github-actions bot commented Mar 7, 2024

    PR Description updated to latest commit (7f0351a)

    Copy link
    Contributor

    github-actions bot commented Mar 7, 2024

    PR Review

    ⏱️ Estimated effort to review [1-5]

    3, because the PR introduces a significant feature with multiple new dependencies and changes across several files. The complexity of integrating OpenAPI spec generation and ensuring it works correctly with existing functionality requires a thorough review.

    🧪 Relevant tests

    No

    🔍 Possible issues

    Possible Bug: The writeSchema function in swagger/cmd/main.go does not handle potential errors from file.Close() which can lead to resource leaks or unreported errors.

    Performance Concern: The APIS and GetClassicApiRequest functions in swagger/classic_api.go could potentially be optimized for better performance, especially if they are called frequently.

    🔒 Security concerns

    No

    Code feedback:
    relevant fileswagger/cmd/main.go
    suggestion      

    Consider handling the error returned by file.Close() inside the writeSchema function. Ignoring this error can lead to resource leaks or unreported errors. You can log the error or return a combined error if both file.Write and file.Close fail. [important]

    relevant linedefer file.Close()

    relevant fileswagger/classic_api.go
    suggestion      

    For better error handling, consider wrapping the error returned by r.AddOperation(oc) with additional context before returning it. This can help in debugging issues related to operation addition failures. [medium]

    relevant lineerr = r.AddOperation(oc)

    relevant fileswagger/cmd/main.go
    suggestion      

    The permissions for the created open.yaml file are set to 0o644, which is generally fine, but consider if more restrictive permissions are needed based on the sensitivity of the data contained within. Adjust if necessary to suit security requirements. [medium]

    relevant linefile, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE, 0o644)

    relevant fileswagger/classic_api.go
    suggestion      

    It's good practice to check if new(apidef.APIDefinition) returns a non-nil value before adding it to the request and response structure. This can prevent potential nil pointer dereferences. [medium]

    relevant lineoc.AddReqStructure(new(apidef.APIDefinition))


    ✨ Review tool usage guide:

    Overview:
    The review tool scans the PR code changes, and generates a PR review. The tool can be triggered automatically every time a new PR is opened, or can be invoked manually by commenting on any PR.
    When commenting, to edit configurations related to the review tool (pr_reviewer section), use the following template:

    /review --pr_reviewer.some_config1=... --pr_reviewer.some_config2=...
    

    With a configuration file, use the following template:

    [pr_reviewer]
    some_config1=...
    some_config2=...
    
    Utilizing extra instructions

    The review tool can be configured with extra instructions, which can be used to guide the model to a feedback tailored to the needs of your project.

    Be specific, clear, and concise in the instructions. With extra instructions, you are the prompter. Specify the relevant sub-tool, and the relevant aspects of the PR that you want to emphasize.

    Examples for extra instructions:

    [pr_reviewer] # /review #
    extra_instructions="""
    In the 'possible issues' section, emphasize the following:
    - Does the code logic cover relevant edge cases?
    - Is the code logic clear and easy to understand?
    - Is the code logic efficient?
    ...
    """
    

    Use triple quotes to write multi-line instructions. Use bullet points to make the instructions more readable.

    How to enable\disable automation
    • When you first install PR-Agent app, the default mode for the review tool is:
    pr_commands = ["/review", ...]
    

    meaning the review tool will run automatically on every PR, with the default configuration.
    Edit this field to enable/disable the tool, or to change the used configurations

    Auto-labels

    The review tool can auto-generate two specific types of labels for a PR:

    • a possible security issue label, that detects possible security issues (enable_review_labels_security flag)
    • a Review effort [1-5]: x label, where x is the estimated effort to review the PR (enable_review_labels_effort flag)
    Extra sub-tools

    The review tool provides a collection of possible feedbacks about a PR.
    It is recommended to review the possible options, and choose the ones relevant for your use case.
    Some of the feature that are disabled by default are quite useful, and should be considered for enabling. For example:
    require_score_review, require_soc2_ticket, and more.

    Auto-approve PRs

    By invoking:

    /review auto_approve
    

    The tool will automatically approve the PR, and add a comment with the approval.

    To ensure safety, the auto-approval feature is disabled by default. To enable auto-approval, you need to actively set in a pre-defined configuration file the following:

    [pr_reviewer]
    enable_auto_approval = true
    

    (this specific flag cannot be set with a command line argument, only in the configuration file, committed to the repository)

    You can also enable auto-approval only if the PR meets certain requirements, such as that the estimated_review_effort is equal or below a certain threshold, by adjusting the flag:

    [pr_reviewer]
    maximal_review_effort = 5
    
    More PR-Agent commands

    To invoke the PR-Agent, add a comment using one of the following commands:

    • /review: Request a review of your Pull Request.
    • /describe: Update the PR title and description based on the contents of the PR.
    • /improve [--extended]: Suggest code improvements. Extended mode provides a higher quality feedback.
    • /ask <QUESTION>: Ask a question about the PR.
    • /update_changelog: Update the changelog based on the PR's contents.
    • /add_docs 💎: Generate docstring for new components introduced in the PR.
    • /generate_labels 💎: Generate labels for the PR based on the PR's contents.
    • /analyze 💎: Automatically analyzes the PR, and presents changes walkthrough for each component.

    See the tools guide for more details.
    To list the possible configuration parameters, add a /config comment.

    See the review usage page for a comprehensive guide on using this tool.

    Copy link
    Contributor

    github-actions bot commented Mar 7, 2024

    PR Code Suggestions

    CategorySuggestions                                                                                                                                                       
    Best practice
    Handle errors within the GetClassicApiRequest function for more granular control.

    It's recommended to handle errors directly within the GetClassicApiRequest function
    instead of returning them to be handled elsewhere. This approach allows for more granular
    error handling and logging specific to the operation context creation and operation
    addition process.

    swagger/classic_api.go [12-13]

    -err := GetClassicApiRequest(r)
    -return err
    +if err := GetClassicApiRequest(r); err != nil {
    +    // Log the error or handle it as needed
    +    return err
    +}
    +return nil
     
    Provide context in error messages for easier debugging.

    Use a more specific error message in log.Fatal to provide context about where the error
    occurred. This practice aids in debugging by making it clear at which point in the
    execution flow the error happened.

    swagger/cmd/main.go [25-26]

     if err != nil {
    -    log.Fatal(err)
    +    log.Fatalf("Failed to generate OpenAPI specification: %v", err)
     }
     
    Ensure file closure and error handling in writeSchema.

    To ensure the file is properly closed in case of an error during the write operation,
    consider handling the error returned by file.Write before calling file.Close in a defer
    statement. This can be achieved by using a named return value for the error in
    writeSchema.

    swagger/cmd/main.go [43-44]

    -defer file.Close()
    +defer func() {
    +    if closeErr := file.Close(); closeErr != nil && err == nil {
    +        err = closeErr
    +    }
    +}()
     _, err = file.Write(schema)
     
    Maintainability
    Extract the Reflector setup and OpenAPI spec initialization into a separate function.

    To improve the readability and maintainability of the code, consider extracting the setup
    of the openapi3.Reflector and the OpenAPI spec initialization into a separate function.
    This will make the main function more concise and focused on the high-level flow.

    swagger/cmd/main.go [14-23]

    -r := openapi3.Reflector{
    -    Reflector: jsonschema.Reflector{},
    -}
    -r.DefaultOptions = append(r.DefaultOptions, jsonschema.StripDefinitionNamePrefix("Apidef"))
    +r := setupReflector()
     
    -r.Spec = &openapi3.Spec{Openapi: "3.0.3"}
    -r.Spec.Info.
    -    WithTitle("Tyk Gateway API").
    -    WithVersion("5.2.3").
    -    WithDescription(" The Tyk Gateway API is the primary means for integrating your application with the Tyk API Gateway")
    -
    Use descriptive names for functions to improve readability.

    For consistency and clarity, consider using a more descriptive function name than APIS. A
    name that reflects the action being performed or the specific API being handled would
    improve code readability.

    swagger/classic_api.go [11]

    -func APIS(r *openapi3.Reflector) error {
    +func GenerateClassicAPIOpenAPISpec(r *openapi3.Reflector) error {
     

    ✨ Improve tool usage guide:

    Overview:
    The improve tool scans the PR code changes, and automatically generates suggestions for improving the PR code. The tool can be triggered automatically every time a new PR is opened, or can be invoked manually by commenting on a PR.
    When commenting, to edit configurations related to the improve tool (pr_code_suggestions section), use the following template:

    /improve --pr_code_suggestions.some_config1=... --pr_code_suggestions.some_config2=...
    

    With a configuration file, use the following template:

    [pr_code_suggestions]
    some_config1=...
    some_config2=...
    
    Enabling\disabling automation

    When you first install the app, the default mode for the improve tool is:

    pr_commands = ["/improve --pr_code_suggestions.summarize=true", ...]
    

    meaning the improve tool will run automatically on every PR, with summarization enabled. Delete this line to disable the tool from running automatically.

    Utilizing extra instructions

    Extra instructions are very important for the improve tool, since they enable to guide the model to suggestions that are more relevant to the specific needs of the project.

    Be specific, clear, and concise in the instructions. With extra instructions, you are the prompter. Specify relevant aspects that you want the model to focus on.

    Examples for extra instructions:

    [pr_code_suggestions] # /improve #
    extra_instructions="""
    Emphasize the following aspects:
    - Does the code logic cover relevant edge cases?
    - Is the code logic clear and easy to understand?
    - Is the code logic efficient?
    ...
    """
    

    Use triple quotes to write multi-line instructions. Use bullet points to make the instructions more readable.

    A note on code suggestions quality
    • While the current AI for code is getting better and better (GPT-4), it's not flawless. Not all the suggestions will be perfect, and a user should not accept all of them automatically.
    • Suggestions are not meant to be simplistic. Instead, they aim to give deep feedback and raise questions, ideas and thoughts to the user, who can then use his judgment, experience, and understanding of the code base.
    • Recommended to use the 'extra_instructions' field to guide the model to suggestions that are more relevant to the specific needs of the project, or use the custom suggestions 💎 tool
    • With large PRs, best quality will be obtained by using 'improve --extended' mode.
    More PR-Agent commands

    To invoke the PR-Agent, add a comment using one of the following commands:

    • /review: Request a review of your Pull Request.
    • /describe: Update the PR title and description based on the contents of the PR.
    • /improve [--extended]: Suggest code improvements. Extended mode provides a higher quality feedback.
    • /ask <QUESTION>: Ask a question about the PR.
    • /update_changelog: Update the changelog based on the PR's contents.
    • /add_docs 💎: Generate docstring for new components introduced in the PR.
    • /generate_labels 💎: Generate labels for the PR based on the PR's contents.
    • /analyze 💎: Automatically analyzes the PR, and presents changes walkthrough for each component.

    See the tools guide for more details.
    To list the possible configuration parameters, add a /config comment.

    See the improve usage page for a more comprehensive guide on using this tool.

    Copy link
    Contributor

    github-actions bot commented Mar 7, 2024

    💥 CI tests failed 🙈

    git-state

    diff --git a/go.mod b/go.mod
    index f3e43ca..5a32478 100644
    --- a/go.mod
    +++ b/go.mod
    @@ -92,6 +92,8 @@ require (
     	github.com/go-redis/redismock/v9 v9.2.0
     	github.com/google/go-cmp v0.6.0
     	github.com/newrelic/go-agent v2.13.0+incompatible
    +	github.com/swaggest/jsonschema-go v0.3.66
    +	github.com/swaggest/openapi-go v0.2.49
     	go.opentelemetry.io/otel v1.19.0
     	go.opentelemetry.io/otel/trace v1.19.0
     	go.uber.org/mock v0.4.0
    @@ -183,8 +185,6 @@ require (
     	github.com/shopspring/decimal v1.2.0 // indirect
     	github.com/spf13/cast v1.6.0 // indirect
     	github.com/stretchr/objx v0.5.0 // indirect
    -	github.com/swaggest/jsonschema-go v0.3.66 // indirect
    -	github.com/swaggest/openapi-go v0.2.49 // indirect
     	github.com/swaggest/refl v1.3.0 // indirect
     	github.com/tidwall/gjson v1.11.0 // indirect
     	github.com/tidwall/match v1.1.1 // indirect
    diff --git a/go.sum b/go.sum
    index bf237ac..0f43375 100644
    --- a/go.sum
    +++ b/go.sum
    @@ -99,6 +99,10 @@ github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24
     github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8=
     github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
     github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs=
    +github.com/bool64/dev v0.2.34 h1:P9n315P8LdpxusnYQ0X7MP1CZXwBK5ae5RZrd+GdSZE=
    +github.com/bool64/dev v0.2.34/go.mod h1:iJbh1y/HkunEPhgebWRNcs8wfGq7sjvJ6W5iabL8ACg=
    +github.com/bool64/shared v0.1.5 h1:fp3eUhBsrSjNCQPcSdQqZxxh9bBwrYiZ+zOKFkM0/2E=
    +github.com/bool64/shared v0.1.5/go.mod h1:081yz68YC9jeFB3+Bbmno2RFWvGKv1lPKkMP6MHJlPs=
     github.com/bshuster-repo/logrus-logstash-hook v1.1.0 h1:o2FzZifLg+z/DN1OFmzTWzZZx/roaqt8IPZCIVco8r4=
     github.com/bshuster-repo/logrus-logstash-hook v1.1.0/go.mod h1:Q2aXOe7rNuPgbBtPCOzYyWDvKX7+FpxE5sRdvcPoui0=
     github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
    @@ -360,6 +364,8 @@ github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpO
     github.com/huandu/xstrings v1.2.1/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE=
     github.com/huandu/xstrings v1.3.3 h1:/Gcsuc1x8JVbJ9/rlye4xZnVAbEkGauT8lbebqcQws4=
     github.com/huandu/xstrings v1.3.3/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE=
    +github.com/iancoleman/orderedmap v0.3.0 h1:5cbR2grmZR/DiVt+VJopEhtVs9YGInGIxAoMJn+Ichc=
    +github.com/iancoleman/orderedmap v0.3.0/go.mod h1:XuLcCUkdL5owUCQeF2Ue9uuw1EptkJDkXXS7VoV7XGE=
     github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI=
     github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho=
     github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
    @@ -576,9 +582,8 @@ github.com/sebdah/goldie v0.0.0-20180424091453-8784dd1ab561 h1:IY+sDBJR/wRtsxq+6
     github.com/sebdah/goldie v0.0.0-20180424091453-8784dd1ab561/go.mod h1:lvjGftC8oe7XPtyrOidaMi0rp5B9+XY/ZRUynGnuaxQ=
     github.com/sebdah/goldie/v2 v2.5.3 h1:9ES/mNN+HNUbNWpVAlrzuZ7jE+Nrczbj8uFRjM7624Y=
     github.com/sebdah/goldie/v2 v2.5.3/go.mod h1:oZ9fp0+se1eapSRjfYbsV/0Hqhbuu3bJVvKI/NNtssI=
    -github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0=
    -github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM=
     github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8=
    +github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I=
     github.com/shopspring/decimal v1.2.0 h1:abSATXmQEYyShuxI4/vyW3tV1MrKAJzCZ/0zLUXYbsQ=
     github.com/shopspring/decimal v1.2.0/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o=
     github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
    @@ -610,6 +615,8 @@ github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcU
     github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
     github.com/stvp/tempredis v0.0.0-20181119212430-b82af8480203 h1:QVqDTf3h2WHt08YuiTGPZLls0Wq99X9bWd0Q5ZSBesM=
     github.com/stvp/tempredis v0.0.0-20181119212430-b82af8480203/go.mod h1:oqN97ltKNihBbwlX8dLpwxCl3+HnXKV/R0e+sRLd9C8=
    +github.com/swaggest/assertjson v1.9.0 h1:dKu0BfJkIxv/xe//mkCrK5yZbs79jL7OVf9Ija7o2xQ=
    +github.com/swaggest/assertjson v1.9.0/go.mod h1:b+ZKX2VRiUjxfUIal0HDN85W0nHPAYUbYH5WkkSsFsU=
     github.com/swaggest/jsonschema-go v0.3.66 h1:4c5d7NRRqPLTswsbaypKqcMe3Z+CYHE3/lGsPIByp8o=
     github.com/swaggest/jsonschema-go v0.3.66/go.mod h1:7N43/CwdaWgPUDfYV70K7Qm79tRqe/al7gLSt9YeGIE=
     github.com/swaggest/openapi-go v0.2.49 h1:WxAfdde6DlfQPQayHWTb64CywK9+vpToi7iN17iDPO8=
    @@ -650,6 +657,10 @@ github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17
     github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y=
     github.com/xhit/go-str2duration/v2 v2.1.0 h1:lxklc02Drh6ynqX+DdPyp5pCKLUQpRT8bp8Ydu2Bstc=
     github.com/xhit/go-str2duration/v2 v2.1.0/go.mod h1:ohY8p+0f07DiV6Em5LKB0s2YpLtXVyJfNt1+BlmyAsU=
    +github.com/yudai/gojsondiff v1.0.0 h1:27cbfqXLVEJ1o8I6v3y9lg8Ydm53EKqHXAOMxEGlCOA=
    +github.com/yudai/gojsondiff v1.0.0/go.mod h1:AY32+k2cwILAkW1fbgxQ5mUmMiZFgLIV+FBNExI05xg=
    +github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82 h1:BHyfKlQyqbsFN5p3IfnEUduWvb9is428/nNb5L3U01M=
    +github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82/go.mod h1:lgjkn3NuSvDfVJdfcVVdX+jpBxNmX4rDAzaS45IcYoM=
     github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
     github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
     github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=

    Please look at the run or in the Checks tab.

    @buger
    Copy link
    Member

    buger commented Mar 7, 2024

    API tests result - postgres15-sha256 env: success
    Branch used: refs/pull/6123/merge
    Commit:
    Triggered by: pull_request (@Keithwachira)
    Execution page

    @buger
    Copy link
    Member

    buger commented Mar 7, 2024

    API tests result - mongo44-sha256 env: success
    Branch used: refs/pull/6123/merge
    Commit:
    Triggered by: pull_request (@Keithwachira)
    Execution page

    @letzya letzya requested review from titpetric and removed request for titpetric August 21, 2024 13:11
    Copy link

    Quality Gate Failed Quality Gate failed

    Failed conditions
    0.0% Coverage on New Code (required ≥ 80%)
    29.4% Duplication on New Code (required ≤ 3%)

    See analysis details on SonarCloud

    titpetric pushed a commit that referenced this pull request Sep 18, 2024
    ## **User description**
    
    This pull request contains :
    1. The new gateway swagger
    2.  A new linter
    3.  And a readme of how to generate the swagger 
    .
    
    .This provides the documentation on how you can generate the gateway
    Open Api specification. It contains a read me with all the steps to
    generate the OAS.
    
    The OAS code is in this pr :
    #6123
    [TT-13109]
    
    ___
    
    ## **Type**
    Documentation
    
    
    ___
    
    ## **Description**
    - Added a comprehensive README.md in the `tyk-api-documentation`
    directory.
    - The documentation includes details on the version of OAS used, the
    tooling (Redocly), and the library (`openapi-go`) for OAS generation.
    - Step-by-step instructions are provided for generating the Swagger.yml
    file using a make command in the specified repository branch.
    - Describes the file structure within the Swagger directory, explaining
    the organization of files by OAS tags and the roles of various files in
    the generation process.
    
    
    ___
    
    
    
    ## **Changes walkthrough**
    <table><thead><tr><th></th><th align="left">Relevant
    files</th></tr></thead><tbody><tr><td><strong>Documentation
    </strong></td><td><table>
    <tr>
      <td>
        <details>
    <summary><strong>README.md</strong><dd><code>Add Documentation for
    Generating Tyk API Swagger File</code>&nbsp; &nbsp; &nbsp; &nbsp;
    </dd></summary>
    <hr>
    
    tyk-api-documentation/README.md
    <li>Introduced a new README.md for Tyk API Documentation.<br> <li>
    Detailed the process and tools used to generate the Open API
    <br>Specification (OAS).<br> <li> Provided step-by-step instructions on
    how to generate the Swagger.yml <br>file.<br> <li> Explained the file
    structure within the Swagger directory.<br>
    
    
    </details>
        
    
      </td>
    <td><a
    href="https://github.com/TykTechnologies/tyk/pull/6231/files#diff-25581cb9574ab0d44d58541ab1ead676194ddcb9dfe7ba4687197f9673df6093">+33/-0</a>&nbsp;
    &nbsp; </td>
    </tr>                    
    </table></td></tr></tr></tbody></table>
    
    ___
    
    > ✨ **PR-Agent usage**:
    >Comment `/help` on the PR to get a list of all available PR-Agent tools
    and their descriptions
    
    
    
    [DX-1272]:
    https://tyktech.atlassian.net/browse/DX-1272?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
    
    [TT-13109]:
    https://tyktech.atlassian.net/browse/TT-13109?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
    
    ---------
    
    Co-authored-by: Yaara <[email protected]>
    tykbot bot pushed a commit that referenced this pull request Sep 18, 2024
    ## **User description**
    
    This pull request contains :
    1. The new gateway swagger
    2.  A new linter
    3.  And a readme of how to generate the swagger 
    .
    
    .This provides the documentation on how you can generate the gateway
    Open Api specification. It contains a read me with all the steps to
    generate the OAS.
    
    The OAS code is in this pr :
    #6123
    [TT-13109]
    
    ___
    
    ## **Type**
    Documentation
    
    
    ___
    
    ## **Description**
    - Added a comprehensive README.md in the `tyk-api-documentation`
    directory.
    - The documentation includes details on the version of OAS used, the
    tooling (Redocly), and the library (`openapi-go`) for OAS generation.
    - Step-by-step instructions are provided for generating the Swagger.yml
    file using a make command in the specified repository branch.
    - Describes the file structure within the Swagger directory, explaining
    the organization of files by OAS tags and the roles of various files in
    the generation process.
    
    
    ___
    
    
    
    ## **Changes walkthrough**
    <table><thead><tr><th></th><th align="left">Relevant
    files</th></tr></thead><tbody><tr><td><strong>Documentation
    </strong></td><td><table>
    <tr>
      <td>
        <details>
    <summary><strong>README.md</strong><dd><code>Add Documentation for
    Generating Tyk API Swagger File</code>&nbsp; &nbsp; &nbsp; &nbsp;
    </dd></summary>
    <hr>
    
    tyk-api-documentation/README.md
    <li>Introduced a new README.md for Tyk API Documentation.<br> <li>
    Detailed the process and tools used to generate the Open API
    <br>Specification (OAS).<br> <li> Provided step-by-step instructions on
    how to generate the Swagger.yml <br>file.<br> <li> Explained the file
    structure within the Swagger directory.<br>
    
    
    </details>
        
    
      </td>
    <td><a
    href="https://github.com/TykTechnologies/tyk/pull/6231/files#diff-25581cb9574ab0d44d58541ab1ead676194ddcb9dfe7ba4687197f9673df6093">+33/-0</a>&nbsp;
    &nbsp; </td>
    </tr>                    
    </table></td></tr></tr></tbody></table>
    
    ___
    
    > ✨ **PR-Agent usage**:
    >Comment `/help` on the PR to get a list of all available PR-Agent tools
    and their descriptions
    
    
    
    [DX-1272]:
    https://tyktech.atlassian.net/browse/DX-1272?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
    
    [TT-13109]:
    https://tyktech.atlassian.net/browse/TT-13109?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
    
    ---------
    
    Co-authored-by: Yaara <[email protected]>
    
    (cherry picked from commit ec893f8)
    buger added a commit that referenced this pull request Sep 18, 2024
    …idator for Gateway (#6231)
    
    [TT-13109]Generate New Swagger and Update Validator for Gateway (#6231)
    
    ## **User description**
    
    This pull request contains :
    1. The new gateway swagger
    2.  A new linter
    3.  And a readme of how to generate the swagger 
    .
    
    .This provides the documentation on how you can generate the gateway
    Open Api specification. It contains a read me with all the steps to
    generate the OAS.
    
    The OAS code is in this pr :
    #6123
    [TT-13109]
    
    ___
    
    ## **Type**
    Documentation
    
    
    ___
    
    ## **Description**
    - Added a comprehensive README.md in the `tyk-api-documentation`
    directory.
    - The documentation includes details on the version of OAS used, the
    tooling (Redocly), and the library (`openapi-go`) for OAS generation.
    - Step-by-step instructions are provided for generating the Swagger.yml
    file using a make command in the specified repository branch.
    - Describes the file structure within the Swagger directory, explaining
    the organization of files by OAS tags and the roles of various files in
    the generation process.
    
    
    ___
    
    
    
    ## **Changes walkthrough**
    <table><thead><tr><th></th><th align="left">Relevant
    files</th></tr></thead><tbody><tr><td><strong>Documentation
    </strong></td><td><table>
    <tr>
      <td>
        <details>
    <summary><strong>README.md</strong><dd><code>Add Documentation for
    Generating Tyk API Swagger File</code>&nbsp; &nbsp; &nbsp; &nbsp;
    </dd></summary>
    <hr>
    
    tyk-api-documentation/README.md
    <li>Introduced a new README.md for Tyk API Documentation.<br> <li>
    Detailed the process and tools used to generate the Open API
    <br>Specification (OAS).<br> <li> Provided step-by-step instructions on
    how to generate the Swagger.yml <br>file.<br> <li> Explained the file
    structure within the Swagger directory.<br>
    
    
    </details>
        
    
      </td>
    <td><a
    href="https://github.com/TykTechnologies/tyk/pull/6231/files#diff-25581cb9574ab0d44d58541ab1ead676194ddcb9dfe7ba4687197f9673df6093">+33/-0</a>&nbsp;
    &nbsp; </td>
    </tr>                    
    </table></td></tr></tr></tbody></table>
    
    ___
    
    > ✨ **PR-Agent usage**:
    >Comment `/help` on the PR to get a list of all available PR-Agent tools
    and their descriptions
    
    
    
    [DX-1272]:
    https://tyktech.atlassian.net/browse/DX-1272?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
    
    [TT-13109]:
    https://tyktech.atlassian.net/browse/TT-13109?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
    
    ---------
    
    Co-authored-by: Yaara <[email protected]>
    tykbot bot pushed a commit that referenced this pull request Sep 18, 2024
    ## **User description**
    
    This pull request contains :
    1. The new gateway swagger
    2.  A new linter
    3.  And a readme of how to generate the swagger 
    .
    
    .This provides the documentation on how you can generate the gateway
    Open Api specification. It contains a read me with all the steps to
    generate the OAS.
    
    The OAS code is in this pr :
    #6123
    [TT-13109]
    
    ___
    
    ## **Type**
    Documentation
    
    
    ___
    
    ## **Description**
    - Added a comprehensive README.md in the `tyk-api-documentation`
    directory.
    - The documentation includes details on the version of OAS used, the
    tooling (Redocly), and the library (`openapi-go`) for OAS generation.
    - Step-by-step instructions are provided for generating the Swagger.yml
    file using a make command in the specified repository branch.
    - Describes the file structure within the Swagger directory, explaining
    the organization of files by OAS tags and the roles of various files in
    the generation process.
    
    
    ___
    
    
    
    ## **Changes walkthrough**
    <table><thead><tr><th></th><th align="left">Relevant
    files</th></tr></thead><tbody><tr><td><strong>Documentation
    </strong></td><td><table>
    <tr>
      <td>
        <details>
    <summary><strong>README.md</strong><dd><code>Add Documentation for
    Generating Tyk API Swagger File</code>&nbsp; &nbsp; &nbsp; &nbsp;
    </dd></summary>
    <hr>
    
    tyk-api-documentation/README.md
    <li>Introduced a new README.md for Tyk API Documentation.<br> <li>
    Detailed the process and tools used to generate the Open API
    <br>Specification (OAS).<br> <li> Provided step-by-step instructions on
    how to generate the Swagger.yml <br>file.<br> <li> Explained the file
    structure within the Swagger directory.<br>
    
    
    </details>
        
    
      </td>
    <td><a
    href="https://github.com/TykTechnologies/tyk/pull/6231/files#diff-25581cb9574ab0d44d58541ab1ead676194ddcb9dfe7ba4687197f9673df6093">+33/-0</a>&nbsp;
    &nbsp; </td>
    </tr>                    
    </table></td></tr></tr></tbody></table>
    
    ___
    
    > ✨ **PR-Agent usage**:
    >Comment `/help` on the PR to get a list of all available PR-Agent tools
    and their descriptions
    
    
    
    [DX-1272]:
    https://tyktech.atlassian.net/browse/DX-1272?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
    
    [TT-13109]:
    https://tyktech.atlassian.net/browse/TT-13109?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
    
    ---------
    
    Co-authored-by: Yaara <[email protected]>
    
    (cherry picked from commit ec893f8)
    buger added a commit that referenced this pull request Sep 18, 2024
    …alidator for Gateway (#6231)
    
    [TT-13109]Generate New Swagger and Update Validator for Gateway (#6231)
    
    ## **User description**
    
    This pull request contains :
    1. The new gateway swagger
    2.  A new linter
    3.  And a readme of how to generate the swagger 
    .
    
    .This provides the documentation on how you can generate the gateway
    Open Api specification. It contains a read me with all the steps to
    generate the OAS.
    
    The OAS code is in this pr :
    #6123
    [TT-13109]
    
    ___
    
    ## **Type**
    Documentation
    
    
    ___
    
    ## **Description**
    - Added a comprehensive README.md in the `tyk-api-documentation`
    directory.
    - The documentation includes details on the version of OAS used, the
    tooling (Redocly), and the library (`openapi-go`) for OAS generation.
    - Step-by-step instructions are provided for generating the Swagger.yml
    file using a make command in the specified repository branch.
    - Describes the file structure within the Swagger directory, explaining
    the organization of files by OAS tags and the roles of various files in
    the generation process.
    
    
    ___
    
    
    
    ## **Changes walkthrough**
    <table><thead><tr><th></th><th align="left">Relevant
    files</th></tr></thead><tbody><tr><td><strong>Documentation
    </strong></td><td><table>
    <tr>
      <td>
        <details>
    <summary><strong>README.md</strong><dd><code>Add Documentation for
    Generating Tyk API Swagger File</code>&nbsp; &nbsp; &nbsp; &nbsp;
    </dd></summary>
    <hr>
    
    tyk-api-documentation/README.md
    <li>Introduced a new README.md for Tyk API Documentation.<br> <li>
    Detailed the process and tools used to generate the Open API
    <br>Specification (OAS).<br> <li> Provided step-by-step instructions on
    how to generate the Swagger.yml <br>file.<br> <li> Explained the file
    structure within the Swagger directory.<br>
    
    
    </details>
        
    
      </td>
    <td><a
    href="https://github.com/TykTechnologies/tyk/pull/6231/files#diff-25581cb9574ab0d44d58541ab1ead676194ddcb9dfe7ba4687197f9673df6093">+33/-0</a>&nbsp;
    &nbsp; </td>
    </tr>                    
    </table></td></tr></tr></tbody></table>
    
    ___
    
    > ✨ **PR-Agent usage**:
    >Comment `/help` on the PR to get a list of all available PR-Agent tools
    and their descriptions
    
    
    
    [DX-1272]:
    https://tyktech.atlassian.net/browse/DX-1272?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
    
    [TT-13109]:
    https://tyktech.atlassian.net/browse/TT-13109?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
    
    ---------
    
    Co-authored-by: Yaara <[email protected]>
    @yurisasuke yurisasuke marked this pull request as ready for review December 19, 2024 14:31
    Copy link
    Contributor

    PR Reviewer Guide 🔍

    Here are some key observations to aid the review process:

    ⏱️ Estimated effort to review: 5 🔵🔵🔵🔵🔵
    🧪 No relevant tests
    🔒 Security concerns

    Logging Middleware:
    The loggingMiddleware function in gateway/server.go logs request URLs, which may include sensitive information. Ensure sensitive data such as API keys or tokens are sanitized before logging.

    ⚡ Recommended focus areas for review

    Code Smell
    The RefExamples and RefParameters functions contain commented-out code, which can clutter the codebase and reduce maintainability. Consider removing or uncommenting these lines if they are necessary.

    Missing Documentation
    Several TODO comments indicate missing summaries and descriptions for operations like rotateOauthClientHandler. Ensure all operations have proper documentation for clarity.

    Logging Issue
    The log message in handleGetAllOrgKeys contains a placeholder message ("keith is here"), which seems unintended. Replace it with a meaningful log message.

    Logging Middleware
    The loggingMiddleware function logs the request URL but does not sanitize sensitive information. Ensure sensitive data is not exposed in logs.

    Hardcoded File Paths
    The generate and diff targets use hardcoded file paths like swagger.yml and master_swagger.yml. Consider parameterizing these paths for flexibility.

    Copy link
    Contributor

    PR Code Suggestions ✨

    Explore these optional code suggestions:

    CategorySuggestion                                                                                                                                    Score
    Security
    Remove debug log statements that expose sensitive information to enhance security

    Remove the debug log statement log.Println("token is", token) as it may expose
    sensitive information like tokens in the logs, which is a security risk.

    gateway/api.go [245]

    -log.Println("token is", token)
    +// Removed debug log statement to avoid exposing sensitive information
    Suggestion importance[1-10]: 10

    Why: Removing the debug log statement that exposes sensitive information like tokens is critical for maintaining security. This change prevents potential leaks of sensitive data in logs.

    10
    Avoid logging sensitive information in middleware to enhance security

    Ensure that the loggingMiddleware function logs sensitive information securely by
    avoiding logging the full URL, which may contain sensitive query parameters or data.

    gateway/server.go [1974-1975]

    -log.Printf("%s%s%s%s", "http://", r.Host, "/tyk", r.URL)
    -log.Println(r.URL)
    +log.Printf("Request received at host: %s, path: %s", r.Host, r.URL.Path)
    Suggestion importance[1-10]: 9

    Why: The suggestion improves security by ensuring sensitive information, such as query parameters, is not logged. This is a critical enhancement for protecting user data and maintaining compliance with security best practices.

    9
    General
    Replace placeholder log messages with meaningful descriptions

    Replace the placeholder log message "keith is here" with a meaningful and
    descriptive message to maintain professional logging practices.

    gateway/api.go [1859]

    -"org":    "keith is here",
    +"org":    "organization ID retrieved",
    Suggestion importance[1-10]: 9

    Why: Replacing placeholder log messages with meaningful descriptions enhances the professionalism and clarity of the logs, making them more useful for debugging and monitoring.

    9
    Fix file permission mode representation to ensure compatibility with Go standards

    Correct the file permission mode in ioutil.WriteFile calls from 0o644 to 0644 to
    ensure compatibility with Go's standard file permission representation.

    gateway/api.go [937]

    -if err := ioutil.WriteFile(polFilePath, asByte, 0o644); err != nil {
    +if err := ioutil.WriteFile(polFilePath, asByte, 0644); err != nil {
    Suggestion importance[1-10]: 8

    Why: Correcting the file permission mode from 0o644 to 0644 ensures compatibility with Go's standard file permission representation, which is important for code consistency and avoiding potential issues.

    8
    Remove unnecessary debug log statements to clean up the code

    Remove the unnecessary debug log statement log.Println(hashKeyFunction) as it
    provides no meaningful information and may clutter the logs.

    gateway/api.go [237]

    -log.Println(hashKeyFunction)
    +// Removed unnecessary debug log statement
    Suggestion importance[1-10]: 7

    Why: Removing the unnecessary debug log statement improves code cleanliness and avoids cluttering logs with irrelevant information.

    7
    Use the constant CertsTag instead of a hardcoded string to ensure consistency

    Correct the tag name in the getCertsWithIDs function to use the constant CertsTag
    instead of the hardcoded string "CertsTag".

    swagger/certs.go [61]

    -Tag:         "CertsTag",
    +Tag:         CertsTag,
    Suggestion importance[1-10]: 7

    Why: Replacing the hardcoded string with the constant CertsTag improves code maintainability and reduces the risk of errors due to inconsistencies. This is a good practice for clean and consistent code.

    7
    Replace abrupt termination with proper error handling during JSON unmarshalling in oasSample

    Validate the unmarshalling process in the oasSample function to avoid abrupt
    termination of the program in case of an error.

    swagger/oas_api.go [483-485]

     err := json.Unmarshal([]byte(data), &result)
     if err != nil {
    -    log.Fatalf("Error unmarshalling JSON: %v", err)
    +    return nil, fmt.Errorf("error unmarshalling JSON: %w", err)
     }
    Suggestion importance[1-10]: 7

    Why: This suggestion replaces abrupt termination with proper error handling, improving the resilience of the oasSample function. However, the impact is slightly lower as it addresses a specific edge case.

    7
    Possible issue
    Ensure proper resource cleanup by handling potential errors during file closure

    Ensure the file opened in writeSchema is closed properly even if an error occurs
    during the os.OpenFile operation.

    swagger/cmd/main.go [123-127]

     file, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE, 0o644)
     if err != nil {
         return err
     }
    -defer file.Close()
    +defer func() {
    +    if cerr := file.Close(); cerr != nil && err == nil {
    +        err = cerr
    +    }
    +}()
    Suggestion importance[1-10]: 9

    Why: The suggestion ensures proper resource cleanup by handling errors during file closure, which is crucial for preventing resource leaks and maintaining application stability. This is a significant improvement for error handling.

    9
    Add error handling for the addTag function to prevent runtime failures

    Ensure that the addTag function in the Keys function checks for errors and handles
    them appropriately to prevent potential runtime issues if the function fails.

    swagger/keys.go [20-22]

    -addTag(KeysTag, KeyTagsDesc, optionalTagParameters{})
    +if err := addTag(KeysTag, KeyTagsDesc, optionalTagParameters{}); err != nil {
    +    return err
    +}
     return addOperations(r, getKeyWithID, updateKeyPolicy, previewKeyRequest, putKeyRequest, createKeyRequest, postKeyRequest, getListOfKeys, deleteKeyRequest, createCustomKeyRequest)
    Suggestion importance[1-10]: 9

    Why: Adding error handling for the addTag function is crucial as it ensures that any failure in this function is caught and handled, preventing potential runtime issues. This suggestion directly improves the robustness of the Keys function.

    9
    Add error handling for the addTag function to prevent silent failures

    Add error handling for the addTag function in the InvalidateCache method to ensure
    it does not silently fail.

    swagger/cache.go [16-17]

    -addTag(CacheTag, CacheTagDesc, optionalTagParameters{})
    +if err := addTag(CacheTag, CacheTagDesc, optionalTagParameters{}); err != nil {
    +    return err
    +}
     return invalidateCache(r)
    Suggestion importance[1-10]: 8

    Why: Adding error handling for the addTag function ensures robustness by preventing silent failures, which could lead to undetected issues during runtime. This is a valuable improvement for reliability.

    8
    Ensure error handling for NewOperationWithSafeExample to avoid proceeding with a nil operation

    Add error handling for the NewOperationWithSafeExample call in the
    getListOfOASApisRequest function to ensure the program doesn't proceed with a nil
    operation in case of an error.

    swagger/oas_api.go [35-43]

     op, err := NewOperationWithSafeExample(r, SafeOperation{
         Method:      http.MethodGet,
         PathPattern: "/tyk/apis/oas",
         OperationID: "listApisOAS",
         Tag:         OASTag,
     })
    -oc := op.oc
     if err != nil {
         return err
     }
    +oc := op.oc
    Suggestion importance[1-10]: 8

    Why: The suggestion ensures that the program does not proceed with a nil operation in case of an error, which is critical for maintaining the stability and reliability of the getListOfOASApisRequest function.

    8
    Implement error handling for applyPolicies in the previewKeyRequest function to avoid runtime issues

    Address the TODO comments in the previewKeyRequest function to ensure proper error
    handling for applyPolicies and avoid potential runtime issues.

    swagger/keys.go [295-297]

    -// TODO::in the code we do not check for applyPolicies errors
    +if err := applyPolicies(); err != nil {
    +    return fmt.Errorf("error applying policies: %w", err)
    +}
     op, err := NewOperationWithSafeExample(r, SafeOperation{
         Method:      http.MethodPost,
         PathPattern: "/tyk/keys/preview",
         OperationID: "validateAKeyDefinition",
         Tag:         KeysTag,
     })
    Suggestion importance[1-10]: 6

    Why: While addressing the TODO comment and adding error handling for applyPolicies is beneficial, the suggestion assumes the existence of an applyPolicies function, which is not present in the provided code. This reduces its relevance and applicability.

    6

    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
    Projects
    None yet
    Development

    Successfully merging this pull request may close these issues.

    2 participants