DBPW - Update InfluxDB to adhere to v5 Database interface (#10118)

This commit is contained in:
Michael Golowka
2020-10-12 15:54:26 -06:00
committed by GitHub
parent 1eff3f7daa
commit 6832cfe556
3 changed files with 352 additions and 247 deletions

View File

@@ -8,9 +8,8 @@ import (
"time"
"github.com/hashicorp/errwrap"
"github.com/hashicorp/vault/sdk/database/dbplugin"
"github.com/hashicorp/vault/sdk/database/helper/connutil"
"github.com/hashicorp/vault/sdk/database/helper/dbutil"
"github.com/hashicorp/vault/sdk/database/newdbplugin"
"github.com/hashicorp/vault/sdk/helper/certutil"
"github.com/hashicorp/vault/sdk/helper/parseutil"
"github.com/hashicorp/vault/sdk/helper/tlsutil"
@@ -44,40 +43,35 @@ type influxdbConnectionProducer struct {
sync.Mutex
}
func (i *influxdbConnectionProducer) Initialize(ctx context.Context, conf map[string]interface{}, verifyConnection bool) error {
_, err := i.Init(ctx, conf, verifyConnection)
return err
}
func (i *influxdbConnectionProducer) Init(ctx context.Context, conf map[string]interface{}, verifyConnection bool) (map[string]interface{}, error) {
func (i *influxdbConnectionProducer) Initialize(ctx context.Context, req newdbplugin.InitializeRequest) (newdbplugin.InitializeResponse, error) {
i.Lock()
defer i.Unlock()
i.rawConfig = conf
i.rawConfig = req.Config
err := mapstructure.WeakDecode(conf, i)
err := mapstructure.WeakDecode(req.Config, i)
if err != nil {
return nil, err
return newdbplugin.InitializeResponse{}, err
}
if i.ConnectTimeoutRaw == nil {
i.ConnectTimeoutRaw = "0s"
i.ConnectTimeoutRaw = "5s"
}
if i.Port == "" {
i.Port = "8086"
}
i.connectTimeout, err = parseutil.ParseDurationSecond(i.ConnectTimeoutRaw)
if err != nil {
return nil, errwrap.Wrapf("invalid connect_timeout: {{err}}", err)
return newdbplugin.InitializeResponse{}, errwrap.Wrapf("invalid connect_timeout: {{err}}", err)
}
switch {
case len(i.Host) == 0:
return nil, fmt.Errorf("host cannot be empty")
return newdbplugin.InitializeResponse{}, fmt.Errorf("host cannot be empty")
case len(i.Username) == 0:
return nil, fmt.Errorf("username cannot be empty")
return newdbplugin.InitializeResponse{}, fmt.Errorf("username cannot be empty")
case len(i.Password) == 0:
return nil, fmt.Errorf("password cannot be empty")
return newdbplugin.InitializeResponse{}, fmt.Errorf("password cannot be empty")
}
var certBundle *certutil.CertBundle
@@ -86,11 +80,11 @@ func (i *influxdbConnectionProducer) Init(ctx context.Context, conf map[string]i
case len(i.PemJSON) != 0:
parsedCertBundle, err = certutil.ParsePKIJSON([]byte(i.PemJSON))
if err != nil {
return nil, errwrap.Wrapf("could not parse given JSON; it must be in the format of the output of the PKI backend certificate issuing command: {{err}}", err)
return newdbplugin.InitializeResponse{}, errwrap.Wrapf("could not parse given JSON; it must be in the format of the output of the PKI backend certificate issuing command: {{err}}", err)
}
certBundle, err = parsedCertBundle.ToCertBundle()
if err != nil {
return nil, errwrap.Wrapf("Error marshaling PEM information: {{err}}", err)
return newdbplugin.InitializeResponse{}, errwrap.Wrapf("Error marshaling PEM information: {{err}}", err)
}
i.certificate = certBundle.Certificate
i.privateKey = certBundle.PrivateKey
@@ -100,11 +94,11 @@ func (i *influxdbConnectionProducer) Init(ctx context.Context, conf map[string]i
case len(i.PemBundle) != 0:
parsedCertBundle, err = certutil.ParsePEMBundle(i.PemBundle)
if err != nil {
return nil, errwrap.Wrapf("Error parsing the given PEM information: {{err}}", err)
return newdbplugin.InitializeResponse{}, errwrap.Wrapf("Error parsing the given PEM information: {{err}}", err)
}
certBundle, err = parsedCertBundle.ToCertBundle()
if err != nil {
return nil, errwrap.Wrapf("Error marshaling PEM information: {{err}}", err)
return newdbplugin.InitializeResponse{}, errwrap.Wrapf("Error marshaling PEM information: {{err}}", err)
}
i.certificate = certBundle.Certificate
i.privateKey = certBundle.PrivateKey
@@ -116,13 +110,17 @@ func (i *influxdbConnectionProducer) Init(ctx context.Context, conf map[string]i
// and the connection can be established at a later time.
i.Initialized = true
if verifyConnection {
if req.VerifyConnection {
if _, err := i.Connection(ctx); err != nil {
return nil, errwrap.Wrapf("error verifying connection: {{err}}", err)
return newdbplugin.InitializeResponse{}, errwrap.Wrapf("error verifying connection: {{err}}", err)
}
}
return conf, nil
resp := newdbplugin.InitializeResponse{
Config: req.Config,
}
return resp, nil
}
func (i *influxdbConnectionProducer) Connection(_ context.Context) (interface{}, error) {
@@ -237,8 +235,8 @@ func (i *influxdbConnectionProducer) createClient() (influx.Client, error) {
return cli, nil
}
func (i *influxdbConnectionProducer) secretValues() map[string]interface{} {
return map[string]interface{}{
func (i *influxdbConnectionProducer) secretValues() map[string]string {
return map[string]string{
i.Password: "[password]",
i.PemBundle: "[pem_bundle]",
i.PemJSON: "[pem_json]",
@@ -268,13 +266,3 @@ func isUserAdmin(cli influx.Client, user string) (bool, error) {
}
return false, fmt.Errorf("the provided username is not a valid user in the influxdb")
}
// SetCredentials uses provided information to set/create a user in the
// database. Unlike CreateUser, this method requires a username be provided and
// uses the name given, instead of generating a name. This is used for creating
// and setting the password of static accounts, as well as rolling back
// passwords in the database in the event an updated database fails to save in
// Vault's storage.
func (i *influxdbConnectionProducer) SetCredentials(ctx context.Context, statements dbplugin.Statements, staticUser dbplugin.StaticUserConfig) (username, password string, err error) {
return "", "", dbutil.Unimplemented()
}

View File

@@ -2,14 +2,15 @@ package influxdb
import (
"context"
"fmt"
"strings"
"time"
"github.com/hashicorp/vault/sdk/database/helper/credsutil"
multierror "github.com/hashicorp/go-multierror"
"github.com/hashicorp/vault/api"
"github.com/hashicorp/vault/sdk/database/dbplugin"
"github.com/hashicorp/vault/sdk/database/helper/credsutil"
"github.com/hashicorp/vault/sdk/database/helper/dbutil"
"github.com/hashicorp/vault/sdk/database/newdbplugin"
"github.com/hashicorp/vault/sdk/helper/strutil"
influx "github.com/influxdata/influxdb/client/v2"
)
@@ -21,18 +22,17 @@ const (
influxdbTypeName = "influxdb"
)
var _ dbplugin.Database = &Influxdb{}
var _ newdbplugin.Database = &Influxdb{}
// Influxdb is an implementation of Database interface
type Influxdb struct {
*influxdbConnectionProducer
credsutil.CredentialsProducer
}
// New returns a new Cassandra instance
func New() (interface{}, error) {
db := new()
dbType := dbplugin.NewDatabaseErrorSanitizerMiddleware(db, db.secretValues)
dbType := newdbplugin.NewDatabaseErrorSanitizerMiddleware(db, db.secretValues)
return dbType, nil
}
@@ -41,16 +41,8 @@ func new() *Influxdb {
connProducer := &influxdbConnectionProducer{}
connProducer.Type = influxdbTypeName
credsProducer := &credsutil.SQLCredentialsProducer{
DisplayNameLen: 15,
RoleNameLen: 15,
UsernameLen: 100,
Separator: "_",
}
return &Influxdb{
influxdbConnectionProducer: connProducer,
CredentialsProducer: credsProducer,
}
}
@@ -61,7 +53,7 @@ func Run(apiTLSConfig *api.TLSConfig) error {
return err
}
dbplugin.Serve(dbType.(dbplugin.Database), api.VaultPluginTLSProvider(apiTLSConfig))
newdbplugin.Serve(dbType.(newdbplugin.Database), api.VaultPluginTLSProvider(apiTLSConfig))
return nil
}
@@ -80,43 +72,39 @@ func (i *Influxdb) getConnection(ctx context.Context) (influx.Client, error) {
return cli.(influx.Client), nil
}
// CreateUser generates the username/password on the underlying Influxdb secret backend as instructed by
// the CreationStatement provided.
func (i *Influxdb) CreateUser(ctx context.Context, statements dbplugin.Statements, usernameConfig dbplugin.UsernameConfig, expiration time.Time) (username string, password string, err error) {
// Grab the lock
// NewUser generates the username/password on the underlying Influxdb secret backend as instructed by
// the statements provided.
func (i *Influxdb) NewUser(ctx context.Context, req newdbplugin.NewUserRequest) (resp newdbplugin.NewUserResponse, err error) {
i.Lock()
defer i.Unlock()
statements = dbutil.StatementCompatibilityHelper(statements)
// Get the connection
cli, err := i.getConnection(ctx)
if err != nil {
return "", "", err
return newdbplugin.NewUserResponse{}, fmt.Errorf("unable to get connection: %w", err)
}
creationIFQL := statements.Creation
creationIFQL := req.Statements.Commands
if len(creationIFQL) == 0 {
creationIFQL = []string{defaultUserCreationIFQL}
}
rollbackIFQL := statements.Rollback
rollbackIFQL := req.RollbackStatements.Commands
if len(rollbackIFQL) == 0 {
rollbackIFQL = []string{defaultUserDeletionIFQL}
}
username, err = i.GenerateUsername(usernameConfig)
username, err := credsutil.GenerateUsername(
credsutil.DisplayName(req.UsernameConfig.DisplayName, 15),
credsutil.RoleName(req.UsernameConfig.RoleName, 15),
credsutil.MaxLength(100),
credsutil.Separator("_"),
credsutil.ToLower(),
)
if err != nil {
return newdbplugin.NewUserResponse{}, fmt.Errorf("failed to generate username: %w", err)
}
username = strings.Replace(username, "-", "_", -1)
if err != nil {
return "", "", err
}
username = strings.ToLower(username)
password, err = i.GeneratePassword()
if err != nil {
return "", "", err
}
// Execute each query
for _, stmt := range creationIFQL {
for _, query := range strutil.ParseArbitraryStringSlice(stmt, ";") {
query = strings.TrimSpace(query)
@@ -124,20 +112,24 @@ func (i *Influxdb) CreateUser(ctx context.Context, statements dbplugin.Statement
continue
}
q := influx.NewQuery(dbutil.QueryHelper(query, map[string]string{
m := map[string]string{
"username": username,
"password": password,
}), "", "")
"password": req.Password,
}
q := influx.NewQuery(dbutil.QueryHelper(query, m), "", "")
response, err := cli.Query(q)
if err != nil {
if response != nil && response.Error() != nil {
attemptRollback(cli, username, rollbackIFQL)
}
return "", "", err
return newdbplugin.NewUserResponse{}, fmt.Errorf("failed to run query in InfluxDB: %w", err)
}
}
}
return username, password, nil
resp = newdbplugin.NewUserResponse{
Username: username,
}
return resp, nil
}
// attemptRollback will attempt to roll back user creation if an error occurs in
@@ -165,26 +157,16 @@ func attemptRollback(cli influx.Client, username string, rollbackStatements []st
return nil
}
// RenewUser is not supported on Influxdb, so this is a no-op.
func (i *Influxdb) RenewUser(ctx context.Context, statements dbplugin.Statements, username string, expiration time.Time) error {
// NOOP
return nil
}
// RevokeUser attempts to drop the specified user.
func (i *Influxdb) RevokeUser(ctx context.Context, statements dbplugin.Statements, username string) error {
// Grab the lock
func (i *Influxdb) DeleteUser(ctx context.Context, req newdbplugin.DeleteUserRequest) (newdbplugin.DeleteUserResponse, error) {
i.Lock()
defer i.Unlock()
statements = dbutil.StatementCompatibilityHelper(statements)
cli, err := i.getConnection(ctx)
if err != nil {
return err
return newdbplugin.DeleteUserResponse{}, fmt.Errorf("unable to get connection: %w", err)
}
revocationIFQL := statements.Revocation
revocationIFQL := req.Statements.Commands
if len(revocationIFQL) == 0 {
revocationIFQL = []string{defaultUserDeletionIFQL}
}
@@ -196,9 +178,10 @@ func (i *Influxdb) RevokeUser(ctx context.Context, statements dbplugin.Statement
if len(query) == 0 {
continue
}
q := influx.NewQuery(dbutil.QueryHelper(query, map[string]string{
"username": username,
}), "", "")
m := map[string]string{
"username": req.Username,
}
q := influx.NewQuery(dbutil.QueryHelper(query, m), "", "")
response, err := cli.Query(q)
result = multierror.Append(result, err)
if response != nil {
@@ -206,30 +189,41 @@ func (i *Influxdb) RevokeUser(ctx context.Context, statements dbplugin.Statement
}
}
}
return result.ErrorOrNil()
if result.ErrorOrNil() != nil {
return newdbplugin.DeleteUserResponse{}, fmt.Errorf("failed to delete user cleanly: %w", result.ErrorOrNil())
}
return newdbplugin.DeleteUserResponse{}, nil
}
// RotateRootCredentials is useful when we try to change root credential
func (i *Influxdb) RotateRootCredentials(ctx context.Context, statements []string) (map[string]interface{}, error) {
// Grab the lock
func (i *Influxdb) UpdateUser(ctx context.Context, req newdbplugin.UpdateUserRequest) (newdbplugin.UpdateUserResponse, error) {
if req.Password == nil && req.Expiration == nil {
return newdbplugin.UpdateUserResponse{}, fmt.Errorf("no changes requested")
}
i.Lock()
defer i.Unlock()
if req.Password != nil {
err := i.changeUserPassword(ctx, req.Username, req.Password)
if err != nil {
return newdbplugin.UpdateUserResponse{}, fmt.Errorf("failed to change %q password: %w", req.Username, err)
}
}
// Expiration is a no-op
return newdbplugin.UpdateUserResponse{}, nil
}
func (i *Influxdb) changeUserPassword(ctx context.Context, username string, changePassword *newdbplugin.ChangePassword) error {
cli, err := i.getConnection(ctx)
if err != nil {
return nil, err
return fmt.Errorf("unable to get connection: %w", err)
}
rotateIFQL := statements
rotateIFQL := changePassword.Statements.Commands
if len(rotateIFQL) == 0 {
rotateIFQL = []string{defaultRootCredentialRotationIFQL}
}
password, err := i.GeneratePassword()
if err != nil {
return nil, err
}
var result *multierror.Error
for _, stmt := range rotateIFQL {
for _, query := range strutil.ParseArbitraryStringSlice(stmt, ";") {
@@ -237,10 +231,11 @@ func (i *Influxdb) RotateRootCredentials(ctx context.Context, statements []strin
if len(query) == 0 {
continue
}
q := influx.NewQuery(dbutil.QueryHelper(query, map[string]string{
"username": i.Username,
"password": password,
}), "", "")
m := map[string]string{
"username": username,
"password": changePassword.NewPassword,
}
q := influx.NewQuery(dbutil.QueryHelper(query, m), "", "")
response, err := cli.Query(q)
result = multierror.Append(result, err)
if response != nil {
@@ -251,9 +246,8 @@ func (i *Influxdb) RotateRootCredentials(ctx context.Context, statements []strin
err = result.ErrorOrNil()
if err != nil {
return nil, err
return fmt.Errorf("failed to execute rotation queries: %w", err)
}
i.rawConfig["password"] = password
return i.rawConfig, nil
return nil
}

View File

@@ -5,18 +5,22 @@ import (
"fmt"
"net/url"
"os"
"reflect"
"strconv"
"strings"
"testing"
"time"
"github.com/hashicorp/vault/sdk/database/newdbplugin"
dbtesting "github.com/hashicorp/vault/sdk/database/newdbplugin/testing"
"github.com/hashicorp/errwrap"
"github.com/hashicorp/vault/helper/testhelpers/docker"
"github.com/hashicorp/vault/sdk/database/dbplugin"
influx "github.com/influxdata/influxdb/client/v2"
)
const testInfluxRole = `CREATE USER "{{username}}" WITH PASSWORD '{{password}}';GRANT ALL ON "vault" TO "{{username}}";`
const createUserStatements = `CREATE USER "{{username}}" WITH PASSWORD '{{password}}';GRANT ALL ON "vault" TO "{{username}}";`
type Config struct {
docker.ServiceURL
@@ -96,27 +100,126 @@ func TestInfluxdb_Initialize(t *testing.T) {
cleanup, config := prepareInfluxdbTestContainer(t)
defer cleanup()
db := new()
_, err := db.Init(context.Background(), config.connectionParams(), true)
if err != nil {
t.Fatalf("err: %s", err)
type testCase struct {
req newdbplugin.InitializeRequest
expectedResponse newdbplugin.InitializeResponse
expectErr bool
expectInitialized bool
}
if !db.Initialized {
t.Fatal("Database should be initialized")
tests := map[string]testCase{
"port is an int": {
req: newdbplugin.InitializeRequest{
Config: makeConfig(config.connectionParams()),
VerifyConnection: true,
},
expectedResponse: newdbplugin.InitializeResponse{
Config: config.connectionParams(),
},
expectErr: false,
expectInitialized: true,
},
"port is a string": {
req: newdbplugin.InitializeRequest{
Config: makeConfig(config.connectionParams(), "port", strconv.Itoa(config.connectionParams()["port"].(int))),
VerifyConnection: true,
},
expectedResponse: newdbplugin.InitializeResponse{
Config: makeConfig(config.connectionParams(), "port", strconv.Itoa(config.connectionParams()["port"].(int))),
},
expectErr: false,
expectInitialized: true,
},
"missing config": {
req: newdbplugin.InitializeRequest{
Config: nil,
VerifyConnection: true,
},
expectedResponse: newdbplugin.InitializeResponse{},
expectErr: true,
expectInitialized: false,
},
"missing host": {
req: newdbplugin.InitializeRequest{
Config: makeConfig(config.connectionParams(), "host", ""),
VerifyConnection: true,
},
expectedResponse: newdbplugin.InitializeResponse{},
expectErr: true,
expectInitialized: false,
},
"missing username": {
req: newdbplugin.InitializeRequest{
Config: makeConfig(config.connectionParams(), "username", ""),
VerifyConnection: true,
},
expectedResponse: newdbplugin.InitializeResponse{},
expectErr: true,
expectInitialized: false,
},
"missing password": {
req: newdbplugin.InitializeRequest{
Config: makeConfig(config.connectionParams(), "password", ""),
VerifyConnection: true,
},
expectedResponse: newdbplugin.InitializeResponse{},
expectErr: true,
expectInitialized: false,
},
"failed to validate connection": {
req: newdbplugin.InitializeRequest{
// Host exists, but isn't a running instance
Config: makeConfig(config.connectionParams(), "host", "foobar://bad_connection"),
VerifyConnection: true,
},
expectedResponse: newdbplugin.InitializeResponse{},
expectErr: true,
expectInitialized: true,
},
}
err = db.Close()
if err != nil {
t.Fatalf("err: %s", err)
for name, test := range tests {
t.Run(name, func(t *testing.T) {
db := new()
defer dbtesting.AssertClose(t, db)
resp, err := db.Initialize(context.Background(), test.req)
if test.expectErr && err == nil {
t.Fatalf("err expected, got nil")
}
if !test.expectErr && err != nil {
t.Fatalf("no error expected, got: %s", err)
}
if !reflect.DeepEqual(resp, test.expectedResponse) {
t.Fatalf("Actual response: %#v\nExpected response: %#v", resp, test.expectedResponse)
}
if test.expectInitialized && !db.Initialized {
t.Fatalf("Database should be initialized but wasn't")
} else if !test.expectInitialized && db.Initialized {
t.Fatalf("Database was initiailized when it shouldn't")
}
})
}
}
func makeConfig(rootConfig map[string]interface{}, keyValues ...interface{}) map[string]interface{} {
if len(keyValues)%2 != 0 {
panic("makeConfig must be provided with key and value pairs")
}
connectionParams := config.connectionParams()
connectionParams["port"] = strconv.Itoa(connectionParams["port"].(int))
_, err = db.Init(context.Background(), connectionParams, true)
if err != nil {
t.Fatalf("err: %s", err)
// Make a copy of the map so there isn't a chance of test bleedover between maps
config := make(map[string]interface{}, len(rootConfig)+(len(keyValues)/2))
for k, v := range rootConfig {
config[k] = v
}
for i := 0; i < len(keyValues); i += 2 {
k := keyValues[i].(string) // Will panic if the key field isn't a string and that's fine in a test
v := keyValues[i+1]
config[k] = v
}
return config
}
func TestInfluxdb_CreateUser(t *testing.T) {
@@ -124,103 +227,138 @@ func TestInfluxdb_CreateUser(t *testing.T) {
defer cleanup()
db := new()
_, err := db.Init(context.Background(), config.connectionParams(), true)
if err != nil {
t.Fatalf("err: %s", err)
req := newdbplugin.InitializeRequest{
Config: config.connectionParams(),
VerifyConnection: true,
}
dbtesting.AssertInitialize(t, db, req)
password := "nuozxby98523u89bdfnkjl"
newUserReq := newdbplugin.NewUserRequest{
UsernameConfig: newdbplugin.UsernameMetadata{
DisplayName: "test",
RoleName: "test",
},
Statements: newdbplugin.Statements{
Commands: []string{createUserStatements},
},
Password: password,
Expiration: time.Now().Add(1 * time.Minute),
}
resp := dbtesting.AssertNewUser(t, db, newUserReq)
if resp.Username == "" {
t.Fatalf("Missing username")
}
statements := dbplugin.Statements{
Creation: []string{testInfluxRole},
}
usernameConfig := dbplugin.UsernameConfig{
DisplayName: "test",
RoleName: "test",
}
username, password, err := db.CreateUser(context.Background(), statements, usernameConfig, time.Now().Add(time.Minute))
if err != nil {
t.Fatalf("err: %s", err)
}
config.Username, config.Password = username, password
if err := testCredsExist(t, config); err != nil {
t.Fatalf("Could not connect with new credentials: %s", err)
}
assertCredsExist(t, config.URL().String(), resp.Username, password)
}
func TestMyInfluxdb_RenewUser(t *testing.T) {
func TestUpdateUser_expiration(t *testing.T) {
// This test should end up with a no-op since the expiration doesn't do anything in Influx
cleanup, config := prepareInfluxdbTestContainer(t)
defer cleanup()
db := new()
_, err := db.Init(context.Background(), config.connectionParams(), true)
if err != nil {
t.Fatalf("err: %s", err)
req := newdbplugin.InitializeRequest{
Config: config.connectionParams(),
VerifyConnection: true,
}
dbtesting.AssertInitialize(t, db, req)
statements := dbplugin.Statements{
Creation: []string{testInfluxRole},
password := "nuozxby98523u89bdfnkjl"
newUserReq := newdbplugin.NewUserRequest{
UsernameConfig: newdbplugin.UsernameMetadata{
DisplayName: "test",
RoleName: "test",
},
Statements: newdbplugin.Statements{
Commands: []string{createUserStatements},
},
Password: password,
Expiration: time.Now().Add(1 * time.Minute),
}
newUserResp := dbtesting.AssertNewUser(t, db, newUserReq)
usernameConfig := dbplugin.UsernameConfig{
DisplayName: "test",
RoleName: "test",
}
assertCredsExist(t, config.URL().String(), newUserResp.Username, password)
username, password, err := db.CreateUser(context.Background(), statements, usernameConfig, time.Now().Add(time.Minute))
if err != nil {
t.Fatalf("err: %s", err)
renewReq := newdbplugin.UpdateUserRequest{
Username: newUserResp.Username,
Expiration: &newdbplugin.ChangeExpiration{
NewExpiration: time.Now().Add(5 * time.Minute),
},
}
dbtesting.AssertUpdateUser(t, db, renewReq)
config.Username, config.Password = username, password
if err = testCredsExist(t, config); err != nil {
t.Fatalf("Could not connect with new credentials: %s", err)
}
// Make sure the user hasn't changed
assertCredsExist(t, config.URL().String(), newUserResp.Username, password)
}
err = db.RenewUser(context.Background(), statements, username, time.Now().Add(time.Minute))
if err != nil {
t.Fatalf("err: %s", err)
func TestUpdateUser_password(t *testing.T) {
cleanup, config := prepareInfluxdbTestContainer(t)
defer cleanup()
db := new()
req := newdbplugin.InitializeRequest{
Config: config.connectionParams(),
VerifyConnection: true,
}
dbtesting.AssertInitialize(t, db, req)
initialPassword := "nuozxby98523u89bdfnkjl"
newUserReq := newdbplugin.NewUserRequest{
UsernameConfig: newdbplugin.UsernameMetadata{
DisplayName: "test",
RoleName: "test",
},
Statements: newdbplugin.Statements{
Commands: []string{createUserStatements},
},
Password: initialPassword,
Expiration: time.Now().Add(1 * time.Minute),
}
newUserResp := dbtesting.AssertNewUser(t, db, newUserReq)
assertCredsExist(t, config.URL().String(), newUserResp.Username, initialPassword)
newPassword := "y89qgmbzadiygry8uazodijnb"
newPasswordReq := newdbplugin.UpdateUserRequest{
Username: newUserResp.Username,
Password: &newdbplugin.ChangePassword{
NewPassword: newPassword,
},
}
dbtesting.AssertUpdateUser(t, db, newPasswordReq)
assertCredsDoNotExist(t, config.URL().String(), newUserResp.Username, initialPassword)
assertCredsExist(t, config.URL().String(), newUserResp.Username, newPassword)
}
// TestInfluxdb_RevokeDeletedUser tests attempting to revoke a user that was
// deleted externally. Guards against a panic, see
// https://github.com/hashicorp/vault/issues/6734
// Updated to attempt to delete a user that never existed to replicate a similar scenario since
// the cleanup function from `prepareInfluxdbTestContainer` does not do anything if using an
// external InfluxDB instance rather than spinning one up for the test.
func TestInfluxdb_RevokeDeletedUser(t *testing.T) {
cleanup, config := prepareInfluxdbTestContainer(t)
defer cleanup()
db := new()
_, err := db.Init(context.Background(), config.connectionParams(), true)
if err != nil {
t.Fatalf("err: %s", err)
req := newdbplugin.InitializeRequest{
Config: config.connectionParams(),
VerifyConnection: true,
}
dbtesting.AssertInitialize(t, db, req)
statements := dbplugin.Statements{
Creation: []string{testInfluxRole},
// attempt to revoke a user that does not exist
delReq := newdbplugin.DeleteUserRequest{
Username: "someuser",
}
usernameConfig := dbplugin.UsernameConfig{
DisplayName: "test",
RoleName: "test",
}
username, password, err := db.CreateUser(context.Background(), statements, usernameConfig, time.Now().Add(time.Minute))
if err != nil {
t.Fatalf("err: %s", err)
}
config.Username, config.Password = username, password
if err = testCredsExist(t, config); err != nil {
t.Fatalf("Could not connect with new credentials: %s", err)
}
// call cleanup to remove database
cleanup()
// attempt to revoke the user after database is gone
err = db.RevokeUser(context.Background(), statements, username)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_, err := db.DeleteUser(ctx, delReq)
if err == nil {
t.Fatalf("Expected err, got nil")
}
@@ -231,73 +369,58 @@ func TestInfluxdb_RevokeUser(t *testing.T) {
defer cleanup()
db := new()
_, err := db.Init(context.Background(), config.connectionParams(), true)
if err != nil {
t.Fatalf("err: %s", err)
req := newdbplugin.InitializeRequest{
Config: config.connectionParams(),
VerifyConnection: true,
}
dbtesting.AssertInitialize(t, db, req)
statements := dbplugin.Statements{
Creation: []string{testInfluxRole},
initialPassword := "nuozxby98523u89bdfnkjl"
newUserReq := newdbplugin.NewUserRequest{
UsernameConfig: newdbplugin.UsernameMetadata{
DisplayName: "test",
RoleName: "test",
},
Statements: newdbplugin.Statements{
Commands: []string{createUserStatements},
},
Password: initialPassword,
Expiration: time.Now().Add(1 * time.Minute),
}
newUserResp := dbtesting.AssertNewUser(t, db, newUserReq)
usernameConfig := dbplugin.UsernameConfig{
DisplayName: "test",
RoleName: "test",
}
assertCredsExist(t, config.URL().String(), newUserResp.Username, initialPassword)
username, password, err := db.CreateUser(context.Background(), statements, usernameConfig, time.Now().Add(time.Minute))
if err != nil {
t.Fatalf("err: %s", err)
}
config.Username, config.Password = username, password
if err = testCredsExist(t, config); err != nil {
t.Fatalf("Could not connect with new credentials: %s", err)
}
// Test default revoke statements
err = db.RevokeUser(context.Background(), dbplugin.Statements{}, username)
if err != nil {
t.Fatalf("err: %s", err)
}
if err = testCredsExist(t, config); err == nil {
t.Fatal("Credentials were not revoked")
delReq := newdbplugin.DeleteUserRequest{
Username: newUserResp.Username,
}
dbtesting.AssertDeleteUser(t, db, delReq)
assertCredsDoNotExist(t, config.URL().String(), newUserResp.Username, initialPassword)
}
func TestInfluxdb_RotateRootCredentials(t *testing.T) {
cleanup, config := prepareInfluxdbTestContainer(t)
defer cleanup()
db := new()
connProducer := db.influxdbConnectionProducer
_, err := db.Init(context.Background(), config.connectionParams(), true)
func assertCredsExist(t testing.TB, address, username, password string) {
t.Helper()
err := testCredsExist(address, username, password)
if err != nil {
t.Fatalf("err: %s", err)
}
if !connProducer.Initialized {
t.Fatal("Database should be initialized")
}
newConf, err := db.RotateRootCredentials(context.Background(), nil)
if err != nil {
t.Fatalf("err: %v", err)
}
if newConf["password"] == "influx-root" {
t.Fatal("password was not updated")
}
err = db.Close()
if err != nil {
t.Fatalf("err: %s", err)
t.Fatalf("Could not log in as %q", username)
}
}
func testCredsExist(t testing.TB, c *Config) error {
cli, err := influx.NewHTTPClient(c.apiConfig())
func assertCredsDoNotExist(t testing.TB, address, username, password string) {
t.Helper()
err := testCredsExist(address, username, password)
if err == nil {
t.Fatalf("Able to log in as %q when it shouldn't", username)
}
}
func testCredsExist(address, username, password string) error {
conf := influx.HTTPConfig{
Addr: address,
Username: username,
Password: password,
}
cli, err := influx.NewHTTPClient(conf)
if err != nil {
return errwrap.Wrapf("Error creating InfluxDB Client: ", err)
}