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 35b10a7a9a
5 changed files with 92 additions and 31 deletions

View File

@ -26,7 +26,7 @@ func TestBackend_basic(t *testing.T) {
Backend: Backend(), Backend: Backend(),
Steps: []logicaltest.TestStep{ Steps: []logicaltest.TestStep{
testAccStepConfig(t, config), testAccStepConfig(t, config),
testAccStepWritePolicy(t, "test", testPolicy), testAccStepWritePolicy(t, "test", testPolicy, ""),
testAccStepReadToken(t, "test", config), testAccStepReadToken(t, "test", config),
}, },
}) })
@ -40,8 +40,23 @@ func TestBackend_crud(t *testing.T) {
PreCheck: func() { testAccPreCheck(t) }, PreCheck: func() { testAccPreCheck(t) },
Backend: Backend(), Backend: Backend(),
Steps: []logicaltest.TestStep{ Steps: []logicaltest.TestStep{
testAccStepWritePolicy(t, "test", testPolicy), testAccStepWritePolicy(t, "test", testPolicy, ""),
testAccStepReadPolicy(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"), 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{ return logicaltest.TestStep{
Operation: logical.WriteOperation, Operation: logical.WriteOperation,
Path: "roles/" + name, Path: "roles/" + name,
Data: map[string]interface{}{ Data: map[string]interface{}{
"policy": base64.StdEncoding.EncodeToString([]byte(policy)), "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{ return logicaltest.TestStep{
Operation: logical.ReadOperation, Operation: logical.ReadOperation,
Path: "roles/" + name, Path: "roles/" + name,
@ -165,6 +181,15 @@ func testAccStepReadPolicy(t *testing.T, name string, policy string) logicaltest
if string(out) != policy { if string(out) != policy {
return fmt.Errorf("mismatch: %s %s", 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 return nil
}, },
} }

View File

@ -3,6 +3,7 @@ package consul
import ( import (
"encoding/base64" "encoding/base64"
"fmt" "fmt"
"time"
"github.com/hashicorp/vault/logical" "github.com/hashicorp/vault/logical"
"github.com/hashicorp/vault/logical/framework" "github.com/hashicorp/vault/logical/framework"
@ -21,6 +22,11 @@ func pathRoles() *framework.Path {
Type: framework.TypeString, Type: framework.TypeString,
Description: "Policy document, base64 encoded.", Description: "Policy document, base64 encoded.",
}, },
"lease": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Lease time of the role.",
},
}, },
Callbacks: map[logical.Operation]framework.OperationFunc{ Callbacks: map[logical.Operation]framework.OperationFunc{
@ -35,20 +41,24 @@ func pathRolesRead(
req *logical.Request, d *framework.FieldData) (*logical.Response, error) { req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
name := d.Get("name").(string) name := d.Get("name").(string)
// Read the policy entry, err := req.Storage.Get("policy/" + name)
policy, err := req.Storage.Get("policy/" + name)
if err != nil { if err != nil {
return nil, fmt.Errorf("error retrieving role: %s", err) return nil, err
} }
if policy == nil { if entry == nil {
return logical.ErrorResponse(fmt.Sprintf( return nil, nil
"Role '%s' not found", name)), nil }
var result roleConfig
if err := entry.DecodeJSON(&result); err != nil {
return nil, err
} }
// Generate the response // Generate the response
resp := &logical.Response{ resp := &logical.Response{
Data: map[string]interface{}{ Data: map[string]interface{}{
"policy": base64.StdEncoding.EncodeToString(policy.Value), "policy": base64.StdEncoding.EncodeToString([]byte(result.Policy)),
"lease": result.Lease.String(),
}, },
} }
return resp, nil return resp, nil
@ -56,21 +66,29 @@ func pathRolesRead(
func pathRolesWrite( func pathRolesWrite(
req *logical.Request, d *framework.FieldData) (*logical.Response, error) { req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
name := d.Get("name").(string)
policyRaw, err := base64.StdEncoding.DecodeString(d.Get("policy").(string)) policyRaw, err := base64.StdEncoding.DecodeString(d.Get("policy").(string))
if err != nil { if err != nil {
return logical.ErrorResponse(fmt.Sprintf( return logical.ErrorResponse(fmt.Sprintf(
"Error decoding policy base64: %s", err)), nil "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 entry, err := logical.StorageEntryJSON("policy/"+name, roleConfig{
err = req.Storage.Put(&logical.StorageEntry{ Policy: string(policyRaw),
Key: "policy/" + d.Get("name").(string), Lease: lease,
Value: policyRaw,
}) })
if err != nil { if err != nil {
return nil, err return nil, err
} }
if err := req.Storage.Put(entry); err != nil {
return nil, err
}
return nil, nil return nil, nil
} }
@ -82,3 +100,8 @@ func pathRolesDelete(
} }
return nil, nil 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( func (b *backend) pathTokenRead(
req *logical.Request, d *framework.FieldData) (*logical.Response, error) { 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 entry, err := req.Storage.Get("policy/" + name)
name := fmt.Sprintf("Vault %s %d", req.DisplayName, time.Now().Unix())
// Read the policy
policy, err := req.Storage.Get("policy/" + policyName)
if err != nil { if err != nil {
return nil, fmt.Errorf("error retrieving role: %s", err) return nil, fmt.Errorf("error retrieving role: %s", err)
} }
if policy == nil { if entry == nil {
return logical.ErrorResponse(fmt.Sprintf( return logical.ErrorResponse(fmt.Sprintf("Role '%s' not found", name)), nil
"Role '%s' not found", policyName)), nil }
var result roleConfig
if err := entry.DecodeJSON(&result); err != nil {
return nil, err
} }
// Get the consul client // Get the consul client
@ -48,18 +48,22 @@ func (b *backend) pathTokenRead(
return logical.ErrorResponse(err.Error()), nil 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 // Create it
token, _, err := c.ACL().Create(&api.ACLEntry{ token, _, err := c.ACL().Create(&api.ACLEntry{
Name: name, Name: tokenName,
Type: "client", Type: "client",
Rules: string(policy.Value), Rules: result.Policy,
}, nil) }, nil)
if err != nil { if err != nil {
return logical.ErrorResponse(err.Error()), nil return logical.ErrorResponse(err.Error()), nil
} }
// Use the helper to create the secret // 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, "token": token,
}, nil), nil }, nil), nil
} }

View File

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

View File

@ -143,6 +143,11 @@ Permission denied
<span class="param-flags">required</span> <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). The base64 encoded Consul ACL policy. This is documented in [more detail here](https://consul.io/docs/internals/acl.html).
</li> </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> </ul>
</dd> </dd>