nosql.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package nosql
  2. import (
  3. "context"
  4. "encoding/json"
  5. "time"
  6. "github.com/pkg/errors"
  7. nosqlDB "github.com/smallstep/nosql"
  8. "go.step.sm/crypto/randutil"
  9. )
  10. var (
  11. accountTable = []byte("acme_accounts")
  12. accountByKeyIDTable = []byte("acme_keyID_accountID_index")
  13. authzTable = []byte("acme_authzs")
  14. challengeTable = []byte("acme_challenges")
  15. nonceTable = []byte("nonces")
  16. orderTable = []byte("acme_orders")
  17. ordersByAccountIDTable = []byte("acme_account_orders_index")
  18. certTable = []byte("acme_certs")
  19. )
  20. // DB is a struct that implements the AcmeDB interface.
  21. type DB struct {
  22. db nosqlDB.DB
  23. }
  24. // New configures and returns a new ACME DB backend implemented using a nosql DB.
  25. func New(db nosqlDB.DB) (*DB, error) {
  26. tables := [][]byte{accountTable, accountByKeyIDTable, authzTable,
  27. challengeTable, nonceTable, orderTable, ordersByAccountIDTable, certTable}
  28. for _, b := range tables {
  29. if err := db.CreateTable(b); err != nil {
  30. return nil, errors.Wrapf(err, "error creating table %s",
  31. string(b))
  32. }
  33. }
  34. return &DB{db}, nil
  35. }
  36. // save writes the new data to the database, overwriting the old data if it
  37. // existed.
  38. func (db *DB) save(ctx context.Context, id string, nu, old interface{}, typ string, table []byte) error {
  39. var (
  40. err error
  41. newB []byte
  42. )
  43. if nu == nil {
  44. newB = nil
  45. } else {
  46. newB, err = json.Marshal(nu)
  47. if err != nil {
  48. return errors.Wrapf(err, "error marshaling acme type: %s, value: %v", typ, nu)
  49. }
  50. }
  51. var oldB []byte
  52. if old == nil {
  53. oldB = nil
  54. } else {
  55. oldB, err = json.Marshal(old)
  56. if err != nil {
  57. return errors.Wrapf(err, "error marshaling acme type: %s, value: %v", typ, old)
  58. }
  59. }
  60. _, swapped, err := db.db.CmpAndSwap(table, []byte(id), oldB, newB)
  61. switch {
  62. case err != nil:
  63. return errors.Wrapf(err, "error saving acme %s", typ)
  64. case !swapped:
  65. return errors.Errorf("error saving acme %s; changed since last read", typ)
  66. default:
  67. return nil
  68. }
  69. }
  70. var idLen = 32
  71. func randID() (val string, err error) {
  72. val, err = randutil.Alphanumeric(idLen)
  73. if err != nil {
  74. return "", errors.Wrap(err, "error generating random alphanumeric ID")
  75. }
  76. return val, nil
  77. }
  78. // Clock that returns time in UTC rounded to seconds.
  79. type Clock struct{}
  80. // Now returns the UTC time rounded to seconds.
  81. func (c *Clock) Now() time.Time {
  82. return time.Now().UTC().Truncate(time.Second)
  83. }
  84. var clock = new(Clock)