-
Notifications
You must be signed in to change notification settings - Fork 63
/
fakekubeapi.go
219 lines (187 loc) · 6.54 KB
/
fakekubeapi.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
// Copyright 2021-2024 the Pinniped contributors. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
/*
Package fakekubeapi contains a *very* simple httptest.Server that can be used to stand in for
a real Kube API server in tests.
Usage:
func TestSomething(t *testing.T) {
resources := map[string]kubeclient.Object{
// store preexisting resources here
"/api/v1/namespaces/default/pods/some-pod-name": &corev1.Pod{...},
}
server, restConfig := fakekubeapi.Start(t, resources)
defer server.Close()
client := kubeclient.New(kubeclient.WithConfig(restConfig))
// do stuff with client...
}
*/
package fakekubeapi
import (
"fmt"
"io"
"mime"
"net/http"
"net/http/httptest"
"path"
"strings"
"testing"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/errors"
kubescheme "k8s.io/client-go/kubernetes/scheme"
restclient "k8s.io/client-go/rest"
aggregatorclientscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme"
pinnipedconciergeclientsetscheme "go.pinniped.dev/generated/latest/client/concierge/clientset/versioned/scheme"
pinnipedsupervisorclientsetscheme "go.pinniped.dev/generated/latest/client/supervisor/clientset/versioned/scheme"
"go.pinniped.dev/internal/crypto/ptls"
"go.pinniped.dev/internal/httputil/httperr"
"go.pinniped.dev/internal/testutil/tlsserver"
)
// Start starts an httptest.Server (with TLS) that pretends to be a Kube API server.
//
// The server uses the provided resources map to store API Object's. The map should be from API path
// to Object (e.g., /api/v1/namespaces/default/pods/some-pod-name => &corev1.Pod{}).
//
// Start returns an already started httptest.Server and a restclient.Config that can be used to talk
// to the server.
//
// Note! Only these following verbs are (partially) supported: create, get, update, delete.
func Start(t *testing.T, resources map[string]runtime.Object) (*httptest.Server, *restclient.Config) {
if resources == nil {
resources = make(map[string]runtime.Object)
}
server, serverCA := tlsserver.TestServerIPv4(t, httperr.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error {
tlsserver.AssertTLS(t, r, ptls.Secure)
obj, err := decodeObj(r)
if err != nil {
return err
}
obj, err = handleObj(r, obj, resources)
if err != nil {
return err
}
if obj == nil {
obj = newNotFoundStatus(r.URL.Path)
}
if err := encodeObj(w, r, obj); err != nil {
return err
}
return nil
}), tlsserver.RecordTLSHello)
restConfig := &restclient.Config{
Host: server.URL,
TLSClientConfig: restclient.TLSClientConfig{
CAData: serverCA,
},
}
return server, restConfig
}
func decodeObj(r *http.Request) (runtime.Object, error) {
switch r.Method {
case http.MethodPut, http.MethodPost:
default:
return nil, nil
}
contentType := r.Header.Get("Content-Type")
if len(contentType) == 0 {
return nil, httperr.New(http.StatusUnsupportedMediaType, "empty content-type header is not allowed")
}
mediaType, _, err := mime.ParseMediaType(contentType)
if err != nil {
return nil, httperr.Wrap(http.StatusUnsupportedMediaType, "could not parse mime type from content-type header", err)
}
body, err := io.ReadAll(r.Body)
if err != nil {
return nil, httperr.Wrap(http.StatusInternalServerError, "read body", err)
}
var obj runtime.Object
var errs []error //nolint:prealloc
codecsThatWeUseInOurCode := []runtime.NegotiatedSerializer{
kubescheme.Codecs,
aggregatorclientscheme.Codecs,
pinnipedconciergeclientsetscheme.Codecs,
pinnipedsupervisorclientsetscheme.Codecs,
}
for _, codec := range codecsThatWeUseInOurCode {
obj, err = tryDecodeObj(mediaType, body, codec)
if err == nil {
return obj, nil
}
errs = append(errs, err)
}
return nil, errors.NewAggregate(errs)
}
func tryDecodeObj(
mediaType string,
body []byte,
negotiatedSerializer runtime.NegotiatedSerializer,
) (runtime.Object, error) {
serializerInfo, ok := runtime.SerializerInfoForMediaType(negotiatedSerializer.SupportedMediaTypes(), mediaType)
if !ok {
return nil, httperr.Newf(http.StatusInternalServerError, "unable to find serialier with content-type %s", mediaType)
}
obj, err := runtime.Decode(serializerInfo.Serializer, body)
if err != nil {
return nil, httperr.Wrap(http.StatusInternalServerError, "decode obj", err)
}
return obj, nil
}
func handleObj(r *http.Request, obj runtime.Object, resources map[string]runtime.Object) (runtime.Object, error) {
switch r.Method {
case http.MethodGet:
obj = resources[r.URL.Path]
case http.MethodPost, http.MethodPut:
resources[path.Join(r.URL.Path, obj.(metav1.Object).GetName())] = obj
case http.MethodDelete:
obj = resources[r.URL.Path]
delete(resources, r.URL.Path)
default:
return nil, httperr.New(http.StatusMethodNotAllowed, "check source code for methods supported")
}
return obj, nil
}
func newNotFoundStatus(path string) runtime.Object {
status := &metav1.Status{
Status: metav1.StatusFailure,
Message: fmt.Sprintf("couldn't find object for path %q", path),
Reason: metav1.StatusReasonNotFound,
Code: http.StatusNotFound,
}
status.APIVersion, status.Kind = metav1.SchemeGroupVersion.WithKind("Status").ToAPIVersionAndKind()
return status
}
func encodeObj(w http.ResponseWriter, r *http.Request, obj runtime.Object) error {
if r.Method == http.MethodDelete {
return nil
}
accepts := strings.Split(r.Header.Get("Accept"), ",")
contentType := findGoodContentType(accepts)
if len(contentType) == 0 {
return httperr.Newf(http.StatusUnsupportedMediaType, "can't find good content type in %s", accepts)
}
mediaType, _, err := mime.ParseMediaType(contentType)
if err != nil {
return httperr.Wrap(http.StatusUnsupportedMediaType, "could not parse mime type from accept header", err)
}
serializerInfo, ok := runtime.SerializerInfoForMediaType(kubescheme.Codecs.SupportedMediaTypes(), mediaType)
if !ok {
return httperr.Newf(http.StatusInternalServerError, "unable to find serialier with content-type %s", mediaType)
}
data, err := runtime.Encode(serializerInfo.Serializer, obj)
if err != nil {
return httperr.Wrap(http.StatusInternalServerError, "decode obj", err)
}
w.Header().Set("Content-Type", contentType)
if _, err := w.Write(data); err != nil {
return httperr.Wrap(http.StatusInternalServerError, "write response", err)
}
return nil
}
func findGoodContentType(contentTypes []string) string {
for _, contentType := range contentTypes {
if strings.Contains(contentType, "json") || strings.Contains(contentType, "yaml") || strings.Contains(contentType, "protobuf") {
return contentType
}
}
return ""
}