-
Notifications
You must be signed in to change notification settings - Fork 5
/
path_creds.go
77 lines (67 loc) · 2 KB
/
path_creds.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
75
76
77
package packet
import (
"context"
"fmt"
"log"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/logical"
"github.com/packethost/packngo"
)
func (b *backend) pathCredentials() *framework.Path {
return &framework.Path{
Pattern: "creds/" + framework.GenericNameRegex("name"),
Fields: map[string]*framework.FieldSchema{
"name": {
Type: framework.TypeLowerCaseString,
Description: "The name of the role.",
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.ReadOperation: b.operationCredsRead,
},
HelpSynopsis: pathCredsHelpSyn,
HelpDescription: pathCredsHelpDesc,
}
}
func (b *backend) operationCredsRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
roleName := data.Get("name").(string)
if roleName == "" {
return logical.ErrorResponse("missing role name"), nil
}
role, err := readRole(ctx, req.Storage, roleName)
if err != nil {
return nil, err
}
if role == nil {
log.Println("Role", roleName, "doesn't exist")
// Attempting to read a role that doesn't exist.
return nil, nil
}
tokenCreateRequest := packngo.APIKeyCreateRequest{
Description: fmt.Sprintf("Vault-%s", roleName),
ReadOnly: role.ReadOnly,
ProjectID: role.ProjectID,
}
client, err := b.Client(ctx, req.Storage)
if err != nil {
return nil, err
}
apiKey, _, err := client.APIKeys.Create(&tokenCreateRequest)
if err != nil {
return logical.ErrorResponse(fmt.Sprintf("err '%s' when attempting to create API key in Packet", err)), nil
}
resp := b.Secret(secretType).Response(map[string]interface{}{
"api_key_token": apiKey.Token,
}, map[string]interface{}{
"api_key_id": apiKey.ID,
})
if role.TTL != 0 {
resp.Secret.TTL = role.TTL
}
if role.MaxTTL != 0 {
resp.Secret.MaxTTL = role.MaxTTL
}
return resp, nil
}
const pathCredsHelpSyn = `Generate an API token using the given role's configuration.`
const pathCredsHelpDesc = `This path will generate a new API key for Packet API.`