github.com/hhrutter/nomad@v0.6.0-rc2.0.20170723054333-80c4b03f0705/command/agent/keyring_test.go (about)

     1  package agent
     2  
     3  import (
     4  	"fmt"
     5  	"io/ioutil"
     6  	"os"
     7  	"path/filepath"
     8  	"testing"
     9  )
    10  
    11  func TestAgent_LoadKeyrings(t *testing.T) {
    12  	t.Parallel()
    13  	key := "tbLJg26ZJyJ9pK3qhc9jig=="
    14  
    15  	// Should be no configured keyring file by default
    16  	agent1 := NewTestAgent(t.Name(), nil)
    17  	defer agent1.Shutdown()
    18  
    19  	c := agent1.server.GetConfig()
    20  	if c.SerfConfig.KeyringFile != "" {
    21  		t.Fatalf("bad: %#v", c.SerfConfig.KeyringFile)
    22  	}
    23  	if c.SerfConfig.MemberlistConfig.Keyring != nil {
    24  		t.Fatalf("keyring should not be loaded")
    25  	}
    26  
    27  	// Server should auto-load WAN keyring files
    28  	agent2 := &TestAgent{
    29  		Name: t.Name() + "2",
    30  		Key:  key,
    31  	}
    32  	agent2.Start()
    33  	defer agent2.Shutdown()
    34  
    35  	c = agent2.server.GetConfig()
    36  	if c.SerfConfig.KeyringFile == "" {
    37  		t.Fatalf("should have keyring file")
    38  	}
    39  	if c.SerfConfig.MemberlistConfig.Keyring == nil {
    40  		t.Fatalf("keyring should be loaded")
    41  	}
    42  }
    43  
    44  func TestAgent_InitKeyring(t *testing.T) {
    45  	t.Parallel()
    46  	key1 := "tbLJg26ZJyJ9pK3qhc9jig=="
    47  	key2 := "4leC33rgtXKIVUr9Nr0snQ=="
    48  	expected := fmt.Sprintf(`["%s"]`, key1)
    49  
    50  	dir, err := ioutil.TempDir("", "nomad")
    51  	if err != nil {
    52  		t.Fatalf("err: %s", err)
    53  	}
    54  	defer os.RemoveAll(dir)
    55  
    56  	file := filepath.Join(dir, "keyring")
    57  
    58  	// First initialize the keyring
    59  	if err := initKeyring(file, key1); err != nil {
    60  		t.Fatalf("err: %s", err)
    61  	}
    62  
    63  	content, err := ioutil.ReadFile(file)
    64  	if err != nil {
    65  		t.Fatalf("err: %s", err)
    66  	}
    67  	if string(content) != expected {
    68  		t.Fatalf("bad: %s", content)
    69  	}
    70  
    71  	// Try initializing again with a different key
    72  	if err := initKeyring(file, key2); err != nil {
    73  		t.Fatalf("err: %s", err)
    74  	}
    75  
    76  	// Content should still be the same
    77  	content, err = ioutil.ReadFile(file)
    78  	if err != nil {
    79  		t.Fatalf("err: %s", err)
    80  	}
    81  	if string(content) != expected {
    82  		t.Fatalf("bad: %s", content)
    83  	}
    84  }