diff --git a/discovery/targetgroup/targetgroup.go b/discovery/targetgroup/targetgroup.go index 4bafcef9e..0197622c2 100644 --- a/discovery/targetgroup/targetgroup.go +++ b/discovery/targetgroup/targetgroup.go @@ -14,6 +14,7 @@ package targetgroup import ( + "bytes" "encoding/json" "github.com/prometheus/common/model" @@ -77,7 +78,10 @@ func (tg *Group) UnmarshalJSON(b []byte) error { Targets []string `json:"targets"` Labels model.LabelSet `json:"labels"` }{} - if err := json.Unmarshal(b, &g); err != nil { + + dec := json.NewDecoder(bytes.NewReader(b)) + dec.DisallowUnknownFields() + if err := dec.Decode(&g); err != nil { return err } tg.Targets = make([]model.LabelSet, 0, len(g.Targets)) diff --git a/discovery/targetgroup/targetgroup_test.go b/discovery/targetgroup/targetgroup_test.go new file mode 100644 index 000000000..0087b272f --- /dev/null +++ b/discovery/targetgroup/targetgroup_test.go @@ -0,0 +1,48 @@ +// Copyright 2018 The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package targetgroup + +import ( + "errors" + "testing" + + "github.com/prometheus/prometheus/util/testutil" +) + +func TestTargetGroupStrictJsonUnmarshal(t *testing.T) { + tests := []struct { + json string + expectedReply error + }{ + { + json: ` {"labels": {},"targets": []}`, + expectedReply: nil, + }, + { + json: ` {"label": {},"targets": []}`, + expectedReply: errors.New("json: unknown field \"label\""), + }, + { + json: ` {"labels": {},"target": []}`, + expectedReply: errors.New("json: unknown field \"target\""), + }, + } + tg := Group{} + + for _, test := range tests { + actual := tg.UnmarshalJSON([]byte(test.json)) + testutil.Equals(t, test.expectedReply, actual) + } + +}