Skip to content

Commit 206020d

Browse files
committed
Add ability to support strict JSON unmarshal for limits
This is the default behaviour for YAML now. ``` in := `{"unknown_fields": 100}` l := cortex.Limits{} fmt.Println(yaml.UnmarshalStrict([]byte(in), &l)) // yaml: unmarshal errors: // line 1: field unknown_fields not found in type validation.plain ``` This PR adds same behaviour if unmarshalled from JSON input as well. Signed-off-by: Kaviraj <[email protected]>
1 parent b15782e commit 206020d

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

pkg/util/validation/limits.go

+5-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package validation
22

33
import (
4+
"bytes"
45
"encoding/json"
56
"errors"
67
"flag"
@@ -229,7 +230,10 @@ func (l *Limits) UnmarshalJSON(data []byte) error {
229230
}
230231

231232
type plain Limits
232-
return json.Unmarshal(data, (*plain)(l))
233+
dec := json.NewDecoder(bytes.NewReader(data))
234+
dec.DisallowUnknownFields()
235+
236+
return dec.Decode((*plain)(l))
233237
}
234238

235239
func (l *Limits) copyNotificationIntegrationLimits(defaults NotificationRateLimitMap) {

pkg/util/validation/limits_test.go

+10
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package validation
33
import (
44
"encoding/json"
55
"reflect"
6+
"strings"
67
"testing"
78
"time"
89

@@ -165,6 +166,15 @@ func TestLimitsLoadingFromJson(t *testing.T) {
165166

166167
assert.Equal(t, 0.5, l.IngestionRate, "from json")
167168
assert.Equal(t, 100, l.MaxLabelNameLength, "from defaults")
169+
170+
// Unmarshal should fail if input contains unknown struct fields and
171+
// the decoder flag `json.Decoder.DisallowUnknownFields()` is set
172+
inp = `{"unknown_fields": 100}`
173+
l = Limits{}
174+
dec := json.NewDecoder(strings.NewReader(inp))
175+
dec.DisallowUnknownFields()
176+
err = dec.Decode(&l)
177+
assert.Error(t, err)
168178
}
169179

170180
func TestLimitsTagsYamlMatchJson(t *testing.T) {

0 commit comments

Comments
 (0)