account.go 6.9 KB

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