contentsecurityhandler.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package handler
  2. import (
  3. "net/http"
  4. "time"
  5. "github.com/tal-tech/go-zero/core/codec"
  6. "github.com/tal-tech/go-zero/core/logx"
  7. "github.com/tal-tech/go-zero/rest/httpx"
  8. "github.com/tal-tech/go-zero/rest/internal/security"
  9. )
  10. const contentSecurity = "X-Content-Security"
  11. // UnsignedCallback defines the method of the unsigned callback.
  12. type UnsignedCallback func(w http.ResponseWriter, r *http.Request, next http.Handler, strict bool, code int)
  13. // ContentSecurityHandler returns a middleware to verify content security.
  14. func ContentSecurityHandler(decrypters map[string]codec.RsaDecrypter, tolerance time.Duration,
  15. strict bool, callbacks ...UnsignedCallback) func(http.Handler) http.Handler {
  16. if len(callbacks) == 0 {
  17. callbacks = append(callbacks, handleVerificationFailure)
  18. }
  19. return func(next http.Handler) http.Handler {
  20. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  21. switch r.Method {
  22. case http.MethodDelete, http.MethodGet, http.MethodPost, http.MethodPut:
  23. header, err := security.ParseContentSecurity(decrypters, r)
  24. if err != nil {
  25. logx.Errorf("Signature parse failed, X-Content-Security: %s, error: %s",
  26. r.Header.Get(contentSecurity), err.Error())
  27. executeCallbacks(w, r, next, strict, httpx.CodeSignatureInvalidHeader, callbacks)
  28. } else if code := security.VerifySignature(r, header, tolerance); code != httpx.CodeSignaturePass {
  29. logx.Errorf("Signature verification failed, X-Content-Security: %s",
  30. r.Header.Get(contentSecurity))
  31. executeCallbacks(w, r, next, strict, code, callbacks)
  32. } else if r.ContentLength > 0 && header.Encrypted() {
  33. CryptionHandler(header.Key)(next).ServeHTTP(w, r)
  34. } else {
  35. next.ServeHTTP(w, r)
  36. }
  37. default:
  38. next.ServeHTTP(w, r)
  39. }
  40. })
  41. }
  42. }
  43. func executeCallbacks(w http.ResponseWriter, r *http.Request, next http.Handler, strict bool,
  44. code int, callbacks []UnsignedCallback) {
  45. for _, callback := range callbacks {
  46. callback(w, r, next, strict, code)
  47. }
  48. }
  49. func handleVerificationFailure(w http.ResponseWriter, r *http.Request, next http.Handler, strict bool, code int) {
  50. if strict {
  51. w.WriteHeader(http.StatusForbidden)
  52. } else {
  53. next.ServeHTTP(w, r)
  54. }
  55. }