-
Notifications
You must be signed in to change notification settings - Fork 99
/
server.go
179 lines (153 loc) · 4.36 KB
/
server.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
package server
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/controlplaneio/kubesec/v2/pkg/report"
"github.com/controlplaneio/kubesec/v2/pkg/ruler"
"github.com/in-toto/in-toto-golang/in_toto"
"github.com/prometheus/client_golang/prometheus/promhttp"
"go.uber.org/zap"
)
// ListenAndServe starts a web server and waits for SIGTERM
func ListenAndServe(
addr string,
timeout time.Duration,
logger *zap.SugaredLogger,
stopCh <-chan struct{},
keypath string,
schemaConfig ruler.SchemaConfig,
) {
mux := http.DefaultServeMux
mux.Handle("/", scanHandler(logger, keypath, schemaConfig))
mux.Handle("/scan", scanHandler(logger, keypath, schemaConfig))
mux.Handle("/metrics", promhttp.Handler())
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK\n"))
})
srv := &http.Server{
Addr: addr,
Handler: mux,
ReadTimeout: 5 * time.Second,
WriteTimeout: 1 * time.Minute,
IdleTimeout: 15 * time.Second,
}
logger.Infof("Starting HTTP server on %s", addr)
// run server in background
go func() {
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
logger.Fatalf("HTTP server crashed %v", err)
}
}()
// wait for SIGTERM or SIGINT
<-stopCh
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
logger.Errorf("HTTP server graceful shutdown failed %v", err)
} else {
logger.Info("HTTP server stopped")
}
}
var shutdownSignals = []os.Signal{os.Interrupt, syscall.SIGTERM}
var onlyOneSignalHandler = make(chan struct{})
func SetupSignalHandler() (stopCh <-chan struct{}) {
close(onlyOneSignalHandler)
stop := make(chan struct{})
c := make(chan os.Signal, 2)
signal.Notify(c, shutdownSignals...)
go func() {
<-c
close(stop)
<-c
os.Exit(1)
}()
return stop
}
func retrieveRequestData(r *http.Request) ([]byte, error) {
// TODO: Implement breaking change respecting header Content-Type
// contentType := r.Header.Get("Content-Type")
// err := r.ParseForm()
// formData := r.Form.Get(formPrefix)
formPrefix := "file="
formPrefixLen := len(formPrefix)
body, err := io.ReadAll(r.Body)
if err != nil {
return nil, errors.New("Error reading request body")
}
defer r.Body.Close()
if string(body[:formPrefixLen]) == formPrefix {
body = body[formPrefixLen:]
}
return body, nil
}
func scanHandler(logger *zap.SugaredLogger, keypath string, schemaConfig ruler.SchemaConfig) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
http.Redirect(w, r, "https://kubesec.io", http.StatusSeeOther)
return
}
// fail early if no in-toto signing key is configured for this server
if r.URL.Query().Get("in-toto") != "" && keypath == "" {
logger.Errorf("Attempted to serve an in-toto payload but no key is available")
w.WriteHeader(http.StatusInternalServerError)
return
}
const fileName = "API"
body, err := retrieveRequestData(r)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error() + "\n"))
return
}
var payload interface{}
reports, err := ruler.NewRuleset(logger).Run(fileName, body, schemaConfig)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error() + "\n"))
return
}
if r.URL.Query().Get("in-toto") != "" {
intotoKey := in_toto.Key{}
err := intotoKey.LoadKey(keypath, "ed25519", []string{"sha256", "sha512"})
if err != nil {
logger.Errorf("Attempted to serve an in-toto payload but the key is unavailable: %v",
err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
link := ruler.GenerateInTotoLink(reports, body)
err = link.Sign(intotoKey)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
payload = map[string]interface{}{
"reports": reports,
"link": link,
}
} else {
payload = reports
}
res, err := json.Marshal(payload)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
formattedOutput, err := report.PrettyJSON(res)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Write([]byte(string(formattedOutput) + "\n"))
})
}