certificate.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package acme
  2. import (
  3. "crypto/x509"
  4. "encoding/json"
  5. "encoding/pem"
  6. "time"
  7. "github.com/pkg/errors"
  8. "github.com/smallstep/nosql"
  9. )
  10. type certificate struct {
  11. ID string `json:"id"`
  12. Created time.Time `json:"created"`
  13. AccountID string `json:"accountID"`
  14. OrderID string `json:"orderID"`
  15. Leaf []byte `json:"leaf"`
  16. Intermediates []byte `json:"intermediates"`
  17. }
  18. // CertOptions options with which to create and store a cert object.
  19. type CertOptions struct {
  20. AccountID string
  21. OrderID string
  22. Leaf *x509.Certificate
  23. Intermediates []*x509.Certificate
  24. }
  25. func newCert(db nosql.DB, ops CertOptions) (*certificate, error) {
  26. id, err := randID()
  27. if err != nil {
  28. return nil, err
  29. }
  30. leaf := pem.EncodeToMemory(&pem.Block{
  31. Type: "CERTIFICATE",
  32. Bytes: ops.Leaf.Raw,
  33. })
  34. var intermediates []byte
  35. for _, cert := range ops.Intermediates {
  36. intermediates = append(intermediates, pem.EncodeToMemory(&pem.Block{
  37. Type: "CERTIFICATE",
  38. Bytes: cert.Raw,
  39. })...)
  40. }
  41. cert := &certificate{
  42. ID: id,
  43. AccountID: ops.AccountID,
  44. OrderID: ops.OrderID,
  45. Leaf: leaf,
  46. Intermediates: intermediates,
  47. Created: time.Now().UTC(),
  48. }
  49. certB, err := json.Marshal(cert)
  50. if err != nil {
  51. return nil, ServerInternalErr(errors.Wrap(err, "error marshaling certificate"))
  52. }
  53. _, swapped, err := db.CmpAndSwap(certTable, []byte(id), nil, certB)
  54. switch {
  55. case err != nil:
  56. return nil, ServerInternalErr(errors.Wrap(err, "error storing certificate"))
  57. case !swapped:
  58. return nil, ServerInternalErr(errors.New("error storing certificate; " +
  59. "value has changed since last read"))
  60. default:
  61. return cert, nil
  62. }
  63. }
  64. func (c *certificate) toACME(db nosql.DB, dir *directory) ([]byte, error) {
  65. return append(c.Leaf, c.Intermediates...), nil
  66. }
  67. func getCert(db nosql.DB, id string) (*certificate, error) {
  68. b, err := db.Get(certTable, []byte(id))
  69. if nosql.IsErrNotFound(err) {
  70. return nil, MalformedErr(errors.Wrapf(err, "certificate %s not found", id))
  71. } else if err != nil {
  72. return nil, ServerInternalErr(errors.Wrap(err, "error loading certificate"))
  73. }
  74. var cert certificate
  75. if err := json.Unmarshal(b, &cert); err != nil {
  76. return nil, ServerInternalErr(errors.Wrap(err, "error unmarshaling certificate"))
  77. }
  78. return &cert, nil
  79. }