forked from hashicorp/vault
-
Notifications
You must be signed in to change notification settings - Fork 0
/
path_token.go
74 lines (62 loc) · 1.7 KB
/
path_token.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
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"),
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(
req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
name := d.Get("name").(string)
entry, err := req.Storage.Get("policy/" + name)
if err != nil {
return nil, fmt.Errorf("error retrieving role: %s", err)
}
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
}
if result.TokenType == "" {
result.TokenType = "client"
}
// Get the consul client
c, err := client(req.Storage)
if err != 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
token, _, err := c.ACL().Create(&api.ACLEntry{
Name: tokenName,
Type: result.TokenType,
Rules: result.Policy,
}, 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{}{
"token": token,
}, nil)
s.Secret.TTL = result.Lease
return s, nil
}