From 6b0e9ef183fddf5b27b4ea4d2052153a6bdf0660 Mon Sep 17 00:00:00 2001 From: Krasi Georgiev Date: Tue, 27 Feb 2018 14:33:27 +0200 Subject: [PATCH] Validate json parse for TargetGroup Unmarshal (#3614) Using DisallowUnknownFields in golang 1.10 to forbid unknown fields in targetGroups added the license header for the targetGroup test --- discovery/targetgroup/targetgroup.go | 6 ++- discovery/targetgroup/targetgroup_test.go | 48 +++++++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 discovery/targetgroup/targetgroup_test.go 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) + } + +}