certificates/acme/db/nosql/nonce.go

67 lines
1.5 KiB
Go
Raw Normal View History

2021-02-25 18:24:24 +00:00
package nosql
import (
2021-03-01 06:49:20 +00:00
"context"
2021-02-25 18:24:24 +00:00
"encoding/base64"
"time"
"github.com/pkg/errors"
2021-03-01 06:49:20 +00:00
"github.com/smallstep/certificates/acme"
"github.com/smallstep/nosql"
2021-03-29 19:04:14 +00:00
"github.com/smallstep/nosql/database"
2021-02-25 18:24:24 +00:00
)
// dbNonce contains nonce metadata used in the ACME protocol.
type dbNonce struct {
ID string
CreatedAt time.Time
DeletedAt time.Time
}
2021-02-25 18:24:24 +00:00
// CreateNonce creates, stores, and returns an ACME replay-nonce.
// Implements the acme.DB interface.
2021-03-01 06:49:20 +00:00
func (db *DB) CreateNonce(ctx context.Context) (acme.Nonce, error) {
2021-02-25 18:24:24 +00:00
_id, err := randID()
if err != nil {
2021-03-01 06:49:20 +00:00
return "", err
2021-02-25 18:24:24 +00:00
}
id := base64.RawURLEncoding.EncodeToString([]byte(_id))
n := &dbNonce{
ID: id,
CreatedAt: clock.Now(),
2021-02-25 18:24:24 +00:00
}
if err := db.save(ctx, id, n, nil, "nonce", nonceTable); err != nil {
2021-02-28 01:05:37 +00:00
return "", err
2021-02-25 18:24:24 +00:00
}
2021-03-01 06:49:20 +00:00
return acme.Nonce(id), nil
2021-02-25 18:24:24 +00:00
}
// DeleteNonce verifies that the nonce is valid (by checking if it exists),
// and if so, consumes the nonce resource by deleting it from the database.
2023-05-10 06:47:28 +00:00
func (db *DB) DeleteNonce(_ context.Context, nonce acme.Nonce) error {
2021-03-29 19:04:14 +00:00
err := db.db.Update(&database.Tx{
Operations: []*database.TxEntry{
{
Bucket: nonceTable,
Key: []byte(nonce),
Cmd: database.Get,
},
{
Bucket: nonceTable,
Key: []byte(nonce),
Cmd: database.Delete,
},
},
})
2021-02-25 18:24:24 +00:00
2021-03-29 19:04:14 +00:00
switch {
case nosql.IsErrNotFound(err):
return acme.NewError(acme.ErrorBadNonceType, "nonce %s not found", string(nonce))
case err != nil:
return errors.Wrapf(err, "error deleting nonce %s", string(nonce))
default:
return nil
2021-02-25 18:24:24 +00:00
}
}