-
Notifications
You must be signed in to change notification settings - Fork 0
/
token.go
78 lines (63 loc) · 2.35 KB
/
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
75
76
77
78
package main
import (
"context"
"github.com/spf13/cobra"
api "github.com/chef/automate/api/interservice/deployment"
"github.com/chef/automate/components/automate-cli/pkg/client/apiclient"
"github.com/chef/automate/components/automate-cli/pkg/status"
"github.com/chef/automate/components/automate-deployment/pkg/client"
policies_common "github.com/chef/automate/components/automate-gateway/api/iam/v2beta/common"
policies_req "github.com/chef/automate/components/automate-gateway/api/iam/v2beta/request"
)
func init() {
RootCmd.AddCommand(adminTokenCmd)
}
var adminTokenCmd = &cobra.Command{
Use: "admin-token",
Short: "generate an admin token for use against the Automate API",
Long: `
Generate an admin token for use against the Automate API.
You can pass token with the "api-token" header. For example, you could query
for all existing auth policies with curl:
curl -H "api-token: <YOUR_TOKEN>" <AUTOMATE_FQDN>/api/v0/auth/policies
The admin API token has access to the entire Automate API. With great power
comes great responsibility. Keep it secret, keep it safe.`,
RunE: runGenerateTokenCmd,
}
const tokenCmdIAMPreconditionError = "`chef-automate admin-token` is an IAM v1 command.\n" +
"For v2 use `chef-automate iam token create NAME --admin`.\n"
func runGenerateTokenCmd(cmd *cobra.Command, args []string) error {
ctx := context.Background()
apiClient, err := apiclient.OpenConnection(ctx)
if err != nil {
return err
}
resp, err := apiClient.PoliciesClient().GetPolicyVersion(ctx, &policies_req.GetPolicyVersionReq{})
if err != nil {
return status.Wrap(err, status.APIError, "Failed to verify IAM version")
}
if resp.Version.Major == policies_common.Version_V2 {
return status.New(status.APIError, tokenCmdIAMPreconditionError)
}
connection, err := client.Connection(client.DefaultClientTimeout)
if err != nil {
return err
}
req := &api.GenerateAdminTokenRequest{
Description: "This token was generated by the chef-automate CLI tool. " +
"It has admin level access on the entire Automate API.",
}
tokenResp, err := connection.GenerateAdminToken(ctx, req)
if err != nil {
return status.Wrap(
err,
status.DeploymentServiceCallError,
"Request to generate admin token failed",
)
}
status.GlobalResult = struct {
Token string `json:"admin_token"`
}{Token: tokenResp.ApiToken}
writer.Println(tokenResp.ApiToken)
return nil
}