open-vault/builtin/logical/consul/path_token.go

81 lines
1.8 KiB
Go
Raw Normal View History

2015-03-21 16:19:37 +00:00
package consul
import (
"fmt"
"time"
"github.com/hashicorp/consul/api"
"github.com/hashicorp/vault/logical"
"github.com/hashicorp/vault/logical/framework"
)
func pathToken(b *backend) *framework.Path {
return &framework.Path{
Pattern: "creds/" + framework.GenericNameRegex("name"),
2015-03-21 16:19:37 +00:00
Fields: map[string]*framework.FieldSchema{
"name": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Name of the role",
2015-03-21 16:19:37 +00:00
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.ReadOperation: b.pathTokenRead,
},
}
}
func (b *backend) pathTokenRead(
req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
name := d.Get("name").(string)
2015-03-21 16:19:37 +00:00
entry, err := req.Storage.Get("policy/" + name)
2015-03-21 16:19:37 +00:00
if err != nil {
return nil, fmt.Errorf("error retrieving role: %s", err)
2015-03-21 16:19:37 +00:00
}
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
2015-03-21 16:19:37 +00:00
}
if result.TokenType == "" {
result.TokenType = "client"
}
2015-03-21 16:19:37 +00:00
// Get the consul client
c, userErr, intErr := client(req.Storage)
if intErr != nil {
return nil, intErr
}
if userErr != nil {
2015-03-21 16:19:37 +00:00
return logical.ErrorResponse(err.Error()), nil
}
// Generate a name for the token
tokenName := fmt.Sprintf("Vault %s %s %d", name, req.DisplayName, time.Now().UnixNano())
2015-03-21 16:19:37 +00:00
// Create it
token, _, err := c.ACL().Create(&api.ACLEntry{
Name: tokenName,
Type: result.TokenType,
Rules: result.Policy,
2015-03-21 16:19:37 +00:00
}, nil)
if err != nil {
return logical.ErrorResponse(err.Error()), nil
}
// Use the helper to create the secret
s := b.Secret(SecretTokenType).Response(map[string]interface{}{
2015-03-21 16:19:37 +00:00
"token": token,
}, map[string]interface{}{
"token": token,
})
s.Secret.TTL = result.Lease
return s, nil
2015-03-21 16:19:37 +00:00
}