nonce.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package nosql
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "time"
  6. "github.com/pkg/errors"
  7. "github.com/smallstep/certificates/acme"
  8. "github.com/smallstep/nosql"
  9. "github.com/smallstep/nosql/database"
  10. )
  11. // dbNonce contains nonce metadata used in the ACME protocol.
  12. type dbNonce struct {
  13. ID string
  14. CreatedAt time.Time
  15. DeletedAt time.Time
  16. }
  17. // CreateNonce creates, stores, and returns an ACME replay-nonce.
  18. // Implements the acme.DB interface.
  19. func (db *DB) CreateNonce(ctx context.Context) (acme.Nonce, error) {
  20. _id, err := randID()
  21. if err != nil {
  22. return "", err
  23. }
  24. id := base64.RawURLEncoding.EncodeToString([]byte(_id))
  25. n := &dbNonce{
  26. ID: id,
  27. CreatedAt: clock.Now(),
  28. }
  29. if err = db.save(ctx, id, n, nil, "nonce", nonceTable); err != nil {
  30. return "", err
  31. }
  32. return acme.Nonce(id), nil
  33. }
  34. // DeleteNonce verifies that the nonce is valid (by checking if it exists),
  35. // and if so, consumes the nonce resource by deleting it from the database.
  36. func (db *DB) DeleteNonce(ctx context.Context, nonce acme.Nonce) error {
  37. err := db.db.Update(&database.Tx{
  38. Operations: []*database.TxEntry{
  39. {
  40. Bucket: nonceTable,
  41. Key: []byte(nonce),
  42. Cmd: database.Get,
  43. },
  44. {
  45. Bucket: nonceTable,
  46. Key: []byte(nonce),
  47. Cmd: database.Delete,
  48. },
  49. },
  50. })
  51. switch {
  52. case nosql.IsErrNotFound(err):
  53. return acme.NewError(acme.ErrorBadNonceType, "nonce %s not found", string(nonce))
  54. case err != nil:
  55. return errors.Wrapf(err, "error deleting nonce %s", string(nonce))
  56. default:
  57. return nil
  58. }
  59. }