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

Added noRequestBody function to check that HTTP GET and DELETE methods do not contain a requestBody #588

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions functions/functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ func MapBuiltinFunctions() Functions {
funcs["infoLicenseUrl"] = openapi_functions.InfoLicenseURL{}
funcs["infoLicenseURLSPDX"] = openapi_functions.InfoLicenseURLSPDX{}
funcs["infoContactProperties"] = openapi_functions.InfoContactProperties{}
funcs["noRequestBody"] = openapi_functions.NoRequestBody{}

// add owasp functions used by the owasp rules
funcs["owaspHeaderDefinition"] = owasp.HeaderDefinition{}
Expand Down
2 changes: 1 addition & 1 deletion functions/functions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@ import (

func TestMapBuiltinFunctions(t *testing.T) {
funcs := MapBuiltinFunctions()
assert.Len(t, funcs.GetAllFunctions(), 73)
assert.Len(t, funcs.GetAllFunctions(), 74)
}
72 changes: 72 additions & 0 deletions functions/openapi/no_request_body.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// Copyright 2022 Dave Shanley / Quobix
// SPDX-License-Identifier: MIT

package openapi

import (
"fmt"
"github.com/daveshanley/vacuum/model"
vacuumUtils "github.com/daveshanley/vacuum/utils"
"github.com/pb33f/doctor/model/high/base"
"gopkg.in/yaml.v3"
"strings"
)

// NoRequestBody is a rule that checks operations are using tags and they are not empty.
type NoRequestBody struct {
}

// GetSchema returns a model.RuleFunctionSchema defining the schema of the NoRequestBody rule.
func (r NoRequestBody) GetSchema() model.RuleFunctionSchema {
return model.RuleFunctionSchema{
Name: "noRequestBody",
}
}

// GetCategory returns the category of the TagDefined rule.
func (r NoRequestBody) GetCategory() string {
return model.FunctionCategoryOpenAPI
}

// RunRule will execute the NoRequestBody rule, based on supplied context and a supplied []*yaml.Node slice.
func (r NoRequestBody) RunRule(nodes []*yaml.Node, context model.RuleFunctionContext) []model.RuleFunctionResult {

var results []model.RuleFunctionResult

if context.DrDocument == nil {
return results
}

paths := context.DrDocument.V3Document.Paths
if paths != nil {
for pathItemPairs := paths.PathItems.First(); pathItemPairs != nil; pathItemPairs = pathItemPairs.Next() {
path := pathItemPairs.Key()
v := pathItemPairs.Value()

for opPairs := v.GetOperations().First(); opPairs != nil; opPairs = opPairs.Next() {
method := opPairs.Key()
op := opPairs.Value()

for _, checkedMethods := range []string{"GET", "DELETE"} {
if strings.EqualFold(method, checkedMethods) {
if op.RequestBody != nil {

res := model.RuleFunctionResult{
Message: vacuumUtils.SuppliedOrDefault(context.Rule.Message, fmt.Sprintf("`%s` operation should not have a requestBody defined",
strings.ToUpper(method))),
StartNode: op.Value.GoLow().KeyNode,
EndNode: vacuumUtils.BuildEndNode(op.Value.GoLow().KeyNode),
Path: fmt.Sprintf("$.paths['%s'].%s", path, method),
Rule: context.Rule,
}
results = append(results, res)
op.AddRuleFunctionResult(base.ConvertRuleResult(&res))
}
}
}
}
}
}
return results

}
147 changes: 147 additions & 0 deletions functions/openapi/no_request_body_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
package openapi

import (
"fmt"
"github.com/daveshanley/vacuum/model"
drModel "github.com/pb33f/doctor/model"
"github.com/pb33f/libopenapi"
"github.com/stretchr/testify/assert"
"testing"
)

func TestNoRequestBody_GetSchema(t *testing.T) {
def := NoRequestBody{}
assert.Equal(t, "noRequestBody", def.GetSchema().Name)
}

func TestNoRequestBody_RunRule(t *testing.T) {
def := NoRequestBody{}
res := def.RunRule(nil, model.RuleFunctionContext{})
assert.Len(t, res, 0)
}

func TestNoRequestBody_RunRule_Fail(t *testing.T) {

yml := `openapi: 3.0.1
paths:
/melody:
post:
requestBody:
description: "the body of the request"
content:
application/json:
schema:
properties:
id:
type: string
/maddox:
get:
requestBody:
description: "the body of the request"
content:
application/json:
schema:
properties:
id:
type: string
delete:
requestBody:
description: "the body of the request"
content:
application/json:
schema:
properties:
id:
type: string
/ember:
get:
requestBody:
description: "the body of the request"
content:
application/json:
schema:
properties:
id:
type: string
`
document, err := libopenapi.NewDocument([]byte(yml))
if err != nil {
panic(fmt.Sprintf("cannot create new document: %e", err))
}

m, _ := document.BuildV3Model()
path := "$"

drDocument := drModel.NewDrDocument(m)

rule := buildOpenApiTestRuleAction(path, "responses", "", nil)
ctx := buildOpenApiTestContext(model.CastToRuleAction(rule.Then), nil)

ctx.Document = document
ctx.DrDocument = drDocument
ctx.Rule = &rule

def := NoRequestBody{}
res := def.RunRule(nil, ctx)
assert.Len(t, res, 3)
}

func TestNoRequestBody_RunRule_Success(t *testing.T) {

yml := `openapi: 3.0.1
paths:
/melody:
post:
requestBody:
description: "the body of the request"
content:
application/json:
schema:
properties:
id:
type: string
/maddox:
post:
requestBody:
description: "the body of the request"
content:
application/json:
schema:
properties:
id:
type: string
/ember:
patch:
requestBody:
description: "the body of the request"
content:
application/json:
schema:
properties:
id:
type: string
`

document, err := libopenapi.NewDocument([]byte(yml))
if err != nil {
panic(fmt.Sprintf("cannot create new document: %e", err))
}

m, _ := document.BuildV3Model()
path := "$"

drDocument := drModel.NewDrDocument(m)

rule := buildOpenApiTestRuleAction(path, "responses", "", nil)
ctx := buildOpenApiTestContext(model.CastToRuleAction(rule.Then), nil)

ctx.Document = document
ctx.DrDocument = drDocument
ctx.Rule = &rule

def := NoRequestBody{}
res := def.RunRule(nil, ctx)

assert.Len(t, res, 0)

}
1 change: 1 addition & 0 deletions model/rules.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ type RuleFunctionResult struct {
ModelContext any `json:"-" yaml:"-"`
}

// IgnoredItems is a map of the rule ID to an array of violation paths
type IgnoredItems map[string][]string

// RuleResultSet contains all the results found during a linting run, and all the methods required to
Expand Down
2 changes: 2 additions & 0 deletions rulesets/rule_fixes.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,8 @@ const (
schemaTypeFix string = "Make sure each schema has a value type defined. Without a type, the schema is useless"

postSuccessResponseFix string = "Make sure your POST operations return a 'success' response via 2xx or 3xx response code. "

noRequestBodyResponseFix string = "Remove 'requestBody' from HTTP GET and DELETE methods"
)

const (
Expand Down
22 changes: 21 additions & 1 deletion rulesets/ruleset_functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -1307,6 +1307,26 @@ func GetPostSuccessResponseRule() *model.Rule {
Function: "postResponseSuccess",
FunctionOptions: opts,
},
HowToFix: oas3HostNotExampleFix,
HowToFix: postSuccessResponseFix,
}
}

// GetNoRequestBodyRule will check that HTTP GET and DELETE do not accept request bodies
func GetNoRequestBodyRule() *model.Rule {
return &model.Rule{
Name: "Check GET and DELETE methods do not accept request bodies",
Id: NoRequestBody,
Formats: model.OAS3AllFormat,
Description: "HTTP GET and DELETE should not accept request bodies",
Given: "$",
Resolved: false,
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@daveshanley I don't know what Resolved means. Should it be true or false here?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Resolved means that the $ref values have all been stitched together by the resolver in libopenapi

This is used for rules that assume everything is resolved and inlined. It only makes a difference if the logic in your rule / function is recursive - if so, it means that any circular references could create an infinite loop.

RuleCategory: model.RuleCategories[model.CategoryOperations],
Recommended: true,
Type: Style,
Severity: model.SeverityWarn,
Then: model.RuleAction{
Function: "noRequestBody",
},
HowToFix: noRequestBodyResponseFix,
}
}
2 changes: 2 additions & 0 deletions rulesets/rulesets.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ const (
OwaspConstrainedAdditionalProperties = "owasp-constrained-additionalProperties"
OwaspSecurityHostsHttpsOAS3 = "owasp-security-hosts-https-oas3"
PostResponseSuccess = "post-response-success"
NoRequestBody = "no-request-body"
SpectralOpenAPI = "spectral:oas"
SpectralOwasp = "spectral:owasp"
VacuumOwasp = "vacuum:owasp"
Expand Down Expand Up @@ -439,6 +440,7 @@ func GetAllBuiltInRules() map[string]*model.Rule {
rules[Oas3ExampleExternalCheck] = GetOAS3ExamplesExternalCheck()
rules[OasSchemaCheck] = GetSchemaTypeCheckRule()
rules[PostResponseSuccess] = GetPostSuccessResponseRule()
rules[NoRequestBody] = GetNoRequestBodyRule()

// dead.
//rules[Oas2ValidSchemaExample] = GetOAS2ExamplesRule()
Expand Down
8 changes: 4 additions & 4 deletions rulesets/rulesets_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ import (
"time"
)

var totalRules = 58
var totalRules = 59
var totalOwaspRules = 23
var totalRecommendedRules = 46
var totalRecommendedRules = 47

func TestBuildDefaultRuleSets(t *testing.T) {

Expand Down Expand Up @@ -545,7 +545,7 @@ rules:
rs, err := CreateRuleSetFromData([]byte(yamlA))
assert.NoError(t, err)
override := def.GenerateRuleSetFromSuppliedRuleSet(rs)
assert.Len(t, override.Rules, 48)
assert.Len(t, override.Rules, 49)
assert.Len(t, override.RuleDefinitions, 2)
assert.NotNil(t, rs.Rules["ding"])
assert.NotNil(t, rs.Rules["dong"])
Expand Down Expand Up @@ -734,7 +734,7 @@ func TestRuleSet_GetExtendsLocalSpec_Multi_Chain(t *testing.T) {
rs, err := CreateRuleSetFromData([]byte(yaml))
assert.NoError(t, err)
override := def.GenerateRuleSetFromSuppliedRuleSet(rs)
assert.Len(t, override.Rules, 59)
assert.Len(t, override.Rules, 60)
assert.Len(t, override.RuleDefinitions, 1)

}
Expand Down