error.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. package errs
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "github.com/pkg/errors"
  7. "github.com/smallstep/certificates/api/log"
  8. "github.com/smallstep/certificates/api/render"
  9. )
  10. // Option modifies the Error type.
  11. type Option func(e *Error) error
  12. // withDefaultMessage returns an Option that modifies the error by overwriting the
  13. // message only if it is empty.
  14. func withDefaultMessage(format string, args ...interface{}) Option {
  15. return func(e *Error) error {
  16. if e.Msg != "" {
  17. return e
  18. }
  19. e.Msg = fmt.Sprintf(format, args...)
  20. return e
  21. }
  22. }
  23. // WithMessage returns an Option that modifies the error by overwriting the
  24. // message only if it is empty.
  25. func WithMessage(format string, args ...interface{}) Option {
  26. return func(e *Error) error {
  27. e.Msg = fmt.Sprintf(format, args...)
  28. return e
  29. }
  30. }
  31. // WithKeyVal returns an Option that adds the given key-value pair to the
  32. // Error details. This is helpful for debugging errors.
  33. func WithKeyVal(key string, val interface{}) Option {
  34. return func(e *Error) error {
  35. if e.Details == nil {
  36. e.Details = make(map[string]interface{})
  37. }
  38. e.Details[key] = val
  39. return e
  40. }
  41. }
  42. // Error represents the CA API errors.
  43. type Error struct {
  44. Status int
  45. Err error
  46. Msg string
  47. Details map[string]interface{}
  48. }
  49. // ErrorResponse represents an error in JSON format.
  50. type ErrorResponse struct {
  51. Status int `json:"status"`
  52. Message string `json:"message"`
  53. }
  54. // Cause implements the errors.Causer interface and returns the original error.
  55. func (e *Error) Cause() error {
  56. return e.Err
  57. }
  58. // Error implements the error interface and returns the error string.
  59. func (e *Error) Error() string {
  60. return e.Err.Error()
  61. }
  62. // StatusCode implements the StatusCoder interface and returns the HTTP response
  63. // code.
  64. func (e *Error) StatusCode() int {
  65. return e.Status
  66. }
  67. // Message returns a user friendly error, if one is set.
  68. func (e *Error) Message() string {
  69. if len(e.Msg) > 0 {
  70. return e.Msg
  71. }
  72. return e.Err.Error()
  73. }
  74. // Wrap returns an error annotating err with a stack trace at the point Wrap is
  75. // called, and the supplied message. If err is nil, Wrap returns nil.
  76. func Wrap(status int, e error, m string, args ...interface{}) error {
  77. if e == nil {
  78. return nil
  79. }
  80. _, opts := splitOptionArgs(args)
  81. if err, ok := e.(*Error); ok {
  82. err.Err = errors.Wrap(err.Err, m)
  83. e = err
  84. } else {
  85. e = errors.Wrap(e, m)
  86. }
  87. return StatusCodeError(status, e, opts...)
  88. }
  89. // Wrapf returns an error annotating err with a stack trace at the point Wrap is
  90. // called, and the supplied message. If err is nil, Wrap returns nil.
  91. func Wrapf(status int, e error, format string, args ...interface{}) error {
  92. if e == nil {
  93. return nil
  94. }
  95. as, opts := splitOptionArgs(args)
  96. if err, ok := e.(*Error); ok {
  97. err.Err = errors.Wrapf(err.Err, format, args...)
  98. e = err
  99. } else {
  100. e = errors.Wrapf(e, format, as...)
  101. }
  102. return StatusCodeError(status, e, opts...)
  103. }
  104. // MarshalJSON implements json.Marshaller interface for the Error struct.
  105. func (e *Error) MarshalJSON() ([]byte, error) {
  106. var msg string
  107. if len(e.Msg) > 0 {
  108. msg = e.Msg
  109. } else {
  110. msg = http.StatusText(e.Status)
  111. }
  112. return json.Marshal(&ErrorResponse{Status: e.Status, Message: msg})
  113. }
  114. // UnmarshalJSON implements json.Unmarshaler interface for the Error struct.
  115. func (e *Error) UnmarshalJSON(data []byte) error {
  116. var er ErrorResponse
  117. if err := json.Unmarshal(data, &er); err != nil {
  118. return err
  119. }
  120. e.Status = er.Status
  121. e.Err = fmt.Errorf("%s", er.Message)
  122. return nil
  123. }
  124. // Format implements the fmt.Formatter interface.
  125. func (e *Error) Format(f fmt.State, c rune) {
  126. if err, ok := e.Err.(fmt.Formatter); ok {
  127. err.Format(f, c)
  128. return
  129. }
  130. fmt.Fprint(f, e.Err.Error())
  131. }
  132. // Messenger is a friendly message interface that errors can implement.
  133. type Messenger interface {
  134. Message() string
  135. }
  136. // StatusCodeError selects the proper error based on the status code.
  137. func StatusCodeError(code int, e error, opts ...Option) error {
  138. switch code {
  139. case http.StatusBadRequest:
  140. opts = append(opts, withDefaultMessage(BadRequestDefaultMsg))
  141. return NewErr(http.StatusBadRequest, e, opts...)
  142. case http.StatusUnauthorized:
  143. return UnauthorizedErr(e, opts...)
  144. case http.StatusForbidden:
  145. opts = append(opts, withDefaultMessage(ForbiddenDefaultMsg))
  146. return NewErr(http.StatusForbidden, e, opts...)
  147. case http.StatusInternalServerError:
  148. return InternalServerErr(e, opts...)
  149. case http.StatusNotImplemented:
  150. return NotImplementedErr(e, opts...)
  151. default:
  152. return UnexpectedErr(code, e, opts...)
  153. }
  154. }
  155. var (
  156. seeLogs = "Please see the certificate authority logs for more info."
  157. // BadRequestDefaultMsg 400 default msg
  158. BadRequestDefaultMsg = "The request could not be completed; malformed or missing data. " + seeLogs
  159. // UnauthorizedDefaultMsg 401 default msg
  160. UnauthorizedDefaultMsg = "The request lacked necessary authorization to be completed. " + seeLogs
  161. // ForbiddenDefaultMsg 403 default msg
  162. ForbiddenDefaultMsg = "The request was forbidden by the certificate authority. " + seeLogs
  163. // NotFoundDefaultMsg 404 default msg
  164. NotFoundDefaultMsg = "The requested resource could not be found. " + seeLogs
  165. // InternalServerErrorDefaultMsg 500 default msg
  166. InternalServerErrorDefaultMsg = "The certificate authority encountered an Internal Server Error. " + seeLogs
  167. // NotImplementedDefaultMsg 501 default msg
  168. NotImplementedDefaultMsg = "The requested method is not implemented by the certificate authority. " + seeLogs
  169. )
  170. var (
  171. // BadRequestPrefix is the prefix added to the bad request messages that are
  172. // directly sent to the cli.
  173. BadRequestPrefix = "The request could not be completed: "
  174. // ForbiddenPrefix is the prefix added to the forbidden messates that are
  175. // sent to the cli.
  176. ForbiddenPrefix = "The request was forbidden by the certificate authority: "
  177. )
  178. func formatMessage(status int, msg string) string {
  179. switch status {
  180. case http.StatusBadRequest:
  181. return BadRequestPrefix + msg + "."
  182. case http.StatusForbidden:
  183. return ForbiddenPrefix + msg + "."
  184. default:
  185. return msg
  186. }
  187. }
  188. // splitOptionArgs splits the variadic length args into string formatting args
  189. // and Option(s) to apply to an Error.
  190. func splitOptionArgs(args []interface{}) ([]interface{}, []Option) {
  191. indexOptionStart := -1
  192. for i, a := range args {
  193. if _, ok := a.(Option); ok {
  194. indexOptionStart = i
  195. break
  196. }
  197. }
  198. if indexOptionStart < 0 {
  199. return args, []Option{}
  200. }
  201. opts := []Option{}
  202. // Ignore any non-Option args that come after the first Option.
  203. for _, o := range args[indexOptionStart:] {
  204. if opt, ok := o.(Option); ok {
  205. opts = append(opts, opt)
  206. }
  207. }
  208. return args[:indexOptionStart], opts
  209. }
  210. // New creates a new http error with the given status and message.
  211. func New(status int, format string, args ...interface{}) error {
  212. msg := fmt.Sprintf(format, args...)
  213. return &Error{
  214. Status: status,
  215. Msg: formatMessage(status, msg),
  216. Err: errors.New(msg),
  217. }
  218. }
  219. // NewError creates a new http error with the given error and message.
  220. func NewError(status int, err error, format string, args ...interface{}) error {
  221. if _, ok := err.(*Error); ok {
  222. return err
  223. }
  224. msg := fmt.Sprintf(format, args...)
  225. if _, ok := err.(log.StackTracedError); !ok {
  226. err = errors.Wrap(err, msg)
  227. }
  228. return &Error{
  229. Status: status,
  230. Msg: formatMessage(status, msg),
  231. Err: err,
  232. }
  233. }
  234. // NewErr returns a new Error. If the given error implements the StatusCoder
  235. // interface we will ignore the given status.
  236. func NewErr(status int, err error, opts ...Option) error {
  237. var (
  238. e *Error
  239. ok bool
  240. )
  241. if e, ok = err.(*Error); !ok {
  242. if sc, ok := err.(render.StatusCodedError); ok {
  243. e = &Error{Status: sc.StatusCode(), Err: err}
  244. } else {
  245. cause := errors.Cause(err)
  246. if sc, ok := cause.(render.StatusCodedError); ok {
  247. e = &Error{Status: sc.StatusCode(), Err: err}
  248. } else {
  249. e = &Error{Status: status, Err: err}
  250. }
  251. }
  252. }
  253. for _, o := range opts {
  254. o(e)
  255. }
  256. return e
  257. }
  258. // Errorf creates a new error using the given format and status code.
  259. func Errorf(code int, format string, args ...interface{}) error {
  260. as, opts := splitOptionArgs(args)
  261. opts = append(opts, withDefaultMessage(NotImplementedDefaultMsg))
  262. e := &Error{Status: code, Err: fmt.Errorf(format, as...)}
  263. for _, o := range opts {
  264. o(e)
  265. }
  266. return e
  267. }
  268. // ApplyOptions applies the given options to the error if is the type *Error.
  269. // TODO(mariano): try to get rid of this.
  270. func ApplyOptions(err error, opts ...interface{}) error {
  271. if e, ok := err.(*Error); ok {
  272. _, o := splitOptionArgs(opts)
  273. for _, fn := range o {
  274. fn(e)
  275. }
  276. }
  277. return err
  278. }
  279. // InternalServer creates a 500 error with the given format and arguments.
  280. func InternalServer(format string, args ...interface{}) error {
  281. args = append(args, withDefaultMessage(InternalServerErrorDefaultMsg))
  282. return Errorf(http.StatusInternalServerError, format, args...)
  283. }
  284. // InternalServerErr returns a 500 error with the given error.
  285. func InternalServerErr(err error, opts ...Option) error {
  286. opts = append(opts, withDefaultMessage(InternalServerErrorDefaultMsg))
  287. return NewErr(http.StatusInternalServerError, err, opts...)
  288. }
  289. // NotImplemented creates a 501 error with the given format and arguments.
  290. func NotImplemented(format string, args ...interface{}) error {
  291. args = append(args, withDefaultMessage(NotImplementedDefaultMsg))
  292. return Errorf(http.StatusNotImplemented, format, args...)
  293. }
  294. // NotImplementedErr returns a 501 error with the given error.
  295. func NotImplementedErr(err error, opts ...Option) error {
  296. opts = append(opts, withDefaultMessage(NotImplementedDefaultMsg))
  297. return NewErr(http.StatusNotImplemented, err, opts...)
  298. }
  299. // BadRequest creates a 400 error with the given format and arguments.
  300. func BadRequest(format string, args ...interface{}) error {
  301. return New(http.StatusBadRequest, format, args...)
  302. }
  303. // BadRequestErr returns an 400 error with the given error.
  304. func BadRequestErr(err error, format string, args ...interface{}) error {
  305. return NewError(http.StatusBadRequest, err, format, args...)
  306. }
  307. // Unauthorized creates a 401 error with the given format and arguments.
  308. func Unauthorized(format string, args ...interface{}) error {
  309. args = append(args, withDefaultMessage(UnauthorizedDefaultMsg))
  310. return Errorf(http.StatusUnauthorized, format, args...)
  311. }
  312. // UnauthorizedErr returns an 401 error with the given error.
  313. func UnauthorizedErr(err error, opts ...Option) error {
  314. opts = append(opts, withDefaultMessage(UnauthorizedDefaultMsg))
  315. return NewErr(http.StatusUnauthorized, err, opts...)
  316. }
  317. // Forbidden creates a 403 error with the given format and arguments.
  318. func Forbidden(format string, args ...interface{}) error {
  319. return New(http.StatusForbidden, format, args...)
  320. }
  321. // ForbiddenErr returns an 403 error with the given error.
  322. func ForbiddenErr(err error, format string, args ...interface{}) error {
  323. return NewError(http.StatusForbidden, err, format, args...)
  324. }
  325. // NotFound creates a 404 error with the given format and arguments.
  326. func NotFound(format string, args ...interface{}) error {
  327. args = append(args, withDefaultMessage(NotFoundDefaultMsg))
  328. return Errorf(http.StatusNotFound, format, args...)
  329. }
  330. // NotFoundErr returns an 404 error with the given error.
  331. func NotFoundErr(err error, opts ...Option) error {
  332. opts = append(opts, withDefaultMessage(NotFoundDefaultMsg))
  333. return NewErr(http.StatusNotFound, err, opts...)
  334. }
  335. // UnexpectedErr will be used when the certificate authority makes an outgoing
  336. // request and receives an unhandled status code.
  337. func UnexpectedErr(code int, err error, opts ...Option) error {
  338. opts = append(opts, withDefaultMessage("The certificate authority received an "+
  339. "unexpected HTTP status code - '%d'. "+seeLogs, code))
  340. return NewErr(code, err, opts...)
  341. }