errors.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. package mgmt
  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 ACME 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. // ErrorServerInternalType internal server error.
  23. ErrorServerInternalType
  24. )
  25. // String returns the string representation of the acme problem type,
  26. // fulfilling the Stringer interface.
  27. func (ap ProblemType) String() string {
  28. switch ap {
  29. case ErrorNotFoundType:
  30. return "notFound"
  31. case ErrorAuthorityMismatchType:
  32. return "authorityMismatch"
  33. case ErrorDeletedType:
  34. return "deleted"
  35. case ErrorServerInternalType:
  36. return "internalServerError"
  37. default:
  38. return fmt.Sprintf("unsupported error type '%d'", int(ap))
  39. }
  40. }
  41. type errorMetadata struct {
  42. details string
  43. status int
  44. typ string
  45. String string
  46. }
  47. var (
  48. errorServerInternalMetadata = errorMetadata{
  49. typ: ErrorServerInternalType.String(),
  50. details: "the server experienced an internal error",
  51. status: 500,
  52. }
  53. errorMap = map[ProblemType]errorMetadata{
  54. ErrorNotFoundType: {
  55. typ: ErrorNotFoundType.String(),
  56. details: "resource not found",
  57. status: 400,
  58. },
  59. ErrorAuthorityMismatchType: {
  60. typ: ErrorAuthorityMismatchType.String(),
  61. details: "resource not owned by authority",
  62. status: 401,
  63. },
  64. ErrorDeletedType: {
  65. typ: ErrorNotFoundType.String(),
  66. details: "resource is deleted",
  67. status: 403,
  68. },
  69. ErrorServerInternalType: errorServerInternalMetadata,
  70. }
  71. )
  72. // Error represents an ACME
  73. type Error struct {
  74. Type string `json:"type"`
  75. Detail string `json:"detail"`
  76. Subproblems []interface{} `json:"subproblems,omitempty"`
  77. Identifier interface{} `json:"identifier,omitempty"`
  78. Err error `json:"-"`
  79. Status int `json:"-"`
  80. }
  81. // IsType returns true if the error type matches the input type.
  82. func (e *Error) IsType(pt ProblemType) bool {
  83. return pt.String() == e.Type
  84. }
  85. // NewError creates a new Error type.
  86. func NewError(pt ProblemType, msg string, args ...interface{}) *Error {
  87. return newError(pt, errors.Errorf(msg, args...))
  88. }
  89. func newError(pt ProblemType, err error) *Error {
  90. meta, ok := errorMap[pt]
  91. if !ok {
  92. meta = errorServerInternalMetadata
  93. return &Error{
  94. Type: meta.typ,
  95. Detail: meta.details,
  96. Status: meta.status,
  97. Err: err,
  98. }
  99. }
  100. return &Error{
  101. Type: meta.typ,
  102. Detail: meta.details,
  103. Status: meta.status,
  104. Err: err,
  105. }
  106. }
  107. // NewErrorISE creates a new ErrorServerInternalType Error.
  108. func NewErrorISE(msg string, args ...interface{}) *Error {
  109. return NewError(ErrorServerInternalType, msg, args...)
  110. }
  111. // WrapError attempts to wrap the internal error.
  112. func WrapError(typ ProblemType, err error, msg string, args ...interface{}) *Error {
  113. switch e := err.(type) {
  114. case nil:
  115. return nil
  116. case *Error:
  117. if e.Err == nil {
  118. e.Err = errors.Errorf(msg+"; "+e.Detail, args...)
  119. } else {
  120. e.Err = errors.Wrapf(e.Err, msg, args...)
  121. }
  122. return e
  123. default:
  124. return newError(typ, errors.Wrapf(err, msg, args...))
  125. }
  126. }
  127. // WrapErrorISE shortcut to wrap an internal server error type.
  128. func WrapErrorISE(err error, msg string, args ...interface{}) *Error {
  129. return WrapError(ErrorServerInternalType, err, msg, args...)
  130. }
  131. // StatusCode returns the status code and implements the StatusCoder interface.
  132. func (e *Error) StatusCode() int {
  133. return e.Status
  134. }
  135. // Error allows AError to implement the error interface.
  136. func (e *Error) Error() string {
  137. return e.Detail
  138. }
  139. // Cause returns the internal error and implements the Causer interface.
  140. func (e *Error) Cause() error {
  141. if e.Err == nil {
  142. return errors.New(e.Detail)
  143. }
  144. return e.Err
  145. }
  146. // ToLog implements the EnableLogger interface.
  147. func (e *Error) ToLog() (interface{}, error) {
  148. b, err := json.Marshal(e)
  149. if err != nil {
  150. return nil, WrapErrorISE(err, "error marshaling authority.Error for logging")
  151. }
  152. return string(b), nil
  153. }
  154. // WriteError writes to w a JSON representation of the given error.
  155. func WriteError(w http.ResponseWriter, err *Error) {
  156. w.Header().Set("Content-Type", "application/problem+json")
  157. w.WriteHeader(err.StatusCode())
  158. // Write errors in the response writer
  159. if rl, ok := w.(logging.ResponseLogger); ok {
  160. rl.WithFields(map[string]interface{}{
  161. "error": err.Err,
  162. })
  163. if os.Getenv("STEPDEBUG") == "1" {
  164. if e, ok := err.Err.(errs.StackTracer); ok {
  165. rl.WithFields(map[string]interface{}{
  166. "stack-trace": fmt.Sprintf("%+v", e),
  167. })
  168. }
  169. }
  170. }
  171. if err := json.NewEncoder(w).Encode(err); err != nil {
  172. log.Println(err)
  173. }
  174. }