From a1466e1707732634e3ea739a388c73614395e668 Mon Sep 17 00:00:00 2001 From: Kevin Wan Date: Sun, 28 Aug 2022 17:49:26 +0800 Subject: [PATCH] fix: range validation on mapping (#2317) --- core/mapping/marshaler_test.go | 52 ++++++++++++++++++++++++++++++++++ core/mapping/utils.go | 12 +++++++- 2 files changed, 63 insertions(+), 1 deletion(-) diff --git a/core/mapping/marshaler_test.go b/core/mapping/marshaler_test.go index fe98b8f6..5e34dd85 100644 --- a/core/mapping/marshaler_test.go +++ b/core/mapping/marshaler_test.go @@ -281,6 +281,58 @@ func TestMarshal_RangeIllegal(t *testing.T) { } } +func TestMarshal_RangeLeftEqualsToRight(t *testing.T) { + tests := []struct { + name string + value interface{} + err error + }{ + { + name: "left inclusive, right inclusive", + value: struct { + Int int `json:"int,range=[2:2]"` + }{ + Int: 2, + }, + }, + { + name: "left inclusive, right exclusive", + value: struct { + Int int `json:"int,range=[2:2)"` + }{ + Int: 2, + }, + err: errNumberRange, + }, + { + name: "left exclusive, right inclusive", + value: struct { + Int int `json:"int,range=(2:2]"` + }{ + Int: 2, + }, + err: errNumberRange, + }, + { + name: "left exclusive, right exclusive", + value: struct { + Int int `json:"int,range=(2:2)"` + }{ + Int: 2, + }, + err: errNumberRange, + }, + } + + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + _, err := Marshal(test.value) + assert.Equal(t, test.err, err) + }) + } +} + func TestMarshal_FromString(t *testing.T) { v := struct { Age int `json:"age,string"` diff --git a/core/mapping/utils.go b/core/mapping/utils.go index 7f052bdf..7d8af4df 100644 --- a/core/mapping/utils.go +++ b/core/mapping/utils.go @@ -311,10 +311,20 @@ func parseNumberRange(str string) (*numberRange, error) { right = math.MaxFloat64 } - if left >= right { + if left > right { return nil, errNumberRange } + // [2:2] valid + // [2:2) invalid + // (2:2] invalid + // (2:2) invalid + if left == right { + if !leftInclude || !rightInclude { + return nil, errNumberRange + } + } + return &numberRange{ left: left, leftInclude: leftInclude,