1package command
2
3import (
4	"os"
5	"strings"
6	"testing"
7
8	"github.com/hashicorp/nomad/acl"
9	"github.com/hashicorp/nomad/command/agent"
10	"github.com/hashicorp/nomad/nomad/mock"
11	"github.com/hashicorp/nomad/nomad/structs"
12	"github.com/mitchellh/cli"
13	"github.com/stretchr/testify/assert"
14)
15
16func TestACLTokenInfoCommand_ViaEnvVar(t *testing.T) {
17	assert := assert.New(t)
18	t.Parallel()
19	config := func(c *agent.Config) {
20		c.ACL.Enabled = true
21	}
22
23	srv, _, url := testServer(t, true, config)
24	defer srv.Shutdown()
25	state := srv.Agent.Server().State()
26
27	// Bootstrap an initial ACL token
28	token := srv.RootToken
29	assert.NotNil(token, "failed to bootstrap ACL token")
30
31	ui := new(cli.MockUi)
32	cmd := &ACLTokenInfoCommand{Meta: Meta{Ui: ui, flagAddress: url}}
33
34	// Create a valid token
35	mockToken := mock.ACLToken()
36	mockToken.Policies = []string{acl.PolicyWrite}
37	mockToken.SetHash()
38	assert.Nil(state.UpsertACLTokens(1000, []*structs.ACLToken{mockToken}))
39
40	// Attempt to fetch info on a token without providing a valid management
41	// token
42	invalidToken := mock.ACLToken()
43	os.Setenv("NOMAD_TOKEN", invalidToken.SecretID)
44	code := cmd.Run([]string{"-address=" + url, mockToken.AccessorID})
45	assert.Equal(1, code)
46
47	// Fetch info on a token with a valid management token
48	os.Setenv("NOMAD_TOKEN", token.SecretID)
49	code = cmd.Run([]string{"-address=" + url, mockToken.AccessorID})
50	assert.Equal(0, code)
51
52	// Fetch info on a token with a valid management token via a CLI option
53	os.Setenv("NOMAD_TOKEN", "")
54	code = cmd.Run([]string{"-address=" + url, "-token=" + token.SecretID, mockToken.AccessorID})
55	assert.Equal(0, code)
56
57	// Check the output
58	out := ui.OutputWriter.String()
59	if !strings.Contains(out, mockToken.AccessorID) {
60		t.Fatalf("bad: %v", out)
61	}
62}
63