From e1b6971e1c3377fb7595ad058acdee1e7d297397 Mon Sep 17 00:00:00 2001 From: Michel Vocks Date: Wed, 11 Dec 2019 20:59:19 +0100 Subject: [PATCH] Add accept header check for prometheus mime type (#7958) * Add accept header check for prometheus mime type * Fix small header filter bug. Add test --- helper/metricsutil/metricsutil.go | 11 ++++++- helper/metricsutil/metricsutil_test.go | 45 ++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 helper/metricsutil/metricsutil_test.go diff --git a/helper/metricsutil/metricsutil.go b/helper/metricsutil/metricsutil.go index f6ac99f89239..83ca85a2d8fe 100644 --- a/helper/metricsutil/metricsutil.go +++ b/helper/metricsutil/metricsutil.go @@ -16,6 +16,8 @@ import ( const ( OpenMetricsMIMEType = "application/openmetrics-text" + PrometheusSchemaMIMEType = "prometheus/telemetry" + // ErrorContentType is the content type returned by an error response. ErrorContentType = "text/plain" ) @@ -38,7 +40,14 @@ func FormatFromRequest(req *logical.Request) string { if len(acceptHeaders) > 0 { acceptHeader := acceptHeaders[0] if strings.HasPrefix(acceptHeader, OpenMetricsMIMEType) { - return "prometheus" + return PrometheusMetricFormat + } + + // Look for prometheus accept header + for _, header := range acceptHeaders { + if strings.Contains(header, PrometheusSchemaMIMEType) { + return PrometheusMetricFormat + } } } return "" diff --git a/helper/metricsutil/metricsutil_test.go b/helper/metricsutil/metricsutil_test.go new file mode 100644 index 000000000000..bf33b76045f9 --- /dev/null +++ b/helper/metricsutil/metricsutil_test.go @@ -0,0 +1,45 @@ +package metricsutil + +import ( + "github.com/hashicorp/vault/sdk/logical" + "testing" +) + +func TestFormatFromRequest(t *testing.T) { + testCases := []struct { + original *logical.Request + expected string + }{ + { + original: &logical.Request{Headers: map[string][]string{ + "Accept": { + "application/vnd.google.protobuf", + "schema=\"prometheus/telemetry\"", + }, + }}, + expected: "prometheus", + }, + { + original: &logical.Request{Headers: map[string][]string{ + "Accept": { + "schema=\"prometheus\"", + }, + }}, + expected: "", + }, + { + original: &logical.Request{Headers: map[string][]string{ + "Accept": { + "application/openmetrics-text", + }, + }}, + expected: "prometheus", + }, + } + + for _, tCase := range testCases { + if metricsType := FormatFromRequest(tCase.original); metricsType != tCase.expected { + t.Fatalf("expected %s but got %s", tCase.expected, metricsType) + } + } +}