This repository has been archived by the owner on Oct 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 63
/
serve.go
379 lines (314 loc) · 13.4 KB
/
serve.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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
package entrypoints
import (
"context"
"crypto/tls"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/flyteorg/flytepropeller/pkg/controller/nodes/task/secretmanager"
authConfig "github.com/flyteorg/flyteadmin/auth/config"
"github.com/flyteorg/flyteadmin/auth/authzserver"
"github.com/gorilla/handlers"
"github.com/flyteorg/flyteadmin/auth"
"github.com/flyteorg/flyteadmin/auth/interfaces"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
grpcauth "github.com/grpc-ecosystem/go-grpc-middleware/auth"
"net"
"net/http"
_ "net/http/pprof" // Required to serve application.
"strings"
"github.com/flyteorg/flyteadmin/pkg/server"
"github.com/pkg/errors"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/health"
"google.golang.org/grpc/health/grpc_health_v1"
"github.com/flyteorg/flyteadmin/pkg/common"
flyteService "github.com/flyteorg/flyteidl/gen/pb-go/flyteidl/service"
"github.com/flyteorg/flytestdlib/logger"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/flyteorg/flyteadmin/pkg/config"
"github.com/flyteorg/flyteadmin/pkg/rpc/adminservice"
"github.com/spf13/cobra"
"github.com/flyteorg/flytestdlib/contextutils"
"github.com/flyteorg/flytestdlib/promutils/labeled"
grpcPrometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
)
var defaultCorsHeaders = []string{"Content-Type"}
// serveCmd represents the serve command
var serveCmd = &cobra.Command{
Use: "serve",
Short: "Launches the Flyte admin server",
RunE: func(cmd *cobra.Command, args []string) error {
ctx := context.Background()
serverConfig := config.GetConfig()
if serverConfig.Security.Secure {
return serveGatewaySecure(ctx, serverConfig, authConfig.GetConfig())
}
return serveGatewayInsecure(ctx, serverConfig, authConfig.GetConfig())
},
}
func init() {
// Command information
RootCmd.AddCommand(serveCmd)
RootCmd.AddCommand(secretsCmd)
// Set Keys
labeled.SetMetricKeys(contextutils.AppNameKey, contextutils.ProjectKey, contextutils.DomainKey,
contextutils.ExecIDKey, contextutils.WorkflowIDKey, contextutils.NodeIDKey, contextutils.TaskIDKey,
contextutils.TaskTypeKey, common.RuntimeTypeKey, common.RuntimeVersionKey)
}
func blanketAuthorization(ctx context.Context, req interface{}, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (
resp interface{}, err error) {
identityContext := auth.IdentityContextFromContext(ctx)
if identityContext.IsEmpty() {
return handler(ctx, req)
}
if !identityContext.Scopes().Has(auth.ScopeAll) {
return nil, status.Errorf(codes.Unauthenticated, "authenticated user doesn't have required scope")
}
return handler(ctx, req)
}
// Creates a new gRPC Server with all the configuration
func newGRPCServer(ctx context.Context, cfg *config.ServerConfig, authCtx interfaces.AuthenticationContext,
opts ...grpc.ServerOption) (*grpc.Server, error) {
// Not yet implemented for streaming
var chainedUnaryInterceptors grpc.UnaryServerInterceptor
if cfg.Security.UseAuth {
logger.Infof(ctx, "Creating gRPC server with authentication")
chainedUnaryInterceptors = grpc_middleware.ChainUnaryServer(grpcPrometheus.UnaryServerInterceptor,
auth.GetAuthenticationCustomMetadataInterceptor(authCtx),
grpcauth.UnaryServerInterceptor(auth.GetAuthenticationInterceptor(authCtx)),
auth.AuthenticationLoggingInterceptor,
blanketAuthorization,
)
} else {
logger.Infof(ctx, "Creating gRPC server without authentication")
chainedUnaryInterceptors = grpc_middleware.ChainUnaryServer(grpcPrometheus.UnaryServerInterceptor)
}
serverOpts := []grpc.ServerOption{
grpc.StreamInterceptor(grpcPrometheus.StreamServerInterceptor),
grpc.UnaryInterceptor(chainedUnaryInterceptors),
}
serverOpts = append(serverOpts, opts...)
grpcServer := grpc.NewServer(serverOpts...)
grpcPrometheus.Register(grpcServer)
flyteService.RegisterAdminServiceServer(grpcServer, adminservice.NewAdminServer(cfg.KubeConfig, cfg.Master))
if cfg.Security.UseAuth {
flyteService.RegisterAuthMetadataServiceServer(grpcServer, authCtx.AuthMetadataService())
flyteService.RegisterIdentityServiceServer(grpcServer, authCtx.IdentityService())
}
healthServer := health.NewServer()
healthServer.SetServingStatus("flyteadmin", grpc_health_v1.HealthCheckResponse_SERVING)
grpc_health_v1.RegisterHealthServer(grpcServer, healthServer)
if cfg.GrpcServerReflection {
reflection.Register(grpcServer)
}
return grpcServer, nil
}
func GetHandleOpenapiSpec(ctx context.Context) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
swaggerBytes, err := flyteService.Asset("admin.swagger.json")
if err != nil {
logger.Warningf(ctx, "Err %v", err)
w.WriteHeader(http.StatusFailedDependency)
} else {
w.WriteHeader(http.StatusOK)
_, err := w.Write(swaggerBytes)
if err != nil {
logger.Errorf(ctx, "failed to write openAPI information, error: %s", err.Error())
}
}
}
}
func healthCheckFunc(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}
func newHTTPServer(ctx context.Context, cfg *config.ServerConfig, authCfg *authConfig.Config, authCtx interfaces.AuthenticationContext,
grpcAddress string, grpcConnectionOpts ...grpc.DialOption) (*http.ServeMux, error) {
// Register the server that will serve HTTP/REST Traffic
mux := http.NewServeMux()
// Register healthcheck
mux.HandleFunc("/healthcheck", healthCheckFunc)
// Register OpenAPI endpoint
// This endpoint will serve the OpenAPI2 spec generated by the swagger protoc plugin, and bundled by go-bindata
mux.HandleFunc("/api/v1/openapi", GetHandleOpenapiSpec(ctx))
var gwmuxOptions = make([]runtime.ServeMuxOption, 0)
// This option means that http requests are served with protobufs, instead of json. We always want this.
gwmuxOptions = append(gwmuxOptions, runtime.WithMarshalerOption("application/octet-stream", &runtime.ProtoMarshaller{}))
if cfg.Security.UseAuth {
// Add HTTP handlers for OIDC endpoints
auth.RegisterHandlers(ctx, mux, authCtx)
// Add HTTP handlers for OAuth2 endpoints
authzserver.RegisterHandlers(mux, authCtx)
// This option translates HTTP authorization data (cookies) into a gRPC metadata field
gwmuxOptions = append(gwmuxOptions, runtime.WithMetadata(auth.GetHTTPRequestCookieToMetadataHandler(authCtx)))
// In an attempt to be able to selectively enforce whether or not authentication is required, we're going to tag
// the requests that come from the HTTP gateway. See the enforceHttp/Grpc options for more information.
gwmuxOptions = append(gwmuxOptions, runtime.WithMetadata(auth.GetHTTPMetadataTaggingHandler()))
}
// Create the grpc-gateway server with the options specified
gwmux := runtime.NewServeMux(gwmuxOptions...)
err := flyteService.RegisterAdminServiceHandlerFromEndpoint(ctx, gwmux, grpcAddress, grpcConnectionOpts)
if err != nil {
return nil, errors.Wrap(err, "error registering admin service")
}
err = flyteService.RegisterAuthMetadataServiceHandlerFromEndpoint(ctx, gwmux, grpcAddress, grpcConnectionOpts)
if err != nil {
return nil, errors.Wrap(err, "error registering auth service")
}
err = flyteService.RegisterIdentityServiceHandlerFromEndpoint(ctx, gwmux, grpcAddress, grpcConnectionOpts)
if err != nil {
return nil, errors.Wrap(err, "error registering identity service")
}
mux.Handle("/", gwmux)
return mux, nil
}
func serveGatewayInsecure(ctx context.Context, cfg *config.ServerConfig, authCfg *authConfig.Config) error {
logger.Infof(ctx, "Serving Flyte Admin Insecure")
// This will parse configuration and create the necessary objects for dealing with auth
var authCtx interfaces.AuthenticationContext
var err error
// This code is here to support authentication without SSL. This setup supports a network topology where
// Envoy does the SSL termination. The final hop is made over localhost only on a trusted machine.
// Warning: Running authentication without SSL in any other topology is a severe security flaw.
// See the auth.Config object for additional settings as well.
if cfg.Security.UseAuth {
sm := secretmanager.NewFileEnvSecretManager(secretmanager.GetConfig())
var oauth2Provider interfaces.OAuth2Provider
var oauth2ResourceServer interfaces.OAuth2ResourceServer
if authCfg.AppAuth.AuthServerType == authConfig.AuthorizationServerTypeSelf {
oauth2Provider, err = authzserver.NewProvider(ctx, authCfg.AppAuth.SelfAuthServer, sm)
if err != nil {
logger.Errorf(ctx, "Error creating authorization server %s", err)
return err
}
oauth2ResourceServer = oauth2Provider
} else {
oauth2ResourceServer, err = authzserver.NewOAuth2ResourceServer(ctx, authCfg.AppAuth.ExternalAuthServer, authCfg.UserAuth.OpenID.BaseURL)
if err != nil {
logger.Errorf(ctx, "Error creating resource server %s", err)
return err
}
}
oauth2MetadataProvider := authzserver.NewService(authCfg)
oidcUserInfoProvider := auth.NewUserInfoProvider()
authCtx, err = auth.NewAuthenticationContext(ctx, sm, oauth2Provider, oauth2ResourceServer, oauth2MetadataProvider, oidcUserInfoProvider, authCfg)
if err != nil {
logger.Errorf(ctx, "Error creating auth context %s", err)
return err
}
}
grpcServer, err := newGRPCServer(ctx, cfg, authCtx)
if err != nil {
return errors.Wrap(err, "failed to create GRPC server")
}
logger.Infof(ctx, "Serving GRPC Traffic on: %s", cfg.GetGrpcHostAddress())
lis, err := net.Listen("tcp", cfg.GetGrpcHostAddress())
if err != nil {
return errors.Wrapf(err, "failed to listen on GRPC port: %s", cfg.GetGrpcHostAddress())
}
go func() {
err := grpcServer.Serve(lis)
logger.Fatalf(ctx, "Failed to create GRPC Server, Err: ", err)
}()
logger.Infof(ctx, "Starting HTTP/1 Gateway server on %s", cfg.GetHostAddress())
httpServer, err := newHTTPServer(ctx, cfg, authCfg, authCtx, cfg.GetGrpcHostAddress(), grpc.WithInsecure(),
grpc.WithMaxHeaderListSize(common.MaxResponseStatusBytes))
if err != nil {
return err
}
var handler http.Handler
if cfg.Security.AllowCors {
handler = handlers.CORS(
handlers.AllowCredentials(),
handlers.AllowedOrigins(cfg.Security.AllowedOrigins),
handlers.AllowedHeaders(append(defaultCorsHeaders, cfg.Security.AllowedHeaders...)),
handlers.AllowedMethods([]string{"GET", "POST", "DELETE", "HEAD", "PUT", "PATCH"}),
)(httpServer)
} else {
handler = httpServer
}
err = http.ListenAndServe(cfg.GetHostAddress(), handler)
if err != nil {
return errors.Wrapf(err, "failed to Start HTTP Server")
}
return nil
}
// grpcHandlerFunc returns an http.Handler that delegates to grpcServer on incoming gRPC
// connections or otherHandler otherwise.
// See https://github.com/philips/grpc-gateway-example/blob/master/cmd/serve.go for reference
func grpcHandlerFunc(grpcServer *grpc.Server, otherHandler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// This is a partial recreation of gRPC's internal checks
if r.ProtoMajor == 2 && strings.Contains(r.Header.Get("Content-Type"), "application/grpc") {
grpcServer.ServeHTTP(w, r)
} else {
otherHandler.ServeHTTP(w, r)
}
})
}
func serveGatewaySecure(ctx context.Context, cfg *config.ServerConfig, authCfg *authConfig.Config) error {
certPool, cert, err := server.GetSslCredentials(ctx, cfg.Security.Ssl.CertificateFile, cfg.Security.Ssl.KeyFile)
if err != nil {
return err
}
// This will parse configuration and create the necessary objects for dealing with auth
var authCtx interfaces.AuthenticationContext
if cfg.Security.UseAuth {
sm := secretmanager.NewFileEnvSecretManager(secretmanager.GetConfig())
var oauth2Provider interfaces.OAuth2Provider
var oauth2ResourceServer interfaces.OAuth2ResourceServer
if authCfg.AppAuth.AuthServerType == authConfig.AuthorizationServerTypeSelf {
oauth2Provider, err = authzserver.NewProvider(ctx, authCfg.AppAuth.SelfAuthServer, sm)
if err != nil {
logger.Errorf(ctx, "Error creating authorization server %s", err)
return err
}
oauth2ResourceServer = oauth2Provider
} else {
oauth2ResourceServer, err = authzserver.NewOAuth2ResourceServer(ctx, authCfg.AppAuth.ExternalAuthServer, authCfg.UserAuth.OpenID.BaseURL)
if err != nil {
logger.Errorf(ctx, "Error creating resource server %s", err)
return err
}
}
oauth2MetadataProvider := authzserver.NewService(authCfg)
oidcUserInfoProvider := auth.NewUserInfoProvider()
authCtx, err = auth.NewAuthenticationContext(ctx, sm, oauth2Provider, oauth2ResourceServer, oauth2MetadataProvider, oidcUserInfoProvider, authCfg)
if err != nil {
logger.Errorf(ctx, "Error creating auth context %s", err)
return err
}
}
grpcServer, err := newGRPCServer(ctx, cfg, authCtx,
grpc.Creds(credentials.NewServerTLSFromCert(cert)))
if err != nil {
return errors.Wrap(err, "failed to create GRPC server")
}
// Whatever certificate is used, pass it along for easier development
dialCreds := credentials.NewTLS(&tls.Config{
ServerName: cfg.GetHostAddress(),
RootCAs: certPool,
})
httpServer, err := newHTTPServer(ctx, cfg, authCfg, authCtx, cfg.GetHostAddress(), grpc.WithTransportCredentials(dialCreds))
if err != nil {
return err
}
conn, err := net.Listen("tcp", cfg.GetHostAddress())
if err != nil {
panic(err)
}
srv := &http.Server{
Addr: cfg.GetHostAddress(),
Handler: grpcHandlerFunc(grpcServer, httpServer),
TLSConfig: &tls.Config{
Certificates: []tls.Certificate{*cert},
NextProtos: []string{"h2"},
},
}
err = srv.Serve(tls.NewListener(conn, srv.TLSConfig))
if err != nil {
return errors.Wrapf(err, "failed to Start HTTP/2 Server")
}
return nil
}