DBPW - Update MSSQL to adhere to v5 Database interface (#10128)

This commit is contained in:
Michael Golowka
2020-10-13 11:11:00 -06:00
committed by GitHub
parent dfb041598d
commit 21d13e4671
2 changed files with 310 additions and 378 deletions

View File

@@ -4,162 +4,43 @@ import (
"context"
"database/sql"
"fmt"
"reflect"
"regexp"
"strings"
"testing"
"time"
mssqlhelper "github.com/hashicorp/vault/helper/testhelpers/mssql"
"github.com/hashicorp/vault/sdk/database/dbplugin"
"github.com/hashicorp/vault/sdk/database/newdbplugin"
dbtesting "github.com/hashicorp/vault/sdk/database/newdbplugin/testing"
"github.com/hashicorp/vault/sdk/helper/dbtxn"
mssqlhelper "github.com/hashicorp/vault/helper/testhelpers/mssql"
)
func TestMSSQL_Initialize(t *testing.T) {
func TestInitialize(t *testing.T) {
cleanup, connURL := mssqlhelper.PrepareMSSQLTestContainer(t)
defer cleanup()
connectionDetails := map[string]interface{}{
"connection_url": connURL,
}
db := new()
_, err := db.Init(context.Background(), connectionDetails, true)
if err != nil {
t.Fatalf("err: %s", err)
}
if !db.Initialized {
t.Fatal("Database should be initialized")
}
err = db.Close()
if err != nil {
t.Fatalf("err: %s", err)
}
// Test decoding a string value for max_open_connections
connectionDetails = map[string]interface{}{
"connection_url": connURL,
"max_open_connections": "5",
}
_, err = db.Init(context.Background(), connectionDetails, true)
if err != nil {
t.Fatalf("err: %s", err)
}
}
func TestMSSQL_CreateUser(t *testing.T) {
cleanup, connURL := mssqlhelper.PrepareMSSQLTestContainer(t)
defer cleanup()
connectionDetails := map[string]interface{}{
"connection_url": connURL,
}
db := new()
_, err := db.Init(context.Background(), connectionDetails, true)
if err != nil {
t.Fatalf("err: %s", err)
}
usernameConfig := dbplugin.UsernameConfig{
DisplayName: "test",
RoleName: "test",
}
// Test with no configured Creation Statement
_, _, err = db.CreateUser(context.Background(), dbplugin.Statements{}, usernameConfig, time.Now().Add(time.Minute))
if err == nil {
t.Fatal("Expected error when no creation statement is provided")
}
statements := dbplugin.Statements{
Creation: []string{testMSSQLRole},
}
username, password, err := db.CreateUser(context.Background(), statements, usernameConfig, time.Now().Add(time.Minute))
if err != nil {
t.Fatalf("err: %s", err)
}
if err = testCredsExist(t, connURL, username, password); err != nil {
t.Fatalf("Could not connect with new credentials: %s", err)
}
}
func TestMSSQL_RotateRootCredentials(t *testing.T) {
cleanup, connURL := mssqlhelper.PrepareMSSQLTestContainer(t)
defer cleanup()
connectionDetails := map[string]interface{}{
"connection_url": connURL,
"username": "sa",
"password": "yourStrong(!)Password",
}
db := new()
connProducer := db.SQLConnectionProducer
_, err := db.Init(context.Background(), connectionDetails, true)
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"] == "yourStrong(!)Password" {
t.Fatal("password was not updated")
}
err = db.Close()
if err != nil {
t.Fatalf("err: %s", err)
}
}
func TestMSSQL_SetCredentials_missingArgs(t *testing.T) {
type testCase struct {
statements dbplugin.Statements
userConfig dbplugin.StaticUserConfig
req newdbplugin.InitializeRequest
}
tests := map[string]testCase{
"empty rotation statements": {
statements: dbplugin.Statements{
Rotation: nil,
},
userConfig: dbplugin.StaticUserConfig{
Username: "testuser",
Password: "password",
"happy path": {
req: newdbplugin.InitializeRequest{
Config: map[string]interface{}{
"connection_url": connURL,
},
VerifyConnection: true,
},
},
"empty username": {
statements: dbplugin.Statements{
Rotation: []string{`
ALTER LOGIN [{{username}}] WITH PASSWORD = '{{password}}';`,
"max_open_connections set": {
newdbplugin.InitializeRequest{
Config: map[string]interface{}{
"connection_url": connURL,
"max_open_connections": "5",
},
},
userConfig: dbplugin.StaticUserConfig{
Username: "",
Password: "password",
},
},
"empty password": {
statements: dbplugin.Statements{
Rotation: []string{`
ALTER LOGIN [{{username}}] WITH PASSWORD = '{{password}}';`,
},
},
userConfig: dbplugin.StaticUserConfig{
Username: "testuser",
Password: "",
VerifyConnection: true,
},
},
}
@@ -167,33 +48,165 @@ func TestMSSQL_SetCredentials_missingArgs(t *testing.T) {
for name, test := range tests {
t.Run(name, func(t *testing.T) {
db := new()
dbtesting.AssertInitialize(t, db, test.req)
defer dbtesting.AssertClose(t, db)
username, password, err := db.SetCredentials(context.Background(), test.statements, test.userConfig)
if err == nil {
t.Fatalf("expected err, got nil")
}
if username != "" {
t.Fatalf("expected empty username, got [%s]", username)
}
if password != "" {
t.Fatalf("expected empty password, got [%s]", password)
if !db.Initialized {
t.Fatal("Database should be initialized")
}
})
}
}
func TestMSSQL_SetCredentials(t *testing.T) {
func TestNewUser(t *testing.T) {
cleanup, connURL := mssqlhelper.PrepareMSSQLTestContainer(t)
defer cleanup()
type testCase struct {
rotationStmts []string
req newdbplugin.NewUserRequest
usernameRegex string
expectErr bool
assertUser func(t testing.TB, connURL, username, password string)
}
tests := map[string]testCase{
"empty rotation statements": {
rotationStmts: []string{},
}, "username rotation": {
rotationStmts: []string{`
ALTER LOGIN [{{username}}] WITH PASSWORD = '{{password}}';`,
"no creation statements": {
req: newdbplugin.NewUserRequest{
UsernameConfig: newdbplugin.UsernameMetadata{
DisplayName: "test",
RoleName: "test",
},
Statements: newdbplugin.Statements{},
Password: "AG4qagho-dsvZ",
Expiration: time.Now().Add(1 * time.Second),
},
usernameRegex: "^$",
expectErr: true,
assertUser: assertCredsDoNotExist,
},
"with creation statements": {
req: newdbplugin.NewUserRequest{
UsernameConfig: newdbplugin.UsernameMetadata{
DisplayName: "test",
RoleName: "test",
},
Statements: newdbplugin.Statements{
Commands: []string{testMSSQLRole},
},
Password: "AG4qagho-dsvZ",
Expiration: time.Now().Add(1 * time.Second),
},
usernameRegex: "^v-test-test-[a-zA-Z0-9]{20}-[0-9]{10}$",
expectErr: false,
assertUser: assertCredsExist,
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
usernameRe, err := regexp.Compile(test.usernameRegex)
if err != nil {
t.Fatalf("failed to compile username regex %q: %s", test.usernameRegex, err)
}
initReq := newdbplugin.InitializeRequest{
Config: map[string]interface{}{
"connection_url": connURL,
},
VerifyConnection: true,
}
db := new()
dbtesting.AssertInitialize(t, db, initReq)
defer dbtesting.AssertClose(t, db)
createResp, err := db.NewUser(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 !usernameRe.MatchString(createResp.Username) {
t.Fatalf("Generated username %q did not match regex %q", createResp.Username, test.usernameRegex)
}
// Protect against future fields that aren't specified
expectedResp := newdbplugin.NewUserResponse{
Username: createResp.Username,
}
if !reflect.DeepEqual(createResp, expectedResp) {
t.Fatalf("Fields missing from expected response: Actual: %#v", createResp)
}
test.assertUser(t, connURL, createResp.Username, test.req.Password)
})
}
}
func TestUpdateUser_password(t *testing.T) {
type testCase struct {
req newdbplugin.UpdateUserRequest
expectErr bool
expectedPassword string
}
dbUser := "vaultuser"
initPassword := "p4$sw0rd"
tests := map[string]testCase{
"missing password": {
req: newdbplugin.UpdateUserRequest{
Username: dbUser,
Password: &newdbplugin.ChangePassword{
NewPassword: "",
Statements: newdbplugin.Statements{},
},
},
expectErr: true,
expectedPassword: initPassword,
},
"empty rotation statements": {
req: newdbplugin.UpdateUserRequest{
Username: dbUser,
Password: &newdbplugin.ChangePassword{
NewPassword: "N90gkKLy8$angf",
Statements: newdbplugin.Statements{},
},
},
expectErr: false,
expectedPassword: "N90gkKLy8$angf",
},
"username rotation": {
req: newdbplugin.UpdateUserRequest{
Username: dbUser,
Password: &newdbplugin.ChangePassword{
NewPassword: "N90gkKLy8$angf",
Statements: newdbplugin.Statements{
Commands: []string{
"ALTER LOGIN [{{username}}] WITH PASSWORD = '{{password}}'",
},
},
},
},
expectErr: false,
expectedPassword: "N90gkKLy8$angf",
},
"bad statements": {
req: newdbplugin.UpdateUserRequest{
Username: dbUser,
Password: &newdbplugin.ChangePassword{
NewPassword: "N90gkKLy8$angf",
Statements: newdbplugin.Statements{
Commands: []string{
"ahosh98asjdffs",
},
},
},
},
expectErr: true,
expectedPassword: initPassword,
},
}
@@ -202,124 +215,101 @@ func TestMSSQL_SetCredentials(t *testing.T) {
cleanup, connURL := mssqlhelper.PrepareMSSQLTestContainer(t)
defer cleanup()
connectionDetails := map[string]interface{}{
"connection_url": connURL,
initReq := newdbplugin.InitializeRequest{
Config: map[string]interface{}{
"connection_url": connURL,
},
VerifyConnection: true,
}
db := new()
dbtesting.AssertInitialize(t, db, initReq)
defer dbtesting.AssertClose(t, db)
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
_, err := db.Init(ctx, connectionDetails, true)
if err != nil {
t.Fatalf("err: %s", err)
}
dbUser := "vaultstatictest"
initPassword := "p4$sw0rd"
createTestMSSQLUser(t, connURL, dbUser, initPassword, testMSSQLLogin)
if err := testCredsExist(t, connURL, dbUser, initPassword); err != nil {
t.Fatalf("Could not connect with initial credentials: %s", err)
assertCredsExist(t, connURL, dbUser, initPassword)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
updateResp, err := db.UpdateUser(ctx, 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)
}
statements := dbplugin.Statements{
Rotation: test.rotationStmts,
}
newPassword, err := db.GenerateCredentials(context.Background())
if err != nil {
t.Fatal(err)
}
usernameConfig := dbplugin.StaticUserConfig{
Username: dbUser,
Password: newPassword,
}
username, password, err := db.SetCredentials(ctx, statements, usernameConfig)
if err != nil {
t.Fatalf("err: %s", err)
}
if err := testCredsExist(t, connURL, username, password); err != nil {
t.Fatalf("Could not connect with new credentials: %s", err)
}
if err := testCredsExist(t, connURL, username, initPassword); err == nil {
t.Fatalf("Should not be able to connect with initial credentials")
// Protect against future fields that aren't specified
expectedResp := newdbplugin.UpdateUserResponse{}
if !reflect.DeepEqual(updateResp, expectedResp) {
t.Fatalf("Fields missing from expected response: Actual: %#v", updateResp)
}
assertCredsExist(t, connURL, dbUser, test.expectedPassword)
})
}
}
func TestMSSQL_RevokeUser(t *testing.T) {
func TestDeleteUser(t *testing.T) {
cleanup, connURL := mssqlhelper.PrepareMSSQLTestContainer(t)
defer cleanup()
connectionDetails := map[string]interface{}{
"connection_url": connURL,
dbUser := "vaultuser"
initPassword := "p4$sw0rd"
initReq := newdbplugin.InitializeRequest{
Config: map[string]interface{}{
"connection_url": connURL,
},
VerifyConnection: true,
}
db := new()
_, err := db.Init(context.Background(), connectionDetails, true)
dbtesting.AssertInitialize(t, db, initReq)
defer dbtesting.AssertClose(t, db)
createTestMSSQLUser(t, connURL, dbUser, initPassword, testMSSQLLogin)
assertCredsExist(t, connURL, dbUser, initPassword)
deleteReq := newdbplugin.DeleteUserRequest{
Username: dbUser,
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
deleteResp, err := db.DeleteUser(ctx, deleteReq)
if err != nil {
t.Fatalf("err: %s", err)
t.Fatalf("Failed to delete user: %s", err)
}
statements := dbplugin.Statements{
Creation: []string{testMSSQLRole},
// Protect against future fields that aren't specified
expectedResp := newdbplugin.DeleteUserResponse{}
if !reflect.DeepEqual(deleteResp, expectedResp) {
t.Fatalf("Fields missing from expected response: Actual: %#v", deleteResp)
}
usernameConfig := dbplugin.UsernameConfig{
DisplayName: "test",
RoleName: "test",
}
assertCredsDoNotExist(t, connURL, dbUser, initPassword)
}
username, password, err := db.CreateUser(context.Background(), statements, usernameConfig, time.Now().Add(2*time.Second))
func assertCredsExist(t testing.TB, connURL, username, password string) {
t.Helper()
err := testCredsExist(connURL, username, password)
if err != nil {
t.Fatalf("err: %s", err)
}
if err = testCredsExist(t, connURL, username, password); err != nil {
t.Fatalf("Could not connect with new credentials: %s", err)
}
// Test default revoke statements
err = db.RevokeUser(context.Background(), statements, username)
if err != nil {
t.Fatalf("err: %s", err)
}
if err := testCredsExist(t, connURL, username, password); err == nil {
t.Fatal("Credentials were not revoked")
}
username, password, err = db.CreateUser(context.Background(), statements, usernameConfig, time.Now().Add(2*time.Second))
if err != nil {
t.Fatalf("err: %s", err)
}
if err = testCredsExist(t, connURL, username, password); err != nil {
t.Fatalf("Could not connect with new credentials: %s", err)
}
// Test custom revoke statement
statements.Revocation = []string{testMSSQLDrop}
err = db.RevokeUser(context.Background(), statements, username)
if err != nil {
t.Fatalf("err: %s", err)
}
if err := testCredsExist(t, connURL, username, password); err == nil {
t.Fatal("Credentials were not revoked")
t.Fatalf("Unable to log in as %q: %s", username, err)
}
}
func testCredsExist(t testing.TB, connURL, username, password string) error {
func assertCredsDoNotExist(t testing.TB, connURL, username, password string) {
t.Helper()
err := testCredsExist(connURL, username, password)
if err == nil {
t.Fatalf("Able to log in when it shouldn't")
}
}
func testCredsExist(connURL, username, password string) error {
// Log in with the new creds
parts := strings.Split(connURL, "@")
connURL = fmt.Sprintf("sqlserver://%s:%s@%s", username, password, parts[1])
@@ -332,7 +322,6 @@ func testCredsExist(t testing.TB, connURL, username, password string) error {
}
func createTestMSSQLUser(t *testing.T, connURL string, username, password, query string) {
db, err := sql.Open("mssql", connURL)
defer db.Close()
if err != nil {