2018-11-19 12:15:18 -06:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/base64"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
"testing"
|
|
|
|
|
2020-11-17 04:31:35 -06:00
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
"github.com/stretchr/testify/require"
|
2018-11-19 12:15:18 -06:00
|
|
|
"gopkg.in/macaron.v1"
|
|
|
|
)
|
|
|
|
|
|
|
|
func TestBasicAuthenticatedRequest(t *testing.T) {
|
2020-11-17 04:31:35 -06:00
|
|
|
const expectedUser = "prometheus"
|
|
|
|
const expectedPass = "password"
|
2018-11-19 12:15:18 -06:00
|
|
|
|
2020-11-17 04:31:35 -06:00
|
|
|
t.Run("Given a valid set of basic auth credentials", func(t *testing.T) {
|
2018-11-19 12:15:18 -06:00
|
|
|
httpReq, err := http.NewRequest("GET", "http://localhost:3000/metrics", nil)
|
2020-11-17 04:31:35 -06:00
|
|
|
require.NoError(t, err)
|
2018-11-19 12:15:18 -06:00
|
|
|
req := macaron.Request{
|
|
|
|
Request: httpReq,
|
|
|
|
}
|
|
|
|
encodedCreds := encodeBasicAuthCredentials(expectedUser, expectedPass)
|
2020-12-14 08:13:01 -06:00
|
|
|
req.Header.Set("Authorization", fmt.Sprintf("Basic %s", encodedCreds))
|
2018-11-19 12:15:18 -06:00
|
|
|
authenticated := BasicAuthenticatedRequest(req, expectedUser, expectedPass)
|
2020-11-17 04:31:35 -06:00
|
|
|
|
|
|
|
assert.True(t, authenticated)
|
2018-11-19 12:15:18 -06:00
|
|
|
})
|
|
|
|
|
2020-11-17 04:31:35 -06:00
|
|
|
t.Run("Given an invalid set of basic auth credentials", func(t *testing.T) {
|
2018-11-19 12:15:18 -06:00
|
|
|
httpReq, err := http.NewRequest("GET", "http://localhost:3000/metrics", nil)
|
2020-11-17 04:31:35 -06:00
|
|
|
require.NoError(t, err)
|
2018-11-19 12:15:18 -06:00
|
|
|
req := macaron.Request{
|
|
|
|
Request: httpReq,
|
|
|
|
}
|
|
|
|
encodedCreds := encodeBasicAuthCredentials("invaliduser", "invalidpass")
|
2020-12-14 08:13:01 -06:00
|
|
|
req.Header.Set("Authorization", fmt.Sprintf("Basic %s", encodedCreds))
|
2018-11-19 12:15:18 -06:00
|
|
|
authenticated := BasicAuthenticatedRequest(req, expectedUser, expectedPass)
|
2020-11-17 04:31:35 -06:00
|
|
|
|
|
|
|
assert.False(t, authenticated)
|
2018-11-19 12:15:18 -06:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func encodeBasicAuthCredentials(user, pass string) string {
|
|
|
|
creds := fmt.Sprintf("%s:%s", user, pass)
|
|
|
|
return base64.StdEncoding.EncodeToString([]byte(creds))
|
|
|
|
}
|