open-vault/builtin/logical/database/backend.go

182 lines
4.1 KiB
Go
Raw Normal View History

2016-12-19 18:15:58 +00:00
package database
import (
"fmt"
"net/rpc"
2016-12-19 18:15:58 +00:00
"strings"
"sync"
log "github.com/mgutz/logxi/v1"
2017-04-06 19:20:10 +00:00
"github.com/hashicorp/vault/builtin/logical/database/dbplugin"
2016-12-19 18:15:58 +00:00
"github.com/hashicorp/vault/logical"
"github.com/hashicorp/vault/logical/framework"
)
2017-04-13 00:35:02 +00:00
const databaseConfigPath = "database/config/"
2016-12-19 18:15:58 +00:00
func Factory(conf *logical.BackendConfig) (logical.Backend, error) {
Backend plugin system (#2874) * Add backend plugin changes * Fix totp backend plugin tests * Fix logical/plugin InvalidateKey test * Fix plugin catalog CRUD test, fix NoopBackend * Clean up commented code block * Fix system backend mount test * Set plugin_name to omitempty, fix handleMountTable config parsing * Clean up comments, keep shim connections alive until cleanup * Include pluginClient, disallow LookupPlugin call from within a plugin * Add wrapper around backendPluginClient for proper cleanup * Add logger shim tests * Add logger, storage, and system shim tests * Use pointer receivers for system view shim * Use plugin name if no path is provided on mount * Enable plugins for auth backends * Add backend type attribute, move builtin/plugin/package * Fix merge conflict * Fix missing plugin name in mount config * Add integration tests on enabling auth backend plugins * Remove dependency cycle on mock-plugin * Add passthrough backend plugin, use logical.BackendType to determine lease generation * Remove vault package dependency on passthrough package * Add basic impl test for passthrough plugin * Incorporate feedback; set b.backend after shims creation on backendPluginServer * Fix totp plugin test * Add plugin backends docs * Fix tests * Fix builtin/plugin tests * Remove flatten from PluginRunner fields * Move mock plugin to logical/plugin, remove totp and passthrough plugins * Move pluginMap into newPluginClient * Do not create storage RPC connection on HandleRequest and HandleExistenceCheck * Change shim logger's Fatal to no-op * Change BackendType to uint32, match UX backend types * Change framework.Backend Setup signature * Add Setup func to logical.Backend interface * Move OptionallyEnableMlock call into plugin.Serve, update docs and comments * Remove commented var in plugin package * RegisterLicense on logical.Backend interface (#3017) * Add RegisterLicense to logical.Backend interface * Update RegisterLicense to use callback func on framework.Backend * Refactor framework.Backend.RegisterLicense * plugin: Prevent plugin.SystemViewClient.ResponseWrapData from getting JWTs * plugin: Revert BackendType to remove TypePassthrough and related references * Fix typo in plugin backends docs
2017-07-20 17:28:40 +00:00
b := Backend(conf)
if err := b.Setup(conf); err != nil {
return nil, err
}
return b, nil
2016-12-19 18:15:58 +00:00
}
func Backend(conf *logical.BackendConfig) *databaseBackend {
var b databaseBackend
b.Backend = &framework.Backend{
Help: strings.TrimSpace(backendHelp),
Paths: []*framework.Path{
pathListPluginConnection(&b),
pathConfigurePluginConnection(&b),
2016-12-19 18:15:58 +00:00
pathListRoles(&b),
pathRoles(&b),
pathCredsCreate(&b),
pathResetConnection(&b),
2016-12-19 18:15:58 +00:00
},
Secrets: []*framework.Secret{
secretCreds(&b),
},
Clean: b.closeAllDBs,
Invalidate: b.invalidate,
BackendType: logical.TypeLogical,
2016-12-19 18:15:58 +00:00
}
b.logger = conf.Logger
2017-04-24 20:59:12 +00:00
b.connections = make(map[string]dbplugin.Database)
2016-12-19 18:15:58 +00:00
return &b
}
type databaseBackend struct {
2017-04-24 20:59:12 +00:00
connections map[string]dbplugin.Database
2016-12-19 18:15:58 +00:00
logger log.Logger
*framework.Backend
2017-04-26 22:23:14 +00:00
sync.RWMutex
2016-12-19 18:15:58 +00:00
}
2017-05-04 00:37:34 +00:00
// closeAllDBs closes all connections from all database types
2017-03-10 06:35:45 +00:00
func (b *databaseBackend) closeAllDBs() {
2016-12-19 18:15:58 +00:00
b.Lock()
defer b.Unlock()
for _, db := range b.connections {
db.Close()
}
2017-04-11 00:12:52 +00:00
2017-04-24 20:59:12 +00:00
b.connections = make(map[string]dbplugin.Database)
2016-12-19 18:15:58 +00:00
}
// This function is used to retrieve a database object either from the cached
2017-04-26 22:23:14 +00:00
// connection map. The caller of this function needs to hold the backend's read
// lock.
func (b *databaseBackend) getDBObj(name string) (dbplugin.Database, bool) {
db, ok := b.connections[name]
2017-04-26 22:23:14 +00:00
return db, ok
}
2017-04-26 22:23:14 +00:00
// This function creates a new db object from the stored configuration and
// caches it in the connections map. The caller of this function needs to hold
// the backend's write lock
func (b *databaseBackend) createDBObj(s logical.Storage, name string) (dbplugin.Database, error) {
db, ok := b.connections[name]
if ok {
return db, nil
}
2017-04-13 17:33:34 +00:00
config, err := b.DatabaseConfig(s, name)
if err != nil {
return nil, err
}
db, err = dbplugin.PluginFactory(config.PluginName, b.System(), b.logger)
if err != nil {
return nil, err
}
err = db.Initialize(config.ConnectionDetails, true)
if err != nil {
return nil, err
}
b.connections[name] = db
return db, nil
}
2017-04-13 17:33:34 +00:00
func (b *databaseBackend) DatabaseConfig(s logical.Storage, name string) (*DatabaseConfig, error) {
entry, err := s.Get(fmt.Sprintf("config/%s", name))
if err != nil {
return nil, fmt.Errorf("failed to read connection configuration: %s", err)
2017-04-13 17:33:34 +00:00
}
if entry == nil {
return nil, fmt.Errorf("failed to find entry for connection with name: %s", name)
}
var config DatabaseConfig
if err := entry.DecodeJSON(&config); err != nil {
return nil, err
}
return &config, nil
}
2017-05-04 00:37:34 +00:00
func (b *databaseBackend) Role(s logical.Storage, roleName string) (*roleEntry, error) {
entry, err := s.Get("role/" + roleName)
2016-12-19 18:15:58 +00:00
if err != nil {
return nil, err
}
if entry == nil {
return nil, nil
}
var result roleEntry
if err := entry.DecodeJSON(&result); err != nil {
return nil, err
}
return &result, nil
}
func (b *databaseBackend) invalidate(key string) {
b.Lock()
defer b.Unlock()
switch {
case strings.HasPrefix(key, databaseConfigPath):
name := strings.TrimPrefix(key, databaseConfigPath)
b.clearConnection(name)
}
}
// clearConnection closes the database connection and
// removes it from the b.connections map.
func (b *databaseBackend) clearConnection(name string) {
db, ok := b.connections[name]
if ok {
db.Close()
delete(b.connections, name)
}
}
func (b *databaseBackend) closeIfShutdown(name string, err error) {
// Plugin has shutdown, close it so next call can reconnect.
if err == rpc.ErrShutdown {
b.Lock()
b.clearConnection(name)
b.Unlock()
}
}
2016-12-19 18:15:58 +00:00
const backendHelp = `
The database backend supports using many different databases
as secret backends, including but not limited to:
2017-05-04 00:37:34 +00:00
cassandra, mssql, mysql, postgres
2016-12-19 18:15:58 +00:00
After mounting this backend, configure it using the endpoints within
2017-04-12 23:41:06 +00:00
the "database/config/" path.
2016-12-19 18:15:58 +00:00
`