Merge pull request #261 from jsok/consul-lease

Add ability to configure consul lease durations
This commit is contained in:
Armon Dadgar 2015-06-01 13:04:28 +02:00
commit 98cca9cb18
5 changed files with 92 additions and 31 deletions

View file

@ -26,7 +26,7 @@ func TestBackend_basic(t *testing.T) {
Backend: Backend(),
Steps: []logicaltest.TestStep{
testAccStepConfig(t, config),
testAccStepWritePolicy(t, "test", testPolicy),
testAccStepWritePolicy(t, "test", testPolicy, ""),
testAccStepReadToken(t, "test", config),
},
})
@ -40,8 +40,23 @@ func TestBackend_crud(t *testing.T) {
PreCheck: func() { testAccPreCheck(t) },
Backend: Backend(),
Steps: []logicaltest.TestStep{
testAccStepWritePolicy(t, "test", testPolicy),
testAccStepReadPolicy(t, "test", testPolicy),
testAccStepWritePolicy(t, "test", testPolicy, ""),
testAccStepReadPolicy(t, "test", testPolicy, DefaultLeaseDuration),
testAccStepDeletePolicy(t, "test"),
},
})
}
func TestBackend_role_lease(t *testing.T) {
_, process := testStartConsulServer(t)
defer testStopConsulServer(t, process)
logicaltest.Test(t, logicaltest.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Backend: Backend(),
Steps: []logicaltest.TestStep{
testAccStepWritePolicy(t, "test", testPolicy, "6h"),
testAccStepReadPolicy(t, "test", testPolicy, 6*time.Hour),
testAccStepDeletePolicy(t, "test"),
},
})
@ -142,17 +157,18 @@ func testAccStepReadToken(
}
}
func testAccStepWritePolicy(t *testing.T, name string, policy string) logicaltest.TestStep {
func testAccStepWritePolicy(t *testing.T, name string, policy string, lease string) logicaltest.TestStep {
return logicaltest.TestStep{
Operation: logical.WriteOperation,
Path: "roles/" + name,
Data: map[string]interface{}{
"policy": base64.StdEncoding.EncodeToString([]byte(policy)),
"lease": lease,
},
}
}
func testAccStepReadPolicy(t *testing.T, name string, policy string) logicaltest.TestStep {
func testAccStepReadPolicy(t *testing.T, name string, policy string, lease time.Duration) logicaltest.TestStep {
return logicaltest.TestStep{
Operation: logical.ReadOperation,
Path: "roles/" + name,
@ -165,6 +181,15 @@ func testAccStepReadPolicy(t *testing.T, name string, policy string) logicaltest
if string(out) != policy {
return fmt.Errorf("mismatch: %s %s", out, policy)
}
leaseRaw := resp.Data["lease"].(string)
l, err := time.ParseDuration(leaseRaw)
if err != nil {
return err
}
if l != lease {
return fmt.Errorf("mismatch: %v %v", l, lease)
}
return nil
},
}

View file

@ -3,6 +3,7 @@ package consul
import (
"encoding/base64"
"fmt"
"time"
"github.com/hashicorp/vault/logical"
"github.com/hashicorp/vault/logical/framework"
@ -21,6 +22,11 @@ func pathRoles() *framework.Path {
Type: framework.TypeString,
Description: "Policy document, base64 encoded.",
},
"lease": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Lease time of the role.",
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
@ -35,20 +41,24 @@ func pathRolesRead(
req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
name := d.Get("name").(string)
// Read the policy
policy, err := req.Storage.Get("policy/" + name)
entry, err := req.Storage.Get("policy/" + name)
if err != nil {
return nil, fmt.Errorf("error retrieving role: %s", err)
return nil, err
}
if policy == nil {
return logical.ErrorResponse(fmt.Sprintf(
"Role '%s' not found", name)), nil
if entry == nil {
return nil, nil
}
var result roleConfig
if err := entry.DecodeJSON(&result); err != nil {
return nil, err
}
// Generate the response
resp := &logical.Response{
Data: map[string]interface{}{
"policy": base64.StdEncoding.EncodeToString(policy.Value),
"policy": base64.StdEncoding.EncodeToString([]byte(result.Policy)),
"lease": result.Lease.String(),
},
}
return resp, nil
@ -56,21 +66,29 @@ func pathRolesRead(
func pathRolesWrite(
req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
name := d.Get("name").(string)
policyRaw, err := base64.StdEncoding.DecodeString(d.Get("policy").(string))
if err != nil {
return logical.ErrorResponse(fmt.Sprintf(
"Error decoding policy base64: %s", err)), nil
}
lease, err := time.ParseDuration(d.Get("lease").(string))
if err != nil || lease == time.Duration(0) {
lease = DefaultLeaseDuration
}
// Write the policy into storage
err = req.Storage.Put(&logical.StorageEntry{
Key: "policy/" + d.Get("name").(string),
Value: policyRaw,
entry, err := logical.StorageEntryJSON("policy/"+name, roleConfig{
Policy: string(policyRaw),
Lease: lease,
})
if err != nil {
return nil, err
}
if err := req.Storage.Put(entry); err != nil {
return nil, err
}
return nil, nil
}
@ -82,3 +100,8 @@ func pathRolesDelete(
}
return nil, nil
}
type roleConfig struct {
Policy string `json:"policy"`
Lease time.Duration `json:"lease"`
}

View file

@ -27,19 +27,19 @@ func pathToken(b *backend) *framework.Path {
func (b *backend) pathTokenRead(
req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
policyName := d.Get("name").(string)
name := d.Get("name").(string)
// Generate a random name for the token
name := fmt.Sprintf("Vault %s %d", req.DisplayName, time.Now().Unix())
// Read the policy
policy, err := req.Storage.Get("policy/" + policyName)
entry, err := req.Storage.Get("policy/" + name)
if err != nil {
return nil, fmt.Errorf("error retrieving role: %s", err)
}
if policy == nil {
return logical.ErrorResponse(fmt.Sprintf(
"Role '%s' not found", policyName)), nil
if entry == nil {
return logical.ErrorResponse(fmt.Sprintf("Role '%s' not found", name)), nil
}
var result roleConfig
if err := entry.DecodeJSON(&result); err != nil {
return nil, err
}
// Get the consul client
@ -48,18 +48,22 @@ func (b *backend) pathTokenRead(
return logical.ErrorResponse(err.Error()), nil
}
// Generate a random name for the token
tokenName := fmt.Sprintf("Vault %s %d", req.DisplayName, time.Now().Unix())
// Create it
token, _, err := c.ACL().Create(&api.ACLEntry{
Name: name,
Name: tokenName,
Type: "client",
Rules: string(policy.Value),
Rules: result.Policy,
}, nil)
if err != nil {
return logical.ErrorResponse(err.Error()), nil
}
// Use the helper to create the secret
return b.Secret(SecretTokenType).Response(map[string]interface{}{
s := b.Secret(SecretTokenType)
s.DefaultDuration = result.Lease
return s.Response(map[string]interface{}{
"token": token,
}, nil), nil
}

View file

@ -7,7 +7,11 @@ import (
"github.com/hashicorp/vault/logical/framework"
)
const SecretTokenType = "token"
const (
SecretTokenType = "token"
DefaultLeaseDuration = 1 * time.Hour
DefaultGracePeriod = 10 * time.Minute
)
func secretToken() *framework.Secret {
return &framework.Secret{
@ -19,8 +23,8 @@ func secretToken() *framework.Secret {
},
},
DefaultDuration: 1 * time.Hour,
DefaultGracePeriod: 10 * time.Minute,
DefaultDuration: DefaultLeaseDuration,
DefaultGracePeriod: DefaultGracePeriod,
Renew: framework.LeaseExtend(1*time.Hour, 0),
Revoke: secretTokenRevoke,

View file

@ -143,6 +143,11 @@ Permission denied
<span class="param-flags">required</span>
The base64 encoded Consul ACL policy. This is documented in [more detail here](https://consul.io/docs/internals/acl.html).
</li>
<li>
<span class="param">lease</span>
<span class="param-flags">optional</span>
The lease value provided as a string duration with time suffix. Hour is the largest suffix.
</li>
</ul>
</dd>