-
Notifications
You must be signed in to change notification settings - Fork 154
/
Copy pathhelper_test.go
58 lines (48 loc) · 1.49 KB
/
helper_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
// or more contributor license agreements. Licensed under the Elastic License;
// you may not use this file except in compliance with the Elastic License.
package fleetapi
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/stretchr/testify/require"
"github.com/elastic/elastic-agent/internal/pkg/fleetapi/client"
"github.com/elastic/elastic-agent/internal/pkg/remote"
"github.com/elastic/elastic-agent/pkg/core/logger"
)
func authHandler(handler http.HandlerFunc, apiKey string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
const key = "Authorization"
const prefix = "ApiKey "
v := strings.TrimPrefix(r.Header.Get(key), prefix)
if v != apiKey {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
handler(w, r)
}
}
func withServer(m func(t *testing.T) *http.ServeMux, test func(t *testing.T, host string)) func(t *testing.T) {
return func(t *testing.T) {
s := httptest.NewServer(m(t))
defer s.Close()
test(t, s.Listener.Addr().String())
}
}
func withServerWithAuthClient(
m func(t *testing.T) *http.ServeMux,
apiKey string,
test func(t *testing.T, client client.Sender),
) func(t *testing.T) {
return withServer(m, func(t *testing.T, host string) {
log, _ := logger.New("", false)
cfg := remote.Config{
Host: host,
}
client, err := client.NewAuthWithConfig(log, apiKey, cfg)
require.NoError(t, err)
test(t, client)
})
}