-
Notifications
You must be signed in to change notification settings - Fork 417
/
testserver.go
177 lines (150 loc) · 5.16 KB
/
testserver.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
package testutils
import (
"context"
"errors"
"fmt"
"net/http"
"os"
"path/filepath"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws/endpoints"
"github.com/prometheus/client_golang/prometheus"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/apimachinery/pkg/util/wait"
client "k8s.io/client-go/kubernetes"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
"k8s.io/kubernetes/cmd/kube-apiserver/app/options"
"k8s.io/kubernetes/pkg/controlplane"
"k8s.io/kubernetes/test/integration/framework"
"sigs.k8s.io/aws-iam-authenticator/pkg/config"
"sigs.k8s.io/aws-iam-authenticator/pkg/mapper"
"sigs.k8s.io/aws-iam-authenticator/pkg/metrics"
"sigs.k8s.io/aws-iam-authenticator/pkg/server"
)
const (
hardcodedHealthcheckPort = 21363
hardcodedAuthenticatorServerPort = 21362
)
// AuthenticatorTestFrameworkSetup holds configuration information for a kube-apiserver test server.
type AuthenticatorTestFrameworkSetup struct {
ModifyAuthenticatorServerConfig func(*config.Config)
AuthenticatorClientBinaryPath string
TestArtifacts string
ClusterID string
BackendMode []string
RoleArn string
}
func StartAuthenticatorTestFramework(t *testing.T, setup AuthenticatorTestFrameworkSetup) (client.Interface, client.Interface, framework.TearDownFunc) {
metrics.InitMetrics(prometheus.NewRegistry())
cfg, err := testConfig(t, setup)
if err != nil {
t.Fatal(err)
}
if _, err := cfg.GetOrCreateX509KeyPair(); err != nil {
t.Fatal(err)
}
if err := cfg.GenerateWebhookKubeconfig(); err != nil {
t.Fatal(err)
}
adminClient, kubeAPIServerClientConfig, tearDownFn := framework.StartTestServer(context.Background(), t, framework.TestServerSetup{
ModifyServerRunOptions: func(opts *options.ServerRunOptions) {
opts.Authentication.WebHook.ConfigFile = cfg.GenerateKubeconfigPath
},
ModifyServerConfig: func(config *controlplane.Config) {},
})
cert, err := LoadX509Certificate(kubeAPIServerClientConfig.TLSClientConfig.CAFile)
if err != nil {
t.Fatal(err)
}
// Create API server client kubeconfig, used by the authenticator to update its mapping store when using CRD or EKSConfigMap
if err := CreateAPIServerClientKubeconfig(cert, kubeAPIServerClientConfig.BearerToken, cfg.Kubeconfig, kubeAPIServerClientConfig.Host); err != nil {
t.Fatal(err)
}
stopCh := make(chan struct{})
httpServer := server.New(cfg, stopCh)
go func() {
httpServer.Run(stopCh)
}()
err = wait.PollImmediate(100*time.Millisecond, 10*time.Second, func() (done bool, err error) {
t.Log("Checking authenticator server health...")
done, err = checkHealth(cfg)
if err != nil {
t.Log(err)
return false, nil
}
if !done {
return false, nil
}
t.Log("Authenticator server healthy.")
return true, nil
})
if err != nil {
t.Fatal(err)
}
args := []string{"token", "-i", setup.ClusterID}
if setup.RoleArn != "" {
args = append(args, "--role", setup.RoleArn)
}
// Create aws-iam-authenticator client
kubeAPIServerClientConfig.ExecProvider = &clientcmdapi.ExecConfig{
Command: setup.AuthenticatorClientBinaryPath,
Args: args,
APIVersion: "client.authentication.k8s.io/v1beta1",
InteractiveMode: clientcmdapi.NeverExecInteractiveMode,
}
kubeAPIServerClientConfig.BearerToken = ""
clientWithExecAuthenticator, err := client.NewForConfig(kubeAPIServerClientConfig)
if err != nil {
t.Fatal(err)
}
return adminClient, clientWithExecAuthenticator, func() {
close(stopCh)
httpServer.Close()
tearDownFn()
}
}
func testConfig(t *testing.T, setup AuthenticatorTestFrameworkSetup) (config.Config, error) {
testDir, _ := os.MkdirTemp(setup.TestArtifacts, "test-integration-"+t.Name())
t.Logf("Test dir: %v.\n", testDir)
cfg := config.Config{
PartitionID: "aws",
ClusterID: setup.ClusterID,
Hostname: "localhost",
HostPort: hardcodedAuthenticatorServerPort,
KubeconfigPregenerated: true,
Address: "127.0.0.1",
Kubeconfig: filepath.Join(testDir, "apiserver.kubeconfig"),
GenerateKubeconfigPath: filepath.Join(testDir, "webhook.kubeconfig"),
BackendMode: setup.BackendMode,
StateDir: testDir,
}
if setup.ModifyAuthenticatorServerConfig != nil {
setup.ModifyAuthenticatorServerConfig(&cfg)
}
// validate any overrides
if cfg.ClusterID == "" {
return cfg, errors.New("cluster ID cannot be empty")
}
partitionKeys := []string{}
partitionMap := map[string]endpoints.Partition{}
for _, p := range endpoints.DefaultPartitions() {
partitionMap[p.ID()] = p
partitionKeys = append(partitionKeys, p.ID())
}
if _, ok := partitionMap[cfg.PartitionID]; !ok {
return cfg, errors.New("Invalid partition")
}
if errs := mapper.ValidateBackendMode(cfg.BackendMode); len(errs) > 0 {
return cfg, utilerrors.NewAggregate(errs)
}
return cfg, nil
}
// checkHealth returns true when the authenticator server is healthy
func checkHealth(cfg config.Config) (bool, error) {
resp, err := http.Get(fmt.Sprintf("http://%s:%d/healthz", cfg.Address, hardcodedHealthcheckPort))
if err != nil {
return false, err
}
return resp.StatusCode == http.StatusOK, nil
}