utils.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. package api
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "io"
  6. "log"
  7. "net/http"
  8. "google.golang.org/protobuf/encoding/protojson"
  9. "google.golang.org/protobuf/proto"
  10. "github.com/smallstep/certificates/errs"
  11. "github.com/smallstep/certificates/logging"
  12. )
  13. // EnableLogger is an interface that enables response logging for an object.
  14. type EnableLogger interface {
  15. ToLog() (interface{}, error)
  16. }
  17. // LogError adds to the response writer the given error if it implements
  18. // logging.ResponseLogger. If it does not implement it, then writes the error
  19. // using the log package.
  20. func LogError(rw http.ResponseWriter, err error) {
  21. if rl, ok := rw.(logging.ResponseLogger); ok {
  22. rl.WithFields(map[string]interface{}{
  23. "error": err,
  24. })
  25. } else {
  26. log.Println(err)
  27. }
  28. }
  29. // LogEnabledResponse log the response object if it implements the EnableLogger
  30. // interface.
  31. func LogEnabledResponse(rw http.ResponseWriter, v interface{}) {
  32. if el, ok := v.(EnableLogger); ok {
  33. out, err := el.ToLog()
  34. if err != nil {
  35. LogError(rw, err)
  36. return
  37. }
  38. if rl, ok := rw.(logging.ResponseLogger); ok {
  39. rl.WithFields(map[string]interface{}{
  40. "response": out,
  41. })
  42. } else {
  43. log.Println(out)
  44. }
  45. }
  46. }
  47. // JSON writes the passed value into the http.ResponseWriter.
  48. func JSON(w http.ResponseWriter, v interface{}) {
  49. JSONStatus(w, v, http.StatusOK)
  50. }
  51. // JSONStatus writes the given value into the http.ResponseWriter and the
  52. // given status is written as the status code of the response.
  53. func JSONStatus(w http.ResponseWriter, v interface{}, status int) {
  54. w.Header().Set("Content-Type", "application/json")
  55. w.WriteHeader(status)
  56. if err := json.NewEncoder(w).Encode(v); err != nil {
  57. LogError(w, err)
  58. return
  59. }
  60. LogEnabledResponse(w, v)
  61. }
  62. // JSONNotFound writes a HTTP Not Found response with empty body.
  63. func JSONNotFound(w http.ResponseWriter) {
  64. w.Header().Set("Content-Type", "application/json")
  65. w.WriteHeader(http.StatusNotFound)
  66. LogEnabledResponse(w, nil)
  67. }
  68. // ProtoJSON writes the passed value into the http.ResponseWriter.
  69. func ProtoJSON(w http.ResponseWriter, m proto.Message) {
  70. ProtoJSONStatus(w, m, http.StatusOK)
  71. }
  72. // ProtoJSONStatus writes the given value into the http.ResponseWriter and the
  73. // given status is written as the status code of the response.
  74. func ProtoJSONStatus(w http.ResponseWriter, m proto.Message, status int) {
  75. w.Header().Set("Content-Type", "application/json")
  76. w.WriteHeader(status)
  77. b, err := protojson.Marshal(m)
  78. if err != nil {
  79. LogError(w, err)
  80. return
  81. }
  82. if _, err := w.Write(b); err != nil {
  83. LogError(w, err)
  84. return
  85. }
  86. //LogEnabledResponse(w, v)
  87. }
  88. // ReadJSON reads JSON from the request body and stores it in the value
  89. // pointed by v.
  90. func ReadJSON(r io.Reader, v interface{}) error {
  91. if err := json.NewDecoder(r).Decode(v); err != nil {
  92. return errs.BadRequestErr(err, "error decoding json")
  93. }
  94. return nil
  95. }
  96. // ReadProtoJSON reads JSON from the request body and stores it in the value
  97. // pointed by v.
  98. func ReadProtoJSON(r io.Reader, m proto.Message) error {
  99. data, err := io.ReadAll(r)
  100. if err != nil {
  101. return errs.BadRequestErr(err, "error reading request body")
  102. }
  103. return protojson.Unmarshal(data, m)
  104. }
  105. // ReadProtoJSONWithCheck reads JSON from the request body and stores it in the value
  106. // pointed by v. TODO(hs): move this to and integrate with render package.
  107. func ReadProtoJSONWithCheck(w http.ResponseWriter, r io.Reader, m proto.Message) bool {
  108. data, err := io.ReadAll(r)
  109. if err != nil {
  110. var wrapper = struct {
  111. Status int `json:"code"`
  112. Message string `json:"message"`
  113. }{
  114. Status: http.StatusBadRequest,
  115. Message: err.Error(),
  116. }
  117. data, err := json.Marshal(wrapper) // TODO(hs): handle err; even though it's very unlikely to fail
  118. if err != nil {
  119. panic(err)
  120. }
  121. w.Header().Set("Content-Type", "application/json")
  122. w.WriteHeader(http.StatusBadRequest)
  123. w.Write(data)
  124. return false
  125. }
  126. if err := protojson.Unmarshal(data, m); err != nil {
  127. if errors.Is(err, proto.Error) {
  128. var wrapper = struct {
  129. Message string `json:"message"`
  130. }{
  131. Message: err.Error(),
  132. }
  133. data, err := json.Marshal(wrapper) // TODO(hs): handle err; even though it's very unlikely to fail
  134. if err != nil {
  135. panic(err)
  136. }
  137. w.Header().Set("Content-Type", "application/json")
  138. w.WriteHeader(http.StatusBadRequest)
  139. w.Write(data)
  140. return false
  141. }
  142. // fallback to the default error writer
  143. WriteError(w, err)
  144. return false
  145. }
  146. return true
  147. }