-
Notifications
You must be signed in to change notification settings - Fork 23
/
utils.go
238 lines (206 loc) · 5.9 KB
/
utils.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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
/*
* SPDX-FileCopyrightText: 2019 SAP SE or an SAP affiliate company and Gardener contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
package config
import (
"crypto/ecdsa"
"crypto/rsa"
"crypto/x509"
"encoding/json"
"fmt"
"os/exec"
"strings"
"time"
"github.com/gardener/cert-management/pkg/cert/legobridge"
"github.com/onsi/gomega"
corev1 "k8s.io/api/core/v1"
)
const STATE_DELETED = "~DELETED~"
type TestUtils struct {
AwaitTimeout time.Duration
PollingPeriod time.Duration
Namespace string
Verbose bool
}
func CreateDefaultTestUtils() *TestUtils {
return &TestUtils{
AwaitTimeout: 180 * time.Second,
PollingPeriod: 200 * time.Millisecond,
Namespace: "default",
Verbose: true,
}
}
func (u *TestUtils) KubectlGetAllCertificates() (map[string]interface{}, error) {
output, err := u.runKubeCtl("get cert -o json")
if err != nil {
return nil, err
}
return u.toItemMap(output)
}
func (u *TestUtils) KubectlGetSecret(name string) (*corev1.Secret, error) {
output, err := u.runKubeCtl("get secret " + name + " -o json")
if err != nil {
return nil, err
}
secret := &corev1.Secret{}
if err = json.Unmarshal([]byte(output), secret); err != nil {
return nil, err
}
return secret, nil
}
func (u *TestUtils) CheckCertificatePrivateKey(secretName string, algorithm x509.PublicKeyAlgorithm, keySize int) error {
secret, err := u.KubectlGetSecret(secretName)
if err != nil {
return err
}
cert, err := legobridge.DecodeCertificateFromSecretData(secret.Data)
if err != nil {
return err
}
if cert.PublicKeyAlgorithm != algorithm {
return fmt.Errorf("algorithm mismatch: %s != %s", cert.PublicKeyAlgorithm, algorithm)
}
switch pub := cert.PublicKey.(type) {
case *rsa.PublicKey:
size := pub.N.BitLen()
if size != keySize {
return fmt.Errorf("key size mismatch: %d != %d", size, keySize)
}
case *ecdsa.PublicKey:
size := pub.Curve.Params().N.BitLen()
if size != keySize {
return fmt.Errorf("key size mismatch: %d != %d", size, keySize)
}
default:
return fmt.Errorf("unknown public key")
}
return nil
}
func (u *TestUtils) toItemMap(output string) (map[string]interface{}, error) {
untyped := map[string]interface{}{}
err := json.Unmarshal([]byte(output), &untyped)
if err != nil {
return nil, err
}
if untyped["kind"] != "List" {
return nil, fmt.Errorf("Result is not a list")
}
itemMap := map[string]interface{}{}
items := untyped["items"].([]interface{})
for _, rawItem := range items {
item := rawItem.(map[string]interface{})
name := item["metadata"].(map[string]interface{})["name"].(string)
itemMap[name] = item
}
return itemMap, err
}
func (u *TestUtils) KubectlApply(filename string) error {
output, err := u.runKubeCtl(fmt.Sprintf("apply -f %q", filename))
u.LogVerbose(output)
return err
}
func (u *TestUtils) KubectlDelete(filename string) error {
output, err := u.runKubeCtl(fmt.Sprintf("delete -f %q", filename))
u.LogVerbose(output)
return err
}
func (u *TestUtils) LogVerbose(output string) {
if u.Verbose {
println(output)
}
}
func (u *TestUtils) runKubeCtl(cmdline string) (string, error) {
return u.runCmd("kubectl -n " + u.Namespace + " " + cmdline)
}
func (u *TestUtils) runCmd(cmdline string) (string, error) {
cmd := exec.Command("sh", "-c", cmdline)
out, err := cmd.Output()
if err != nil {
println(string(err.(*exec.ExitError).Stderr))
return string(out), fmt.Errorf("command `%s` failed: %w", cmdline, err)
}
return string(out), nil
}
func (u *TestUtils) AwaitIssuerReady(names ...string) error {
return u.AwaitState("issuer", "Ready", names...)
}
func (u *TestUtils) AwaitIssuerDeleted(names ...string) error {
return u.AwaitState("issuer", STATE_DELETED, names...)
}
func (u *TestUtils) AwaitCertReady(names ...string) error {
return u.AwaitState("cert", "Ready", names...)
}
func (u *TestUtils) AwaitCertError(names ...string) error {
return u.AwaitState("cert", "Error", names...)
}
func (u *TestUtils) AwaitCertDeleted(names ...string) error {
return u.AwaitState("cert", STATE_DELETED, names...)
}
func (u *TestUtils) AwaitCertRevoked(names ...string) error {
return u.AwaitState("cert", "Revoked", names...)
}
func (u *TestUtils) AwaitCertRevocationApplied(name string) error {
return u.AwaitState("certrevoke", "Applied", name)
}
func (u *TestUtils) AwaitState(resourceName, expectedState string, names ...string) error {
msg := fmt.Sprintf("%s not %s: %v", resourceName, expectedState, names)
return u.Await(msg, func() (bool, error) {
output, err := u.runKubeCtl("get " + resourceName + " \"-o=jsonpath={range .items[*]}{.metadata.name}={.status.state}{'\\n'}{end}\"")
if err != nil {
return false, err
}
states := map[string]string{}
lines := strings.Split(output, "\n")
for _, line := range lines {
cols := strings.Split(line, "=")
if len(cols) == 2 {
states[cols[0]] = cols[1]
}
}
for _, name := range names {
if expectedState == STATE_DELETED {
if _, ok := states[name]; ok {
return false, nil
}
} else if states[name] != expectedState {
return false, nil
}
}
return true, nil
})
}
type CheckFunc func() (bool, error)
func (u *TestUtils) Await(msg string, check CheckFunc) error {
return u.AwaitWithTimeout(msg, check, u.AwaitTimeout)
}
func (u *TestUtils) AwaitWithTimeout(msg string, check CheckFunc, timeout time.Duration) error {
var err error
var ok bool
limit := time.Now().Add(timeout)
for time.Now().Before(limit) {
ok, err = check()
if ok {
return nil
}
time.Sleep(u.PollingPeriod)
}
if err != nil {
return fmt.Errorf("Timeout during check %s with error: %w", msg, err)
}
return fmt.Errorf("Timeout during check %s", msg)
}
func (u *TestUtils) AwaitKubectlGetCRDs(crds ...string) error {
var err error
for _, crd := range crds {
gomega.Eventually(func() error {
_, err = u.runKubeCtl("get crd " + crd)
return err
}, u.AwaitTimeout, u.PollingPeriod).Should(gomega.BeNil())
if err != nil {
return err
}
}
return err
}