account.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package acme
  2. import (
  3. "crypto"
  4. "encoding/base64"
  5. "encoding/json"
  6. "time"
  7. "go.step.sm/crypto/jose"
  8. )
  9. // Account is a subset of the internal account type containing only those
  10. // attributes required for responses in the ACME protocol.
  11. type Account struct {
  12. ID string `json:"-"`
  13. Key *jose.JSONWebKey `json:"-"`
  14. Contact []string `json:"contact,omitempty"`
  15. Status Status `json:"status"`
  16. OrdersURL string `json:"orders"`
  17. ExternalAccountBinding interface{} `json:"externalAccountBinding,omitempty"`
  18. }
  19. // ToLog enables response logging.
  20. func (a *Account) ToLog() (interface{}, error) {
  21. b, err := json.Marshal(a)
  22. if err != nil {
  23. return nil, WrapErrorISE(err, "error marshaling account for logging")
  24. }
  25. return string(b), nil
  26. }
  27. // IsValid returns true if the Account is valid.
  28. func (a *Account) IsValid() bool {
  29. return Status(a.Status) == StatusValid
  30. }
  31. // KeyToID converts a JWK to a thumbprint.
  32. func KeyToID(jwk *jose.JSONWebKey) (string, error) {
  33. kid, err := jwk.Thumbprint(crypto.SHA256)
  34. if err != nil {
  35. return "", WrapErrorISE(err, "error generating jwk thumbprint")
  36. }
  37. return base64.RawURLEncoding.EncodeToString(kid), nil
  38. }
  39. // ExternalAccountKey is an ACME External Account Binding key.
  40. type ExternalAccountKey struct {
  41. ID string `json:"id"`
  42. ProvisionerID string `json:"provisionerID"`
  43. Reference string `json:"reference"`
  44. AccountID string `json:"-"`
  45. KeyBytes []byte `json:"-"`
  46. CreatedAt time.Time `json:"createdAt"`
  47. BoundAt time.Time `json:"boundAt,omitempty"`
  48. }
  49. // AlreadyBound returns whether this EAK is already bound to
  50. // an ACME Account or not.
  51. func (eak *ExternalAccountKey) AlreadyBound() bool {
  52. return !eak.BoundAt.IsZero()
  53. }
  54. // BindTo binds the EAK to an Account.
  55. // It returns an error if it's already bound.
  56. func (eak *ExternalAccountKey) BindTo(account *Account) error {
  57. if eak.AlreadyBound() {
  58. return NewError(ErrorUnauthorizedType, "external account binding key with id '%s' was already bound to account '%s' on %s", eak.ID, eak.AccountID, eak.BoundAt)
  59. }
  60. eak.AccountID = account.ID
  61. eak.BoundAt = time.Now()
  62. eak.KeyBytes = []byte{} // clearing the key bytes; can only be used once
  63. return nil
  64. }