errors.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. package admin
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "log"
  6. "net/http"
  7. "os"
  8. "github.com/pkg/errors"
  9. "github.com/smallstep/certificates/errs"
  10. "github.com/smallstep/certificates/logging"
  11. )
  12. // ProblemType is the type of the Admin problem.
  13. type ProblemType int
  14. const (
  15. // ErrorNotFoundType resource not found.
  16. ErrorNotFoundType ProblemType = iota
  17. // ErrorAuthorityMismatchType resource Authority ID does not match the
  18. // context Authority ID.
  19. ErrorAuthorityMismatchType
  20. // ErrorDeletedType resource has been deleted.
  21. ErrorDeletedType
  22. // ErrorBadRequestType bad request.
  23. ErrorBadRequestType
  24. // ErrorNotImplementedType not implemented.
  25. ErrorNotImplementedType
  26. // ErrorUnauthorizedType internal server error.
  27. ErrorUnauthorizedType
  28. // ErrorServerInternalType internal server error.
  29. ErrorServerInternalType
  30. )
  31. // String returns the string representation of the admin problem type,
  32. // fulfilling the Stringer interface.
  33. func (ap ProblemType) String() string {
  34. switch ap {
  35. case ErrorNotFoundType:
  36. return "notFound"
  37. case ErrorAuthorityMismatchType:
  38. return "authorityMismatch"
  39. case ErrorDeletedType:
  40. return "deleted"
  41. case ErrorBadRequestType:
  42. return "badRequest"
  43. case ErrorNotImplementedType:
  44. return "notImplemented"
  45. case ErrorUnauthorizedType:
  46. return "unauthorized"
  47. case ErrorServerInternalType:
  48. return "internalServerError"
  49. default:
  50. return fmt.Sprintf("unsupported error type '%d'", int(ap))
  51. }
  52. }
  53. type errorMetadata struct {
  54. details string
  55. status int
  56. typ string
  57. String string
  58. }
  59. var (
  60. errorServerInternalMetadata = errorMetadata{
  61. typ: ErrorServerInternalType.String(),
  62. details: "the server experienced an internal error",
  63. status: 500,
  64. }
  65. errorMap = map[ProblemType]errorMetadata{
  66. ErrorNotFoundType: {
  67. typ: ErrorNotFoundType.String(),
  68. details: "resource not found",
  69. status: http.StatusNotFound,
  70. },
  71. ErrorAuthorityMismatchType: {
  72. typ: ErrorAuthorityMismatchType.String(),
  73. details: "resource not owned by authority",
  74. status: http.StatusUnauthorized,
  75. },
  76. ErrorDeletedType: {
  77. typ: ErrorDeletedType.String(),
  78. details: "resource is deleted",
  79. status: http.StatusNotFound,
  80. },
  81. ErrorNotImplementedType: {
  82. typ: ErrorNotImplementedType.String(),
  83. details: "not implemented",
  84. status: http.StatusNotImplemented,
  85. },
  86. ErrorBadRequestType: {
  87. typ: ErrorBadRequestType.String(),
  88. details: "bad request",
  89. status: http.StatusBadRequest,
  90. },
  91. ErrorUnauthorizedType: {
  92. typ: ErrorUnauthorizedType.String(),
  93. details: "unauthorized",
  94. status: http.StatusUnauthorized,
  95. },
  96. ErrorServerInternalType: errorServerInternalMetadata,
  97. }
  98. )
  99. // Error represents an Admin
  100. type Error struct {
  101. Type string `json:"type"`
  102. Detail string `json:"detail"`
  103. Message string `json:"message"`
  104. Err error `json:"-"`
  105. Status int `json:"-"`
  106. }
  107. // IsType returns true if the error type matches the input type.
  108. func (e *Error) IsType(pt ProblemType) bool {
  109. return pt.String() == e.Type
  110. }
  111. // NewError creates a new Error type.
  112. func NewError(pt ProblemType, msg string, args ...interface{}) *Error {
  113. return newError(pt, errors.Errorf(msg, args...))
  114. }
  115. func newError(pt ProblemType, err error) *Error {
  116. meta, ok := errorMap[pt]
  117. if !ok {
  118. meta = errorServerInternalMetadata
  119. return &Error{
  120. Type: meta.typ,
  121. Detail: meta.details,
  122. Status: meta.status,
  123. Err: err,
  124. }
  125. }
  126. return &Error{
  127. Type: meta.typ,
  128. Detail: meta.details,
  129. Status: meta.status,
  130. Err: err,
  131. }
  132. }
  133. // NewErrorISE creates a new ErrorServerInternalType Error.
  134. func NewErrorISE(msg string, args ...interface{}) *Error {
  135. return NewError(ErrorServerInternalType, msg, args...)
  136. }
  137. // WrapError attempts to wrap the internal error.
  138. func WrapError(typ ProblemType, err error, msg string, args ...interface{}) *Error {
  139. switch e := err.(type) {
  140. case nil:
  141. return nil
  142. case *Error:
  143. if e.Err == nil {
  144. e.Err = errors.Errorf(msg+"; "+e.Detail, args...)
  145. } else {
  146. e.Err = errors.Wrapf(e.Err, msg, args...)
  147. }
  148. return e
  149. default:
  150. return newError(typ, errors.Wrapf(err, msg, args...))
  151. }
  152. }
  153. // WrapErrorISE shortcut to wrap an internal server error type.
  154. func WrapErrorISE(err error, msg string, args ...interface{}) *Error {
  155. return WrapError(ErrorServerInternalType, err, msg, args...)
  156. }
  157. // StatusCode returns the status code and implements the StatusCoder interface.
  158. func (e *Error) StatusCode() int {
  159. return e.Status
  160. }
  161. // Error allows AError to implement the error interface.
  162. func (e *Error) Error() string {
  163. return e.Err.Error()
  164. }
  165. // Cause returns the internal error and implements the Causer interface.
  166. func (e *Error) Cause() error {
  167. if e.Err == nil {
  168. return errors.New(e.Detail)
  169. }
  170. return e.Err
  171. }
  172. // ToLog implements the EnableLogger interface.
  173. func (e *Error) ToLog() (interface{}, error) {
  174. b, err := json.Marshal(e)
  175. if err != nil {
  176. return nil, WrapErrorISE(err, "error marshaling authority.Error for logging")
  177. }
  178. return string(b), nil
  179. }
  180. // WriteError writes to w a JSON representation of the given error.
  181. func WriteError(w http.ResponseWriter, err *Error) {
  182. w.Header().Set("Content-Type", "application/json")
  183. w.WriteHeader(err.StatusCode())
  184. err.Message = err.Err.Error()
  185. // Write errors in the response writer
  186. if rl, ok := w.(logging.ResponseLogger); ok {
  187. rl.WithFields(map[string]interface{}{
  188. "error": err.Err,
  189. })
  190. if os.Getenv("STEPDEBUG") == "1" {
  191. if e, ok := err.Err.(errs.StackTracer); ok {
  192. rl.WithFields(map[string]interface{}{
  193. "stack-trace": fmt.Sprintf("%+v", e),
  194. })
  195. }
  196. }
  197. }
  198. if err := json.NewEncoder(w).Encode(err); err != nil {
  199. log.Println(err)
  200. }
  201. }