Skip to content

Commit

Permalink
Merge pull request #306 from xmidt-org/wrp-validator
Browse files Browse the repository at this point in the history
added WRP validator middleware functionality
  • Loading branch information
maurafortino authored Oct 11, 2023
2 parents 420de1b + 187c79c commit 498d124
Showing 1 changed file with 31 additions and 2 deletions.
33 changes: 31 additions & 2 deletions primaryHandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -63,7 +64,7 @@ const (
jwtAuthConfigKey = "jwtValidator"
wrpCheckConfigKey = "WRPCheck"

deviceID = "deviceID"
deviceID = "devicID"

enforceCheck = "enforce"
)
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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)
})
}
}

0 comments on commit 498d124

Please sign in to comment.