-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathecho-body.go
343 lines (295 loc) · 10 KB
/
echo-body.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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
/*
Copyright 2019 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Copyright (c) 2023 Alibaba Group Holding Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
// "bytes"
"crypto/tls"
"crypto/x509"
"encoding/json"
"encoding/pem"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"regexp"
"strconv"
"strings"
)
// RequestAssertions contains information about the request body and the Ingress
type RequestAssertions struct {
// Path string `json:"path"`
// Host string `json:"host"`
// Method string `json:"method"`
// Proto string `json:"proto"`
// Headers map[string][]string `json:"headers"`
Context `json:",inline"`
TLS *TLSAssertions `json:"tls,omitempty"`
}
// TLSAssertions contains information about the TLS connection.
type TLSAssertions struct {
Version string `json:"version"`
PeerCertificates []string `json:"peerCertificates,omitempty"`
ServerName string `json:"serverName"`
NegotiatedProtocol string `json:"negotiatedProtocol,omitempty"`
CipherSuite string `json:"cipherSuite"`
}
type preserveSlashes struct {
mux http.Handler
}
func (s *preserveSlashes) ServeHTTP(w http.ResponseWriter, r *http.Request) {
r.URL.Path = strings.Replace(r.URL.Path, "//", "/", -1)
s.mux.ServeHTTP(w, r)
}
// Context contains information about the context where the echoserver is running
type Context struct {
Namespace string `json:"namespace"`
Ingress string `json:"ingress"`
Service string `json:"service"`
Pod string `json:"pod"`
}
var context Context
const (
ContentTypeApplicationJson = "application/json"
ContentTypeFormUrlencoded = "application/x-www-form-urlencoded"
ContentTypeMultipartForm = "multipart/form-data"
ContextTypeTextPlain = "text/plain"
)
func main() {
httpPort := os.Getenv("HTTP_PORT")
if httpPort == "" {
httpPort = "3000"
}
httpsPort := os.Getenv("HTTPS_PORT")
if httpsPort == "" {
httpsPort = "8443"
}
context = Context{
Namespace: os.Getenv("NAMESPACE"),
Ingress: os.Getenv("INGRESS_NAME"),
Service: os.Getenv("SERVICE_NAME"),
Pod: os.Getenv("POD_NAME"),
}
httpMux := http.NewServeMux()
httpMux.HandleFunc("/health", healthHandler)
httpMux.HandleFunc("/status/", statusHandler)
httpMux.HandleFunc("/", echoHandler)
httpHandler := &preserveSlashes{httpMux}
errchan := make(chan error)
go func() {
fmt.Printf("Starting server, listening on port %s (http)\n", httpPort)
err := http.ListenAndServe(fmt.Sprintf(":%s", httpPort), httpHandler)
if err != nil {
errchan <- err
}
}()
// Enable HTTPS if certificate and private key are given.
if os.Getenv("TLS_SERVER_CERT") != "" && os.Getenv("TLS_SERVER_PRIVKEY") != "" {
go func() {
fmt.Printf("Starting server, listening on port %s (https)\n", httpsPort)
err := listenAndServeTLS(fmt.Sprintf(":%s", httpsPort), os.Getenv("TLS_SERVER_CERT"), os.Getenv("TLS_SERVER_PRIVKEY"), os.Getenv("TLS_CLIENT_CACERTS"), httpHandler)
if err != nil {
errchan <- err
}
}()
}
select {
case err := <-errchan:
panic(fmt.Sprintf("Failed to start listening: %s\n", err.Error()))
}
}
func healthHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
w.Write([]byte(`OK`))
}
func statusHandler(w http.ResponseWriter, r *http.Request) {
code := http.StatusBadRequest
re := regexp.MustCompile(`^/status/(\d\d\d)$`)
match := re.FindStringSubmatch(r.RequestURI)
if match != nil {
code, _ = strconv.Atoi(match[1])
}
w.WriteHeader(code)
}
func echoHandler(w http.ResponseWriter, r *http.Request) {
fmt.Printf("Echoing back request body made to %s to client (%s)\n", r.RequestURI, r.RemoteAddr)
contentType := r.Header.Get("Content-Type")
if len(contentType) == 0 {
processError(w, fmt.Errorf("Content-Type is not specified"), http.StatusBadRequest)
return
}
reqBodyInBytes, err := io.ReadAll(r.Body)
var respBodyInBytes []byte
if err != nil {
fmt.Errorf("Content-Type invalid or not support: %q", contentType)
processError(w, err, http.StatusInternalServerError)
return
}
switch contentType {
case ContextTypeTextPlain:
respBodyInBytes = reqBodyInBytes[:]
fmt.Printf("Echoing back %s",string(respBodyInBytes))
case ContentTypeApplicationJson, ContentTypeFormUrlencoded, ContentTypeMultipartForm:
respBody := make(map[string]interface{})
if len(reqBodyInBytes) > 0 {
err = json.Unmarshal(reqBodyInBytes, &respBody)
if err != nil {
processError(w, fmt.Errorf("body unmarshall fail, please check your body format: %q", err.Error()), http.StatusBadRequest)
return
}
}
// body中默认不带ingress信息
if echoIngressInfo, ok := r.Header["X-Echo-Ingress-Info"]; ok && echoIngressInfo[0] == "true" {
writeIngressInfo(w, respBody)
}
// 追加自定义数据
if _, ok := r.Header["X-Echo-Set-Body"]; ok {
writeEchoResponseBody(w, r.Header, respBody)
}
respBodyInBytes, err = json.MarshalIndent(respBody, "", " ")
if err != nil {
processError(w, err, http.StatusInternalServerError)
return
}
default:
processError(w, fmt.Errorf("Content-Type invalid or not support: %q", contentType), http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", contentType)
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Write(respBodyInBytes)
}
// 将ingress信息追加至response body中
func writeIngressInfo(w http.ResponseWriter, respBody map[string]interface{}) {
if _, ok := respBody["namespace"]; !ok {
respBody["namespace"] = context.Namespace
} else {
processError(w, fmt.Errorf("namespace field already used in body. If you want to close this warning, please set X-Echo-Ingress-Info to be false."), http.StatusBadRequest)
return
}
if _, ok := respBody["ingress"]; !ok {
respBody["ingress"] = context.Ingress
} else {
processError(w, fmt.Errorf("ingress field already used in body. If you want to close this warning, please set X-Echo-Ingress-Info to be false."), http.StatusBadRequest)
return
}
if _, ok := respBody["service"]; !ok {
respBody["service"] = context.Service
} else {
processError(w, fmt.Errorf("service field already used in body. If you want to close this warning, please set X-Echo-Ingress-Info to be false."), http.StatusBadRequest)
return
}
if _, ok := respBody["pod"]; !ok {
respBody["pod"] = context.Pod
} else {
processError(w, fmt.Errorf("pod field already used in body. If you want to close this warning, please set X-Echo-Ingress-Info to be false."), http.StatusBadRequest)
return
}
}
// 将request header["X-Echo-Set-Body"]中的内容追加至response body中
func writeEchoResponseBody(w http.ResponseWriter, headers http.Header, respBody map[string]interface{}) {
kvs := make(map[string][]string)
for _, bodyKVList := range headers["X-Echo-Set-Body"] {
bodyKVs := strings.Split(bodyKVList, ",")
for _, bodyKV := range bodyKVs {
name, value, _ := strings.Cut(strings.TrimSpace(bodyKV), ":")
kvs[name] = append(kvs[name], string(value))
}
}
for key, vs := range kvs {
if _, ok := respBody[key]; !ok {
respBody[key] = vs
}
}
}
func processError(w http.ResponseWriter, err error, code int) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Content-Type-Options", "nosniff")
body, err := json.Marshal(struct {
Message string `json:"message"`
}{
err.Error(),
})
if err != nil {
w.WriteHeader(code)
fmt.Fprintln(w, err)
return
}
w.WriteHeader(code)
w.Write(body)
}
func listenAndServeTLS(addr string, serverCert string, serverPrivKey string, clientCA string, handler http.Handler) error {
var config tls.Config
// Optionally enable client certificate validation when client CA certificates are given.
if clientCA != "" {
ca, err := ioutil.ReadFile(clientCA)
if err != nil {
return err
}
certPool := x509.NewCertPool()
if ok := certPool.AppendCertsFromPEM(ca); !ok {
return fmt.Errorf("unable to append certificate in %q to CA pool", clientCA)
}
// Verify certificate against given CA but also allow unauthenticated connections.
config.ClientAuth = tls.VerifyClientCertIfGiven
config.ClientCAs = certPool
}
srv := &http.Server{
Addr: addr,
Handler: handler,
TLSConfig: &config,
}
return srv.ListenAndServeTLS(serverCert, serverPrivKey)
}
func tlsStateToAssertions(connectionState *tls.ConnectionState) *TLSAssertions {
if connectionState != nil {
var state TLSAssertions
switch connectionState.Version {
case tls.VersionTLS13:
state.Version = "TLSv1.3"
case tls.VersionTLS12:
state.Version = "TLSv1.2"
case tls.VersionTLS11:
state.Version = "TLSv1.1"
case tls.VersionTLS10:
state.Version = "TLSv1.0"
}
state.NegotiatedProtocol = connectionState.NegotiatedProtocol
state.ServerName = connectionState.ServerName
state.CipherSuite = tls.CipherSuiteName(connectionState.CipherSuite)
// Convert peer certificates to PEM blocks.
for _, c := range connectionState.PeerCertificates {
var out strings.Builder
pem.Encode(&out, &pem.Block{
Type: "CERTIFICATE",
Bytes: c.Raw,
})
state.PeerCertificates = append(state.PeerCertificates, out.String())
}
return &state
}
return nil
}