Skip to content

Commit

Permalink
Include validateRequest if any parameters are defined (TykTechnologie…
Browse files Browse the repository at this point in the history
…s#4765)

<!-- Provide a general summary of your changes in the Title above -->

## Description

ValidateRequest middleware needs to check for parameters defined and
enable validation for parameters too.

<!-- Describe your changes in detail -->

## Related Issue

https://tyktech.atlassian.net/browse/TT-7861

<!-- This project only accepts pull requests related to open issues. -->
<!-- If suggesting a new feature or change, please discuss it in an
issue first. -->
<!-- If fixing a bug, there should be an issue describing it with steps
to reproduce. -->
<!-- OSS: Please link to the issue here. Tyk: please create/link the
JIRA ticket. -->

## Motivation and Context

<!-- Why is this change required? What problem does it solve? -->

## How This Has Been Tested

<!-- Please describe in detail how you tested your changes -->
<!-- Include details of your testing environment, and the tests -->
<!-- you ran to see how your change affects other areas of the code,
etc. -->
<!-- This information is helpful for reviewers and QA. -->

## Screenshots (if appropriate)

## Types of changes

<!-- What types of changes does your code introduce? Put an `x` in all
the boxes that apply: -->

- [x] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Refactoring or add test (improvements in base code or adds test
coverage to functionality)

## Checklist

<!-- Go over all the following points, and put an `x` in all the boxes
that apply -->
<!-- If there are no documentation updates required, mark the item as
checked. -->
<!-- Raise up any additional concerns not covered by the checklist. -->

- [ ] I ensured that the documentation is up to date
- [ ] I explained why this PR updates go.mod in detail with reasoning
why it's required
- [ ] I would like a code coverage CI quality gate exception and have
explained why

---------

Co-authored-by: Tit Petric <[email protected]>
  • Loading branch information
titpetric and Tit Petric authored Feb 13, 2023
1 parent edca919 commit 7e996cd
Show file tree
Hide file tree
Showing 4 changed files with 958 additions and 8 deletions.
116 changes: 116 additions & 0 deletions apidef/oas/import_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
package oas_test

import (
"encoding/json"
"io/ioutil"
"path"
"runtime"
"sort"
"testing"

"github.com/stretchr/testify/assert"

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

// findTestPath makes tests work with any working dir.
func findTestPath(filename string) string {
_, testFilename, _, _ := runtime.Caller(0)
testDir := path.Dir(testFilename)
return path.Join(testDir, filename)
}

// TestImportValidateRequest
//
// - Loads the complete petstore,
// - Imports the petstore,
// - Asserts expected routes for validateRequest.
func TestImportValidateRequest(t *testing.T) {
// Load petstore
oasContents, err := ioutil.ReadFile(findTestPath("testdata/petstore-no-responses.json"))
assert.NoError(t, err)
assert.NotNil(t, oasContents)

// Decode petstore
var petstore oas.OAS
assert.NoError(t, json.Unmarshal(oasContents, &petstore))

// Build tyk extension
trueVal, falseVal := true, false

isImport := true
params := oas.TykExtensionConfigParams{
ListenPath: "/listen-api",
UpstreamURL: "https://example.org/api",
ValidateRequest: &trueVal,
MockResponse: &falseVal,
}
assert.NoError(t, petstore.BuildDefaultTykExtension(params, isImport))

t.Run("Check paths got imported", func(t *testing.T) {
assert.Len(t, petstore.Paths, 13)

want := []string{
"/pet/{petId}/uploadImage",
"/store/inventory",
"/user",
"/user/createWithList",
"/user/login",
"/pet",
"/pet/findByStatus",
"/pet/{petId}",
"/user/{username}",
"/user/logout",
"/pet/findByTags",
"/store/order",
"/store/order/{orderId}",
}

got := make([]string, 0, len(petstore.Paths))
for endpoint, _ := range petstore.Paths {
got = append(got, endpoint)
}

sort.Strings(want)
sort.Strings(got)

assert.Equal(t, want, got)
})

t.Run("Check middlware for validateRequest got defined", func(t *testing.T) {
extension := petstore.GetTykExtension()
assert.NotNil(t, extension, "Expected Tyk Extension")
assert.NotNil(t, extension.Middleware, "Expected middleware")
assert.NotNil(t, extension.Middleware.Operations, "Expected operations")

want := []string{
"createUser",
"createUsersWithListInput",
"deleteOrder",
"deletePet",
"deleteUser",
"findPetsByStatus",
"findPetsByTags",
"getOrderById",
"getPetById",
"getUserByName",
"loginUser",
"placeOrder",
"updatePetWithForm",
"updateUser",
"uploadFile",
}

got := make([]string, 0, len(extension.Middleware.Operations))
for operationID, op := range extension.Middleware.Operations {
if op.ValidateRequest != nil {
got = append(got, operationID)
}
}

sort.Strings(want)
sort.Strings(got)

assert.Equal(t, want, got)
})
}
12 changes: 8 additions & 4 deletions apidef/oas/operation.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ func (o *Operation) Import(oasOperation *openapi3.Operation, overRideValues TykE
validate = &ValidateRequest{}
}

if shouldImport := validate.shouldImportValidateRequest(oasOperation); shouldImport {
if ok := validate.shouldImport(oasOperation); ok {
validate.Import(*overRideValues.ValidateRequest)
o.ValidateRequest = validate
}
Expand All @@ -91,7 +91,7 @@ func (o *Operation) Import(oasOperation *openapi3.Operation, overRideValues TykE
mock = &MockResponse{}
}

if shouldImport := mock.shouldImport(oasOperation); shouldImport {
if ok := mock.shouldImport(oasOperation); ok {
mock.Import(*overRideValues.MockResponse)
o.MockResponse = mock
}
Expand Down Expand Up @@ -471,7 +471,11 @@ func (v *ValidateRequest) Fill(meta apidef.ValidatePathMeta) {
v.ErrorResponseCode = meta.ErrorResponseCode
}

func (*ValidateRequest) shouldImportValidateRequest(operation *openapi3.Operation) bool {
func (*ValidateRequest) shouldImport(operation *openapi3.Operation) bool {
if len(operation.Parameters) > 0 {
return true
}

reqBody := operation.RequestBody
if reqBody == nil {
return false
Expand Down Expand Up @@ -570,7 +574,7 @@ type FromOASExamples struct {
ExampleName string `bson:"exampleName,omitempty" json:"exampleName,omitempty"`
}

func (m *MockResponse) shouldImport(operation *openapi3.Operation) bool {
func (*MockResponse) shouldImport(operation *openapi3.Operation) bool {
for _, response := range operation.Responses {
for _, content := range response.Value.Content {
if content.Example != nil || content.Schema != nil {
Expand Down
4 changes: 0 additions & 4 deletions apidef/oas/operation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,3 @@ func TestOAS_RegexPaths(t *testing.T) {
assert.Equalf(t, tc.input, got, "test %d: rebuilt link, expected %v, got %v", i, tc.input, got)
}
}

func TestValidateRequest(t *testing.T) {

}
Loading

0 comments on commit 7e996cd

Please sign in to comment.