Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

InfluxDB - Add username customization #11796

Merged
merged 3 commits into from
Jun 9, 2021
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 30 additions & 10 deletions plugins/database/influxdb/influxdb.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ package influxdb
import (
"context"
"fmt"
"github.com/hashicorp/vault/sdk/helper/template"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You may not have set this up already, but the goimports tool is useful to organize imports in a consistent way. I suggest to try running that tool on this file! I would expect to see this import grouped with the other group ("github.com/*") below.

This is just a stylistic suggestion. We usually try to organize imports consistently in Vault.

"strings"

multierror "github.com/hashicorp/go-multierror"
dbplugin "github.com/hashicorp/vault/sdk/database/dbplugin/v5"
"github.com/hashicorp/vault/sdk/database/helper/credsutil"
"github.com/hashicorp/vault/sdk/database/helper/dbutil"
"github.com/hashicorp/vault/sdk/helper/strutil"
influx "github.com/influxdata/influxdb/client/v2"
Expand All @@ -18,13 +18,17 @@ const (
defaultUserDeletionIFQL = `DROP USER "{{username}}";`
defaultRootCredentialRotationIFQL = `SET PASSWORD FOR "{{username}}" = '{{password}}';`
influxdbTypeName = "influxdb"

defaultUserNameTemplate = `{{ printf "v_%s_%s_%s_%s" (.DisplayName | truncate 15) (.RoleName | truncate 15) (random 20) (unix_time) | truncate 100 | replace "-" "_" | lowercase }}`
)

var _ dbplugin.Database = &Influxdb{}

// Influxdb is an implementation of Database interface
type Influxdb struct {
*influxdbConnectionProducer

usernameProducer template.StringTemplate
}

// New returns a new Cassandra instance
Expand Down Expand Up @@ -58,6 +62,29 @@ func (i *Influxdb) getConnection(ctx context.Context) (influx.Client, error) {
return cli.(influx.Client), nil
}

func (i *Influxdb) Initialize(ctx context.Context, req dbplugin.InitializeRequest) (resp dbplugin.InitializeResponse, err error) {
usernameTemplate, err := strutil.GetString(req.Config, "username_template")
if err != nil {
return dbplugin.InitializeResponse{}, fmt.Errorf("failed to retrieve username_template: %w", err)
}
if usernameTemplate == "" {
usernameTemplate = defaultUserNameTemplate
}

up, err := template.NewTemplate(template.Template(usernameTemplate))
if err != nil {
return dbplugin.InitializeResponse{}, fmt.Errorf("unable to initialize username template: %w", err)
}
i.usernameProducer = up

_, err = i.usernameProducer.Generate(dbplugin.UsernameMetadata{})
if err != nil {
return dbplugin.InitializeResponse{}, fmt.Errorf("invalid username template: %w", err)
}

return i.influxdbConnectionProducer.Initialize(ctx, req)
}

// 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 dbplugin.NewUserRequest) (resp dbplugin.NewUserResponse, err error) {
Expand All @@ -79,17 +106,10 @@ func (i *Influxdb) NewUser(ctx context.Context, req dbplugin.NewUserRequest) (re
rollbackIFQL = []string{defaultUserDeletionIFQL}
}

username, err := credsutil.GenerateUsername(
credsutil.DisplayName(req.UsernameConfig.DisplayName, 15),
credsutil.RoleName(req.UsernameConfig.RoleName, 15),
credsutil.MaxLength(100),
credsutil.Separator("_"),
credsutil.ToLower(),
)
username, err := i.usernameProducer.Generate(req.UsernameConfig)
if err != nil {
return dbplugin.NewUserResponse{}, fmt.Errorf("failed to generate username: %w", err)
return dbplugin.NewUserResponse{}, err
}
username = strings.Replace(username, "-", "_", -1)

for _, stmt := range creationIFQL {
for _, query := range strutil.ParseArbitraryStringSlice(stmt, ";") {
Expand Down
47 changes: 44 additions & 3 deletions plugins/database/influxdb/influxdb_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
dbplugin "github.com/hashicorp/vault/sdk/database/dbplugin/v5"
dbtesting "github.com/hashicorp/vault/sdk/database/dbplugin/v5/testing"
influx "github.com/influxdata/influxdb/client/v2"
"github.com/stretchr/testify/require"
)

const createUserStatements = `CREATE USER "{{username}}" WITH PASSWORD '{{password}}';GRANT ALL ON "vault" TO "{{username}}";`
Expand Down Expand Up @@ -220,7 +221,7 @@ func makeConfig(rootConfig map[string]interface{}, keyValues ...interface{}) map
return config
}

func TestInfluxdb_CreateUser(t *testing.T) {
func TestInfluxdb_CreateUser_DefaultUsernameTemplate(t *testing.T) {
cleanup, config := prepareInfluxdbTestContainer(t)
defer cleanup()

Expand All @@ -234,8 +235,46 @@ func TestInfluxdb_CreateUser(t *testing.T) {
password := "nuozxby98523u89bdfnkjl"
newUserReq := dbplugin.NewUserRequest{
UsernameConfig: dbplugin.UsernameMetadata{
DisplayName: "test",
RoleName: "test",
DisplayName: "token",
RoleName: "mylongrolenamewithmanycharacters",
},
Statements: dbplugin.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")
}

assertCredsExist(t, config.URL().String(), resp.Username, password)

require.Regexp(t, `^v_token_mylongrolenamew_[a-z0-9]{20}_[0-9]{10}$`, resp.Username)
}

func TestInfluxdb_CreateUser_CustomUsernameTemplate(t *testing.T) {
cleanup, config := prepareInfluxdbTestContainer(t)
defer cleanup()

db := new()

conf := config.connectionParams()
conf["username_template"] = "{{.DisplayName}}_{{random 10}}"

req := dbplugin.InitializeRequest{
Config: conf,
VerifyConnection: true,
}
dbtesting.AssertInitialize(t, db, req)

password := "nuozxby98523u89bdfnkjl"
newUserReq := dbplugin.NewUserRequest{
UsernameConfig: dbplugin.UsernameMetadata{
DisplayName: "token",
RoleName: "mylongrolenamewithmanycharacters",
},
Statements: dbplugin.Statements{
Commands: []string{createUserStatements},
Expand All @@ -250,6 +289,8 @@ func TestInfluxdb_CreateUser(t *testing.T) {
}

assertCredsExist(t, config.URL().String(), resp.Username, password)

require.Regexp(t, `^token_[a-zA-Z0-9]{10}$`, resp.Username)
}

func TestUpdateUser_expiration(t *testing.T) {
Expand Down