github.com/Ilhicas/nomad@v1.0.4-0.20210304152020-e86851182bc3/command/acl_token_self_test.go (about)

     1  package command
     2  
     3  import (
     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  
    16  func TestACLTokenSelfCommand_ViaEnvVar(t *testing.T) {
    17  	defer os.Setenv("NOMAD_TOKEN", os.Getenv("NOMAD_TOKEN"))
    18  
    19  	assert := assert.New(t)
    20  	t.Parallel()
    21  	config := func(c *agent.Config) {
    22  		c.ACL.Enabled = true
    23  	}
    24  
    25  	srv, _, url := testServer(t, true, config)
    26  	defer srv.Shutdown()
    27  	state := srv.Agent.Server().State()
    28  
    29  	// Bootstrap an initial ACL token
    30  	token := srv.RootToken
    31  	assert.NotNil(token, "failed to bootstrap ACL token")
    32  
    33  	ui := cli.NewMockUi()
    34  	cmd := &ACLTokenSelfCommand{Meta: Meta{Ui: ui, flagAddress: url}}
    35  
    36  	// Create a valid token
    37  	mockToken := mock.ACLToken()
    38  	mockToken.Policies = []string{acl.PolicyWrite}
    39  	mockToken.SetHash()
    40  	assert.Nil(state.UpsertACLTokens(structs.MsgTypeTestSetup, 1000, []*structs.ACLToken{mockToken}))
    41  
    42  	// Attempt to fetch info on a token without providing a valid management
    43  	// token
    44  	invalidToken := mock.ACLToken()
    45  	os.Setenv("NOMAD_TOKEN", invalidToken.SecretID)
    46  	code := cmd.Run([]string{"-address=" + url})
    47  	assert.Equal(1, code)
    48  
    49  	// Fetch info on a token with a valid token
    50  	os.Setenv("NOMAD_TOKEN", mockToken.SecretID)
    51  	code = cmd.Run([]string{"-address=" + url})
    52  	assert.Equal(0, code)
    53  
    54  	// Check the output
    55  	out := ui.OutputWriter.String()
    56  	if !strings.Contains(out, mockToken.AccessorID) {
    57  		t.Fatalf("bad: %v", out)
    58  	}
    59  }