error.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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. var fe fmt.Formatter
  129. if errors.As(e.Err, &fe) {
  130. fe.Format(f, c)
  131. return
  132. }
  133. fmt.Fprint(f, e.Err.Error())
  134. }
  135. // Messenger is a friendly message interface that errors can implement.
  136. type Messenger interface {
  137. Message() string
  138. }
  139. // StatusCodeError selects the proper error based on the status code.
  140. func StatusCodeError(code int, e error, opts ...Option) error {
  141. switch code {
  142. case http.StatusBadRequest:
  143. opts = append(opts, withDefaultMessage(BadRequestDefaultMsg))
  144. return NewErr(http.StatusBadRequest, e, opts...)
  145. case http.StatusUnauthorized:
  146. return UnauthorizedErr(e, opts...)
  147. case http.StatusForbidden:
  148. opts = append(opts, withDefaultMessage(ForbiddenDefaultMsg))
  149. return NewErr(http.StatusForbidden, e, opts...)
  150. case http.StatusInternalServerError:
  151. return InternalServerErr(e, opts...)
  152. case http.StatusNotImplemented:
  153. return NotImplementedErr(e, opts...)
  154. default:
  155. return UnexpectedErr(code, e, opts...)
  156. }
  157. }
  158. var (
  159. seeLogs = "Please see the certificate authority logs for more info."
  160. // BadRequestDefaultMsg 400 default msg
  161. BadRequestDefaultMsg = "The request could not be completed; malformed or missing data. " + seeLogs
  162. // UnauthorizedDefaultMsg 401 default msg
  163. UnauthorizedDefaultMsg = "The request lacked necessary authorization to be completed. " + seeLogs
  164. // ForbiddenDefaultMsg 403 default msg
  165. ForbiddenDefaultMsg = "The request was forbidden by the certificate authority. " + seeLogs
  166. // NotFoundDefaultMsg 404 default msg
  167. NotFoundDefaultMsg = "The requested resource could not be found. " + seeLogs
  168. // InternalServerErrorDefaultMsg 500 default msg
  169. InternalServerErrorDefaultMsg = "The certificate authority encountered an Internal Server Error. " + seeLogs
  170. // NotImplementedDefaultMsg 501 default msg
  171. NotImplementedDefaultMsg = "The requested method is not implemented by the certificate authority. " + seeLogs
  172. )
  173. var (
  174. // BadRequestPrefix is the prefix added to the bad request messages that are
  175. // directly sent to the cli.
  176. BadRequestPrefix = "The request could not be completed: "
  177. // ForbiddenPrefix is the prefix added to the forbidden messates that are
  178. // sent to the cli.
  179. ForbiddenPrefix = "The request was forbidden by the certificate authority: "
  180. )
  181. func formatMessage(status int, msg string) string {
  182. switch status {
  183. case http.StatusBadRequest:
  184. return BadRequestPrefix + msg + "."
  185. case http.StatusForbidden:
  186. return ForbiddenPrefix + msg + "."
  187. default:
  188. return msg
  189. }
  190. }
  191. // splitOptionArgs splits the variadic length args into string formatting args
  192. // and Option(s) to apply to an Error.
  193. func splitOptionArgs(args []interface{}) ([]interface{}, []Option) {
  194. indexOptionStart := -1
  195. for i, a := range args {
  196. if _, ok := a.(Option); ok {
  197. indexOptionStart = i
  198. break
  199. }
  200. }
  201. if indexOptionStart < 0 {
  202. return args, []Option{}
  203. }
  204. opts := []Option{}
  205. // Ignore any non-Option args that come after the first Option.
  206. for _, o := range args[indexOptionStart:] {
  207. if opt, ok := o.(Option); ok {
  208. opts = append(opts, opt)
  209. }
  210. }
  211. return args[:indexOptionStart], opts
  212. }
  213. // New creates a new http error with the given status and message.
  214. func New(status int, format string, args ...interface{}) error {
  215. msg := fmt.Sprintf(format, args...)
  216. return &Error{
  217. Status: status,
  218. Msg: formatMessage(status, msg),
  219. Err: errors.New(msg),
  220. }
  221. }
  222. // NewError creates a new http error with the given error and message.
  223. func NewError(status int, err error, format string, args ...interface{}) error {
  224. var e *Error
  225. if errors.As(err, &e) {
  226. return err
  227. }
  228. msg := fmt.Sprintf(format, args...)
  229. var ste log.StackTracedError
  230. if !errors.As(err, &ste) {
  231. err = errors.Wrap(err, msg)
  232. }
  233. return &Error{
  234. Status: status,
  235. Msg: formatMessage(status, msg),
  236. Err: err,
  237. }
  238. }
  239. // NewErr returns a new Error. If the given error implements the StatusCoder
  240. // interface we will ignore the given status.
  241. func NewErr(status int, err error, opts ...Option) error {
  242. var e *Error
  243. if !errors.As(err, &e) {
  244. var ste render.StatusCodedError
  245. if errors.As(err, &ste) {
  246. e = &Error{Status: ste.StatusCode(), Err: err}
  247. } else {
  248. e = &Error{Status: status, Err: err}
  249. }
  250. }
  251. for _, o := range opts {
  252. o(e)
  253. }
  254. return e
  255. }
  256. // Errorf creates a new error using the given format and status code.
  257. func Errorf(code int, format string, args ...interface{}) error {
  258. as, opts := splitOptionArgs(args)
  259. opts = append(opts, withDefaultMessage(NotImplementedDefaultMsg))
  260. e := &Error{Status: code, Err: fmt.Errorf(format, as...)}
  261. for _, o := range opts {
  262. o(e)
  263. }
  264. return e
  265. }
  266. // ApplyOptions applies the given options to the error if is the type *Error.
  267. // TODO(mariano): try to get rid of this.
  268. func ApplyOptions(err error, opts ...interface{}) error {
  269. var e *Error
  270. if errors.As(err, &e) {
  271. _, o := splitOptionArgs(opts)
  272. for _, fn := range o {
  273. fn(e)
  274. }
  275. }
  276. return err
  277. }
  278. // InternalServer creates a 500 error with the given format and arguments.
  279. func InternalServer(format string, args ...interface{}) error {
  280. args = append(args, withDefaultMessage(InternalServerErrorDefaultMsg))
  281. return Errorf(http.StatusInternalServerError, format, args...)
  282. }
  283. // InternalServerErr returns a 500 error with the given error.
  284. func InternalServerErr(err error, opts ...Option) error {
  285. opts = append(opts, withDefaultMessage(InternalServerErrorDefaultMsg))
  286. return NewErr(http.StatusInternalServerError, err, opts...)
  287. }
  288. // NotImplemented creates a 501 error with the given format and arguments.
  289. func NotImplemented(format string, args ...interface{}) error {
  290. args = append(args, withDefaultMessage(NotImplementedDefaultMsg))
  291. return Errorf(http.StatusNotImplemented, format, args...)
  292. }
  293. // NotImplementedErr returns a 501 error with the given error.
  294. func NotImplementedErr(err error, opts ...Option) error {
  295. opts = append(opts, withDefaultMessage(NotImplementedDefaultMsg))
  296. return NewErr(http.StatusNotImplemented, err, opts...)
  297. }
  298. // BadRequest creates a 400 error with the given format and arguments.
  299. func BadRequest(format string, args ...interface{}) error {
  300. return New(http.StatusBadRequest, format, args...)
  301. }
  302. // BadRequestErr returns an 400 error with the given error.
  303. func BadRequestErr(err error, format string, args ...interface{}) error {
  304. return NewError(http.StatusBadRequest, err, format, args...)
  305. }
  306. // Unauthorized creates a 401 error with the given format and arguments.
  307. func Unauthorized(format string, args ...interface{}) error {
  308. args = append(args, withDefaultMessage(UnauthorizedDefaultMsg))
  309. return Errorf(http.StatusUnauthorized, format, args...)
  310. }
  311. // UnauthorizedErr returns an 401 error with the given error.
  312. func UnauthorizedErr(err error, opts ...Option) error {
  313. opts = append(opts, withDefaultMessage(UnauthorizedDefaultMsg))
  314. return NewErr(http.StatusUnauthorized, err, opts...)
  315. }
  316. // Forbidden creates a 403 error with the given format and arguments.
  317. func Forbidden(format string, args ...interface{}) error {
  318. return New(http.StatusForbidden, format, args...)
  319. }
  320. // ForbiddenErr returns an 403 error with the given error.
  321. func ForbiddenErr(err error, format string, args ...interface{}) error {
  322. return NewError(http.StatusForbidden, err, format, args...)
  323. }
  324. // NotFound creates a 404 error with the given format and arguments.
  325. func NotFound(format string, args ...interface{}) error {
  326. args = append(args, withDefaultMessage(NotFoundDefaultMsg))
  327. return Errorf(http.StatusNotFound, format, args...)
  328. }
  329. // NotFoundErr returns an 404 error with the given error.
  330. func NotFoundErr(err error, opts ...Option) error {
  331. opts = append(opts, withDefaultMessage(NotFoundDefaultMsg))
  332. return NewErr(http.StatusNotFound, err, opts...)
  333. }
  334. // UnexpectedErr will be used when the certificate authority makes an outgoing
  335. // request and receives an unhandled status code.
  336. func UnexpectedErr(code int, err error, opts ...Option) error {
  337. opts = append(opts, withDefaultMessage("The certificate authority received an "+
  338. "unexpected HTTP status code - '%d'. "+seeLogs, code))
  339. return NewErr(code, err, opts...)
  340. }