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. RequestID string `json:"-"`
  49. }
  50. // ErrorResponse represents an error in JSON format.
  51. type ErrorResponse struct {
  52. Status int `json:"status"`
  53. Message string `json:"message"`
  54. }
  55. // Cause implements the errors.Causer interface and returns the original error.
  56. func (e *Error) Cause() error {
  57. return e.Err
  58. }
  59. // Error implements the error interface and returns the error string.
  60. func (e *Error) Error() string {
  61. return e.Err.Error()
  62. }
  63. // StatusCode implements the StatusCoder interface and returns the HTTP response
  64. // code.
  65. func (e *Error) StatusCode() int {
  66. return e.Status
  67. }
  68. // Message returns a user friendly error, if one is set.
  69. func (e *Error) Message() string {
  70. if len(e.Msg) > 0 {
  71. return e.Msg
  72. }
  73. return e.Err.Error()
  74. }
  75. // Wrap returns an error annotating err with a stack trace at the point Wrap is
  76. // called, and the supplied message. If err is nil, Wrap returns nil.
  77. func Wrap(status int, e error, m string, args ...interface{}) error {
  78. if e == nil {
  79. return nil
  80. }
  81. _, opts := splitOptionArgs(args)
  82. var err *Error
  83. if errors.As(e, &err) {
  84. err.Err = errors.Wrap(err.Err, m)
  85. e = err
  86. } else {
  87. e = errors.Wrap(e, m)
  88. }
  89. return StatusCodeError(status, e, opts...)
  90. }
  91. // Wrapf returns an error annotating err with a stack trace at the point Wrap is
  92. // called, and the supplied message. If err is nil, Wrap returns nil.
  93. func Wrapf(status int, e error, format string, args ...interface{}) error {
  94. if e == nil {
  95. return nil
  96. }
  97. as, opts := splitOptionArgs(args)
  98. var err *Error
  99. if errors.As(e, &err) {
  100. err.Err = errors.Wrapf(err.Err, format, args...)
  101. e = err
  102. } else {
  103. e = errors.Wrapf(e, format, as...)
  104. }
  105. return StatusCodeError(status, e, opts...)
  106. }
  107. // MarshalJSON implements json.Marshaller interface for the Error struct.
  108. func (e *Error) MarshalJSON() ([]byte, error) {
  109. var msg string
  110. if len(e.Msg) > 0 {
  111. msg = e.Msg
  112. } else {
  113. msg = http.StatusText(e.Status)
  114. }
  115. return json.Marshal(&ErrorResponse{Status: e.Status, Message: msg})
  116. }
  117. // UnmarshalJSON implements json.Unmarshaler interface for the Error struct.
  118. func (e *Error) UnmarshalJSON(data []byte) error {
  119. var er ErrorResponse
  120. if err := json.Unmarshal(data, &er); err != nil {
  121. return err
  122. }
  123. e.Status = er.Status
  124. e.Err = fmt.Errorf("%s", er.Message)
  125. return nil
  126. }
  127. // Format implements the fmt.Formatter interface.
  128. func (e *Error) Format(f fmt.State, c rune) {
  129. var fe fmt.Formatter
  130. if errors.As(e.Err, &fe) {
  131. fe.Format(f, c)
  132. return
  133. }
  134. fmt.Fprint(f, e.Err.Error())
  135. }
  136. // Messenger is a friendly message interface that errors can implement.
  137. type Messenger interface {
  138. Message() string
  139. }
  140. // StatusCodeError selects the proper error based on the status code.
  141. func StatusCodeError(code int, e error, opts ...Option) error {
  142. switch code {
  143. case http.StatusBadRequest:
  144. opts = append(opts, withDefaultMessage(BadRequestDefaultMsg))
  145. return NewErr(http.StatusBadRequest, e, opts...)
  146. case http.StatusUnauthorized:
  147. return UnauthorizedErr(e, opts...)
  148. case http.StatusForbidden:
  149. opts = append(opts, withDefaultMessage(ForbiddenDefaultMsg))
  150. return NewErr(http.StatusForbidden, e, opts...)
  151. case http.StatusInternalServerError:
  152. return InternalServerErr(e, opts...)
  153. case http.StatusNotImplemented:
  154. return NotImplementedErr(e, opts...)
  155. default:
  156. return UnexpectedErr(code, e, opts...)
  157. }
  158. }
  159. var (
  160. seeLogs = "Please see the certificate authority logs for more info."
  161. // BadRequestDefaultMsg 400 default msg
  162. BadRequestDefaultMsg = "The request could not be completed; malformed or missing data. " + seeLogs
  163. // UnauthorizedDefaultMsg 401 default msg
  164. UnauthorizedDefaultMsg = "The request lacked necessary authorization to be completed. " + seeLogs
  165. // ForbiddenDefaultMsg 403 default msg
  166. ForbiddenDefaultMsg = "The request was forbidden by the certificate authority. " + seeLogs
  167. // NotFoundDefaultMsg 404 default msg
  168. NotFoundDefaultMsg = "The requested resource could not be found. " + seeLogs
  169. // InternalServerErrorDefaultMsg 500 default msg
  170. InternalServerErrorDefaultMsg = "The certificate authority encountered an Internal Server Error. " + seeLogs
  171. // NotImplementedDefaultMsg 501 default msg
  172. NotImplementedDefaultMsg = "The requested method is not implemented by the certificate authority. " + seeLogs
  173. )
  174. var (
  175. // BadRequestPrefix is the prefix added to the bad request messages that are
  176. // directly sent to the cli.
  177. BadRequestPrefix = "The request could not be completed: "
  178. // ForbiddenPrefix is the prefix added to the forbidden messates that are
  179. // sent to the cli.
  180. ForbiddenPrefix = "The request was forbidden by the certificate authority: "
  181. )
  182. func formatMessage(status int, msg string) string {
  183. switch status {
  184. case http.StatusBadRequest:
  185. return BadRequestPrefix + msg + "."
  186. case http.StatusForbidden:
  187. return ForbiddenPrefix + msg + "."
  188. default:
  189. return msg
  190. }
  191. }
  192. // splitOptionArgs splits the variadic length args into string formatting args
  193. // and Option(s) to apply to an Error.
  194. func splitOptionArgs(args []interface{}) ([]interface{}, []Option) {
  195. indexOptionStart := -1
  196. for i, a := range args {
  197. if _, ok := a.(Option); ok {
  198. indexOptionStart = i
  199. break
  200. }
  201. }
  202. if indexOptionStart < 0 {
  203. return args, []Option{}
  204. }
  205. opts := []Option{}
  206. // Ignore any non-Option args that come after the first Option.
  207. for _, o := range args[indexOptionStart:] {
  208. if opt, ok := o.(Option); ok {
  209. opts = append(opts, opt)
  210. }
  211. }
  212. return args[:indexOptionStart], opts
  213. }
  214. // New creates a new http error with the given status and message.
  215. func New(status int, format string, args ...interface{}) error {
  216. msg := fmt.Sprintf(format, args...)
  217. return &Error{
  218. Status: status,
  219. Msg: formatMessage(status, msg),
  220. Err: errors.New(msg),
  221. }
  222. }
  223. // NewError creates a new http error with the given error and message.
  224. func NewError(status int, err error, format string, args ...interface{}) error {
  225. var e *Error
  226. if errors.As(err, &e) {
  227. return err
  228. }
  229. msg := fmt.Sprintf(format, args...)
  230. var ste log.StackTracedError
  231. if !errors.As(err, &ste) {
  232. err = errors.Wrap(err, msg)
  233. }
  234. return &Error{
  235. Status: status,
  236. Msg: formatMessage(status, msg),
  237. Err: err,
  238. }
  239. }
  240. // NewErr returns a new Error. If the given error implements the StatusCoder
  241. // interface we will ignore the given status.
  242. func NewErr(status int, err error, opts ...Option) error {
  243. var e *Error
  244. if !errors.As(err, &e) {
  245. var ste render.StatusCodedError
  246. if errors.As(err, &ste) {
  247. e = &Error{Status: ste.StatusCode(), Err: err}
  248. } else {
  249. e = &Error{Status: status, Err: err}
  250. }
  251. }
  252. for _, o := range opts {
  253. o(e)
  254. }
  255. return e
  256. }
  257. // Errorf creates a new error using the given format and status code.
  258. func Errorf(code int, format string, args ...interface{}) error {
  259. as, opts := splitOptionArgs(args)
  260. opts = append(opts, withDefaultMessage(NotImplementedDefaultMsg))
  261. e := &Error{Status: code, Err: fmt.Errorf(format, as...)}
  262. for _, o := range opts {
  263. o(e)
  264. }
  265. return e
  266. }
  267. // ApplyOptions applies the given options to the error if is the type *Error.
  268. // TODO(mariano): try to get rid of this.
  269. func ApplyOptions(err error, opts ...interface{}) error {
  270. var e *Error
  271. if errors.As(err, &e) {
  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. }