2017-08-03 17:24:27 +00:00
|
|
|
package cassandra
|
2017-01-07 16:30:25 +00:00
|
|
|
|
|
|
|
import (
|
2018-01-19 06:44:44 +00:00
|
|
|
"context"
|
2017-06-07 14:32:11 +00:00
|
|
|
"crypto/tls"
|
2017-01-07 16:30:25 +00:00
|
|
|
"fmt"
|
2017-06-08 10:58:41 +00:00
|
|
|
"io/ioutil"
|
2017-07-31 14:58:38 +00:00
|
|
|
"net"
|
2017-06-07 09:24:04 +00:00
|
|
|
"strconv"
|
2017-01-07 16:30:25 +00:00
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
|
2019-01-09 00:48:57 +00:00
|
|
|
metrics "github.com/armon/go-metrics"
|
2017-01-07 16:30:25 +00:00
|
|
|
"github.com/gocql/gocql"
|
2021-04-16 21:52:35 +00:00
|
|
|
log "github.com/hashicorp/go-hclog"
|
2019-04-12 21:54:35 +00:00
|
|
|
"github.com/hashicorp/vault/sdk/helper/certutil"
|
|
|
|
"github.com/hashicorp/vault/sdk/physical"
|
2017-01-07 16:30:25 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// CassandraBackend is a physical backend that stores data in Cassandra.
|
|
|
|
type CassandraBackend struct {
|
|
|
|
sess *gocql.Session
|
|
|
|
table string
|
|
|
|
|
|
|
|
logger log.Logger
|
|
|
|
}
|
|
|
|
|
2018-01-20 01:44:24 +00:00
|
|
|
// Verify CassandraBackend satisfies the correct interfaces
|
|
|
|
var _ physical.Backend = (*CassandraBackend)(nil)
|
|
|
|
|
2017-08-03 17:24:27 +00:00
|
|
|
// NewCassandraBackend constructs a Cassandra backend using a pre-existing
|
2017-01-07 16:30:25 +00:00
|
|
|
// keyspace and table.
|
2017-08-03 17:24:27 +00:00
|
|
|
func NewCassandraBackend(conf map[string]string, logger log.Logger) (physical.Backend, error) {
|
2017-01-07 16:30:25 +00:00
|
|
|
splitArray := func(v string) []string {
|
|
|
|
return strings.FieldsFunc(v, func(r rune) bool {
|
|
|
|
return r == ','
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
var (
|
2017-07-31 14:58:38 +00:00
|
|
|
hosts = splitArray(conf["hosts"])
|
|
|
|
port = 9042
|
|
|
|
explicitPort = false
|
|
|
|
keyspace = conf["keyspace"]
|
|
|
|
table = conf["table"]
|
|
|
|
consistency = gocql.LocalQuorum
|
2017-01-07 16:30:25 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
if len(hosts) == 0 {
|
|
|
|
hosts = []string{"localhost"}
|
|
|
|
}
|
2017-07-31 14:58:38 +00:00
|
|
|
for i, hp := range hosts {
|
|
|
|
h, ps, err := net.SplitHostPort(hp)
|
|
|
|
if err != nil {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
p, err := strconv.Atoi(ps)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if explicitPort && p != port {
|
|
|
|
return nil, fmt.Errorf("all hosts must have the same port")
|
|
|
|
}
|
|
|
|
hosts[i], port = h, p
|
|
|
|
explicitPort = true
|
|
|
|
}
|
|
|
|
|
2017-01-07 16:30:25 +00:00
|
|
|
if keyspace == "" {
|
|
|
|
keyspace = "vault"
|
|
|
|
}
|
|
|
|
if table == "" {
|
|
|
|
table = "entries"
|
|
|
|
}
|
|
|
|
if cs, ok := conf["consistency"]; ok {
|
|
|
|
switch cs {
|
|
|
|
case "ANY":
|
|
|
|
consistency = gocql.Any
|
|
|
|
case "ONE":
|
|
|
|
consistency = gocql.One
|
|
|
|
case "TWO":
|
|
|
|
consistency = gocql.Two
|
|
|
|
case "THREE":
|
|
|
|
consistency = gocql.Three
|
|
|
|
case "QUORUM":
|
|
|
|
consistency = gocql.Quorum
|
|
|
|
case "ALL":
|
|
|
|
consistency = gocql.All
|
|
|
|
case "LOCAL_QUORUM":
|
|
|
|
consistency = gocql.LocalQuorum
|
|
|
|
case "EACH_QUORUM":
|
|
|
|
consistency = gocql.EachQuorum
|
|
|
|
case "LOCAL_ONE":
|
|
|
|
consistency = gocql.LocalOne
|
|
|
|
default:
|
|
|
|
return nil, fmt.Errorf("'consistency' must be one of {ANY, ONE, TWO, THREE, QUORUM, ALL, LOCAL_QUORUM, EACH_QUORUM, LOCAL_ONE}")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
connectStart := time.Now()
|
|
|
|
cluster := gocql.NewCluster(hosts...)
|
2017-07-31 14:58:38 +00:00
|
|
|
cluster.Port = port
|
2017-01-07 16:30:25 +00:00
|
|
|
cluster.Keyspace = keyspace
|
2017-06-07 09:24:04 +00:00
|
|
|
|
|
|
|
cluster.ProtoVersion = 2
|
|
|
|
if protoVersionStr, ok := conf["protocol_version"]; ok {
|
|
|
|
protoVersion, err := strconv.Atoi(protoVersionStr)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("'protocol_version' must be an integer")
|
|
|
|
}
|
|
|
|
cluster.ProtoVersion = protoVersion
|
|
|
|
}
|
|
|
|
|
|
|
|
if username, ok := conf["username"]; ok {
|
|
|
|
if cluster.ProtoVersion < 2 {
|
2018-04-09 18:35:21 +00:00
|
|
|
return nil, fmt.Errorf("authentication is not supported with protocol version < 2")
|
2017-06-07 09:24:04 +00:00
|
|
|
}
|
|
|
|
authenticator := gocql.PasswordAuthenticator{Username: username}
|
|
|
|
if password, ok := conf["password"]; ok {
|
|
|
|
authenticator.Password = password
|
|
|
|
}
|
|
|
|
cluster.Authenticator = authenticator
|
|
|
|
}
|
|
|
|
|
|
|
|
if connTimeoutStr, ok := conf["connection_timeout"]; ok {
|
|
|
|
connectionTimeout, err := strconv.Atoi(connTimeoutStr)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("'connection_timeout' must be an integer")
|
|
|
|
}
|
2017-06-08 08:04:32 +00:00
|
|
|
cluster.Timeout = time.Duration(connectionTimeout) * time.Second
|
2017-06-07 09:24:04 +00:00
|
|
|
}
|
|
|
|
|
2017-06-07 14:32:11 +00:00
|
|
|
if err := setupCassandraTLS(conf, cluster); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2017-01-07 16:30:25 +00:00
|
|
|
sess, err := cluster.CreateSession()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
metrics.MeasureSince([]string{"cassandra", "connect"}, connectStart)
|
|
|
|
sess.SetConsistency(consistency)
|
|
|
|
|
|
|
|
impl := &CassandraBackend{
|
|
|
|
sess: sess,
|
|
|
|
table: table,
|
2018-04-03 00:46:59 +00:00
|
|
|
logger: logger,
|
|
|
|
}
|
2017-01-07 16:30:25 +00:00
|
|
|
return impl, nil
|
|
|
|
}
|
|
|
|
|
2017-06-07 14:32:11 +00:00
|
|
|
func setupCassandraTLS(conf map[string]string, cluster *gocql.ClusterConfig) error {
|
|
|
|
tlsOnStr, ok := conf["tls"]
|
|
|
|
if !ok {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
tlsOn, err := strconv.Atoi(tlsOnStr)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("'tls' must be an integer (0 or 1)")
|
|
|
|
}
|
|
|
|
|
|
|
|
if tlsOn == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-04-08 16:43:39 +00:00
|
|
|
tlsConfig := &tls.Config{}
|
2017-06-08 12:46:33 +00:00
|
|
|
if pemBundlePath, ok := conf["pem_bundle_file"]; ok {
|
2017-06-08 10:58:41 +00:00
|
|
|
pemBundleData, err := ioutil.ReadFile(pemBundlePath)
|
|
|
|
if err != nil {
|
2021-05-31 16:54:05 +00:00
|
|
|
return fmt.Errorf("error reading pem bundle from %q: %w", pemBundlePath, err)
|
2017-06-08 10:58:41 +00:00
|
|
|
}
|
|
|
|
pemBundle, err := certutil.ParsePEMBundle(string(pemBundleData))
|
2017-06-07 14:32:11 +00:00
|
|
|
if err != nil {
|
2021-05-31 16:54:05 +00:00
|
|
|
return fmt.Errorf("error parsing 'pem_bundle': %w", err)
|
2017-06-07 14:32:11 +00:00
|
|
|
}
|
|
|
|
tlsConfig, err = pemBundle.GetTLSConfig(certutil.TLSClient)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2021-04-16 21:52:35 +00:00
|
|
|
} else if pemJSONPath, ok := conf["pem_json_file"]; ok {
|
|
|
|
pemJSONData, err := ioutil.ReadFile(pemJSONPath)
|
|
|
|
if err != nil {
|
2021-05-31 16:54:05 +00:00
|
|
|
return fmt.Errorf("error reading json bundle from %q: %w", pemJSONPath, err)
|
2021-04-16 21:52:35 +00:00
|
|
|
}
|
|
|
|
pemJSON, err := certutil.ParsePKIJSON([]byte(pemJSONData))
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
tlsConfig, err = pemJSON.GetTLSConfig(certutil.TLSClient)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2017-06-07 14:32:11 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-06-08 08:26:53 +00:00
|
|
|
if tlsSkipVerifyStr, ok := conf["tls_skip_verify"]; ok {
|
|
|
|
tlsSkipVerify, err := strconv.Atoi(tlsSkipVerifyStr)
|
2017-06-07 14:32:11 +00:00
|
|
|
if err != nil {
|
2017-06-08 08:26:53 +00:00
|
|
|
return fmt.Errorf("'tls_skip_verify' must be an integer (0 or 1)")
|
2017-06-07 14:32:11 +00:00
|
|
|
}
|
2017-06-08 08:26:53 +00:00
|
|
|
if tlsSkipVerify == 0 {
|
2017-06-07 14:32:11 +00:00
|
|
|
tlsConfig.InsecureSkipVerify = false
|
|
|
|
} else {
|
|
|
|
tlsConfig.InsecureSkipVerify = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-06-08 08:26:53 +00:00
|
|
|
if tlsMinVersion, ok := conf["tls_min_version"]; ok {
|
|
|
|
switch tlsMinVersion {
|
|
|
|
case "tls10":
|
|
|
|
tlsConfig.MinVersion = tls.VersionTLS10
|
|
|
|
case "tls11":
|
|
|
|
tlsConfig.MinVersion = tls.VersionTLS11
|
|
|
|
case "tls12":
|
|
|
|
tlsConfig.MinVersion = tls.VersionTLS12
|
2020-02-15 19:40:18 +00:00
|
|
|
case "tls13":
|
|
|
|
tlsConfig.MinVersion = tls.VersionTLS13
|
2017-06-08 08:26:53 +00:00
|
|
|
default:
|
2020-02-15 19:40:18 +00:00
|
|
|
return fmt.Errorf("'tls_min_version' must be one of `tls10`, `tls11`, `tls12` or `tls13`")
|
2017-06-07 14:32:11 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
cluster.SslOpts = &gocql.SslOptions{
|
2021-04-16 21:52:35 +00:00
|
|
|
Config: tlsConfig,
|
|
|
|
EnableHostVerification: !tlsConfig.InsecureSkipVerify,
|
2021-04-08 16:43:39 +00:00
|
|
|
}
|
2017-06-07 14:32:11 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2017-01-07 16:30:25 +00:00
|
|
|
// bucketName sanitises a bucket name for Cassandra
|
|
|
|
func (c *CassandraBackend) bucketName(name string) string {
|
|
|
|
if name == "" {
|
|
|
|
name = "."
|
|
|
|
}
|
|
|
|
return strings.TrimRight(name, "/")
|
|
|
|
}
|
|
|
|
|
|
|
|
// bucket returns all the prefix buckets the key should be stored at
|
|
|
|
func (c *CassandraBackend) buckets(key string) []string {
|
2017-08-03 17:24:27 +00:00
|
|
|
vals := append([]string{""}, physical.Prefixes(key)...)
|
2017-01-07 16:30:25 +00:00
|
|
|
for i, v := range vals {
|
|
|
|
vals[i] = c.bucketName(v)
|
|
|
|
}
|
|
|
|
return vals
|
|
|
|
}
|
|
|
|
|
|
|
|
// bucket returns the most specific bucket for the key
|
|
|
|
func (c *CassandraBackend) bucket(key string) string {
|
|
|
|
bs := c.buckets(key)
|
|
|
|
return bs[len(bs)-1]
|
|
|
|
}
|
|
|
|
|
|
|
|
// Put is used to insert or update an entry
|
2018-01-19 06:44:44 +00:00
|
|
|
func (c *CassandraBackend) Put(ctx context.Context, entry *physical.Entry) error {
|
2017-01-07 16:30:25 +00:00
|
|
|
defer metrics.MeasureSince([]string{"cassandra", "put"}, time.Now())
|
|
|
|
|
2017-07-31 13:48:48 +00:00
|
|
|
// Execute inserts to each key prefix simultaneously
|
2017-01-07 16:30:25 +00:00
|
|
|
stmt := fmt.Sprintf(`INSERT INTO "%s" (bucket, key, value) VALUES (?, ?, ?)`, c.table)
|
2017-07-31 13:48:48 +00:00
|
|
|
buckets := c.buckets(entry.Key)
|
2019-08-19 18:50:00 +00:00
|
|
|
results := make(chan error, len(buckets))
|
|
|
|
for i, _bucket := range buckets {
|
|
|
|
go func(i int, bucket string) {
|
|
|
|
var value []byte
|
|
|
|
if i == len(buckets)-1 {
|
|
|
|
// Only store the full value if this is the leaf bucket where the entry will actually be read
|
|
|
|
// otherwise this write is just to allow for list operations
|
|
|
|
value = entry.Value
|
|
|
|
}
|
|
|
|
results <- c.sess.Query(stmt, bucket, entry.Key, value).Exec()
|
|
|
|
}(i, _bucket)
|
2017-01-07 16:30:25 +00:00
|
|
|
}
|
2017-07-31 13:48:48 +00:00
|
|
|
for i := 0; i < len(buckets); i++ {
|
|
|
|
if err := <-results; err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
2017-01-07 16:30:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Get is used to fetch an entry
|
2018-01-19 06:44:44 +00:00
|
|
|
func (c *CassandraBackend) Get(ctx context.Context, key string) (*physical.Entry, error) {
|
2017-01-07 16:30:25 +00:00
|
|
|
defer metrics.MeasureSince([]string{"cassandra", "get"}, time.Now())
|
|
|
|
|
|
|
|
v := []byte(nil)
|
|
|
|
stmt := fmt.Sprintf(`SELECT value FROM "%s" WHERE bucket = ? AND key = ? LIMIT 1`, c.table)
|
|
|
|
q := c.sess.Query(stmt, c.bucket(key), key)
|
|
|
|
if err := q.Scan(&v); err != nil {
|
|
|
|
if err == gocql.ErrNotFound {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2017-08-03 17:24:27 +00:00
|
|
|
return &physical.Entry{
|
2017-01-07 16:30:25 +00:00
|
|
|
Key: key,
|
|
|
|
Value: v,
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Delete is used to permanently delete an entry
|
2018-01-19 06:44:44 +00:00
|
|
|
func (c *CassandraBackend) Delete(ctx context.Context, key string) error {
|
2017-01-07 16:30:25 +00:00
|
|
|
defer metrics.MeasureSince([]string{"cassandra", "delete"}, time.Now())
|
|
|
|
|
|
|
|
stmt := fmt.Sprintf(`DELETE FROM "%s" WHERE bucket = ? AND key = ?`, c.table)
|
2018-03-23 16:42:35 +00:00
|
|
|
buckets := c.buckets(key)
|
2019-08-19 18:50:00 +00:00
|
|
|
results := make(chan error, len(buckets))
|
2018-03-23 16:42:35 +00:00
|
|
|
|
|
|
|
for _, bucket := range buckets {
|
|
|
|
go func(bucket string) {
|
|
|
|
results <- c.sess.Query(stmt, bucket, key).Exec()
|
|
|
|
}(bucket)
|
|
|
|
}
|
|
|
|
|
|
|
|
for i := 0; i < len(buckets); i++ {
|
|
|
|
if err := <-results; err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2017-01-07 16:30:25 +00:00
|
|
|
}
|
2018-03-23 16:42:35 +00:00
|
|
|
return nil
|
2017-01-07 16:30:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// List is used ot list all the keys under a given
|
|
|
|
// prefix, up to the next prefix.
|
2018-01-19 06:44:44 +00:00
|
|
|
func (c *CassandraBackend) List(ctx context.Context, prefix string) ([]string, error) {
|
2017-01-07 16:30:25 +00:00
|
|
|
defer metrics.MeasureSince([]string{"cassandra", "list"}, time.Now())
|
|
|
|
|
|
|
|
stmt := fmt.Sprintf(`SELECT key FROM "%s" WHERE bucket = ?`, c.table)
|
|
|
|
q := c.sess.Query(stmt, c.bucketName(prefix))
|
|
|
|
iter := q.Iter()
|
|
|
|
k, keys := "", []string{}
|
|
|
|
for iter.Scan(&k) {
|
|
|
|
// Only return the next "component" (with a trailing slash if it has children)
|
|
|
|
k = strings.TrimPrefix(k, prefix)
|
|
|
|
if parts := strings.SplitN(k, "/", 2); len(parts) > 1 {
|
|
|
|
k = parts[0] + "/"
|
|
|
|
} else {
|
|
|
|
k = parts[0]
|
|
|
|
}
|
|
|
|
|
|
|
|
// Deduplicate; this works because the keys are sorted
|
|
|
|
if len(keys) > 0 && keys[len(keys)-1] == k {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
keys = append(keys, k)
|
|
|
|
}
|
|
|
|
return keys, iter.Close()
|
|
|
|
}
|