-
Notifications
You must be signed in to change notification settings - Fork 19
/
rest.go
338 lines (275 loc) · 11.2 KB
/
rest.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
// Copyright 2016-2022 Fraunhofer AISEC
//
// 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.
//
// $$\ $$\ $$\ $$\
// $$ | $$ |\__| $$ |
// $$$$$$$\ $$ | $$$$$$\ $$\ $$\ $$$$$$$ |$$\ $$$$$$\ $$$$$$\ $$$$$$\
// $$ _____|$$ |$$ __$$\ $$ | $$ |$$ __$$ |$$ |\_$$ _| $$ __$$\ $$ __$$\
// $$ / $$ |$$ / $$ |$$ | $$ |$$ / $$ |$$ | $$ | $$ / $$ |$$ | \__|
// $$ | $$ |$$ | $$ |$$ | $$ |$$ | $$ |$$ | $$ |$$\ $$ | $$ |$$ |
// \$$$$$$\ $$ |\$$$$$ |\$$$$$ |\$$$$$$ |$$ | \$$$ |\$$$$$ |$$ |
// \_______|\__| \______/ \______/ \_______|\__| \____/ \______/ \__|
//
// This file is part of Clouditor Community Edition.
package rest
import (
"context"
"crypto/ecdsa"
"errors"
"fmt"
"net"
"net/http"
"os"
"os/signal"
"strings"
"time"
"clouditor.io/clouditor/api/assessment"
"clouditor.io/clouditor/api/discovery"
"clouditor.io/clouditor/api/evaluation"
"clouditor.io/clouditor/api/evidence"
"clouditor.io/clouditor/api/orchestrator"
"clouditor.io/clouditor/internal/auth"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
oauth2 "github.com/oxisto/oauth2go"
"github.com/sirupsen/logrus"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
var (
log *logrus.Entry
// srv holds the global http.Server of our REST API.
srv *http.Server
// httpPort holds the used HTTP port of the http.Server
httpPort uint16
// sock holds the listener socket of our REST API.
sock net.Listener
ready = make(chan bool)
cnf config
)
// config holds different configuration options for the REST gateway.
type config struct {
// cors holds the global CORS configuration.
cors *corsConfig
// opts contains the gRPC options used for the gateway-to-backend calls.
opts []grpc.DialOption
}
// corsConfig holds all necessary configuration options for Cross-Origin Resource Sharing of our REST API.
type corsConfig struct {
// allowedOrigins contains a list of the allowed origins
allowedOrigins []string
// allowedHeaders contains a list of the allowed headers
allowedHeaders []string
// allowedMethods contains a list of the allowed methods
allowedMethods []string
}
// ServerConfigOption represents functional-style options to modify the server configuration in RunServer.
type ServerConfigOption func(*config, *runtime.ServeMux)
var (
// DefaultAllowedOrigins contains a nil slice, as per default, no origins are allowed.
DefaultAllowedOrigins []string = nil
// DefaultAllowedHeaders contains sensible defaults for the Access-Control-Allow-Headers header.
// Please adjust accordingly in production using WithAllowedHeaders.
DefaultAllowedHeaders = []string{"Content-Type", "Accept", "Authorization"}
// DefaultAllowedMethods contains sensible defaults for the Access-Control-Allow-Methods header.
// Please adjust accordingly in production using WithAllowedMethods.
DefaultAllowedMethods = []string{"GET", "POST", "PUT", "DELETE"}
// DefaultAPIHTTPPort specifies the default port for the REST API.
DefaultAPIHTTPPort uint16 = 8080
)
func init() {
log = logrus.WithField("component", "rest")
// initialize the CORS config with restrictive default values, e.g. no origin allowed
cnf.cors = &corsConfig{
allowedOrigins: DefaultAllowedOrigins,
allowedHeaders: DefaultAllowedHeaders,
allowedMethods: DefaultAllowedMethods,
}
}
// WithAllowedOrigins is an option to supply allowed origins in CORS.
func WithAllowedOrigins(origins []string) ServerConfigOption {
return func(c *config, _ *runtime.ServeMux) {
c.cors.allowedOrigins = origins
}
}
// WithAllowedHeaders is an option to supply allowed headers in CORS.
func WithAllowedHeaders(headers []string) ServerConfigOption {
return func(c *config, _ *runtime.ServeMux) {
c.cors.allowedHeaders = headers
}
}
// WithAllowedMethods is an option to supply allowed methods in CORS.
func WithAllowedMethods(methods []string) ServerConfigOption {
return func(c *config, _ *runtime.ServeMux) {
c.cors.allowedMethods = methods
}
}
// WithAdditionalHandler is an option to add an additional handler func in the REST server.
func WithAdditionalHandler(method string, path string, h runtime.HandlerFunc) ServerConfigOption {
return func(_ *config, sm *runtime.ServeMux) {
_ = sm.HandlePath(method, path, h)
}
}
// WithAdditionalGRPCOpts is an option to add an additional gRPC dial options in the REST server communication to the
// backend.
func WithAdditionalGRPCOpts(opts []grpc.DialOption) ServerConfigOption {
return func(c *config, sm *runtime.ServeMux) {
c.opts = append(c.opts, opts...)
}
}
// WithEmbeddedOAuth2Server configures our REST gateway to include an embedded OAuth 2.0
// authorization server with the given parameters. This server can be used to authenticate
// and authorize API clients, such as our own micro-services as well as users logging in
// through the UI.
//
// For the various options to configure the OAuth 2.0 server, please refer to
// https://pkg.go.dev/github.com/oxisto/oauth2go#AuthorizationServerOption.
//
// In production scenarios, the usage of a dedicated authentication and authorization server is
// recommended.
func WithEmbeddedOAuth2Server(keyPath string, keyPassword string, saveOnCreate bool, opts ...oauth2.AuthorizationServerOption) ServerConfigOption {
return func(c *config, sm *runtime.ServeMux) {
opts = append(opts, oauth2.WithSigningKeysFunc(func() map[int]*ecdsa.PrivateKey {
return auth.LoadSigningKeys(keyPath, keyPassword, saveOnCreate)
}), oauth2.WithPublicURL(fmt.Sprintf("http://localhost:%d/v1/auth", httpPort)))
authSrv := oauth2.NewServer("", opts...)
authHandler := func(w http.ResponseWriter, r *http.Request, pathParams map[string]string) {
http.StripPrefix("/v1/auth", authSrv.Handler).ServeHTTP(w, r)
}
WithAdditionalHandler("GET", "/.well-known/openid-configuration", func(w http.ResponseWriter, r *http.Request, pathParams map[string]string) {
authSrv.Handler.ServeHTTP(w, r)
})(c, sm)
WithAdditionalHandler("GET", "/v1/auth/certs", authHandler)(c, sm)
WithAdditionalHandler("GET", "/v1/auth/login", authHandler)(c, sm)
WithAdditionalHandler("GET", "/v1/auth/authorize", authHandler)(c, sm)
WithAdditionalHandler("POST", "/v1/auth/login", authHandler)(c, sm)
WithAdditionalHandler("POST", "/v1/auth/token", authHandler)(c, sm)
}
}
// RunServer starts our REST API. The REST API is a reverse proxy using grpc-gateway that
// exposes certain gRPC calls as RESTful HTTP methods.
func RunServer(ctx context.Context, grpcPort uint16, port uint16, serverOpts ...ServerConfigOption) (err error) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
httpPort = port
mux := runtime.NewServeMux()
cnf.opts = []grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())}
for _, o := range serverOpts {
o(&cnf, mux)
}
if err := discovery.RegisterDiscoveryHandlerFromEndpoint(ctx, mux, fmt.Sprintf("localhost:%d", grpcPort), cnf.opts); err != nil {
return fmt.Errorf("failed to connect to discovery gRPC service %w", err)
}
if err := assessment.RegisterAssessmentHandlerFromEndpoint(ctx, mux, fmt.Sprintf("localhost:%d", grpcPort), cnf.opts); err != nil {
return fmt.Errorf("failed to connect to assessment gRPC service %w", err)
}
if err := orchestrator.RegisterOrchestratorHandlerFromEndpoint(ctx, mux, fmt.Sprintf("localhost:%d", grpcPort), cnf.opts); err != nil {
return fmt.Errorf("failed to connect to orchestrator gRPC service %w", err)
}
if err := evaluation.RegisterEvaluationHandlerFromEndpoint(ctx, mux, fmt.Sprintf("localhost:%d", grpcPort), cnf.opts); err != nil {
return fmt.Errorf("failed to connect to evaluation gRPC service %w", err)
}
if err := evidence.RegisterEvidenceStoreHandlerFromEndpoint(ctx, mux, fmt.Sprintf("localhost:%d", grpcPort), cnf.opts); err != nil {
return fmt.Errorf("failed to connect to evidence gRPC service %w", err)
}
srv = &http.Server{
Addr: fmt.Sprintf(":%d", httpPort),
Handler: handleCORS(mux),
ReadHeaderTimeout: 2 * time.Second,
}
// graceful shutdown
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
for range c {
// sig is a ^C, handle it
break
}
StopServer(ctx)
}()
log.Printf("Starting REST gateway on :%d", httpPort)
log.WithFields(logrus.Fields{
"allowed-origins": cnf.cors.allowedOrigins,
"allowed-methods": cnf.cors.allowedMethods,
"allowed-headers": cnf.cors.allowedHeaders,
}).Info("Applying CORS configuration...")
sock, err = net.Listen("tcp", srv.Addr)
if err != nil {
return err
}
go func() {
ready <- true
}()
return srv.Serve(sock)
}
// StopServer is in charge of stopping the REST API.
func StopServer(ctx context.Context) {
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
log.Printf("Shutting down REST gateway")
// Clear our ready channel, otherwise, this will block the exit
select {
case <-ready:
default:
}
_ = srv.Shutdown(ctx)
}
// GetReadyChannel returns a channel which will notify when the server is ready
func GetReadyChannel() chan bool {
return ready
}
// GetServerPort returns the actual port used by the REST API
func GetServerPort() (uint16, error) {
if sock == nil {
return 0, errors.New("server socket is empty")
}
tcpAddr, ok := sock.Addr().(*net.TCPAddr)
if !ok {
return 0, errors.New("server socket address is not a TCP address")
}
return tcpAddr.AddrPort().Port(), nil
}
// handleCORS adds an appropriate http.HandlerFunc to an existing http.Handler to configure
// Cross-Origin Resource Sharing (CORS) according to our global configuration.
func handleCORS(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Check, if we allow this specific origin
origin := r.Header.Get("Origin")
if cnf.cors.OriginAllowed(origin) {
// Set the appropriate access control header
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Add("Vary", "Origin")
// Additionally, we need to handle preflight (OPTIONS) requests to specify allowed headers and methods
if r.Method == "OPTIONS" && r.Header.Get("Access-Control-Request-Method") != "" {
w.Header().Set("Access-Control-Allow-Headers", strings.Join(cnf.cors.allowedHeaders, ","))
w.Header().Set("Access-Control-Allow-Methods", strings.Join(cnf.cors.allowedMethods, ","))
return
}
}
h.ServeHTTP(w, r)
})
}
// OriginAllowed checks if the supplied origin is allowed according to our global CORS configuration.
func (cors *corsConfig) OriginAllowed(origin string) bool {
// If no origin is specified, we are running in a non-browser environment and
// this means, that all origins are allowed
if origin == "" {
return true
}
for _, v := range cors.allowedOrigins {
if origin == v {
return true
}
}
return false
}