diff --git a/primaryHandler.go b/primaryHandler.go index 1704ef3..28706a9 100644 --- a/primaryHandler.go +++ b/primaryHandler.go @@ -24,6 +24,7 @@ import ( "github.com/xmidt-org/sallust" "github.com/xmidt-org/touchstone" "go.opentelemetry.io/contrib/instrumentation/github.com/gorilla/mux/otelmux" + "go.uber.org/multierr" "go.uber.org/zap" "github.com/xmidt-org/webpa-common/secure/handler" @@ -63,7 +64,7 @@ const ( jwtAuthConfigKey = "jwtValidator" wrpCheckConfigKey = "WRPCheck" - deviceID = "deviceID" + deviceID = "devicID" enforceCheck = "enforce" ) @@ -391,7 +392,7 @@ func NewPrimaryHandler(logger *zap.Logger, v *viper.Viper, registry xmetrics.Reg otelmux.WithPropagators(tracing.Propagator()), otelmux.WithTracerProvider(tracing.TracerProvider()), } - router.Use(otelmux.Middleware("mainSpan", otelMuxOptions...), candlelight.EchoFirstTraceNodeInfo(tracing.Propagator())) + router.Use(otelmux.Middleware("mainSpan", otelMuxOptions...), candlelight.EchoFirstTraceNodeInfo(tracing.Propagator()), ValidateWRP()) router.NotFoundHandler = http.HandlerFunc(func(response http.ResponseWriter, _ *http.Request) { xhttp.WriteError(response, http.StatusBadRequest, "Invalid endpoint") @@ -561,3 +562,31 @@ func validateDeviceID() alice.Chain { }) }) } + +func ValidateWRP() func(http.Handler) http.Handler { + return func(delegate http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + + ctx := r.Context() + if msg, ok := wrpcontext.Get[*wrp.Message](ctx); ok { + validators := wrp.SpecValidators() + var err error + for _, v := range validators { + err = multierr.Append(err, v.Validate(*msg)) + } + 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 validate WRP message: %s", err), + ) + return + } + } + delegate.ServeHTTP(w, r) + }) + } +}