4
0

account.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. package api
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "net/http"
  7. "github.com/go-chi/chi/v5"
  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, r, err)
  75. return
  76. }
  77. var nar NewAccountRequest
  78. if err := json.Unmarshal(payload.value, &nar); err != nil {
  79. render.Error(w, r, 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, r, err)
  85. return
  86. }
  87. prov, err := acmeProvisionerFromContext(ctx)
  88. if err != nil {
  89. render.Error(w, r, 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, r, err)
  99. return
  100. }
  101. // Account does not exist //
  102. if nar.OnlyReturnExisting {
  103. render.Error(w, r, 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, r, err)
  110. return
  111. }
  112. eak, err := validateExternalAccountBinding(ctx, &nar)
  113. if err != nil {
  114. render.Error(w, r, 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. ProvisionerID: prov.ID,
  123. ProvisionerName: prov.Name,
  124. }
  125. if err := db.CreateAccount(ctx, acc); err != nil {
  126. render.Error(w, r, acme.WrapErrorISE(err, "error creating account"))
  127. return
  128. }
  129. if eak != nil { // means that we have a (valid) External Account Binding key that should be bound, updated and sent in the response
  130. if err := eak.BindTo(acc); err != nil {
  131. render.Error(w, r, err)
  132. return
  133. }
  134. if err := db.UpdateExternalAccountKey(ctx, prov.ID, eak); err != nil {
  135. render.Error(w, r, acme.WrapErrorISE(err, "error updating external account binding key"))
  136. return
  137. }
  138. acc.ExternalAccountBinding = nar.ExternalAccountBinding
  139. }
  140. } else {
  141. // Account exists
  142. httpStatus = http.StatusOK
  143. }
  144. linker.LinkAccount(ctx, acc)
  145. w.Header().Set("Location", getAccountLocationPath(ctx, linker, acc.ID))
  146. render.JSONStatus(w, r, acc, httpStatus)
  147. }
  148. // GetOrUpdateAccount is the api for updating an ACME account.
  149. func GetOrUpdateAccount(w http.ResponseWriter, r *http.Request) {
  150. ctx := r.Context()
  151. db := acme.MustDatabaseFromContext(ctx)
  152. linker := acme.MustLinkerFromContext(ctx)
  153. acc, err := accountFromContext(ctx)
  154. if err != nil {
  155. render.Error(w, r, err)
  156. return
  157. }
  158. payload, err := payloadFromContext(ctx)
  159. if err != nil {
  160. render.Error(w, r, err)
  161. return
  162. }
  163. // If PostAsGet just respond with the account, otherwise process like a
  164. // normal Post request.
  165. if !payload.isPostAsGet {
  166. var uar UpdateAccountRequest
  167. if err := json.Unmarshal(payload.value, &uar); err != nil {
  168. render.Error(w, r, acme.WrapError(acme.ErrorMalformedType, err,
  169. "failed to unmarshal new-account request payload"))
  170. return
  171. }
  172. if err := uar.Validate(); err != nil {
  173. render.Error(w, r, err)
  174. return
  175. }
  176. if len(uar.Status) > 0 || len(uar.Contact) > 0 {
  177. if len(uar.Status) > 0 {
  178. acc.Status = uar.Status
  179. } else if len(uar.Contact) > 0 {
  180. acc.Contact = uar.Contact
  181. }
  182. if err := db.UpdateAccount(ctx, acc); err != nil {
  183. render.Error(w, r, acme.WrapErrorISE(err, "error updating account"))
  184. return
  185. }
  186. }
  187. }
  188. linker.LinkAccount(ctx, acc)
  189. w.Header().Set("Location", linker.GetLink(ctx, acme.AccountLinkType, acc.ID))
  190. render.JSON(w, r, acc)
  191. }
  192. func logOrdersByAccount(w http.ResponseWriter, oids []string) {
  193. if rl, ok := w.(logging.ResponseLogger); ok {
  194. m := map[string]interface{}{
  195. "orders": oids,
  196. }
  197. rl.WithFields(m)
  198. }
  199. }
  200. // GetOrdersByAccountID ACME api for retrieving the list of order urls belonging to an account.
  201. func GetOrdersByAccountID(w http.ResponseWriter, r *http.Request) {
  202. ctx := r.Context()
  203. db := acme.MustDatabaseFromContext(ctx)
  204. linker := acme.MustLinkerFromContext(ctx)
  205. acc, err := accountFromContext(ctx)
  206. if err != nil {
  207. render.Error(w, r, err)
  208. return
  209. }
  210. accID := chi.URLParam(r, "accID")
  211. if acc.ID != accID {
  212. render.Error(w, r, acme.NewError(acme.ErrorUnauthorizedType, "account ID '%s' does not match url param '%s'", acc.ID, accID))
  213. return
  214. }
  215. orders, err := db.GetOrdersByAccountID(ctx, acc.ID)
  216. if err != nil {
  217. render.Error(w, r, err)
  218. return
  219. }
  220. linker.LinkOrdersByAccountID(ctx, orders)
  221. render.JSON(w, r, orders)
  222. logOrdersByAccount(w, orders)
  223. }