account.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. package api
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "net/http"
  6. "github.com/go-chi/chi"
  7. "github.com/smallstep/certificates/acme"
  8. "github.com/smallstep/certificates/api/render"
  9. "github.com/smallstep/certificates/logging"
  10. )
  11. // NewAccountRequest represents the payload for a new account request.
  12. type NewAccountRequest struct {
  13. Contact []string `json:"contact"`
  14. OnlyReturnExisting bool `json:"onlyReturnExisting"`
  15. TermsOfServiceAgreed bool `json:"termsOfServiceAgreed"`
  16. ExternalAccountBinding *ExternalAccountBinding `json:"externalAccountBinding,omitempty"`
  17. }
  18. func validateContacts(cs []string) error {
  19. for _, c := range cs {
  20. if c == "" {
  21. return acme.NewError(acme.ErrorMalformedType, "contact cannot be empty string")
  22. }
  23. }
  24. return nil
  25. }
  26. // Validate validates a new-account request body.
  27. func (n *NewAccountRequest) Validate() error {
  28. if n.OnlyReturnExisting && len(n.Contact) > 0 {
  29. return acme.NewError(acme.ErrorMalformedType, "incompatible input; onlyReturnExisting must be alone")
  30. }
  31. return validateContacts(n.Contact)
  32. }
  33. // UpdateAccountRequest represents an update-account request.
  34. type UpdateAccountRequest struct {
  35. Contact []string `json:"contact"`
  36. Status acme.Status `json:"status"`
  37. }
  38. // Validate validates a update-account request body.
  39. func (u *UpdateAccountRequest) Validate() error {
  40. switch {
  41. case len(u.Status) > 0 && len(u.Contact) > 0:
  42. return acme.NewError(acme.ErrorMalformedType, "incompatible input; contact and "+
  43. "status updates are mutually exclusive")
  44. case len(u.Contact) > 0:
  45. if err := validateContacts(u.Contact); err != nil {
  46. return err
  47. }
  48. return nil
  49. case len(u.Status) > 0:
  50. if u.Status != acme.StatusDeactivated {
  51. return acme.NewError(acme.ErrorMalformedType, "cannot update account "+
  52. "status to %s, only deactivated", u.Status)
  53. }
  54. return nil
  55. default:
  56. // According to the ACME spec (https://tools.ietf.org/html/rfc8555#section-7.3.2)
  57. // accountUpdate should ignore any fields not recognized by the server.
  58. return nil
  59. }
  60. }
  61. // NewAccount is the handler resource for creating new ACME accounts.
  62. func NewAccount(w http.ResponseWriter, r *http.Request) {
  63. ctx := r.Context()
  64. db := acme.MustDatabaseFromContext(ctx)
  65. linker := acme.MustLinkerFromContext(ctx)
  66. payload, err := payloadFromContext(ctx)
  67. if err != nil {
  68. render.Error(w, err)
  69. return
  70. }
  71. var nar NewAccountRequest
  72. if err := json.Unmarshal(payload.value, &nar); err != nil {
  73. render.Error(w, acme.WrapError(acme.ErrorMalformedType, err,
  74. "failed to unmarshal new-account request payload"))
  75. return
  76. }
  77. if err := nar.Validate(); err != nil {
  78. render.Error(w, err)
  79. return
  80. }
  81. prov, err := acmeProvisionerFromContext(ctx)
  82. if err != nil {
  83. render.Error(w, err)
  84. return
  85. }
  86. httpStatus := http.StatusCreated
  87. acc, err := accountFromContext(ctx)
  88. if err != nil {
  89. var acmeErr *acme.Error
  90. if !errors.As(err, &acmeErr) || acmeErr.Status != http.StatusBadRequest {
  91. // Something went wrong ...
  92. render.Error(w, err)
  93. return
  94. }
  95. // Account does not exist //
  96. if nar.OnlyReturnExisting {
  97. render.Error(w, acme.NewError(acme.ErrorAccountDoesNotExistType,
  98. "account does not exist"))
  99. return
  100. }
  101. jwk, err := jwkFromContext(ctx)
  102. if err != nil {
  103. render.Error(w, err)
  104. return
  105. }
  106. eak, err := validateExternalAccountBinding(ctx, &nar)
  107. if err != nil {
  108. render.Error(w, err)
  109. return
  110. }
  111. acc = &acme.Account{
  112. Key: jwk,
  113. Contact: nar.Contact,
  114. Status: acme.StatusValid,
  115. }
  116. if err := db.CreateAccount(ctx, acc); err != nil {
  117. render.Error(w, acme.WrapErrorISE(err, "error creating account"))
  118. return
  119. }
  120. if eak != nil { // means that we have a (valid) External Account Binding key that should be bound, updated and sent in the response
  121. if err := eak.BindTo(acc); err != nil {
  122. render.Error(w, err)
  123. return
  124. }
  125. if err := db.UpdateExternalAccountKey(ctx, prov.ID, eak); err != nil {
  126. render.Error(w, acme.WrapErrorISE(err, "error updating external account binding key"))
  127. return
  128. }
  129. acc.ExternalAccountBinding = nar.ExternalAccountBinding
  130. }
  131. } else {
  132. // Account exists
  133. httpStatus = http.StatusOK
  134. }
  135. linker.LinkAccount(ctx, acc)
  136. w.Header().Set("Location", linker.GetLink(r.Context(), acme.AccountLinkType, acc.ID))
  137. render.JSONStatus(w, acc, httpStatus)
  138. }
  139. // GetOrUpdateAccount is the api for updating an ACME account.
  140. func GetOrUpdateAccount(w http.ResponseWriter, r *http.Request) {
  141. ctx := r.Context()
  142. db := acme.MustDatabaseFromContext(ctx)
  143. linker := acme.MustLinkerFromContext(ctx)
  144. acc, err := accountFromContext(ctx)
  145. if err != nil {
  146. render.Error(w, err)
  147. return
  148. }
  149. payload, err := payloadFromContext(ctx)
  150. if err != nil {
  151. render.Error(w, err)
  152. return
  153. }
  154. // If PostAsGet just respond with the account, otherwise process like a
  155. // normal Post request.
  156. if !payload.isPostAsGet {
  157. var uar UpdateAccountRequest
  158. if err := json.Unmarshal(payload.value, &uar); err != nil {
  159. render.Error(w, acme.WrapError(acme.ErrorMalformedType, err,
  160. "failed to unmarshal new-account request payload"))
  161. return
  162. }
  163. if err := uar.Validate(); err != nil {
  164. render.Error(w, err)
  165. return
  166. }
  167. if len(uar.Status) > 0 || len(uar.Contact) > 0 {
  168. if len(uar.Status) > 0 {
  169. acc.Status = uar.Status
  170. } else if len(uar.Contact) > 0 {
  171. acc.Contact = uar.Contact
  172. }
  173. if err := db.UpdateAccount(ctx, acc); err != nil {
  174. render.Error(w, acme.WrapErrorISE(err, "error updating account"))
  175. return
  176. }
  177. }
  178. }
  179. linker.LinkAccount(ctx, acc)
  180. w.Header().Set("Location", linker.GetLink(ctx, acme.AccountLinkType, acc.ID))
  181. render.JSON(w, acc)
  182. }
  183. func logOrdersByAccount(w http.ResponseWriter, oids []string) {
  184. if rl, ok := w.(logging.ResponseLogger); ok {
  185. m := map[string]interface{}{
  186. "orders": oids,
  187. }
  188. rl.WithFields(m)
  189. }
  190. }
  191. // GetOrdersByAccountID ACME api for retrieving the list of order urls belonging to an account.
  192. func GetOrdersByAccountID(w http.ResponseWriter, r *http.Request) {
  193. ctx := r.Context()
  194. db := acme.MustDatabaseFromContext(ctx)
  195. linker := acme.MustLinkerFromContext(ctx)
  196. acc, err := accountFromContext(ctx)
  197. if err != nil {
  198. render.Error(w, err)
  199. return
  200. }
  201. accID := chi.URLParam(r, "accID")
  202. if acc.ID != accID {
  203. render.Error(w, acme.NewError(acme.ErrorUnauthorizedType, "account ID '%s' does not match url param '%s'", acc.ID, accID))
  204. return
  205. }
  206. orders, err := db.GetOrdersByAccountID(ctx, acc.ID)
  207. if err != nil {
  208. render.Error(w, err)
  209. return
  210. }
  211. linker.LinkOrdersByAccountID(ctx, orders)
  212. render.JSON(w, orders)
  213. logOrdersByAccount(w, orders)
  214. }