-
Notifications
You must be signed in to change notification settings - Fork 33
/
server.go
429 lines (359 loc) · 11.9 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
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
package cmd
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
"net/http/pprof"
"os"
"os/signal"
"syscall"
"time"
"github.com/boring-registry/boring-registry/pkg/auth"
"github.com/boring-registry/boring-registry/pkg/discovery"
"github.com/boring-registry/boring-registry/pkg/mirror"
"github.com/boring-registry/boring-registry/pkg/module"
o11y "github.com/boring-registry/boring-registry/pkg/observability"
"github.com/boring-registry/boring-registry/pkg/provider"
"github.com/boring-registry/boring-registry/pkg/storage"
"github.com/go-kit/kit/endpoint"
httptransport "github.com/go-kit/kit/transport/http"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/spf13/cobra"
"golang.org/x/sync/errgroup"
)
const (
apiVersion = "v1"
)
var (
prefix = fmt.Sprintf("/%s", apiVersion)
prefixModules = fmt.Sprintf("%s/modules", prefix)
prefixProviders = fmt.Sprintf("%s/providers", prefix)
prefixMirror = fmt.Sprintf("%s/mirror", prefix)
)
var (
// General server options.
flagTLSCertFile string
flagTLSKeyFile string
flagListenAddr string
flagTelemetryListenAddr string
flagModuleArchiveFormat string
// Login options.
flagLoginIssuer string
flagLoginClient string
flagLoginScopes []string
flagLoginGrantTypes []string
flagLoginAuthz string
flagLoginToken string
flagLoginPorts []int
// Static auth.
flagAuthStaticTokens []string
// Okta auth.
flagAuthOktaIssuer string
flagAuthOktaClaims []string
// Provider Network Mirror
flagProviderNetworkMirrorEnabled bool
flagProviderNetworkMirrorPullThroughEnabled bool
)
var serverCmd = &cobra.Command{
Use: "server",
Short: "Starts the server component",
RunE: func(cmd *cobra.Command, args []string) error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
group, ctx := errgroup.WithContext(ctx)
mux, err := serveMux(ctx)
if err != nil {
return fmt.Errorf("failed to setup server: %w", err)
}
server := &http.Server{
Addr: flagListenAddr,
ReadTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,
Handler: mux,
}
telemetryServer := &http.Server{
Addr: flagTelemetryListenAddr,
ReadTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,
Handler: mux,
}
sigint := make(chan os.Signal, 1)
signal.Notify(sigint, os.Interrupt, syscall.SIGTERM, syscall.SIGINT)
// Signal handler.
group.Go(func() error {
select {
case <-sigint:
cancel()
case <-ctx.Done():
return ctx.Err()
}
return nil
})
// Server handler.
group.Go(func() error {
<-ctx.Done()
if err := server.Shutdown(ctx); err != nil {
if err != context.Canceled {
slog.Error("failed to terminate server", slog.String("error", err.Error()))
}
}
if err := telemetryServer.Shutdown(ctx); err != nil {
if err != context.Canceled {
slog.Error("failed to terminate telemetry server", slog.String("error", err.Error()))
}
}
return nil
})
// Main server.
group.Go(func() error {
logger := slog.Default().With(slog.String("listen", flagListenAddr))
logger.Info("starting server")
defer logger.Info("shutting down server")
if flagTLSCertFile != "" || flagTLSKeyFile != "" {
if err := server.ListenAndServeTLS(flagTLSCertFile, flagTLSKeyFile); err != nil {
if err != http.ErrServerClosed {
return err
}
}
} else {
if err := server.ListenAndServe(); err != nil {
if err != http.ErrServerClosed {
return err
}
}
}
return nil
})
// Telemetry server.
group.Go(func() error {
logger := slog.Default().With(slog.String("listen", flagTelemetryListenAddr))
logger.Info("starting telemetry server")
defer logger.Info("shutting down telemetry server")
if err := telemetryServer.ListenAndServe(); err != nil {
if err != http.ErrServerClosed {
return err
}
}
return nil
})
return group.Wait()
},
}
func init() {
rootCmd.AddCommand(serverCmd)
// General options.
serverCmd.Flags().StringVar(&flagTLSKeyFile, "tls-key-file", "", "TLS private key to serve")
serverCmd.Flags().StringVar(&flagTLSCertFile, "tls-cert-file", "", "TLS certificate to serve")
serverCmd.Flags().StringVar(&flagListenAddr, "listen-address", ":5601", "Address to listen on")
serverCmd.Flags().StringVar(&flagTelemetryListenAddr, "listen-telemetry-address", ":7801", "Telemetry address to listen on")
serverCmd.Flags().StringVar(&flagModuleArchiveFormat, "storage-module-archive-format", storage.DefaultModuleArchiveFormat, "Archive file format for modules, specified without the leading dot")
// Static auth options.
serverCmd.Flags().StringSliceVar(&flagAuthStaticTokens, "auth-static-token", nil, "Static API token to protect the boring-registry")
// Okta auth options.
serverCmd.Flags().StringVar(&flagAuthOktaIssuer, "auth-okta-issuer", "", "Okta issuer")
serverCmd.Flags().StringSliceVar(&flagAuthOktaClaims, "auth-okta-claims", nil, "Okta claims to validate")
// Terraform Login Protocol options.
serverCmd.Flags().StringVar(&flagLoginClient, "login-client", "", "The client_id value to use when making requests")
serverCmd.Flags().StringSliceVar(&flagLoginGrantTypes, "login-grant-types", []string{"authz_code"}, "An array describing a set of OAuth 2.0 grant types")
serverCmd.Flags().StringVar(&flagLoginAuthz, "login-authz", "", "The server's authorization endpoint")
serverCmd.Flags().StringVar(&flagLoginToken, "login-token", "", "The server's token endpoint")
serverCmd.Flags().IntSliceVar(&flagLoginPorts, "login-ports", []int{10000, 10010}, "Inclusive range of TCP ports that Terraform may use")
serverCmd.Flags().StringSliceVar(&flagLoginScopes, "login-scopes", nil, "List of scopes")
// Provider Network Mirror options
serverCmd.Flags().BoolVar(&flagProviderNetworkMirrorEnabled, "network-mirror", true, "Enable the provider network mirror")
serverCmd.Flags().BoolVar(&flagProviderNetworkMirrorPullThroughEnabled, "network-mirror-pull-through", false, "Enable the pull-through provider network mirror. This setting takes no effect if network-mirror is disabled")
}
// TODO(oliviermichaelis): move to root, as the storage flags are defined in root?
func setupStorage(ctx context.Context) (storage.Storage, error) {
switch {
case flagS3Bucket != "":
return storage.NewS3Storage(ctx,
flagS3Bucket,
storage.WithS3StorageBucketPrefix(flagS3Prefix),
storage.WithS3StorageBucketRegion(flagS3Region),
storage.WithS3StorageBucketEndpoint(flagS3Endpoint),
storage.WithS3StoragePathStyle(flagS3PathStyle),
storage.WithS3ArchiveFormat(flagModuleArchiveFormat),
storage.WithS3StorageSignedUrlExpiry(flagS3SignedURLExpiry),
)
case flagGCSBucket != "":
return storage.NewGCSStorage(flagGCSBucket,
storage.WithGCSStorageBucketPrefix(flagGCSPrefix),
storage.WithGCSServiceAccount(flagGCSServiceAccount),
storage.WithGCSSignedUrlExpiry(flagGCSSignedURLExpiry),
storage.WithGCSArchiveFormat(flagModuleArchiveFormat),
)
case flagAzureStorageContainer != "":
return storage.NewAzureStorage(flagAzureStorageAccount,
flagAzureStorageContainer,
storage.WithAzureStoragePrefix(flagAzureStoragePrefix),
storage.WithAzureStorageArchiveFormat(flagModuleArchiveFormat),
storage.WithAzureStorageSignedUrlExpiry(flagAzureStorageSignedURLExpiry),
)
default:
return nil, errors.New("storage provider is not specified")
}
}
func serveMux(ctx context.Context) (*http.ServeMux, error) {
mux := http.NewServeMux()
options := []discovery.Option{
discovery.WithModulesV1(fmt.Sprintf("%s/", prefixModules)),
discovery.WithProvidersV1(fmt.Sprintf("%s/", prefixProviders)),
}
if flagLoginClient != "" {
login := &discovery.LoginV1{
Client: flagLoginClient,
}
if flagLoginGrantTypes != nil {
login.GrantTypes = flagLoginGrantTypes
}
if flagLoginAuthz != "" {
login.Authz = flagLoginAuthz
}
if flagLoginToken != "" {
login.Token = flagLoginToken
}
if flagLoginPorts != nil {
login.Ports = flagLoginPorts
}
if flagLoginScopes != nil {
login.Scopes = flagLoginScopes
}
options = append(options, discovery.WithLoginV1(login))
}
terraformJSON, err := json.Marshal(discovery.New(options...))
if err != nil {
return nil, err
}
mux.HandleFunc("/.well-known/terraform.json", func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-type", "application/json")
w.Write(terraformJSON)
})
metrics := o11y.NewMetrics(nil)
instrumentation := o11y.NewMiddleware(metrics.Http)
registerMetrics(mux)
s, err := setupStorage(ctx)
if err != nil {
return nil, err
}
if err := registerModule(mux, s, metrics.Module, instrumentation); err != nil {
return nil, err
}
if err := registerProvider(mux, s, metrics.Provider, instrumentation); err != nil {
return nil, err
}
if flagProviderNetworkMirrorEnabled {
var svc mirror.Service
if flagProviderNetworkMirrorPullThroughEnabled {
copier := mirror.NewCopier(ctx, s)
svc = mirror.NewPullThroughMirror(s, copier)
} else {
svc = mirror.NewMirror(s)
}
if err := registerMirror(mux, s, svc, metrics.Mirror, instrumentation); err != nil {
return nil, err
}
}
return mux, nil
}
func registerMetrics(mux *http.ServeMux) {
mux.Handle("/metrics", promhttp.Handler())
mux.HandleFunc("/debug/pprof/", pprof.Index)
mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
mux.Handle("/debug/pprof/block", pprof.Handler("block"))
mux.Handle("/debug/pprof/goroutine", pprof.Handler("goroutine"))
mux.Handle("/debug/pprof/heap", pprof.Handler("heap"))
mux.Handle("/debug/pprof/mutex", pprof.Handler("mutex"))
mux.Handle("/debug/pprof/threadcreate", pprof.Handler("threadcreate"))
}
func registerModule(mux *http.ServeMux, s storage.Storage, metrics *o11y.ModuleMetrics, instrumentation o11y.Middleware) error {
service := module.NewService(s)
{
service = module.LoggingMiddleware()(service)
}
opts := []httptransport.ServerOption{
httptransport.ServerErrorEncoder(module.ErrorEncoder),
httptransport.ServerBefore(
httptransport.PopulateRequestContext,
),
}
mux.Handle(
fmt.Sprintf(`%s/`, prefixModules),
http.StripPrefix(
prefixModules,
module.MakeHandler(
service,
authMiddleware(),
metrics,
instrumentation,
opts...,
),
),
)
return nil
}
func authMiddleware() endpoint.Middleware {
var providers []auth.Provider
if flagAuthStaticTokens != nil {
providers = append(providers, auth.NewStaticProvider(flagAuthStaticTokens...))
}
if flagAuthOktaIssuer != "" {
providers = append(providers, auth.NewOktaProvider(flagAuthOktaIssuer, flagAuthOktaClaims...))
}
return auth.Middleware(providers...)
}
func registerProvider(mux *http.ServeMux, s storage.Storage, metrics *o11y.ProviderMetrics, instrumentation o11y.Middleware) error {
service := provider.NewService(s)
{
service = provider.LoggingMiddleware()(service)
}
opts := []httptransport.ServerOption{
httptransport.ServerErrorEncoder(provider.ErrorEncoder),
httptransport.ServerBefore(
httptransport.PopulateRequestContext,
),
}
mux.Handle(
fmt.Sprintf(`%s/`, prefixProviders),
http.StripPrefix(
prefixProviders,
provider.MakeHandler(
service,
authMiddleware(),
metrics,
instrumentation,
opts...,
),
),
)
return nil
}
func registerMirror(mux *http.ServeMux, s storage.Storage, svc mirror.Service, metrics *o11y.MirrorMetrics, instrumentation o11y.Middleware) error {
service := mirror.LoggingMiddleware()(svc)
opts := []httptransport.ServerOption{
httptransport.ServerErrorEncoder(mirror.ErrorEncoder),
httptransport.ServerBefore(
httptransport.PopulateRequestContext,
),
}
mux.Handle(
fmt.Sprintf(`%s/`, prefixMirror),
http.StripPrefix(
prefixMirror,
mirror.MakeHandler(
service,
authMiddleware(),
metrics,
instrumentation,
opts...,
),
),
)
return nil
}