GoogleCloudPlatform / microservices-demo

Sample cloud-first application with 10 microservices showcasing Kubernetes, Istio, and gRPC.
https://cymbal-shops.retail.cymbal.dev
Apache License 2.0
16.82k stars 7.21k forks source link

Validate HTTP input passed into frontend microservice #2416

Closed NimJay closed 6 months ago

NimJay commented 7 months ago
emzola commented 7 months ago

Hi @NimJay, I would like to work on this issue. Since no one has commented, may I continue with this work?

NimJay commented 7 months ago

Hi @emzola, thank you for reaching out and your interest in contributing. :) I just assigned this ticket you.

What I suggest as next steps:

  1. Go through /.github/CONTRIBUTING.md.
  2. Research best practices for validating HTTP input in Golang. Share you findings in this GitHub issue. I would look into https://github.com/go-playground/validator. It seems promising.
  3. Set up your Online Boutique dev environment. See development guide here.

Other thoughts:

emzola commented 7 months ago

Great! I’ve looked at the following validation packages:

https://github.com/asaskevich/govalidator https://github.com/go-ozzo/ozzo-validation https://github.com/go-playground/validator

I decided to settle for go playground (like you suggested) because in addition to being promising and used by lots of projects, I think the package provides functions and tags that are easier to understand.

I’ve also looked through the codebase of the frontend microservice. I see that there are 3 handlers in src/frontend/handlers.go that require validation (addToCartHandler, placeOrderHandler and setCurrencyHandler).

In terms of how to go about implementing a validation layer, I’m thinking about creating a validator package in the src/frontend folder. In this package, there will be maybe 2 files: validator.go and validator_test.go. In validator.go, we could have 3 structs. Each struct will represent the HTTP form data expected from each handler. Of course, we specify the validation rules for each struct field using tags, and each struct will have a Validate method that actually performs the validation based on the rules set in the tags.

Then in src/frontend/handlers.go, in each handler that requires validation, we initialize a validator struct and populate it with data from r.FormValue. We call the Validate method on the struct and return a HTTP error with 422 status code if validation fails.

That’s a rough idea of things. I could translate this to code for just the placeOrderHandler and make a PR so you see.

NimJay commented 7 months ago

@emzola, thank you for that very clear explanation and excellent progress! 💯

Let's go with what you suggested! :)

Optional: Ideally, the body of the 422 HTTP error response would state which field is invalid (e.g., "The streetAddress in your request is invalid."). But this is totally optional — since I don't think it will add a lot of value.