account.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. package api
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "net/http"
  7. "slices"
  8. "github.com/go-chi/chi/v5"
  9. "github.com/smallstep/certificates/acme"
  10. "github.com/smallstep/certificates/api/render"
  11. "github.com/smallstep/certificates/logging"
  12. )
  13. // NewAccountRequest represents the payload for a new account request.
  14. type NewAccountRequest struct {
  15. Contact []string `json:"contact"`
  16. OnlyReturnExisting bool `json:"onlyReturnExisting"`
  17. TermsOfServiceAgreed bool `json:"termsOfServiceAgreed"`
  18. ExternalAccountBinding *ExternalAccountBinding `json:"externalAccountBinding,omitempty"`
  19. }
  20. func validateContacts(cs []string) error {
  21. if slices.Contains(cs, "") {
  22. return acme.NewError(acme.ErrorMalformedType, "contact cannot be empty string")
  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. // getAccountLocationPath returns the current account URL location.
  62. // Returned location will be of the form: https://<ca-url>/acme/<provisioner>/account/<accID>
  63. func getAccountLocationPath(ctx context.Context, linker acme.Linker, accID string) string {
  64. return linker.GetLink(ctx, acme.AccountLinkType, accID)
  65. }
  66. // NewAccount is the handler resource for creating new ACME accounts.
  67. func NewAccount(w http.ResponseWriter, r *http.Request) {
  68. ctx := r.Context()
  69. db := acme.MustDatabaseFromContext(ctx)
  70. linker := acme.MustLinkerFromContext(ctx)
  71. payload, err := payloadFromContext(ctx)
  72. if err != nil {
  73. render.Error(w, r, err)
  74. return
  75. }
  76. var nar NewAccountRequest
  77. if err := json.Unmarshal(payload.value, &nar); err != nil {
  78. render.Error(w, r, acme.WrapError(acme.ErrorMalformedType, err,
  79. "failed to unmarshal new-account request payload"))
  80. return
  81. }
  82. if err := nar.Validate(); err != nil {
  83. render.Error(w, r, err)
  84. return
  85. }
  86. prov, err := acmeProvisionerFromContext(ctx)
  87. if err != nil {
  88. render.Error(w, r, err)
  89. return
  90. }
  91. httpStatus := http.StatusCreated
  92. acc, err := accountFromContext(ctx)
  93. if err != nil {
  94. var acmeErr *acme.Error
  95. if !errors.As(err, &acmeErr) || acmeErr.Status != http.StatusBadRequest {
  96. // Something went wrong ...
  97. render.Error(w, r, err)
  98. return
  99. }
  100. // Account does not exist //
  101. if nar.OnlyReturnExisting {
  102. render.Error(w, r, acme.NewError(acme.ErrorAccountDoesNotExistType,
  103. "account does not exist"))
  104. return
  105. }
  106. jwk, err := jwkFromContext(ctx)
  107. if err != nil {
  108. render.Error(w, r, err)
  109. return
  110. }
  111. eak, err := validateExternalAccountBinding(ctx, &nar)
  112. if err != nil {
  113. render.Error(w, r, err)
  114. return
  115. }
  116. acc = &acme.Account{
  117. Key: jwk,
  118. Contact: nar.Contact,
  119. Status: acme.StatusValid,
  120. LocationPrefix: getAccountLocationPath(ctx, linker, ""),
  121. ProvisionerID: prov.ID,
  122. ProvisionerName: prov.Name,
  123. }
  124. if err := db.CreateAccount(ctx, acc); err != nil {
  125. render.Error(w, r, 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, r, err)
  131. return
  132. }
  133. if err := db.UpdateExternalAccountKey(ctx, prov.ID, eak); err != nil {
  134. render.Error(w, r, 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, r, 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, r, err)
  155. return
  156. }
  157. payload, err := payloadFromContext(ctx)
  158. if err != nil {
  159. render.Error(w, r, 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, r, 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, r, 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, r, 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, r, acc)
  190. }
  191. func logOrdersByAccount(w http.ResponseWriter, oids []string) {
  192. if rl, ok := w.(logging.ResponseLogger); ok {
  193. m := map[string]any{
  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, r, err)
  207. return
  208. }
  209. accID := chi.URLParam(r, "accID")
  210. if acc.ID != accID {
  211. render.Error(w, r, 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, r, err)
  217. return
  218. }
  219. linker.LinkOrdersByAccountID(ctx, orders)
  220. render.JSON(w, r, orders)
  221. logOrdersByAccount(w, orders)
  222. }