Skip to content

Commit

Permalink
[TT-9586] Prevent panic in setHasMock func (#5361)
Browse files Browse the repository at this point in the history
This PR fixes a panic case inside `APISpec.setHasMock` func.
  • Loading branch information
furkansenharputlu authored Jul 26, 2023
1 parent 808df11 commit 8a2b4c1
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 4 deletions.
7 changes: 4 additions & 3 deletions apidef/oas/oas.go
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,8 @@ func (s *OAS) getTykSecurityScheme(name string) interface{} {
return securitySchemes[name]
}

func (s *OAS) getTykMiddleware() (middleware *Middleware) {
// GetTykMiddleware returns middleware section from XTykAPIGateway.
func (s *OAS) GetTykMiddleware() (middleware *Middleware) {
if s.GetTykExtension() != nil {
middleware = s.GetTykExtension().Middleware
}
Expand All @@ -292,8 +293,8 @@ func (s *OAS) getTykMiddleware() (middleware *Middleware) {
}

func (s *OAS) getTykOperations() (operations Operations) {
if s.getTykMiddleware() != nil {
operations = s.getTykMiddleware().Operations
if s.GetTykMiddleware() != nil {
operations = s.GetTykMiddleware().Operations
}

return
Expand Down
2 changes: 1 addition & 1 deletion gateway/api_definition.go
Original file line number Diff line number Diff line change
Expand Up @@ -1728,7 +1728,7 @@ func (a *APISpec) setHasMock() {
return
}

middleware := a.OAS.GetTykExtension().Middleware
middleware := a.OAS.GetTykMiddleware()
if middleware == nil {
a.HasMock = false
return
Expand Down
43 changes: 43 additions & 0 deletions gateway/api_definition_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ import (
"text/template"
"time"

"github.com/TykTechnologies/tyk/apidef/oas"

"github.com/TykTechnologies/storage/persistent/model"
"github.com/TykTechnologies/tyk/config"
"github.com/TykTechnologies/tyk/rpc"
Expand Down Expand Up @@ -1489,3 +1491,44 @@ func Test_LoadAPIsFromRPC(t *testing.T) {
assert.Equal(t, 1, len(apisMap), "expected 0 APIs to be loaded from RPC backup")
})
}

func TestAPISpec_setHasMock(t *testing.T) {
s := APISpec{APIDefinition: &apidef.APIDefinition{}}

s.setHasMock()
assert.False(t, s.HasMock)

s.IsOAS = true
s.setHasMock()
assert.False(t, s.HasMock)

s.OAS = oas.OAS{}
s.setHasMock()
assert.False(t, s.HasMock)

xTyk := &oas.XTykAPIGateway{}
s.OAS.SetTykExtension(xTyk)
s.setHasMock()
assert.False(t, s.HasMock)

middleware := &oas.Middleware{}
xTyk.Middleware = middleware
s.setHasMock()
assert.False(t, s.HasMock)

op := &oas.Operation{}
middleware.Operations = oas.Operations{
"my-operation": op,
}
s.setHasMock()
assert.False(t, s.HasMock)

mock := &oas.MockResponse{}
op.MockResponse = mock
s.setHasMock()
assert.False(t, s.HasMock)

mock.Enabled = true
s.setHasMock()
assert.True(t, s.HasMock)
}

0 comments on commit 8a2b4c1

Please sign in to comment.