error.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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. var err *Error
  82. if errors.As(e, &err) {
  83. err.Err = errors.Wrap(err.Err, m)
  84. e = err
  85. } else {
  86. e = errors.Wrap(e, m)
  87. }
  88. return StatusCodeError(status, e, opts...)
  89. }
  90. // Wrapf returns an error annotating err with a stack trace at the point Wrap is
  91. // called, and the supplied message. If err is nil, Wrap returns nil.
  92. func Wrapf(status int, e error, format string, args ...interface{}) error {
  93. if e == nil {
  94. return nil
  95. }
  96. as, opts := splitOptionArgs(args)
  97. var err *Error
  98. if errors.As(e, &err) {
  99. err.Err = errors.Wrapf(err.Err, format, args...)
  100. e = err
  101. } else {
  102. e = errors.Wrapf(e, format, as...)
  103. }
  104. return StatusCodeError(status, e, opts...)
  105. }
  106. // MarshalJSON implements json.Marshaller interface for the Error struct.
  107. func (e *Error) MarshalJSON() ([]byte, error) {
  108. var msg string
  109. if len(e.Msg) > 0 {
  110. msg = e.Msg
  111. } else {
  112. msg = http.StatusText(e.Status)
  113. }
  114. return json.Marshal(&ErrorResponse{Status: e.Status, Message: msg})
  115. }
  116. // UnmarshalJSON implements json.Unmarshaler interface for the Error struct.
  117. func (e *Error) UnmarshalJSON(data []byte) error {
  118. var er ErrorResponse
  119. if err := json.Unmarshal(data, &er); err != nil {
  120. return err
  121. }
  122. e.Status = er.Status
  123. e.Err = fmt.Errorf("%s", er.Message)
  124. return nil
  125. }
  126. // Format implements the fmt.Formatter interface.
  127. func (e *Error) Format(f fmt.State, c rune) {
  128. if err, ok := e.Err.(fmt.Formatter); ok {
  129. err.Format(f, c)
  130. return
  131. }
  132. fmt.Fprint(f, e.Err.Error())
  133. }
  134. // Messenger is a friendly message interface that errors can implement.
  135. type Messenger interface {
  136. Message() string
  137. }
  138. // StatusCodeError selects the proper error based on the status code.
  139. func StatusCodeError(code int, e error, opts ...Option) error {
  140. switch code {
  141. case http.StatusBadRequest:
  142. opts = append(opts, withDefaultMessage(BadRequestDefaultMsg))
  143. return NewErr(http.StatusBadRequest, e, opts...)
  144. case http.StatusUnauthorized:
  145. return UnauthorizedErr(e, opts...)
  146. case http.StatusForbidden:
  147. opts = append(opts, withDefaultMessage(ForbiddenDefaultMsg))
  148. return NewErr(http.StatusForbidden, e, opts...)
  149. case http.StatusInternalServerError:
  150. return InternalServerErr(e, opts...)
  151. case http.StatusNotImplemented:
  152. return NotImplementedErr(e, opts...)
  153. default:
  154. return UnexpectedErr(code, e, opts...)
  155. }
  156. }
  157. var (
  158. seeLogs = "Please see the certificate authority logs for more info."
  159. // BadRequestDefaultMsg 400 default msg
  160. BadRequestDefaultMsg = "The request could not be completed; malformed or missing data. " + seeLogs
  161. // UnauthorizedDefaultMsg 401 default msg
  162. UnauthorizedDefaultMsg = "The request lacked necessary authorization to be completed. " + seeLogs
  163. // ForbiddenDefaultMsg 403 default msg
  164. ForbiddenDefaultMsg = "The request was forbidden by the certificate authority. " + seeLogs
  165. // NotFoundDefaultMsg 404 default msg
  166. NotFoundDefaultMsg = "The requested resource could not be found. " + seeLogs
  167. // InternalServerErrorDefaultMsg 500 default msg
  168. InternalServerErrorDefaultMsg = "The certificate authority encountered an Internal Server Error. " + seeLogs
  169. // NotImplementedDefaultMsg 501 default msg
  170. NotImplementedDefaultMsg = "The requested method is not implemented by the certificate authority. " + seeLogs
  171. )
  172. var (
  173. // BadRequestPrefix is the prefix added to the bad request messages that are
  174. // directly sent to the cli.
  175. BadRequestPrefix = "The request could not be completed: "
  176. // ForbiddenPrefix is the prefix added to the forbidden messates that are
  177. // sent to the cli.
  178. ForbiddenPrefix = "The request was forbidden by the certificate authority: "
  179. )
  180. func formatMessage(status int, msg string) string {
  181. switch status {
  182. case http.StatusBadRequest:
  183. return BadRequestPrefix + msg + "."
  184. case http.StatusForbidden:
  185. return ForbiddenPrefix + msg + "."
  186. default:
  187. return msg
  188. }
  189. }
  190. // splitOptionArgs splits the variadic length args into string formatting args
  191. // and Option(s) to apply to an Error.
  192. func splitOptionArgs(args []interface{}) ([]interface{}, []Option) {
  193. indexOptionStart := -1
  194. for i, a := range args {
  195. if _, ok := a.(Option); ok {
  196. indexOptionStart = i
  197. break
  198. }
  199. }
  200. if indexOptionStart < 0 {
  201. return args, []Option{}
  202. }
  203. opts := []Option{}
  204. // Ignore any non-Option args that come after the first Option.
  205. for _, o := range args[indexOptionStart:] {
  206. if opt, ok := o.(Option); ok {
  207. opts = append(opts, opt)
  208. }
  209. }
  210. return args[:indexOptionStart], opts
  211. }
  212. // New creates a new http error with the given status and message.
  213. func New(status int, format string, args ...interface{}) error {
  214. msg := fmt.Sprintf(format, args...)
  215. return &Error{
  216. Status: status,
  217. Msg: formatMessage(status, msg),
  218. Err: errors.New(msg),
  219. }
  220. }
  221. // NewError creates a new http error with the given error and message.
  222. func NewError(status int, err error, format string, args ...interface{}) error {
  223. var e *Error
  224. if errors.As(err, &e) {
  225. return err
  226. }
  227. msg := fmt.Sprintf(format, args...)
  228. if _, ok := err.(log.StackTracedError); !ok {
  229. err = errors.Wrap(err, msg)
  230. }
  231. return &Error{
  232. Status: status,
  233. Msg: formatMessage(status, msg),
  234. Err: err,
  235. }
  236. }
  237. // NewErr returns a new Error. If the given error implements the StatusCoder
  238. // interface we will ignore the given status.
  239. func NewErr(status int, err error, opts ...Option) error {
  240. var e *Error
  241. if !errors.As(err, &e) {
  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. var e *Error
  272. if errors.As(err, &e) {
  273. _, o := splitOptionArgs(opts)
  274. for _, fn := range o {
  275. fn(e)
  276. }
  277. }
  278. return err
  279. }
  280. // InternalServer creates a 500 error with the given format and arguments.
  281. func InternalServer(format string, args ...interface{}) error {
  282. args = append(args, withDefaultMessage(InternalServerErrorDefaultMsg))
  283. return Errorf(http.StatusInternalServerError, format, args...)
  284. }
  285. // InternalServerErr returns a 500 error with the given error.
  286. func InternalServerErr(err error, opts ...Option) error {
  287. opts = append(opts, withDefaultMessage(InternalServerErrorDefaultMsg))
  288. return NewErr(http.StatusInternalServerError, err, opts...)
  289. }
  290. // NotImplemented creates a 501 error with the given format and arguments.
  291. func NotImplemented(format string, args ...interface{}) error {
  292. args = append(args, withDefaultMessage(NotImplementedDefaultMsg))
  293. return Errorf(http.StatusNotImplemented, format, args...)
  294. }
  295. // NotImplementedErr returns a 501 error with the given error.
  296. func NotImplementedErr(err error, opts ...Option) error {
  297. opts = append(opts, withDefaultMessage(NotImplementedDefaultMsg))
  298. return NewErr(http.StatusNotImplemented, err, opts...)
  299. }
  300. // BadRequest creates a 400 error with the given format and arguments.
  301. func BadRequest(format string, args ...interface{}) error {
  302. return New(http.StatusBadRequest, format, args...)
  303. }
  304. // BadRequestErr returns an 400 error with the given error.
  305. func BadRequestErr(err error, format string, args ...interface{}) error {
  306. return NewError(http.StatusBadRequest, err, format, args...)
  307. }
  308. // Unauthorized creates a 401 error with the given format and arguments.
  309. func Unauthorized(format string, args ...interface{}) error {
  310. args = append(args, withDefaultMessage(UnauthorizedDefaultMsg))
  311. return Errorf(http.StatusUnauthorized, format, args...)
  312. }
  313. // UnauthorizedErr returns an 401 error with the given error.
  314. func UnauthorizedErr(err error, opts ...Option) error {
  315. opts = append(opts, withDefaultMessage(UnauthorizedDefaultMsg))
  316. return NewErr(http.StatusUnauthorized, err, opts...)
  317. }
  318. // Forbidden creates a 403 error with the given format and arguments.
  319. func Forbidden(format string, args ...interface{}) error {
  320. return New(http.StatusForbidden, format, args...)
  321. }
  322. // ForbiddenErr returns an 403 error with the given error.
  323. func ForbiddenErr(err error, format string, args ...interface{}) error {
  324. return NewError(http.StatusForbidden, err, format, args...)
  325. }
  326. // NotFound creates a 404 error with the given format and arguments.
  327. func NotFound(format string, args ...interface{}) error {
  328. args = append(args, withDefaultMessage(NotFoundDefaultMsg))
  329. return Errorf(http.StatusNotFound, format, args...)
  330. }
  331. // NotFoundErr returns an 404 error with the given error.
  332. func NotFoundErr(err error, opts ...Option) error {
  333. opts = append(opts, withDefaultMessage(NotFoundDefaultMsg))
  334. return NewErr(http.StatusNotFound, err, opts...)
  335. }
  336. // UnexpectedErr will be used when the certificate authority makes an outgoing
  337. // request and receives an unhandled status code.
  338. func UnexpectedErr(code int, err error, opts ...Option) error {
  339. opts = append(opts, withDefaultMessage("The certificate authority received an "+
  340. "unexpected HTTP status code - '%d'. "+seeLogs, code))
  341. return NewErr(code, err, opts...)
  342. }