-
Notifications
You must be signed in to change notification settings - Fork 32
/
main.go
567 lines (477 loc) · 20.6 KB
/
main.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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
/*
Copyright 2020 Red Hat, Inc.
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 (
"context"
"crypto/sha256"
"crypto/tls"
"encoding/hex"
"fmt"
"net"
"net/http"
"os"
"time"
"sigs.k8s.io/controller-runtime/pkg/cache"
metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server"
"sigs.k8s.io/controller-runtime/pkg/webhook"
"github.com/kuadrant/authorino/api/v1beta2"
"github.com/kuadrant/authorino/api/v1beta3"
"github.com/kuadrant/authorino/controllers"
"github.com/kuadrant/authorino/pkg/evaluators"
"github.com/kuadrant/authorino/pkg/health"
"github.com/kuadrant/authorino/pkg/index"
"github.com/kuadrant/authorino/pkg/log"
"github.com/kuadrant/authorino/pkg/metrics"
"github.com/kuadrant/authorino/pkg/service"
"github.com/kuadrant/authorino/pkg/trace"
"github.com/kuadrant/authorino/pkg/utils"
envoy_auth "github.com/envoyproxy/go-control-plane/envoy/service/auth/v3"
"github.com/go-logr/logr"
grpc_prometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
otel_grpc "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
otel_http "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
"go.opentelemetry.io/otel"
otel_propagation "go.opentelemetry.io/otel/propagation"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
healthpb "google.golang.org/grpc/health/grpc_health_v1"
"google.golang.org/grpc/reflection"
"k8s.io/apimachinery/pkg/runtime"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
_ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/healthz"
// +kubebuilder:scaffold:imports
)
const (
gRPCMaxConcurrentStreams = 10000
leaderElectionIDSuffix = "authorino.kuadrant.io"
)
var (
// ldflags
version string
dirty string
gitSHA string
scheme = runtime.NewScheme()
logger logr.Logger
)
func init() {
utilruntime.Must(clientgoscheme.AddToScheme(scheme))
utilruntime.Must(v1beta2.AddToScheme(scheme))
utilruntime.Must(v1beta3.AddToScheme(scheme))
}
type logOptions struct {
level string
mode string
}
type telemetryOptions struct {
tracingServiceEndpoint string
tracingServiceInsecure bool
tracingServiceTags []string
}
type commonServerOptions struct {
log logOptions
metricsAddr string
healthProbeAddr string
telemetry telemetryOptions
}
type authServerOptions struct {
commonServerOptions
watchNamespace string
watchedAuthConfigLabelSelector string
watchedSecretLabelSelector string
allowSupersedingHostSubsets bool
timeout int
extAuthGRPCPort int
extAuthHTTPPort int
tlsCertPath string
tlsCertKeyPath string
oidcHTTPPort int
oidcTLSCertPath string
oidcTLSCertKeyPath string
evaluatorCacheSize int
deepMetricsEnabled bool
webhookServicePort int
enableLeaderElection bool
maxHttpRequestBodySize int64
}
type webhookServerOptions struct {
commonServerOptions
port int
}
type keyAuthServerOptions struct{}
type keyWebhookServerOptions struct{}
func main() {
authServerOpts := &authServerOptions{}
webhookServerOpts := &webhookServerOptions{}
cmdRoot := rootCmd()
cmdRoot.AddCommand(
authServerCmd(authServerOpts),
webhookServerCmd(webhookServerOpts),
versionCmd(),
)
ctx := context.WithValue(context.TODO(), keyAuthServerOptions{}, authServerOpts)
ctx = context.WithValue(ctx, keyWebhookServerOptions{}, webhookServerOpts)
if err := cmdRoot.ExecuteContext(ctx); err != nil {
fmt.Println("error: ", err)
os.Exit(1)
}
}
func rootCmd() *cobra.Command {
return &cobra.Command{
Use: "authorino",
Short: "Authorino is a Kubernetes-native authorization server.",
}
}
func authServerCmd(opts *authServerOptions) *cobra.Command {
cmd := &cobra.Command{
Use: "server",
Short: "Runs the authorization server",
Run: runAuthorizationServer,
}
cmd.PersistentFlags().StringVar(&opts.watchNamespace, "watch-namespace", utils.EnvVar("WATCH_NAMESPACE", ""), "Kubernetes namespace to watch")
cmd.PersistentFlags().StringVar(&opts.watchedAuthConfigLabelSelector, "auth-config-label-selector", utils.EnvVar("AUTH_CONFIG_LABEL_SELECTOR", ""), "Kubernetes label selector to filter AuthConfig resources to watch")
cmd.PersistentFlags().StringVar(&opts.watchedSecretLabelSelector, "secret-label-selector", utils.EnvVar("SECRET_LABEL_SELECTOR", "authorino.kuadrant.io/managed-by=authorino"), "Kubernetes label selector to filter Secret resources to watch")
cmd.PersistentFlags().BoolVar(&opts.allowSupersedingHostSubsets, "allow-superseding-host-subsets", false, "Enable AuthConfigs to supersede strict host subsets of supersets already taken")
cmd.PersistentFlags().IntVar(&opts.timeout, "timeout", utils.EnvVar("TIMEOUT", 0), "Server timeout - in milliseconds")
cmd.PersistentFlags().IntVar(&opts.extAuthGRPCPort, "ext-auth-grpc-port", utils.EnvVar("EXT_AUTH_GRPC_PORT", 50051), "Port number of authorization server - gRPC interface")
cmd.PersistentFlags().IntVar(&opts.extAuthHTTPPort, "ext-auth-http-port", utils.EnvVar("EXT_AUTH_HTTP_PORT", 5001), "Port number of authorization server - raw HTTP interface")
cmd.PersistentFlags().StringVar(&opts.tlsCertPath, "tls-cert", utils.EnvVar("TLS_CERT", ""), "Path to the public TLS server certificate file in the file system - authorization server")
cmd.PersistentFlags().StringVar(&opts.tlsCertKeyPath, "tls-cert-key", utils.EnvVar("TLS_CERT_KEY", ""), "Path to the private TLS server certificate key file in the file system - authorization server")
cmd.PersistentFlags().IntVar(&opts.oidcHTTPPort, "oidc-http-port", utils.EnvVar("OIDC_HTTP_PORT", 8083), "Port number of OIDC Discovery server for Festival Wristband tokens")
cmd.PersistentFlags().StringVar(&opts.oidcTLSCertPath, "oidc-tls-cert", utils.EnvVar("OIDC_TLS_CERT", ""), "Path to the public TLS server certificate file in the file system - Festival Wristband OIDC Discovery server")
cmd.PersistentFlags().StringVar(&opts.oidcTLSCertKeyPath, "oidc-tls-cert-key", utils.EnvVar("OIDC_TLS_CERT_KEY", ""), "Path to the private TLS server certificate key file in the file system - Festival Wristband OIDC Discovery server")
cmd.PersistentFlags().IntVar(&opts.evaluatorCacheSize, "evaluator-cache-size", utils.EnvVar("EVALUATOR_CACHE_SIZE", 1), "Cache size of each Authorino evaluator if enabled in the AuthConfig - in megabytes")
cmd.PersistentFlags().BoolVar(&opts.deepMetricsEnabled, "deep-metrics-enabled", utils.EnvVar("DEEP_METRICS_ENABLED", false), "Enable deep metrics at the level of each evaluator when requested in the AuthConfig, exported by the metrics server")
cmd.PersistentFlags().IntVar(&opts.webhookServicePort, "webhook-service-port", 9443, "Port number of the webhook server")
cmd.PersistentFlags().BoolVar(&opts.enableLeaderElection, "enable-leader-election", false, "Enable leader election for status updater - ensures only one instance of Authorino tries to update the status of reconciled resources")
cmd.PersistentFlags().Int64Var(&opts.maxHttpRequestBodySize, "max-http-request-body-size", utils.EnvVar("MAX_HTTP_REQUEST_BODY_SIZE", int64(8192)), "Maximum size of the body of requests accepted in the raw HTTP interface of the authorization server - in bytes")
registerCommonServerOptions(cmd, &opts.commonServerOptions)
return cmd
}
func webhookServerCmd(opts *webhookServerOptions) *cobra.Command {
cmd := &cobra.Command{
Use: "webhooks",
Short: "Runs the webhook server",
Run: runWebhookServer,
}
cmd.PersistentFlags().IntVar(&opts.port, "port", 9443, "Port number of the webhook server")
registerCommonServerOptions(cmd, &opts.commonServerOptions)
return cmd
}
func versionCmd() *cobra.Command {
return &cobra.Command{
Use: "version",
Short: "Prints the Authorino version info",
Run: printVersion,
}
}
func registerCommonServerOptions(cmd *cobra.Command, opts *commonServerOptions) {
cmd.PersistentFlags().StringVar(&opts.log.level, "log-level", utils.EnvVar("LOG_LEVEL", "info"), "Log level")
cmd.PersistentFlags().StringVar(&opts.log.mode, "log-mode", utils.EnvVar("LOG_MODE", "production"), "Log mode")
cmd.PersistentFlags().StringVar(&opts.metricsAddr, "metrics-addr", ":8080", "The network address the metrics endpoint binds to")
cmd.PersistentFlags().StringVar(&opts.healthProbeAddr, "health-probe-addr", ":8081", "The network address the health probe endpoint binds to")
cmd.PersistentFlags().StringVar(&opts.telemetry.tracingServiceEndpoint, "tracing-service-endpoint", "", "Endpoint URL of the tracing exporter service - use either 'rpc://' or 'http://' scheme")
cmd.PersistentFlags().BoolVar(&opts.telemetry.tracingServiceInsecure, "tracing-service-insecure", false, "Disable TLS for the tracing service connection")
cmd.PersistentFlags().StringArrayVar(&opts.telemetry.tracingServiceTags, "tracing-service-tag", []string{}, "Fixed key=value tag to add to emitted traces")
}
func runAuthorizationServer(cmd *cobra.Command, _ []string) {
opts := cmd.Context().Value(keyAuthServerOptions{}).(*authServerOptions)
setup(cmd, opts.log, opts.telemetry)
// global options
evaluators.EvaluatorCacheSize = opts.evaluatorCacheSize
metrics.DeepMetricsEnabled = opts.deepMetricsEnabled
// creates the index of authconfigs
index := index.NewIndex()
// starts authorization server
startExtAuthServerGRPC(index, *opts)
startExtAuthServerHTTP(index, *opts)
// starts the oidc discovery server
startOIDCServer(index, *opts)
baseManagerOptions := ctrl.Options{
Scheme: scheme,
WebhookServer: webhook.NewServer(webhook.Options{Port: opts.webhookServicePort}),
Metrics: metricsserver.Options{BindAddress: opts.metricsAddr},
HealthProbeBindAddress: opts.healthProbeAddr,
LeaderElection: false,
}
if opts.watchNamespace != "" {
baseManagerOptions.Cache.DefaultNamespaces = map[string]cache.Config{opts.watchNamespace: {}}
}
// sets up the reconciliation manager
mgr, err := setupManager(baseManagerOptions)
if err != nil {
logger.Error(err, "failed to setup reconciliation manager")
os.Exit(1)
}
statusReport := controllers.NewStatusReportMap()
controllerLogger := log.WithName("controller-runtime").WithName("manager").WithName("controller")
// sets up the authconfig reconciler
authConfigReconciler := &controllers.AuthConfigReconciler{
Client: mgr.GetClient(),
Index: index,
AllowSupersedingHostSubsets: opts.allowSupersedingHostSubsets,
StatusReport: statusReport,
Logger: controllerLogger.WithName("authconfig"),
Scheme: mgr.GetScheme(),
LabelSelector: controllers.ToLabelSelector(opts.watchedAuthConfigLabelSelector),
Namespace: opts.watchNamespace,
}
if err = authConfigReconciler.SetupWithManager(mgr); err != nil {
logger.Error(err, "failed to setup controller", "controller", "authconfig")
os.Exit(1)
}
// authconfig readiness check
readinessCheck := health.NewHandler(controllers.AuthConfigsReadyzSubpath, health.Observe(authConfigReconciler))
if err := mgr.AddReadyzCheck(controllers.AuthConfigsReadyzSubpath, readinessCheck.HandleReadyzCheck); err != nil {
logger.Error(err, "failed to setup reconciliation readiness check")
os.Exit(1)
}
// sets up the secret reconciler
if err = (&controllers.SecretReconciler{
Client: mgr.GetClient(),
Logger: controllerLogger.WithName("secret"),
Scheme: mgr.GetScheme(),
Index: index,
LabelSelector: controllers.ToLabelSelector(opts.watchedSecretLabelSelector),
Namespace: opts.watchNamespace,
}).SetupWithManager(mgr); err != nil {
logger.Error(err, "failed to setup controller", "controller", "secret")
os.Exit(1)
}
// starts the reconciliation manager
signalHandler := ctrl.SetupSignalHandler()
logger.Info("starting reconciliation manager")
go func() {
if err := mgr.Start(signalHandler); err != nil {
logger.Error(err, "failed to start reconciliation manager")
os.Exit(1)
}
}()
// sets up the status update manager
leaderElectionId := sha256.Sum256([]byte(opts.watchedAuthConfigLabelSelector))
statusUpdaterOptions := baseManagerOptions
statusUpdaterOptions.Metrics.BindAddress = "0" // disabled so it does not clash with the reconciliation manager
statusUpdaterOptions.HealthProbeBindAddress = "0" // disabled so it does not clash with the reconciliation manager
statusUpdaterOptions.LeaderElection = opts.enableLeaderElection
statusUpdaterOptions.LeaderElectionID = fmt.Sprintf("%v.%v", hex.EncodeToString(leaderElectionId[:4]), leaderElectionIDSuffix)
statusUpdateManager, err := setupManager(statusUpdaterOptions)
if err != nil {
logger.Error(err, "failed to setup status update manager")
os.Exit(1)
}
// sets up the authconfig status update controller
if err = (&controllers.AuthConfigStatusUpdater{
Client: statusUpdateManager.GetClient(),
Logger: controllerLogger.WithName("authconfig").WithName("statusupdater"),
StatusReport: statusReport,
LabelSelector: controllers.ToLabelSelector(opts.watchedAuthConfigLabelSelector),
}).SetupWithManager(statusUpdateManager); err != nil {
logger.Error(err, "failed to create controller", "controller", "authconfigstatusupdate")
}
// starts the status update manager
logger.Info("starting status update manager")
if err := statusUpdateManager.Start(signalHandler); err != nil {
logger.Error(err, "failed to start status update manager")
os.Exit(1)
}
}
func runWebhookServer(cmd *cobra.Command, _ []string) {
opts := cmd.Context().Value(keyWebhookServerOptions{}).(*webhookServerOptions)
setup(cmd, opts.log, opts.telemetry)
// sets up the webhook manager
mgr, err := setupManager(ctrl.Options{
Scheme: scheme,
Metrics: metricsserver.Options{BindAddress: opts.metricsAddr},
HealthProbeBindAddress: opts.healthProbeAddr,
LeaderElection: true,
LeaderElectionID: fmt.Sprintf("670aa2de.%s", leaderElectionIDSuffix),
WebhookServer: webhook.NewServer(webhook.Options{Port: opts.port}),
})
if err != nil {
logger.Error(err, "failed to setup webhook manager")
os.Exit(1)
}
// starts the webhook manager
signalHandler := ctrl.SetupSignalHandler()
logger.Info("starting webhook manager")
if err := mgr.Start(signalHandler); err != nil {
logger.Error(err, "failed to start webhook manager")
os.Exit(1)
}
}
func setup(cmd *cobra.Command, log logOptions, telemetry telemetryOptions) {
setupLogger(log)
logger.Info("build information", "version", version, "commit", gitSHA, "dirty", dirty, "cmd", cmd.Use)
// log the command-line args
if logger.V(1).Enabled() {
var flags []interface{}
cmd.PersistentFlags().VisitAll(func(flag *pflag.Flag) {
flags = append(flags, flag.Name, flag.Value.String())
})
logger.V(1).Info("setting up with options", flags...)
}
setupTelemetryServices(telemetry)
}
func setupLogger(opts logOptions) {
logOpts := log.Options{Level: log.ToLogLevel(opts.level), Mode: log.ToLogMode(opts.mode)}
logger = log.NewLogger(logOpts).WithName("authorino")
log.SetLogger(logger, logOpts)
}
func setupTelemetryServices(opts telemetryOptions) {
telemetryLogger := logger.WithName("telemetry")
otel.SetLogger(telemetryLogger)
otel.SetErrorHandler(&trace.ErrorHandler{Logger: telemetryLogger})
if opts.tracingServiceEndpoint != "" {
tp, err := trace.CreateTraceProvider(trace.Config{
Endpoint: opts.tracingServiceEndpoint,
Insecure: opts.tracingServiceInsecure,
Version: version,
Tags: opts.tracingServiceTags,
})
if err != nil {
telemetryLogger.Error(err, "unable to set trace provider")
} else {
otel.SetTracerProvider(tp)
}
}
otel.SetTextMapPropagator(otel_propagation.NewCompositeTextMapPropagator(otel_propagation.TraceContext{}, otel_propagation.Baggage{}))
}
func setupManager(options ctrl.Options) (ctrl.Manager, error) {
if options.Metrics.BindAddress != "0" {
options.Metrics.ExtraHandlers = map[string]http.Handler{"/server-metrics": promhttp.Handler()}
}
mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), options)
if err != nil {
return nil, err
}
if options.HealthProbeBindAddress != "0" {
if err := mgr.AddHealthzCheck("ping", healthz.Ping); err != nil {
return nil, err
}
}
return mgr, nil
}
func startExtAuthServerGRPC(authConfigIndex index.Index, opts authServerOptions) {
lis, err := listen(opts.extAuthGRPCPort)
if err != nil {
logger.Error(err, "failed to obtain port for the grpc auth service")
os.Exit(1)
}
if lis == nil {
logger.Info("disabling grpc auth service")
return
}
grpcServerOpts := []grpc.ServerOption{
grpc.MaxConcurrentStreams(gRPCMaxConcurrentStreams),
grpc.ChainStreamInterceptor(grpc_prometheus.StreamServerInterceptor, otel_grpc.StreamServerInterceptor()),
grpc.ChainUnaryInterceptor(grpc_prometheus.UnaryServerInterceptor, otel_grpc.UnaryServerInterceptor()),
}
tlsEnabled := opts.tlsCertPath != "" && opts.tlsCertKeyPath != ""
if tlsEnabled {
if tlsCert, err := tls.LoadX509KeyPair(opts.tlsCertPath, opts.tlsCertKeyPath); err != nil {
logger.Error(err, "failed to load tls cert for the grpc auth service")
os.Exit(1)
} else {
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{tlsCert},
ClientAuth: tls.NoClientCert,
MinVersion: tls.VersionTLS12,
}
grpcServerOpts = append(grpcServerOpts, grpc.Creds(credentials.NewTLS(tlsConfig)))
}
}
grpcServer := grpc.NewServer(grpcServerOpts...)
reflection.Register(grpcServer)
envoy_auth.RegisterAuthorizationServer(grpcServer, &service.AuthService{Index: authConfigIndex, Timeout: timeoutMs(opts.timeout)})
healthpb.RegisterHealthServer(grpcServer, &service.HealthService{})
grpc_prometheus.Register(grpcServer)
grpc_prometheus.EnableHandlingTimeHistogram()
go func() {
logger.Info("starting grpc auth service", "port", opts.extAuthGRPCPort, "tls", tlsEnabled)
if err := grpcServer.Serve(lis); err != nil {
logger.Error(err, "failed to start grpc auth service")
os.Exit(1)
}
}()
}
func startExtAuthServerHTTP(authConfigIndex index.Index, opts authServerOptions) {
startHTTPService("auth", opts.extAuthHTTPPort, service.HTTPAuthorizationBasePath, opts.tlsCertPath, opts.tlsCertKeyPath, service.NewAuthService(authConfigIndex, timeoutMs(opts.timeout), opts.maxHttpRequestBodySize))
}
func startOIDCServer(authConfigIndex index.Index, opts authServerOptions) {
startHTTPService("oidc", opts.oidcHTTPPort, service.OIDCBasePath, opts.oidcTLSCertPath, opts.oidcTLSCertKeyPath, &service.OidcService{Index: authConfigIndex})
}
func startHTTPService(name string, port int, basePath, tlsCertPath, tlsCertKeyPath string, handler http.Handler) {
lis, err := listen(port)
if err != nil {
logger.Error(err, fmt.Sprintf("failed to obtain port for the http %s service", name))
os.Exit(1)
}
if lis == nil {
logger.Info(fmt.Sprintf("disabling http %s service", name))
return
}
http.Handle(basePath, otel_http.NewHandler(handler, name))
tlsEnabled := tlsCertPath != "" && tlsCertKeyPath != ""
go func() {
var err error
logger.Info(fmt.Sprintf("starting http %s service", name), "port", port, "tls", tlsEnabled)
if tlsEnabled {
server := &http.Server{
TLSConfig: &tls.Config{
MinVersion: tls.VersionTLS12,
ClientAuth: tls.RequestClientCert,
},
}
err = server.ServeTLS(lis, tlsCertPath, tlsCertKeyPath)
} else {
err = http.Serve(lis, nil)
}
if err != nil {
logger.Error(err, fmt.Sprintf("failed to start http %s service", name))
os.Exit(1)
}
}()
}
func listen(port int) (net.Listener, error) {
if port == 0 {
return nil, nil
}
if lis, err := net.Listen("tcp", fmt.Sprintf(":%d", port)); err != nil {
return nil, err
} else {
return lis, nil
}
}
func fetchEnv(key string, def interface{}) string {
val, ok := os.LookupEnv(key)
if !ok {
return fmt.Sprint(def)
} else {
return val
}
}
func timeoutMs(timeout int) time.Duration {
return time.Duration(timeout) * time.Millisecond
}
func printVersion(_ *cobra.Command, _ []string) {
if dirty == "true" {
fmt.Printf("Authorino %s (%s-dirty)\n", version, gitSHA)
} else {
fmt.Printf("Authorino %s (%s)\n", version, gitSHA)
}
}