More work on getting tests to pass

This commit is contained in:
Brian Kassouf 2017-03-23 15:54:15 -07:00
parent c0223d888e
commit 29ae4602dc
7 changed files with 369 additions and 644 deletions

View file

@ -1,620 +0,0 @@
package database
import (
"database/sql"
"encoding/json"
"fmt"
"log"
"os"
"path"
"reflect"
"sync"
"testing"
"time"
"github.com/hashicorp/vault/logical"
logicaltest "github.com/hashicorp/vault/logical/testing"
"github.com/lib/pq"
"github.com/mitchellh/mapstructure"
"github.com/ory-am/dockertest"
)
var (
testImagePull sync.Once
)
func prepareTestContainer(t *testing.T, s logical.Storage, b logical.Backend) (cid dockertest.ContainerID, retURL string) {
if os.Getenv("PG_URL") != "" {
return "", os.Getenv("PG_URL")
}
// Without this the checks for whether the container has started seem to
// never actually pass. There's really no reason to expose the test
// containers, so don't.
dockertest.BindDockerToLocalhost = "yep"
testImagePull.Do(func() {
dockertest.Pull("postgres")
})
cid, connErr := dockertest.ConnectToPostgreSQL(60, 500*time.Millisecond, func(connURL string) bool {
// This will cause a validation to run
resp, err := b.HandleRequest(&logical.Request{
Storage: s,
Operation: logical.UpdateOperation,
Path: "config/connection",
Data: map[string]interface{}{
"connection_url": connURL,
},
})
if err != nil || (resp != nil && resp.IsError()) {
// It's likely not up and running yet, so return false and try again
return false
}
if resp == nil {
t.Fatal("expected warning")
}
retURL = connURL
return true
})
if connErr != nil {
t.Fatalf("could not connect to database: %v", connErr)
}
return
}
func cleanupTestContainer(t *testing.T, cid dockertest.ContainerID) {
err := cid.KillRemove()
if err != nil {
t.Fatal(err)
}
}
func TestBackend_config_connection(t *testing.T) {
var resp *logical.Response
var err error
config := logical.TestBackendConfig()
config.StorageView = &logical.InmemStorage{}
b, err := Factory(config)
if err != nil {
t.Fatal(err)
}
configData := map[string]interface{}{
"connection_url": "sample_connection_url",
"value": "",
"max_open_connections": 9,
"max_idle_connections": 7,
"verify_connection": false,
}
configReq := &logical.Request{
Operation: logical.UpdateOperation,
Path: "config/connection",
Storage: config.StorageView,
Data: configData,
}
resp, err = b.HandleRequest(configReq)
if err != nil || (resp != nil && resp.IsError()) {
t.Fatalf("err:%s resp:%#v\n", err, resp)
}
configReq.Operation = logical.ReadOperation
resp, err = b.HandleRequest(configReq)
if err != nil || (resp != nil && resp.IsError()) {
t.Fatalf("err:%s resp:%#v\n", err, resp)
}
delete(configData, "verify_connection")
if !reflect.DeepEqual(configData, resp.Data) {
t.Fatalf("bad: expected:%#v\nactual:%#v\n", configData, resp.Data)
}
}
func TestBackend_basic(t *testing.T) {
config := logical.TestBackendConfig()
config.StorageView = &logical.InmemStorage{}
b, err := Factory(config)
if err != nil {
t.Fatal(err)
}
cid, connURL := prepareTestContainer(t, config.StorageView, b)
if cid != "" {
defer cleanupTestContainer(t, cid)
}
connData := map[string]interface{}{
"connection_url": connURL,
}
logicaltest.Test(t, logicaltest.TestCase{
Backend: b,
Steps: []logicaltest.TestStep{
testAccStepConfig(t, connData, false),
testAccStepCreateRole(t, "web", testRole, false),
testAccStepReadCreds(t, b, config.StorageView, "web", connURL),
},
})
}
func TestBackend_roleCrud(t *testing.T) {
config := logical.TestBackendConfig()
config.StorageView = &logical.InmemStorage{}
b, err := Factory(config)
if err != nil {
t.Fatal(err)
}
cid, connURL := prepareTestContainer(t, config.StorageView, b)
if cid != "" {
defer cleanupTestContainer(t, cid)
}
connData := map[string]interface{}{
"connection_url": connURL,
}
logicaltest.Test(t, logicaltest.TestCase{
Backend: b,
Steps: []logicaltest.TestStep{
testAccStepConfig(t, connData, false),
testAccStepCreateRole(t, "web", testRole, false),
testAccStepReadRole(t, "web", testRole),
testAccStepDeleteRole(t, "web"),
testAccStepReadRole(t, "web", ""),
},
})
}
func TestBackend_BlockStatements(t *testing.T) {
config := logical.TestBackendConfig()
config.StorageView = &logical.InmemStorage{}
b, err := Factory(config)
if err != nil {
t.Fatal(err)
}
cid, connURL := prepareTestContainer(t, config.StorageView, b)
if cid != "" {
defer cleanupTestContainer(t, cid)
}
connData := map[string]interface{}{
"connection_url": connURL,
}
jsonBlockStatement, err := json.Marshal(testBlockStatementRoleSlice)
if err != nil {
t.Fatal(err)
}
logicaltest.Test(t, logicaltest.TestCase{
Backend: b,
Steps: []logicaltest.TestStep{
testAccStepConfig(t, connData, false),
// This will also validate the query
testAccStepCreateRole(t, "web-block", testBlockStatementRole, true),
testAccStepCreateRole(t, "web-block", string(jsonBlockStatement), false),
},
})
}
func TestBackend_roleReadOnly(t *testing.T) {
config := logical.TestBackendConfig()
config.StorageView = &logical.InmemStorage{}
b, err := Factory(config)
if err != nil {
t.Fatal(err)
}
cid, connURL := prepareTestContainer(t, config.StorageView, b)
if cid != "" {
defer cleanupTestContainer(t, cid)
}
connData := map[string]interface{}{
"connection_url": connURL,
}
logicaltest.Test(t, logicaltest.TestCase{
Backend: b,
Steps: []logicaltest.TestStep{
testAccStepConfig(t, connData, false),
testAccStepCreateRole(t, "web", testRole, false),
testAccStepCreateRole(t, "web-readonly", testReadOnlyRole, false),
testAccStepReadRole(t, "web-readonly", testReadOnlyRole),
testAccStepCreateTable(t, b, config.StorageView, "web", connURL),
testAccStepReadCreds(t, b, config.StorageView, "web-readonly", connURL),
testAccStepDropTable(t, b, config.StorageView, "web", connURL),
testAccStepDeleteRole(t, "web-readonly"),
testAccStepDeleteRole(t, "web"),
testAccStepReadRole(t, "web-readonly", ""),
},
})
}
func TestBackend_roleReadOnly_revocationSQL(t *testing.T) {
config := logical.TestBackendConfig()
config.StorageView = &logical.InmemStorage{}
b, err := Factory(config)
if err != nil {
t.Fatal(err)
}
cid, connURL := prepareTestContainer(t, config.StorageView, b)
if cid != "" {
defer cleanupTestContainer(t, cid)
}
connData := map[string]interface{}{
"connection_url": connURL,
}
logicaltest.Test(t, logicaltest.TestCase{
Backend: b,
Steps: []logicaltest.TestStep{
testAccStepConfig(t, connData, false),
testAccStepCreateRoleWithRevocationSQL(t, "web", testRole, defaultRevocationSQL, false),
testAccStepCreateRoleWithRevocationSQL(t, "web-readonly", testReadOnlyRole, defaultRevocationSQL, false),
testAccStepReadRole(t, "web-readonly", testReadOnlyRole),
testAccStepCreateTable(t, b, config.StorageView, "web", connURL),
testAccStepReadCreds(t, b, config.StorageView, "web-readonly", connURL),
testAccStepDropTable(t, b, config.StorageView, "web", connURL),
testAccStepDeleteRole(t, "web-readonly"),
testAccStepDeleteRole(t, "web"),
testAccStepReadRole(t, "web-readonly", ""),
},
})
}
func testAccStepConfig(t *testing.T, d map[string]interface{}, expectError bool) logicaltest.TestStep {
return logicaltest.TestStep{
Operation: logical.UpdateOperation,
Path: "config/connection",
Data: d,
ErrorOk: true,
Check: func(resp *logical.Response) error {
if expectError {
if resp.Data == nil {
return fmt.Errorf("data is nil")
}
var e struct {
Error string `mapstructure:"error"`
}
if err := mapstructure.Decode(resp.Data, &e); err != nil {
return err
}
if len(e.Error) == 0 {
return fmt.Errorf("expected error, but write succeeded.")
}
return nil
} else if resp != nil && resp.IsError() {
return fmt.Errorf("got an error response: %v", resp.Error())
}
return nil
},
}
}
func testAccStepCreateRole(t *testing.T, name string, sql string, expectFail bool) logicaltest.TestStep {
return logicaltest.TestStep{
Operation: logical.UpdateOperation,
Path: path.Join("roles", name),
Data: map[string]interface{}{
"sql": sql,
},
ErrorOk: expectFail,
}
}
func testAccStepCreateRoleWithRevocationSQL(t *testing.T, name, sql, revocationSQL string, expectFail bool) logicaltest.TestStep {
return logicaltest.TestStep{
Operation: logical.UpdateOperation,
Path: path.Join("roles", name),
Data: map[string]interface{}{
"sql": sql,
"revocation_sql": revocationSQL,
},
ErrorOk: expectFail,
}
}
func testAccStepDeleteRole(t *testing.T, name string) logicaltest.TestStep {
return logicaltest.TestStep{
Operation: logical.DeleteOperation,
Path: path.Join("roles", name),
}
}
func testAccStepReadCreds(t *testing.T, b logical.Backend, s logical.Storage, name string, connURL string) logicaltest.TestStep {
return logicaltest.TestStep{
Operation: logical.ReadOperation,
Path: path.Join("creds", name),
Check: func(resp *logical.Response) error {
var d struct {
Username string `mapstructure:"username"`
Password string `mapstructure:"password"`
}
if err := mapstructure.Decode(resp.Data, &d); err != nil {
return err
}
log.Printf("[TRACE] Generated credentials: %v", d)
conn, err := pq.ParseURL(connURL)
if err != nil {
t.Fatal(err)
}
conn += " timezone=utc"
db, err := sql.Open("postgres", conn)
if err != nil {
t.Fatal(err)
}
returnedRows := func() int {
stmt, err := db.Prepare("SELECT DISTINCT schemaname FROM pg_tables WHERE has_table_privilege($1, 'information_schema.role_column_grants', 'select');")
if err != nil {
return -1
}
defer stmt.Close()
rows, err := stmt.Query(d.Username)
if err != nil {
return -1
}
defer rows.Close()
i := 0
for rows.Next() {
i++
}
return i
}
// minNumPermissions is the minimum number of permissions that will always be present.
const minNumPermissions = 2
userRows := returnedRows()
if userRows < minNumPermissions {
t.Fatalf("did not get expected number of rows, got %d", userRows)
}
resp, err = b.HandleRequest(&logical.Request{
Operation: logical.RevokeOperation,
Storage: s,
Secret: &logical.Secret{
InternalData: map[string]interface{}{
"secret_type": "creds",
"username": d.Username,
"role": name,
},
},
})
if err != nil {
return err
}
if resp != nil {
if resp.IsError() {
return fmt.Errorf("Error on resp: %#v", *resp)
}
}
userRows = returnedRows()
// User shouldn't exist so returnedRows() should encounter an error and exit with -1
if userRows != -1 {
t.Fatalf("did not get expected number of rows, got %d", userRows)
}
return nil
},
}
}
func testAccStepCreateTable(t *testing.T, b logical.Backend, s logical.Storage, name string, connURL string) logicaltest.TestStep {
return logicaltest.TestStep{
Operation: logical.ReadOperation,
Path: path.Join("creds", name),
Check: func(resp *logical.Response) error {
var d struct {
Username string `mapstructure:"username"`
Password string `mapstructure:"password"`
}
if err := mapstructure.Decode(resp.Data, &d); err != nil {
return err
}
log.Printf("[TRACE] Generated credentials: %v", d)
conn, err := pq.ParseURL(connURL)
if err != nil {
t.Fatal(err)
}
conn += " timezone=utc"
db, err := sql.Open("postgres", conn)
if err != nil {
t.Fatal(err)
}
_, err = db.Exec("CREATE TABLE test (id SERIAL PRIMARY KEY);")
if err != nil {
t.Fatal(err)
}
resp, err = b.HandleRequest(&logical.Request{
Operation: logical.RevokeOperation,
Storage: s,
Secret: &logical.Secret{
InternalData: map[string]interface{}{
"secret_type": "creds",
"username": d.Username,
},
},
})
if err != nil {
return err
}
if resp != nil {
if resp.IsError() {
return fmt.Errorf("Error on resp: %#v", *resp)
}
}
return nil
},
}
}
func testAccStepDropTable(t *testing.T, b logical.Backend, s logical.Storage, name string, connURL string) logicaltest.TestStep {
return logicaltest.TestStep{
Operation: logical.ReadOperation,
Path: path.Join("creds", name),
Check: func(resp *logical.Response) error {
var d struct {
Username string `mapstructure:"username"`
Password string `mapstructure:"password"`
}
if err := mapstructure.Decode(resp.Data, &d); err != nil {
return err
}
log.Printf("[TRACE] Generated credentials: %v", d)
conn, err := pq.ParseURL(connURL)
if err != nil {
t.Fatal(err)
}
conn += " timezone=utc"
db, err := sql.Open("postgres", conn)
if err != nil {
t.Fatal(err)
}
_, err = db.Exec("DROP TABLE test;")
if err != nil {
t.Fatal(err)
}
resp, err = b.HandleRequest(&logical.Request{
Operation: logical.RevokeOperation,
Storage: s,
Secret: &logical.Secret{
InternalData: map[string]interface{}{
"secret_type": "creds",
"username": d.Username,
},
},
})
if err != nil {
return err
}
if resp != nil {
if resp.IsError() {
return fmt.Errorf("Error on resp: %#v", *resp)
}
}
return nil
},
}
}
func testAccStepReadRole(t *testing.T, name string, sql string) logicaltest.TestStep {
return logicaltest.TestStep{
Operation: logical.ReadOperation,
Path: "roles/" + name,
Check: func(resp *logical.Response) error {
if resp == nil {
if sql == "" {
return nil
}
return fmt.Errorf("bad: %#v", resp)
}
var d struct {
SQL string `mapstructure:"sql"`
}
if err := mapstructure.Decode(resp.Data, &d); err != nil {
return err
}
if d.SQL != sql {
return fmt.Errorf("bad: %#v", resp)
}
return nil
},
}
}
const testRole = `
CREATE ROLE "{{name}}" WITH
LOGIN
PASSWORD '{{password}}'
VALID UNTIL '{{expiration}}';
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO "{{name}}";
`
const testReadOnlyRole = `
CREATE ROLE "{{name}}" WITH
LOGIN
PASSWORD '{{password}}'
VALID UNTIL '{{expiration}}';
GRANT SELECT ON ALL TABLES IN SCHEMA public TO "{{name}}";
GRANT SELECT ON ALL SEQUENCES IN SCHEMA public TO "{{name}}";
`
const testBlockStatementRole = `
DO $$
BEGIN
IF NOT EXISTS (SELECT * FROM pg_catalog.pg_roles WHERE rolname='foo-role') THEN
CREATE ROLE "foo-role";
CREATE SCHEMA IF NOT EXISTS foo AUTHORIZATION "foo-role";
ALTER ROLE "foo-role" SET search_path = foo;
GRANT TEMPORARY ON DATABASE "postgres" TO "foo-role";
GRANT ALL PRIVILEGES ON SCHEMA foo TO "foo-role";
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA foo TO "foo-role";
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA foo TO "foo-role";
GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA foo TO "foo-role";
END IF;
END
$$
CREATE ROLE "{{name}}" WITH LOGIN PASSWORD '{{password}}' VALID UNTIL '{{expiration}}';
GRANT "foo-role" TO "{{name}}";
ALTER ROLE "{{name}}" SET search_path = foo;
GRANT CONNECT ON DATABASE "postgres" TO "{{name}}";
`
var testBlockStatementRoleSlice = []string{
`
DO $$
BEGIN
IF NOT EXISTS (SELECT * FROM pg_catalog.pg_roles WHERE rolname='foo-role') THEN
CREATE ROLE "foo-role";
CREATE SCHEMA IF NOT EXISTS foo AUTHORIZATION "foo-role";
ALTER ROLE "foo-role" SET search_path = foo;
GRANT TEMPORARY ON DATABASE "postgres" TO "foo-role";
GRANT ALL PRIVILEGES ON SCHEMA foo TO "foo-role";
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA foo TO "foo-role";
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA foo TO "foo-role";
GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA foo TO "foo-role";
END IF;
END
$$
`,
`CREATE ROLE "{{name}}" WITH LOGIN PASSWORD '{{password}}' VALID UNTIL '{{expiration}}';`,
`GRANT "foo-role" TO "{{name}}";`,
`ALTER ROLE "{{name}}" SET search_path = foo;`,
`GRANT CONNECT ON DATABASE "postgres" TO "{{name}}";`,
}
const defaultRevocationSQL = `
REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM {{name}};
REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public FROM {{name}};
REVOKE USAGE ON SCHEMA public FROM {{name}};
DROP ROLE IF EXISTS {{name}};
`

View file

@ -24,7 +24,7 @@ func prepareMySQLTestContainer(t *testing.T) (cid dockertest.ContainerID, retURL
// containers, so don't.
dockertest.BindDockerToLocalhost = "yep"
testImagePull.Do(func() {
testMySQLImagePull.Do(func() {
dockertest.Pull("mysql")
})

View file

@ -6,12 +6,12 @@ import (
"fmt"
"net/rpc"
"os/exec"
"strings"
"sync"
"time"
"github.com/hashicorp/go-plugin"
"github.com/hashicorp/vault/helper/pluginutil"
"github.com/hashicorp/vault/logical"
)
// handshakeConfigs are used to just do a basic handshake between
@ -55,7 +55,7 @@ func (dc *DatabasePluginClient) Close() error {
// newPluginClient returns a databaseRPCClient with a connection to a running
// plugin. The client is wrapped in a DatabasePluginClient object to ensure the
// plugin is killed on call of Close().
func newPluginClient(sys logical.SystemView, command, checksum string) (DatabaseType, error) {
func newPluginClient(sys pluginutil.Wrapper, command, checksum string) (DatabaseType, error) {
// pluginMap is the map of plugins we can dispense.
var pluginMap = map[string]plugin.Plugin{
"database": new(DatabasePlugin),
@ -81,7 +81,8 @@ func newPluginClient(sys logical.SystemView, command, checksum string) (Database
}
// Add the response wrap token to the ENV of the plugin
cmd := exec.Command(command)
commandArr := strings.Split(command, " ")
cmd := exec.Command(commandArr[0], commandArr[1])
cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", pluginutil.PluginUnwrapTokenEnv, wrapToken))
checksumDecoded, err := hex.DecodeString(checksum)
@ -265,7 +266,7 @@ func (ds *databasePluginRPCServer) Initialize(args map[string]interface{}, _ *st
return err
}
func (ds *databasePluginRPCServer) Close(_ interface{}, _ *struct{}) error {
func (ds *databasePluginRPCServer) Close(_ struct{}, _ *struct{}) error {
ds.impl.Close()
return nil
}

View file

@ -0,0 +1,325 @@
package dbs
import (
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"net"
"os"
"os/exec"
"sync"
"testing"
"time"
"github.com/hashicorp/vault/helper/pluginutil"
"github.com/hashicorp/vault/http"
"github.com/hashicorp/vault/logical"
"github.com/hashicorp/vault/vault"
)
var (
testPluginImagePull sync.Once
)
type mockPlugin struct {
users map[string][]string
CredentialsProducer
}
func (m *mockPlugin) Type() string { return "mock" }
func (m *mockPlugin) CreateUser(statements Statements, username, password, expiration string) error {
err := errors.New("err")
if username == "" || password == "" || expiration == "" {
return err
}
if _, ok := m.users[username]; ok {
return err
}
m.users[username] = []string{password, expiration}
return nil
}
func (m *mockPlugin) RenewUser(statements Statements, username, expiration string) error {
err := errors.New("err")
if username == "" || expiration == "" {
return err
}
if _, ok := m.users[username]; !ok {
return err
}
return nil
}
func (m *mockPlugin) RevokeUser(statements Statements, username string) error {
err := errors.New("err")
if username == "" {
return err
}
if _, ok := m.users[username]; !ok {
return err
}
delete(m.users, username)
return nil
}
func (m *mockPlugin) Initialize(conf map[string]interface{}) error {
err := errors.New("err")
if len(conf) != 1 {
return err
}
return nil
}
func (m *mockPlugin) Close() error {
m.users = nil
return nil
}
func getConf(t *testing.T) *DatabaseConfig {
command := fmt.Sprintf("%s -test.run=TestPlugin_Main", os.Args[0])
cmd := exec.Command(os.Args[0])
hash := sha256.New()
file, err := os.Open(cmd.Path)
if err != nil {
t.Fatal(err)
}
defer file.Close()
_, err = io.Copy(hash, file)
if err != nil {
t.Fatal(err)
}
sum := hash.Sum(nil)
conf := &DatabaseConfig{
DatabaseType: pluginTypeName,
PluginCommand: command,
PluginChecksum: hex.EncodeToString(sum),
ConnectionDetails: map[string]interface{}{
"test": true,
},
}
return conf
}
func getCore(t *testing.T) (*vault.Core, net.Listener, logical.SystemView) {
core, _, _, ln := vault.TestCoreUnsealedWithListener(t)
http.TestServerWithListener(t, ln, "", core)
sys := vault.TestDynamicSystemView(core)
return core, ln, sys
}
func TestPlugin_Main(t *testing.T) {
if os.Getenv(pluginutil.PluginUnwrapTokenEnv) == "" {
return
}
plugin := &mockPlugin{
users: make(map[string][]string),
CredentialsProducer: &sqlCredentialsProducer{5, 50},
}
NewPluginServer(plugin)
}
func TestPlugin_Initialize(t *testing.T) {
_, ln, sys := getCore(t)
defer ln.Close()
conf := getConf(t)
dbRaw, err := PluginFactory(conf, sys)
if err != nil {
t.Fatalf("err: %s", err)
}
err = dbRaw.Initialize(conf.ConnectionDetails)
if err != nil {
t.Fatalf("err: %s", err)
}
err = dbRaw.Close()
if err != nil {
t.Fatalf("err: %s", err)
}
}
func TestPlugin_CreateUser(t *testing.T) {
_, ln, sys := getCore(t)
defer ln.Close()
conf := getConf(t)
db, err := PluginFactory(conf, sys)
if err != nil {
t.Fatalf("err: %s", err)
}
defer db.Close()
err = db.Initialize(conf.ConnectionDetails)
if err != nil {
t.Fatalf("err: %s", err)
}
username, err := db.GenerateUsername("test")
if err != nil {
t.Fatalf("err: %s", err)
}
password, err := db.GeneratePassword()
if err != nil {
t.Fatalf("err: %s", err)
}
expiration, err := db.GenerateExpiration(time.Minute)
if err != nil {
t.Fatalf("err: %s", err)
}
err = db.CreateUser(Statements{}, username, password, expiration)
if err != nil {
t.Fatalf("err: %s", err)
}
// try and save the same user again to verify it saved the first time, this
// should return an error
err = db.CreateUser(Statements{}, username, password, expiration)
if err == nil {
t.Fatal("expected an error, user wasn't created correctly")
}
// Create one more user
username, err = db.GenerateUsername("test")
if err != nil {
t.Fatalf("err: %s", err)
}
err = db.CreateUser(Statements{}, username, password, expiration)
if err != nil {
t.Fatalf("err: %s", err)
}
}
func TestPlugin_RenewUser(t *testing.T) {
_, ln, sys := getCore(t)
defer ln.Close()
conf := getConf(t)
db, err := PluginFactory(conf, sys)
if err != nil {
t.Fatalf("err: %s", err)
}
defer db.Close()
err = db.Initialize(conf.ConnectionDetails)
if err != nil {
t.Fatalf("err: %s", err)
}
username, err := db.GenerateUsername("test")
if err != nil {
t.Fatalf("err: %s", err)
}
password, err := db.GeneratePassword()
if err != nil {
t.Fatalf("err: %s", err)
}
expiration, err := db.GenerateExpiration(time.Minute)
if err != nil {
t.Fatalf("err: %s", err)
}
err = db.CreateUser(Statements{}, username, password, expiration)
if err != nil {
t.Fatalf("err: %s", err)
}
expiration, err = db.GenerateExpiration(time.Minute)
if err != nil {
t.Fatalf("err: %s", err)
}
err = db.RenewUser(Statements{}, username, expiration)
if err != nil {
t.Fatalf("err: %s", err)
}
}
func TestPlugin_RevokeUser(t *testing.T) {
_, ln, sys := getCore(t)
defer ln.Close()
conf := getConf(t)
db, err := PluginFactory(conf, sys)
if err != nil {
t.Fatalf("err: %s", err)
}
defer db.Close()
err = db.Initialize(conf.ConnectionDetails)
if err != nil {
t.Fatalf("err: %s", err)
}
username, err := db.GenerateUsername("test")
if err != nil {
t.Fatalf("err: %s", err)
}
password, err := db.GeneratePassword()
if err != nil {
t.Fatalf("err: %s", err)
}
expiration, err := db.GenerateExpiration(time.Minute)
if err != nil {
t.Fatalf("err: %s", err)
}
err = db.CreateUser(Statements{}, username, password, expiration)
if err != nil {
t.Fatalf("err: %s", err)
}
// Test default revoke statememts
err = db.RevokeUser(Statements{}, username)
if err != nil {
t.Fatalf("err: %s", err)
}
// Try adding the same username back so we can verify it was removed
err = db.CreateUser(Statements{}, username, password, expiration)
if err != nil {
t.Fatalf("err: %s", err)
}
username, err = db.GenerateUsername("test")
if err != nil {
t.Fatalf("err: %s", err)
}
expiration, err = db.GenerateExpiration(time.Minute)
if err != nil {
t.Fatalf("err: %s", err)
}
// try once more
err = db.CreateUser(Statements{}, username, password, expiration)
if err != nil {
t.Fatalf("err: %s", err)
}
err = db.RevokeUser(Statements{}, username)
if err != nil {
t.Fatalf("err: %s", err)
}
}

View file

@ -11,10 +11,10 @@ import (
)
var (
testImagePull sync.Once
testPostgresImagePull sync.Once
)
func prepareTestContainer(t *testing.T) (cid dockertest.ContainerID, retURL string) {
func preparePostgresTestContainer(t *testing.T) (cid dockertest.ContainerID, retURL string) {
if os.Getenv("PG_URL") != "" {
return "", os.Getenv("PG_URL")
}
@ -24,7 +24,7 @@ func prepareTestContainer(t *testing.T) (cid dockertest.ContainerID, retURL stri
// containers, so don't.
dockertest.BindDockerToLocalhost = "yep"
testImagePull.Do(func() {
testPostgresImagePull.Do(func() {
dockertest.Pull("postgres")
})
@ -65,7 +65,7 @@ func cleanupTestContainer(t *testing.T, cid dockertest.ContainerID) {
}
func TestPostgreSQL_Initialize(t *testing.T) {
cid, connURL := prepareTestContainer(t)
cid, connURL := preparePostgresTestContainer(t)
if cid != "" {
defer cleanupTestContainer(t, cid)
}
@ -107,7 +107,7 @@ func TestPostgreSQL_Initialize(t *testing.T) {
}
func TestPostgreSQL_CreateUser(t *testing.T) {
cid, connURL := prepareTestContainer(t)
cid, connURL := preparePostgresTestContainer(t)
if cid != "" {
defer cleanupTestContainer(t, cid)
}
@ -150,7 +150,7 @@ func TestPostgreSQL_CreateUser(t *testing.T) {
}
statements := Statements{
CreationStatements: testRole,
CreationStatements: testPostgresRole,
}
err = db.CreateUser(statements, username, password, expiration)
@ -172,7 +172,7 @@ func TestPostgreSQL_CreateUser(t *testing.T) {
if err != nil {
t.Fatalf("err: %s", err)
}
statements.CreationStatements = testReadOnlyRole
statements.CreationStatements = testPostgresReadOnlyRole
err = db.CreateUser(statements, username, password, expiration)
if err != nil {
t.Fatalf("err: %s", err)
@ -200,7 +200,7 @@ func TestPostgreSQL_CreateUser(t *testing.T) {
}
func TestPostgreSQL_RenewUser(t *testing.T) {
cid, connURL := prepareTestContainer(t)
cid, connURL := preparePostgresTestContainer(t)
if cid != "" {
defer cleanupTestContainer(t, cid)
}
@ -237,7 +237,7 @@ func TestPostgreSQL_RenewUser(t *testing.T) {
}
statements := Statements{
CreationStatements: testRole,
CreationStatements: testPostgresRole,
}
err = db.CreateUser(statements, username, password, expiration)
@ -256,7 +256,7 @@ func TestPostgreSQL_RenewUser(t *testing.T) {
}
func TestPostgreSQL_RevokeUser(t *testing.T) {
cid, connURL := prepareTestContainer(t)
cid, connURL := preparePostgresTestContainer(t)
if cid != "" {
defer cleanupTestContainer(t, cid)
}
@ -293,7 +293,7 @@ func TestPostgreSQL_RevokeUser(t *testing.T) {
}
statements := Statements{
CreationStatements: testRole,
CreationStatements: testPostgresRole,
}
err = db.CreateUser(statements, username, password, expiration)
@ -333,7 +333,7 @@ func TestPostgreSQL_RevokeUser(t *testing.T) {
}
// Test custom revoke statements
statements.RevocationStatements = defaultRevocationSQL
statements.RevocationStatements = defaultPostgresRevocationSQL
err = db.RevokeUser(statements, username)
if err != nil {
t.Fatalf("err: %s", err)
@ -341,7 +341,7 @@ func TestPostgreSQL_RevokeUser(t *testing.T) {
}
const testRole = `
const testPostgresRole = `
CREATE ROLE "{{name}}" WITH
LOGIN
PASSWORD '{{password}}'
@ -349,7 +349,7 @@ CREATE ROLE "{{name}}" WITH
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO "{{name}}";
`
const testReadOnlyRole = `
const testPostgresReadOnlyRole = `
CREATE ROLE "{{name}}" WITH
LOGIN
PASSWORD '{{password}}'
@ -358,7 +358,7 @@ GRANT SELECT ON ALL TABLES IN SCHEMA public TO "{{name}}";
GRANT SELECT ON ALL SEQUENCES IN SCHEMA public TO "{{name}}";
`
const testBlockStatementRole = `
const testPostgresBlockStatementRole = `
DO $$
BEGIN
IF NOT EXISTS (SELECT * FROM pg_catalog.pg_roles WHERE rolname='foo-role') THEN
@ -380,7 +380,7 @@ ALTER ROLE "{{name}}" SET search_path = foo;
GRANT CONNECT ON DATABASE "postgres" TO "{{name}}";
`
var testBlockStatementRoleSlice = []string{
var testPostgresBlockStatementRoleSlice = []string{
`
DO $$
BEGIN
@ -403,7 +403,7 @@ $$
`GRANT CONNECT ON DATABASE "postgres" TO "{{name}}";`,
}
const defaultRevocationSQL = `
const defaultPostgresRevocationSQL = `
REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM "{{name}}";
REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public FROM "{{name}}";
REVOKE USAGE ON SCHEMA public FROM "{{name}}";

View file

@ -21,7 +21,6 @@ import (
"github.com/hashicorp/errwrap"
uuid "github.com/hashicorp/go-uuid"
"github.com/hashicorp/vault/api"
"github.com/hashicorp/vault/logical"
)
var (
@ -30,6 +29,10 @@ var (
PluginUnwrapTokenEnv = "VAULT_UNWRAP_TOKEN"
)
type Wrapper interface {
ResponseWrapData(data map[string]interface{}, ttl time.Duration, jwt bool) (string, error)
}
// GenerateCACert returns a CA cert used to later sign the certificates for the
// plugin client and server.
func GenerateCACert() ([]byte, *x509.Certificate, *ecdsa.PrivateKey, error) {
@ -147,7 +150,7 @@ func CreateClientTLSConfig(CACert *x509.Certificate, CAKey *ecdsa.PrivateKey) (*
// WrapServerConfig is used to create a server certificate and private key, then
// wrap them in an unwrap token for later retrieval by the plugin.
func WrapServerConfig(sys logical.SystemView, CACertBytes []byte, CACert *x509.Certificate, CAKey *ecdsa.PrivateKey) (string, error) {
func WrapServerConfig(sys Wrapper, CACertBytes []byte, CACert *x509.Certificate, CAKey *ecdsa.PrivateKey) (string, error) {
serverCertBytes, _, serverKey, err := generateSignedCert(CACert, CAKey)
if err != nil {
return "", err

View file

@ -231,6 +231,18 @@ func TestCoreUnsealedBackend(t testing.TB, backend physical.Backend) (*Core, [][
return core, keys, token
}
func TestCoreUnsealedWithListener(t testing.TB) (*Core, [][]byte, string, net.Listener) {
core, keys, token := TestCoreUnsealed(t)
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("err: %s", err)
}
addr := "http://" + ln.Addr().String()
core.redirectAddr = addr
return core, keys, token, ln
}
func testTokenStore(t testing.TB, c *Core) *TokenStore {
me := &MountEntry{
Table: credentialTableType,
@ -293,6 +305,10 @@ func TestKeyCopy(key []byte) []byte {
return result
}
func TestDynamicSystemView(c *Core) *dynamicSystemView {
return &dynamicSystemView{c, nil}
}
var testLogicalBackends = map[string]logical.Factory{}
// Starts the test server which responds to SSH authentication.