error.go 13 KB

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