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 TestACLTokenSelfCommand_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 := &ACLTokenSelfCommand{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})
45	assert.Equal(1, code)
46
47	// Fetch info on a token with a valid token
48	os.Setenv("NOMAD_TOKEN", mockToken.SecretID)
49	code = cmd.Run([]string{"-address=" + url})
50	assert.Equal(0, code)
51
52	// Check the output
53	out := ui.OutputWriter.String()
54	if !strings.Contains(out, mockToken.AccessorID) {
55		t.Fatalf("bad: %v", out)
56	}
57}
58