-
Notifications
You must be signed in to change notification settings - Fork 13
/
primaryHandler.go
683 lines (600 loc) · 21.4 KB
/
primaryHandler.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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
// SPDX-FileCopyrightText: 2019 Comcast Cable Communications Management, LLC
// SPDX-License-Identifier: Apache-2.0
package main
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
"os/signal"
"regexp"
"strings"
"syscall"
"github.com/prometheus/client_golang/prometheus"
"github.com/xmidt-org/candlelight"
"github.com/xmidt-org/clortho"
"github.com/xmidt-org/clortho/clorthometrics"
"github.com/xmidt-org/clortho/clorthozap"
"github.com/xmidt-org/touchstone"
"go.opentelemetry.io/contrib/instrumentation/github.com/gorilla/mux/otelmux"
"go.uber.org/zap"
"github.com/xmidt-org/webpa-common/secure/handler"
"github.com/xmidt-org/webpa-common/v2/device"
gokithttp "github.com/go-kit/kit/transport/http"
"github.com/goph/emperror"
"github.com/gorilla/mux"
"github.com/justinas/alice"
"github.com/spf13/viper"
"github.com/xmidt-org/bascule"
"github.com/xmidt-org/bascule/basculechecks"
"github.com/xmidt-org/bascule/basculehelper"
"github.com/xmidt-org/bascule/basculehttp"
// nolint:staticcheck
"github.com/xmidt-org/webpa-common/v2/service"
"github.com/xmidt-org/webpa-common/v2/service/monitor"
"github.com/xmidt-org/webpa-common/v2/xhttp"
"github.com/xmidt-org/webpa-common/v2/xhttp/fanout"
// nolint:staticcheck
"github.com/xmidt-org/webpa-common/v2/xmetrics"
"github.com/xmidt-org/wrp-go/v3"
"github.com/xmidt-org/wrp-go/v3/wrpcontext"
"github.com/xmidt-org/wrp-go/v3/wrphttp"
"github.com/xmidt-org/wrp-go/v3/wrpvalidator"
)
const (
apiVersion = "v3"
prevAPIVersion = "v2"
apiBase = "api/" + apiVersion
prevAPIBase = "api/" + prevAPIVersion
apiBaseDualVersion = "api/{version:" + apiVersion + "|" + prevAPIVersion + "}"
basicAuthConfigKey = "authHeader"
jwtAuthConfigKey = "jwtValidator"
wrpCheckConfigKey = "WRPCheck"
wrpValidatorConfigKey = "wrpValidators"
deviceID = "deviceID"
enforceCheck = "enforce"
// nolint:gosec
zapWRPValidatorLabel = "wrp_validator_level"
)
// Default values
const (
UnknownPartner = "unknown"
)
var (
errNoDeviceName = errors.New("no device name")
errWRPValidatorConfigError = errors.New("failed to configure wrp validators")
)
func authChain(v *viper.Viper, logger *zap.Logger, registry xmetrics.Registry, tf *touchstone.Factory) (alice.Chain, error) {
if registry == nil {
return alice.Chain{}, errors.New("nil registry")
}
basculeMeasures := basculehelper.NewAuthValidationMeasures(registry)
capabilityCheckMeasures := basculehelper.NewAuthCapabilityCheckMeasures(registry)
listener := basculehelper.NewMetricListener(basculeMeasures)
basicAllowed := make(map[string]string)
basicAuth := v.GetStringSlice(basicAuthConfigKey)
for _, a := range basicAuth {
decoded, err := base64.StdEncoding.DecodeString(a)
if err != nil {
logger.Info("failed to decode auth header", zap.Any("authHeader", a))
logger.Error(err.Error())
continue
}
i := bytes.IndexByte(decoded, ':')
logger.Debug("decoded string", zap.Any("string", decoded), zap.Int("i", i))
if i > 0 {
basicAllowed[string(decoded[:i])] = string(decoded[i+1:])
}
}
logger.Debug("Created list of allowed basic auths", zap.Any("allowed", basicAllowed), zap.Any("config", basicAuth))
options := []basculehttp.COption{
basculehttp.WithCLogger(getLogger),
basculehttp.WithCErrorResponseFunc(listener.OnErrorResponse),
}
if len(basicAllowed) > 0 {
options = append(options, basculehttp.WithTokenFactory("Basic", basculehttp.BasicTokenFactory(basicAllowed)))
}
var jwtVal JWTValidator
// Get jwt configuration, including clortho's configuration
v.UnmarshalKey("jwtValidator", &jwtVal)
// Instantiate a keyring for refresher and resolver to share
kr := clortho.NewKeyRing()
// Instantiate a fetcher for refresher and resolver to share
f, err := clortho.NewFetcher()
if err != nil {
return alice.Chain{}, emperror.With(err, "failed to create clortho fetcher")
}
ref, err := clortho.NewRefresher(
clortho.WithConfig(jwtVal.Config),
clortho.WithFetcher(f),
)
if err != nil {
return alice.Chain{}, emperror.With(err, "failed to create clortho refresher")
}
resolver, err := clortho.NewResolver(
clortho.WithConfig(jwtVal.Config),
clortho.WithKeyRing(kr),
clortho.WithFetcher(f),
)
if err != nil {
return alice.Chain{}, emperror.With(err, "failed to create clortho resolver")
}
// Instantiate a metric listener for refresher and resolver to share
cml, err := clorthometrics.NewListener(clorthometrics.WithFactory(tf))
if err != nil {
return alice.Chain{}, emperror.With(err, "failed to create clortho metrics listener")
}
// Instantiate a logging listener for refresher and resolver to share
czl, err := clorthozap.NewListener(
clorthozap.WithLogger(logger),
)
if err != nil {
return alice.Chain{}, emperror.With(err, "failed to create clortho zap logger listener")
}
resolver.AddListener(cml)
resolver.AddListener(czl)
ref.AddListener(cml)
ref.AddListener(czl)
ref.AddListener(kr)
// context.Background() is for the unused `context.Context` argument in refresher.Start
ref.Start(context.Background())
// Shutdown refresher's goroutines when SIGTERM
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGTERM)
go func() {
<-sigs
// context.Background() is for the unused `context.Context` argument in refresher.Stop
ref.Stop(context.Background())
}()
options = append(options, basculehttp.WithTokenFactory("Bearer", basculehttp.BearerTokenFactory{
DefaultKeyID: DefaultKeyID,
Resolver: resolver,
Parser: bascule.DefaultJWTParser,
Leeway: jwtVal.Leeway,
}))
authConstructor := basculehttp.NewConstructor(append([]basculehttp.COption{
basculehttp.WithParseURLFunc(basculehttp.CreateRemovePrefixURLFunc("/"+apiBase+"/", basculehttp.DefaultParseURLFunc)),
}, options...)...)
authConstructorLegacy := basculehttp.NewConstructor(append([]basculehttp.COption{
basculehttp.WithParseURLFunc(basculehttp.CreateRemovePrefixURLFunc("/api/"+prevAPIVersion+"/", basculehttp.DefaultParseURLFunc)),
basculehttp.WithCErrorHTTPResponseFunc(basculehttp.LegacyOnErrorHTTPResponse),
}, options...)...)
bearerRules := bascule.Validators{
basculechecks.NonEmptyPrincipal(),
basculechecks.NonEmptyType(),
basculechecks.ValidType([]string{"jwt"}),
requirePartnersJWTClaim,
}
// only add capability check if the configuration is set
var capabilityCheck basculechecks.CapabilitiesValidatorConfig
v.UnmarshalKey("capabilityCheck", &capabilityCheck)
if capabilityCheck.Type == enforceCheck || capabilityCheck.Type == "monitor" {
var endpoints []*regexp.Regexp
ec, err := basculehelper.NewEndpointRegexCheck(capabilityCheck.Prefix, capabilityCheck.AcceptAllMethod)
if err != nil {
return alice.Chain{}, emperror.With(err, "failed to create capability check")
}
for _, e := range capabilityCheck.EndpointBuckets {
r, err := regexp.Compile(e)
if err != nil {
logger.Error("failed to compile regular expression", zap.Any("regex", e), zap.Error(err))
continue
}
endpoints = append(endpoints, r)
}
m := basculehelper.MetricValidator{
C: basculehelper.CapabilitiesValidator{Checker: ec},
Measures: capabilityCheckMeasures,
Endpoints: endpoints,
}
bearerRules = append(bearerRules, m.CreateValidator(capabilityCheck.Type == enforceCheck))
}
authEnforcer := basculehttp.NewEnforcer(
basculehttp.WithELogger(getLogger),
basculehttp.WithRules("Basic", bascule.Validators{
basculechecks.AllowAll(),
}),
basculehttp.WithRules("Bearer", bearerRules),
basculehttp.WithEErrorResponseFunc(listener.OnErrorResponse),
)
authChain := alice.New(setLogger(logger), authConstructor, authEnforcer, basculehttp.NewListenerDecorator(listener))
authChainLegacy := alice.New(setLogger(logger), authConstructorLegacy, authEnforcer, basculehttp.NewListenerDecorator(listener))
versionCompatibleAuth := alice.New(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(r http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
if vars != nil {
if vars["version"] == prevAPIVersion {
authChainLegacy.Then(next).ServeHTTP(r, req)
return
}
}
authChain.Then(next).ServeHTTP(r, req)
})
})
return versionCompatibleAuth, nil
}
// createEndpoints examines the configuration and produces an appropriate fanout.Endpoints, either using the configured
// endpoints or service discovery.
// nolint:govet
func createEndpoints(logger *zap.Logger, cfg fanout.Configuration, registry xmetrics.Registry, e service.Environment) (fanout.Endpoints, error) {
if len(cfg.Endpoints) > 0 {
logger.Info("using configured endpoints for fanout", zap.Any("endpoints", cfg.Endpoints))
return fanout.ParseURLs(cfg.Endpoints...)
} else if e != nil {
logger.Info("using service discovery for fanout")
endpoints := fanout.NewServiceEndpoints(
fanout.WithAccessorFactory(e.AccessorFactory()),
// required to get deviceID from either the header or the path
fanout.WithKeyFunc(func(request *http.Request) ([]byte, error) {
deviceName := request.Header.Get(device.DeviceNameHeader)
// If deviceID is present in url us it instead.
// This is important for routing to the correct talaria.
if variables := mux.Vars(request); len(variables) > 0 {
if deviceID := variables["deviceID"]; len(deviceID) > 0 {
deviceName = deviceID
}
}
if len(deviceName) == 0 {
return nil, errNoDeviceName
}
id, err := device.ParseID(deviceName)
if err != nil {
return nil, err
}
return id.Bytes(), nil
}),
)
_, err := monitor.New(
monitor.WithLogger(logger),
monitor.WithFilter(monitor.NewNormalizeFilter(e.DefaultScheme())),
monitor.WithEnvironment(e),
monitor.WithListeners(
monitor.NewMetricsListener(registry),
endpoints,
),
)
return endpoints, err
}
return nil, fmt.Errorf("unable to create endpoints")
}
func NewPrimaryHandler(logger *zap.Logger, v *viper.Viper, registry xmetrics.Registry, e service.Environment, tracing candlelight.Tracing) (http.Handler, error) {
var cfg fanout.Configuration
if err := v.UnmarshalKey("fanout", &cfg); err != nil {
return nil, err
}
fanoutPrefix := v.GetString("fanout.pathPrefix")
logger.Info("creating primary handler")
cfg.Tracing = tracing
// nolint:govet
endpoints, err := createEndpoints(logger, cfg, registry, e)
if err != nil {
return nil, err
}
promReg, ok := registry.(prometheus.Registerer)
if !ok {
return nil, errors.New("failed to get prometheus registerer")
}
var tsConfig touchstone.Config
// Get touchstone & zap configurations
v.UnmarshalKey("touchstone", &tsConfig)
tf := touchstone.NewFactory(tsConfig, logger, promReg)
authChain, err := authChain(v, logger, registry, tf)
if err != nil {
return nil, err
}
var (
// nolint:govet,bodyclose
transactor = fanout.NewTransactor(cfg)
options = []fanout.Option{
fanout.WithTransactor(transactor),
fanout.WithErrorEncoder(func(ctx context.Context, err error, w http.ResponseWriter) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Header().Set("X-Xmidt-Error", err.Error())
// nolint:errorlint
if headerer, ok := err.(gokithttp.Headerer); ok {
for k, values := range headerer.Headers() {
// nolint: gosec
for _, v := range values {
w.Header().Add(k, v)
}
}
}
code := http.StatusInternalServerError
// nolint:errorlint
switch err {
case device.ErrorInvalidDeviceName:
code = http.StatusBadRequest
case device.ErrorDeviceNotFound:
code = http.StatusNotFound
case device.ErrorNonUniqueID:
code = http.StatusBadRequest
case device.ErrorInvalidTransactionKey:
code = http.StatusBadRequest
case device.ErrorTransactionAlreadyRegistered:
code = http.StatusBadRequest
case device.ErrorMissingPathVars:
code = http.StatusBadRequest
case device.ErrorNoSuchTransactionKey:
code = http.StatusBadGateway
case device.ErrorMissingDeviceNameHeader:
code = http.StatusBadRequest
case errNoDeviceName:
code = http.StatusBadRequest
}
// nolint:errorlint
if sc, ok := err.(gokithttp.StatusCoder); ok {
code = sc.StatusCode()
}
w.WriteHeader(code)
}),
}
)
if len(cfg.Authorization) > 0 {
options = append(
options,
fanout.WithClientBefore(
gokithttp.SetRequestHeader("Authorization", "Basic "+cfg.Authorization),
),
)
}
router := mux.NewRouter()
// if we want to support the previous API version, then include it in the
// api base.
urlPrefix := fmt.Sprintf("/%s", apiBase)
if v.GetBool("previousVersionSupport") {
urlPrefix = fmt.Sprintf("/%s", apiBaseDualVersion)
}
sendSubrouter := router.Path(fmt.Sprintf("%s/device", urlPrefix)).Methods("POST", "PUT").Subrouter()
otelMuxOptions := []otelmux.Option{
otelmux.WithPropagators(tracing.Propagator()),
otelmux.WithTracerProvider(tracing.TracerProvider()),
}
valWRP, err := validateWRP(v, logger, tf)
if err != nil {
return nil, fmt.Errorf("failed to get wrp validators: %w", err)
}
router.Use(otelmux.Middleware("mainSpan", otelMuxOptions...), candlelight.EchoFirstTraceNodeInfo(tracing.Propagator(), true), valWRP)
router.NotFoundHandler = http.HandlerFunc(func(response http.ResponseWriter, _ *http.Request) {
xhttp.WriteError(response, http.StatusBadRequest, "Invalid endpoint")
})
// nolint:govet
fanoutChain := fanout.NewChain(cfg)
HTTPFanoutHandler := fanoutChain.Then(
fanout.New(
endpoints,
append(
options,
fanout.WithFanoutBefore(
func(ctx context.Context, original, fanout *http.Request, body []byte) (context.Context, error) {
m, ok := wrpcontext.GetMessage(ctx)
if !ok {
f, err := wrphttp.DetermineFormat(wrp.JSON, original.Header, "Content-Type")
if err != nil {
return nil, err
}
err = wrp.NewDecoderBytes(body, f).Decode(&m)
if err != nil {
return nil, err
}
}
return context.WithValue(ctx, ContextKeyWRP, m), nil
},
fanout.ForwardHeaders("Content-Type", "X-Webpa-Device-Name"),
fanout.UsePath(fmt.Sprintf("%s/device/send", fanoutPrefix)),
func(ctx context.Context, _, fanout *http.Request, body []byte) (context.Context, error) {
fanout.Body, fanout.GetBody = xhttp.NewRewindBytes(body)
fanout.ContentLength = int64(len(body))
return ctx, nil
},
),
fanout.WithFanoutFailure(
fanout.ReturnHeadersWithPrefix("X-"),
),
fanout.WithFanoutAfter(
fanout.ReturnHeadersWithPrefix("X-"),
func(ctx context.Context, response http.ResponseWriter, result fanout.Result) context.Context {
var satClientID = "N/A"
reqContextValues, ok := handler.FromContext(result.Request.Context())
if ok {
satClientID = reqContextValues.SatClientID
}
wrpFromCtx, ok := ctx.Value(ContextKeyWRP).(*wrp.Message)
if ok {
logger.Info("Bookkeping response",
zap.Any("messageType", wrpFromCtx.Type),
zap.String("destination", wrpFromCtx.Destination),
zap.String("source", wrpFromCtx.Source),
zap.String("transactionUUID", wrpFromCtx.TransactionUUID),
zap.Any("status", wrpFromCtx.Status),
zap.Strings("partnerIDS", wrpFromCtx.PartnerIDs),
zap.String("satClientID", satClientID))
} else {
logger.Error("no wrp found")
logger.Info("Bookkeeping response", zap.String("satClientID", satClientID))
}
return ctx
},
),
)...,
))
var (
wrpCheckConfig WRPCheckConfig
WRPFanoutHandler wrphttp.Handler
)
if v.IsSet(wrpCheckConfigKey) {
if v.IsSet(basicAuthConfigKey) {
return nil, errors.New("WRP PartnerID checks cannot be enabled with basic authentication")
}
if !v.IsSet(jwtAuthConfigKey) {
return nil, errors.New("WRP PartnerID checks require JWT authentication to be enabled")
}
}
v.UnmarshalKey(wrpCheckConfigKey, &wrpCheckConfig)
if wrpCheckConfig.Type == enforceCheck || wrpCheckConfig.Type == "monitor" {
WRPFanoutHandler = newWRPFanoutHandlerWithPIDCheck(
HTTPFanoutHandler,
&wrpPartnersAccess{
strict: wrpCheckConfig.Type == enforceCheck,
receivedWRPMessageCount: NewReceivedWRPCounter(registry),
})
} else {
WRPFanoutHandler = newWRPFanoutHandler(HTTPFanoutHandler)
}
sendWRPHandler := wrphttp.NewHTTPHandler(WRPFanoutHandler,
wrphttp.WithDecoder(wrphttp.DecodeEntityFromSources(wrp.Msgpack, true)),
wrphttp.WithNewResponseWriter(nonWRPResponseWriterFactory))
sendSubrouter.Headers(
wrphttp.MessageTypeHeader, "").
Handler(authChain.Then(sendWRPHandler))
sendSubrouter.Headers("Content-Type", wrp.Msgpack.ContentType()).
Handler(authChain.Then(sendWRPHandler))
sendSubrouter.Headers("Content-Type", wrp.JSON.ContentType()).
Handler(authChain.Then(sendWRPHandler))
router.Handle(
fmt.Sprintf("%s/device/{%s}/stat", urlPrefix, deviceID),
authChain.Extend(fanoutChain.Extend(validateDeviceID())).Then(
fanout.New(
endpoints,
append(
options,
fanout.WithFanoutBefore(
// required for petasos
fanout.ForwardVariableAsHeader(deviceID, "X-Webpa-Device-Name"),
// required for consul fanout
func(ctx context.Context, original, fanout *http.Request, body []byte) (context.Context, error) {
// strip the initial path and provide the configured one instead.
urlToUse := strings.TrimPrefix(strings.TrimPrefix(strings.TrimPrefix(original.URL.Path, "/"), apiBase), prevAPIBase)
fanout.URL.Path = fmt.Sprintf("%s%s", fanoutPrefix, urlToUse)
fanout.URL.RawPath = ""
return ctx, nil
},
),
fanout.WithFanoutFailure(
fanout.ReturnHeadersWithPrefix("X-"),
),
fanout.WithFanoutAfter(
fanout.ReturnHeadersWithPrefix("X-"),
),
)...,
),
),
).Methods("GET")
return router, nil
}
// validateDeviceID checks the device ID in the URL to make sure it is good before fanout.
func validateDeviceID() alice.Chain {
return alice.New(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
_, err := device.ParseID(vars[deviceID])
if err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(
w,
`{"code": %d, "message": "%s"}`,
http.StatusBadRequest,
fmt.Sprintf("failed to extract device ID: %s", err),
)
return
}
next.ServeHTTP(w, r)
})
})
}
func validateWRP(v *viper.Viper, logger *zap.Logger, tf *touchstone.Factory) (func(http.Handler) http.Handler, error) {
var (
errs error
vals []wrpvalidator.MetaValidator
)
if valsConig := v.Get(wrpValidatorConfigKey); valsConig != nil {
if b, err := json.Marshal(valsConig); err != nil {
return nil, errors.Join(errWRPValidatorConfigError, err)
} else if err = json.Unmarshal(b, &vals); err != nil {
return nil, errors.Join(errWRPValidatorConfigError, err)
}
labelNames := []string{wrpvalidator.ClientIDLabel, wrpvalidator.PartnerIDLabel, wrpvalidator.MessageTypeLabel}
for _, v := range vals {
if err := v.AddMetric(tf, labelNames...); err != nil {
errs = errors.Join(errs, err)
}
}
}
if errs != nil {
return nil, errors.Join(errWRPValidatorConfigError, errs)
}
return func(delegate http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if msg, ok := wrpcontext.GetMessage(r.Context()); ok {
var (
infoErrors error
warningErrors error
failureError error
unknownError error
satClientID = "N/A"
partnerID = device.UnknownPartner
)
auth, ok := bascule.FromContext(r.Context())
if ok {
if principal := auth.Token.Principal(); len(principal) > 0 {
satClientID = principal
}
if s, ok := auth.Token.Attributes().Get(device.PartnerIDClaimKey); ok {
if p, ok := s.(string); ok {
partnerID = p
}
}
}
for _, v := range vals {
err := v.Validate(
*msg,
prometheus.Labels{
wrpvalidator.ClientIDLabel: satClientID,
wrpvalidator.PartnerIDLabel: partnerID,
wrpvalidator.MessageTypeLabel: msg.Type.FriendlyName(),
},
)
switch v.Level() {
case wrpvalidator.InfoLevel:
infoErrors = errors.Join(infoErrors, err)
case wrpvalidator.WarningLevel:
warningErrors = errors.Join(warningErrors, err)
case wrpvalidator.ErrorLevel:
failureError = errors.Join(failureError, err)
default:
unknownError = errors.Join(unknownError, err)
}
}
if unknownError != nil {
logger.Warn("WRP message validation errors found",
zap.Error(unknownError), zap.String(zapWRPValidatorLabel, wrpvalidator.UnknownLevel.String()))
}
if infoErrors != nil {
logger.Warn("WRP message validation errors found",
zap.Error(infoErrors), zap.String(zapWRPValidatorLabel, wrpvalidator.InfoLevel.String()))
}
if warningErrors != nil {
logger.Warn("WRP message validation errors found",
zap.Error(warningErrors), zap.String(zapWRPValidatorLabel, wrpvalidator.WarningLevel.String()))
}
if failureError != nil {
logger.Error("WRP message validation (failure error level) found",
zap.Error(failureError), zap.String(zapWRPValidatorLabel, wrpvalidator.ErrorLevel.String()))
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(
w,
`{"code": %d, "message": "%s"}`,
http.StatusBadRequest,
fmt.Sprintf("failed to validate WRP message: %s", failureError))
return
}
}
delegate.ServeHTTP(w, r)
})
}, errs
}