smallstep-certificates/acme/api/account.go

285 lines
8.0 KiB
Go
Raw Normal View History

2019-05-27 00:41:10 +00:00
package api
import (
"bytes"
"context"
2019-05-27 00:41:10 +00:00
"encoding/json"
"net/http"
2021-03-06 21:06:43 +00:00
"github.com/go-chi/chi"
2019-05-27 00:41:10 +00:00
"github.com/smallstep/certificates/acme"
"github.com/smallstep/certificates/api"
"github.com/smallstep/certificates/authority/provisioner"
2019-05-27 00:41:10 +00:00
"github.com/smallstep/certificates/logging"
squarejose "gopkg.in/square/go-jose.v2"
2019-05-27 00:41:10 +00:00
)
// NewAccountRequest represents the payload for a new account request.
type NewAccountRequest struct {
Contact []string `json:"contact"`
OnlyReturnExisting bool `json:"onlyReturnExisting"`
TermsOfServiceAgreed bool `json:"termsOfServiceAgreed"`
ExternalAccountBinding interface{} `json:"externalAccountBinding,omitempty"`
2019-05-27 00:41:10 +00:00
}
func validateContacts(cs []string) error {
for _, c := range cs {
if len(c) == 0 {
2021-03-03 23:16:25 +00:00
return acme.NewError(acme.ErrorMalformedType, "contact cannot be empty string")
2019-05-27 00:41:10 +00:00
}
}
return nil
}
// Validate validates a new-account request body.
func (n *NewAccountRequest) Validate() error {
if n.OnlyReturnExisting && len(n.Contact) > 0 {
2021-03-03 23:16:25 +00:00
return acme.NewError(acme.ErrorMalformedType, "incompatible input; onlyReturnExisting must be alone")
2019-05-27 00:41:10 +00:00
}
return validateContacts(n.Contact)
}
// UpdateAccountRequest represents an update-account request.
type UpdateAccountRequest struct {
2021-03-05 07:10:46 +00:00
Contact []string `json:"contact"`
Status acme.Status `json:"status"`
2019-05-27 00:41:10 +00:00
}
// Validate validates a update-account request body.
func (u *UpdateAccountRequest) Validate() error {
switch {
case len(u.Status) > 0 && len(u.Contact) > 0:
2021-03-03 23:16:25 +00:00
return acme.NewError(acme.ErrorMalformedType, "incompatible input; contact and "+
"status updates are mutually exclusive")
2019-05-27 00:41:10 +00:00
case len(u.Contact) > 0:
if err := validateContacts(u.Contact); err != nil {
return err
}
return nil
case len(u.Status) > 0:
2021-03-05 07:10:46 +00:00
if u.Status != acme.StatusDeactivated {
2021-03-03 23:16:25 +00:00
return acme.NewError(acme.ErrorMalformedType, "cannot update account "+
"status to %s, only deactivated", u.Status)
2019-05-27 00:41:10 +00:00
}
return nil
default:
// According to the ACME spec (https://tools.ietf.org/html/rfc8555#section-7.3.2)
// accountUpdate should ignore any fields not recognized by the server.
return nil
2019-05-27 00:41:10 +00:00
}
}
// NewAccount is the handler resource for creating new ACME accounts.
func (h *Handler) NewAccount(w http.ResponseWriter, r *http.Request) {
2021-03-05 07:14:56 +00:00
ctx := r.Context()
payload, err := payloadFromContext(ctx)
2019-05-27 00:41:10 +00:00
if err != nil {
api.WriteError(w, err)
return
}
var nar NewAccountRequest
if err := json.Unmarshal(payload.value, &nar); err != nil {
2021-03-05 07:10:46 +00:00
api.WriteError(w, acme.WrapError(acme.ErrorMalformedType, err,
2021-03-03 23:16:25 +00:00
"failed to unmarshal new-account request payload"))
2019-05-27 00:41:10 +00:00
return
}
if err := nar.Validate(); err != nil {
api.WriteError(w, err)
return
}
if err := h.validateExternalAccountBinding(ctx, &nar); err != nil {
api.WriteError(w, err)
return
}
// TODO: link account to the key when created; mark boundat timestamp
// TODO: return the externalAccountBinding field (should contain same info) if new account created
2019-05-27 00:41:10 +00:00
httpStatus := http.StatusCreated
2021-03-05 07:10:46 +00:00
acc, err := accountFromContext(r.Context())
2019-05-27 00:41:10 +00:00
if err != nil {
acmeErr, ok := err.(*acme.Error)
if !ok || acmeErr.Status != http.StatusBadRequest {
2019-05-27 00:41:10 +00:00
// Something went wrong ...
api.WriteError(w, err)
return
}
// Account does not exist //
if nar.OnlyReturnExisting {
2021-03-03 23:16:25 +00:00
api.WriteError(w, acme.NewError(acme.ErrorAccountDoesNotExistType,
"account does not exist"))
2019-05-27 00:41:10 +00:00
return
}
2021-03-05 07:14:56 +00:00
jwk, err := jwkFromContext(ctx)
2019-05-27 00:41:10 +00:00
if err != nil {
api.WriteError(w, err)
return
}
acc = &acme.Account{
2019-05-27 00:41:10 +00:00
Key: jwk,
Contact: nar.Contact,
2021-03-01 06:49:20 +00:00
Status: acme.StatusValid,
2021-03-05 07:10:46 +00:00
}
2021-03-05 07:14:56 +00:00
if err := h.db.CreateAccount(ctx, acc); err != nil {
2021-03-05 07:10:46 +00:00
api.WriteError(w, acme.WrapErrorISE(err, "error creating account"))
2019-05-27 00:41:10 +00:00
return
}
} else {
// Account exists //
httpStatus = http.StatusOK
}
2021-03-05 07:10:46 +00:00
h.linker.LinkAccount(ctx, acc)
w.Header().Set("Location", h.linker.GetLink(r.Context(), AccountLinkType, acc.ID))
2019-05-27 00:41:10 +00:00
api.JSONStatus(w, acc, httpStatus)
}
// GetOrUpdateAccount is the api for updating an ACME account.
func (h *Handler) GetOrUpdateAccount(w http.ResponseWriter, r *http.Request) {
2021-03-05 07:14:56 +00:00
ctx := r.Context()
acc, err := accountFromContext(ctx)
2019-05-27 00:41:10 +00:00
if err != nil {
api.WriteError(w, err)
return
}
2021-03-05 07:14:56 +00:00
payload, err := payloadFromContext(ctx)
2019-05-27 00:41:10 +00:00
if err != nil {
api.WriteError(w, err)
return
}
// If PostAsGet just respond with the account, otherwise process like a
// normal Post request.
2019-05-27 00:41:10 +00:00
if !payload.isPostAsGet {
var uar UpdateAccountRequest
if err := json.Unmarshal(payload.value, &uar); err != nil {
2021-03-05 07:10:46 +00:00
api.WriteError(w, acme.WrapError(acme.ErrorMalformedType, err,
2021-03-03 23:16:25 +00:00
"failed to unmarshal new-account request payload"))
2019-05-27 00:41:10 +00:00
return
}
if err := uar.Validate(); err != nil {
api.WriteError(w, err)
return
}
2021-03-12 08:16:48 +00:00
if len(uar.Status) > 0 || len(uar.Contact) > 0 {
if len(uar.Status) > 0 {
acc.Status = uar.Status
} else if len(uar.Contact) > 0 {
acc.Contact = uar.Contact
}
if err := h.db.UpdateAccount(ctx, acc); err != nil {
api.WriteError(w, acme.WrapErrorISE(err, "error updating account"))
return
}
2019-05-27 00:41:10 +00:00
}
}
2021-03-05 07:10:46 +00:00
h.linker.LinkAccount(ctx, acc)
w.Header().Set("Location", h.linker.GetLink(ctx, AccountLinkType, acc.ID))
2019-05-27 00:41:10 +00:00
api.JSON(w, acc)
}
func logOrdersByAccount(w http.ResponseWriter, oids []string) {
if rl, ok := w.(logging.ResponseLogger); ok {
m := map[string]interface{}{
"orders": oids,
}
rl.WithFields(m)
}
}
// GetOrdersByAccountID ACME api for retrieving the list of order urls belonging to an account.
func (h *Handler) GetOrdersByAccountID(w http.ResponseWriter, r *http.Request) {
2021-03-06 21:06:43 +00:00
ctx := r.Context()
acc, err := accountFromContext(ctx)
if err != nil {
api.WriteError(w, err)
return
}
accID := chi.URLParam(r, "accID")
if acc.ID != accID {
api.WriteError(w, acme.NewError(acme.ErrorUnauthorizedType, "account ID '%s' does not match url param '%s'", acc.ID, accID))
return
}
orders, err := h.db.GetOrdersByAccountID(ctx, acc.ID)
if err != nil {
api.WriteError(w, err)
return
}
h.linker.LinkOrdersByAccountID(ctx, orders)
api.JSON(w, orders)
logOrdersByAccount(w, orders)
2019-05-27 00:41:10 +00:00
}
// validateExternalAccountBinding validates the externalAccountBinding property in a call to new-account
func (h *Handler) validateExternalAccountBinding(ctx context.Context, nar *NewAccountRequest) error {
prov, err := provisionerFromContext(ctx)
if err != nil {
return err
}
acmeProv, ok := prov.(*provisioner.ACME) // TODO: rewrite into providing configuration via function on acme.Provisioner
if !ok || acmeProv == nil {
return acme.NewErrorISE("provisioner in context is not an ACME provisioner")
}
shouldSkipAccountBindingValidation := !acmeProv.RequireEAB
if shouldSkipAccountBindingValidation {
return nil
}
if nar.ExternalAccountBinding == nil {
return acme.NewError(acme.ErrorExternalAccountRequiredType, "no external account binding provided")
}
eabJSONBytes, err := json.Marshal(nar.ExternalAccountBinding)
if err != nil {
return acme.WrapErrorISE(err, "error marshalling externalAccountBinding")
}
eabJWS, err := squarejose.ParseSigned(string(eabJSONBytes))
if err != nil {
return acme.WrapErrorISE(err, "error parsing externalAccountBinding jws")
}
// TODO: verify supported algorithms against the incoming alg (and corresponding settings)?
// TODO: implement strategy pattern to allow for different ways of verification (i.e. webhook call) based on configuration
keyID := eabJWS.Signatures[0].Protected.KeyID
externalAccountKey, err := h.db.GetExternalAccountKey(ctx, keyID)
if err != nil {
return acme.WrapErrorISE(err, "error retrieving external account key")
}
payload, err := eabJWS.Verify(externalAccountKey.KeyBytes)
if err != nil {
return acme.WrapErrorISE(err, "error verifying externalAccountBinding signature")
}
jwk, err := jwkFromContext(ctx)
if err != nil {
return err
}
jwkJSONBytes, err := jwk.MarshalJSON()
if err != nil {
return acme.WrapErrorISE(err, "error marshaling jwk")
}
if bytes.Equal(payload, jwkJSONBytes) {
acme.NewError(acme.ErrorMalformedType, "keys in jws and eab payload do not match") // TODO: decide ACME error type to use
}
return nil
}