open-vault/builtin/logical/nomad/path_creds_create.go

81 lines
1.9 KiB
Go
Raw Normal View History

2017-09-20 20:59:35 +00:00
package nomad
import (
"context"
2017-09-20 20:59:35 +00:00
"fmt"
"time"
2017-12-15 22:06:56 +00:00
"github.com/hashicorp/errwrap"
2017-09-20 20:59:35 +00:00
"github.com/hashicorp/nomad/api"
"github.com/hashicorp/vault/logical"
"github.com/hashicorp/vault/logical/framework"
)
func pathCredsCreate(b *backend) *framework.Path {
2017-09-20 20:59:35 +00:00
return &framework.Path{
Pattern: "creds/" + framework.GenericNameRegex("name"),
Fields: map[string]*framework.FieldSchema{
"name": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Name of the role",
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.ReadOperation: b.pathTokenRead,
},
}
}
func (b *backend) pathTokenRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
2017-09-20 20:59:35 +00:00
name := d.Get("name").(string)
role, err := b.Role(ctx, req.Storage, name)
2017-09-20 20:59:35 +00:00
if err != nil {
2017-12-15 22:06:56 +00:00
return nil, errwrap.Wrapf("error retrieving role: {{err}}", err)
2017-09-20 20:59:35 +00:00
}
if role == nil {
2017-12-15 22:06:56 +00:00
return logical.ErrorResponse(fmt.Sprintf("role %q not found", name)), nil
2017-09-20 20:59:35 +00:00
}
// Determine if we have a lease configuration
leaseConfig, err := b.LeaseConfig(ctx, req.Storage)
if err != nil {
2017-09-20 20:59:35 +00:00
return nil, err
}
if leaseConfig == nil {
leaseConfig = &configLease{}
}
2017-09-20 20:59:35 +00:00
// Get the nomad client
c, err := b.client(ctx, req.Storage)
2017-11-06 21:34:20 +00:00
if err != nil {
return nil, err
2017-09-20 20:59:35 +00:00
}
// Generate a name for the token
2017-12-15 22:06:56 +00:00
tokenName := fmt.Sprintf("vault-%s-%s-%d", name, req.DisplayName, time.Now().UnixNano())
2017-09-20 20:59:35 +00:00
// Create it
token, _, err := c.ACLTokens().Create(&api.ACLToken{
Name: tokenName,
Type: role.TokenType,
2017-11-29 16:31:17 +00:00
Policies: role.Policies,
Global: role.Global,
2017-09-20 20:59:35 +00:00
}, nil)
if err != nil {
2017-11-29 10:58:02 +00:00
return nil, err
2017-09-20 20:59:35 +00:00
}
// Use the helper to create the secret
resp := b.Secret(SecretTokenType).Response(map[string]interface{}{
2017-09-20 22:14:35 +00:00
"secret_id": token.SecretID,
"accessor_id": token.AccessorID,
2017-09-20 20:59:35 +00:00
}, map[string]interface{}{
2017-09-20 22:14:35 +00:00
"accessor_id": token.AccessorID,
2017-09-20 20:59:35 +00:00
})
resp.Secret.TTL = leaseConfig.TTL
2017-09-20 20:59:35 +00:00
return resp, nil
2017-09-20 20:59:35 +00:00
}