4
0

error.go 11 KB

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