4
0

errors.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. package api
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "os"
  7. "github.com/pkg/errors"
  8. "github.com/smallstep/certificates/acme"
  9. "github.com/smallstep/certificates/logging"
  10. )
  11. // StatusCoder interface is used by errors that returns the HTTP response code.
  12. type StatusCoder interface {
  13. StatusCode() int
  14. }
  15. // StackTracer must be by those errors that return an stack trace.
  16. type StackTracer interface {
  17. StackTrace() errors.StackTrace
  18. }
  19. // Error represents the CA API errors.
  20. type Error struct {
  21. Status int
  22. Err error
  23. }
  24. // ErrorResponse represents an error in JSON format.
  25. type ErrorResponse struct {
  26. Status int `json:"status"`
  27. Message string `json:"message"`
  28. }
  29. // Cause implements the errors.Causer interface and returns the original error.
  30. func (e *Error) Cause() error {
  31. return e.Err
  32. }
  33. // Error implements the error interface and returns the error string.
  34. func (e *Error) Error() string {
  35. return e.Err.Error()
  36. }
  37. // StatusCode implements the StatusCoder interface and returns the HTTP response
  38. // code.
  39. func (e *Error) StatusCode() int {
  40. return e.Status
  41. }
  42. // MarshalJSON implements json.Marshaller interface for the Error struct.
  43. func (e *Error) MarshalJSON() ([]byte, error) {
  44. return json.Marshal(&ErrorResponse{Status: e.Status, Message: http.StatusText(e.Status)})
  45. }
  46. // UnmarshalJSON implements json.Unmarshaler interface for the Error struct.
  47. func (e *Error) UnmarshalJSON(data []byte) error {
  48. var er ErrorResponse
  49. if err := json.Unmarshal(data, &er); err != nil {
  50. return err
  51. }
  52. e.Status = er.Status
  53. e.Err = fmt.Errorf(er.Message)
  54. return nil
  55. }
  56. // NewError returns a new Error. If the given error implements the StatusCoder
  57. // interface we will ignore the given status.
  58. func NewError(status int, err error) error {
  59. if sc, ok := err.(StatusCoder); ok {
  60. return &Error{Status: sc.StatusCode(), Err: err}
  61. }
  62. cause := errors.Cause(err)
  63. if sc, ok := cause.(StatusCoder); ok {
  64. return &Error{Status: sc.StatusCode(), Err: err}
  65. }
  66. return &Error{Status: status, Err: err}
  67. }
  68. // InternalServerError returns a 500 error with the given error.
  69. func InternalServerError(err error) error {
  70. return NewError(http.StatusInternalServerError, err)
  71. }
  72. // NotImplemented returns a 500 error with the given error.
  73. func NotImplemented(err error) error {
  74. return NewError(http.StatusNotImplemented, err)
  75. }
  76. // BadRequest returns an 400 error with the given error.
  77. func BadRequest(err error) error {
  78. return NewError(http.StatusBadRequest, err)
  79. }
  80. // Unauthorized returns an 401 error with the given error.
  81. func Unauthorized(err error) error {
  82. return NewError(http.StatusUnauthorized, err)
  83. }
  84. // Forbidden returns an 403 error with the given error.
  85. func Forbidden(err error) error {
  86. return NewError(http.StatusForbidden, err)
  87. }
  88. // NotFound returns an 404 error with the given error.
  89. func NotFound(err error) error {
  90. return NewError(http.StatusNotFound, err)
  91. }
  92. // WriteError writes to w a JSON representation of the given error.
  93. func WriteError(w http.ResponseWriter, err error) {
  94. switch k := err.(type) {
  95. case *acme.Error:
  96. w.Header().Set("Content-Type", "application/problem+json")
  97. err = k.ToACME()
  98. default:
  99. w.Header().Set("Content-Type", "application/json")
  100. }
  101. cause := errors.Cause(err)
  102. if sc, ok := err.(StatusCoder); ok {
  103. w.WriteHeader(sc.StatusCode())
  104. } else {
  105. if sc, ok := cause.(StatusCoder); ok {
  106. w.WriteHeader(sc.StatusCode())
  107. } else {
  108. w.WriteHeader(http.StatusInternalServerError)
  109. }
  110. }
  111. // Write errors in the response writer
  112. if rl, ok := w.(logging.ResponseLogger); ok {
  113. rl.WithFields(map[string]interface{}{
  114. "error": err,
  115. })
  116. if os.Getenv("STEPDEBUG") == "1" {
  117. if e, ok := err.(StackTracer); ok {
  118. rl.WithFields(map[string]interface{}{
  119. "stack-trace": fmt.Sprintf("%+v", e),
  120. })
  121. } else {
  122. if e, ok := cause.(StackTracer); ok {
  123. rl.WithFields(map[string]interface{}{
  124. "stack-trace": fmt.Sprintf("%+v", e),
  125. })
  126. }
  127. }
  128. }
  129. }
  130. if err := json.NewEncoder(w).Encode(err); err != nil {
  131. LogError(w, err)
  132. }
  133. }