nonce.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 := base64.RawURLEncoding.EncodeToString([]byte(randID()))
  21. n := &dbNonce{
  22. ID: id,
  23. CreatedAt: clock.Now(),
  24. }
  25. if err := db.save(ctx, id, n, nil, "nonce", nonceTable); err != nil {
  26. return "", err
  27. }
  28. return acme.Nonce(id), nil
  29. }
  30. // DeleteNonce verifies that the nonce is valid (by checking if it exists),
  31. // and if so, consumes the nonce resource by deleting it from the database.
  32. func (db *DB) DeleteNonce(_ context.Context, nonce acme.Nonce) error {
  33. err := db.db.Update(&database.Tx{
  34. Operations: []*database.TxEntry{
  35. {
  36. Bucket: nonceTable,
  37. Key: []byte(nonce),
  38. Cmd: database.Get,
  39. },
  40. {
  41. Bucket: nonceTable,
  42. Key: []byte(nonce),
  43. Cmd: database.Delete,
  44. },
  45. },
  46. })
  47. switch {
  48. case nosql.IsErrNotFound(err):
  49. return acme.NewError(acme.ErrorBadNonceType, "nonce %s not found", string(nonce))
  50. case err != nil:
  51. return errors.Wrapf(err, "error deleting nonce %s", string(nonce))
  52. default:
  53. return nil
  54. }
  55. }