github.com/anth0d/nomad@v0.0.0-20221214183521-ae3a0a2cad06/command/agent/keyring_test.go (about)

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