Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Bearer Auth for Metrics API scaler #2028

Merged
merged 5 commits into from
Aug 18, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
### Improvements

- Improve validation in Cron scaler in case start & end input is same.([#2032](https://github.com/kedacore/keda/pull/2032))
- Add Bearer auth for Metrics API scaler ([#2028](https://github.com/kedacore/keda/pull/2028))

### Breaking Changes

Expand Down
17 changes: 17 additions & 0 deletions pkg/scalers/metrics_api_scaler.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,10 @@ type metricsAPIScalerMetadata struct {
cert string
key string
ca string

// bearer
enableBearerAuth bool
bearerToken string
}

const (
Expand Down Expand Up @@ -159,6 +163,13 @@ func parseMetricsAPIMetadata(config *ScalerConfig) (*metricsAPIScalerMetadata, e

meta.key = config.AuthParams["key"]
meta.enableTLS = true
case authentication.BearerAuthType:
if len(config.AuthParams["token"]) == 0 {
return nil, errors.New("no token provided")
}

meta.bearerToken = config.AuthParams["token"]
meta.enableBearerAuth = true
default:
return nil, fmt.Errorf("err incorrect value for authMode is given: %s", authMode)
}
Expand Down Expand Up @@ -306,6 +317,12 @@ func getMetricAPIServerRequest(meta *metricsAPIScalerMetadata) (*http.Request, e
}

req.SetBasicAuth(meta.username, meta.password)
case meta.enableBearerAuth:
req, err = http.NewRequest("GET", meta.url, nil)
if err != nil {
return nil, err
}
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", meta.bearerToken))
default:
req, err = http.NewRequest("GET", meta.url, nil)
if err != nil {
Expand Down
55 changes: 54 additions & 1 deletion pkg/scalers/metrics_api_scaler_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
package scalers

import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"
)

type metricsAPIMetadataTestData struct {
Expand Down Expand Up @@ -53,6 +58,10 @@ var testMetricsAPIAuthMetadata = []metricAPIAuthMetadataTestData{
{map[string]string{"url": "http://dummy:1230/api/v1/", "valueLocation": "metric", "targetValue": "42", "authMode": "basic"}, map[string]string{"username": "user", "password": "pass"}, false},
// fail basicAuth with no username
{map[string]string{"url": "http://dummy:1230/api/v1/", "valueLocation": "metric", "targetValue": "42", "authMode": "basic"}, map[string]string{}, true},
// success bearerAuth default
{map[string]string{"url": "http://dummy:1230/api/v1/", "valueLocation": "metric", "targetValue": "42", "authMode": "bearer"}, map[string]string{"token": "bearerTokenValue"}, false},
// fail bearerAuth without token
{map[string]string{"url": "http://dummy:1230/api/v1/", "valueLocation": "metric", "targetValue": "42", "authMode": "bearer"}, map[string]string{}, true},
}

func TestParseMetricsAPIMetadata(t *testing.T) {
Expand Down Expand Up @@ -121,9 +130,53 @@ func TestMetricAPIScalerAuthParams(t *testing.T) {
if err == nil {
if (meta.enableAPIKeyAuth && !(testData.metadata["authMode"] == "apiKey")) ||
(meta.enableBaseAuth && !(testData.metadata["authMode"] == "basic")) ||
(meta.enableTLS && !(testData.metadata["authMode"] == "tls")) {
(meta.enableTLS && !(testData.metadata["authMode"] == "tls")) ||
(meta.enableBearerAuth && !(testData.metadata["authMode"] == "bearer")) {
t.Error("wrong auth mode detected")
}
}
}
}

func TestBearerAuth(t *testing.T) {
authentication := map[string]string{
"token": "secure-token",
}

var apiStub = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if val, ok := r.Header["Authorization"]; ok {
if val[0] != fmt.Sprintf("Bearer %s", authentication["token"]) {
t.Errorf("Authorization header malformed")
}
} else {
t.Errorf("Authorization header not found")
}

w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"components":[{"id": "82328e93e", "tasks": 32, "str": "64", "k":"1k","wrong":"NaN"}],"count":2.43}`))
}))

metadata := map[string]string{
"url": apiStub.URL,
"valueLocation": "components.0.tasks",
"targetValue": "1",
"authMode": "bearer",
}

s, err := NewMetricsAPIScaler(
&ScalerConfig{
ResolvedEnv: map[string]string{},
TriggerMetadata: metadata,
AuthParams: authentication,
GlobalHTTPTimeout: 1000 * time.Millisecond,
},
)
if err != nil {
t.Errorf("Error creating the Scaler")
}

_, err = s.GetMetrics(context.TODO(), "test-metric", nil)
if err != nil {
t.Errorf("Error getting the metric")
}
}