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