Overhauling the client method and attaching it to the backend

This commit is contained in:
Nicolas Corrarello 2017-11-03 07:19:49 +00:00
parent eb7a0c0e83
commit 4b572c064c
4 changed files with 57 additions and 36 deletions

View file

@ -1,6 +1,10 @@
package nomad
import (
"fmt"
"sync"
"github.com/hashicorp/nomad/api"
"github.com/hashicorp/vault/logical"
"github.com/hashicorp/vault/logical/framework"
)
@ -34,4 +38,53 @@ func Backend() *backend {
type backend struct {
*framework.Backend
client *api.Client
lock sync.RWMutex
}
func (b *backend) Client(s logical.Storage) (*api.Client, error) {
b.lock.RLock()
// If we already have a client, return it
if b.client != nil {
b.lock.RUnlock()
return b.client, nil
}
b.lock.RUnlock()
conf, intErr := readConfigAccess(s)
if intErr != nil {
return nil, intErr
}
if conf == nil {
return nil, fmt.Errorf("no error received but no configuration found")
}
nomadConf := api.DefaultConfig()
nomadConf.Address = conf.Address
nomadConf.SecretID = conf.Token
b.lock.Lock()
defer b.lock.Unlock()
// If the client was creted during the lock switch, return it
if b.client != nil {
return b.client, nil
}
var err error
b.client, err = api.NewClient(nomadConf)
if err != nil {
return nil, err
}
return b.client, nil
}
func (b *backend) resetClient() {
b.lock.Lock()
defer b.lock.Unlock()
b.client = nil
}

View file

@ -1,25 +0,0 @@
package nomad
import (
"fmt"
"github.com/hashicorp/nomad/api"
"github.com/hashicorp/vault/logical"
)
func client(s logical.Storage) (*api.Client, error, error) {
conf, intErr := readConfigAccess(s)
if intErr != nil {
return nil, nil, intErr
}
if conf == nil {
return nil, nil, fmt.Errorf("no error received but no configuration found")
}
nomadConf := api.DefaultConfig()
nomadConf.Address = conf.Address
nomadConf.SecretID = conf.Token
client, err := api.NewClient(nomadConf)
return client, nil, err
}

View file

@ -47,13 +47,10 @@ func (b *backend) pathTokenRead(
}
// Get the nomad client
c, userErr, intErr := client(req.Storage)
c, intErr := b.Client(req.Storage)
if intErr != nil {
return nil, intErr
}
if userErr != nil {
return logical.ErrorResponse(userErr.Error()), nil
}
// Generate a name for the token
tokenName := fmt.Sprintf("Vault %s %s %d", name, req.DisplayName, time.Now().UnixNano())

View file

@ -20,7 +20,7 @@ func secretToken(b *backend) *framework.Secret {
},
Renew: b.secretTokenRenew,
Revoke: secretTokenRevoke,
Revoke: b.secretTokenRevoke,
}
}
@ -30,16 +30,12 @@ func (b *backend) secretTokenRenew(
return framework.LeaseExtend(0, 0, b.System())(req, d)
}
func secretTokenRevoke(
func (b *backend) secretTokenRevoke(
req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
c, userErr, intErr := client(req.Storage)
c, intErr := b.Client(req.Storage)
if intErr != nil {
return nil, intErr
}
if userErr != nil {
// Returning logical.ErrorResponse from revocation function is risky
return nil, userErr
}
tokenRaw, _ := req.Secret.InternalData["accessor_id"]