github.com/slackhq/nebula@v1.9.0/cmd/nebula-cert/keygen_test.go (about) 1 package main 2 3 import ( 4 "bytes" 5 "os" 6 "testing" 7 8 "github.com/slackhq/nebula/cert" 9 "github.com/stretchr/testify/assert" 10 ) 11 12 //TODO: test file permissions 13 14 func Test_keygenSummary(t *testing.T) { 15 assert.Equal(t, "keygen <flags>: create a public/private key pair. the public key can be passed to `nebula-cert sign`", keygenSummary()) 16 } 17 18 func Test_keygenHelp(t *testing.T) { 19 ob := &bytes.Buffer{} 20 keygenHelp(ob) 21 assert.Equal( 22 t, 23 "Usage of "+os.Args[0]+" keygen <flags>: create a public/private key pair. the public key can be passed to `nebula-cert sign`\n"+ 24 " -curve string\n"+ 25 " \tECDH Curve (25519, P256) (default \"25519\")\n"+ 26 " -out-key string\n"+ 27 " \tRequired: path to write the private key to\n"+ 28 " -out-pub string\n"+ 29 " \tRequired: path to write the public key to\n", 30 ob.String(), 31 ) 32 } 33 34 func Test_keygen(t *testing.T) { 35 ob := &bytes.Buffer{} 36 eb := &bytes.Buffer{} 37 38 // required args 39 assertHelpError(t, keygen([]string{"-out-pub", "nope"}, ob, eb), "-out-key is required") 40 assert.Equal(t, "", ob.String()) 41 assert.Equal(t, "", eb.String()) 42 43 assertHelpError(t, keygen([]string{"-out-key", "nope"}, ob, eb), "-out-pub is required") 44 assert.Equal(t, "", ob.String()) 45 assert.Equal(t, "", eb.String()) 46 47 // failed key write 48 ob.Reset() 49 eb.Reset() 50 args := []string{"-out-pub", "/do/not/write/pleasepub", "-out-key", "/do/not/write/pleasekey"} 51 assert.EqualError(t, keygen(args, ob, eb), "error while writing out-key: open /do/not/write/pleasekey: "+NoSuchDirError) 52 assert.Equal(t, "", ob.String()) 53 assert.Equal(t, "", eb.String()) 54 55 // create temp key file 56 keyF, err := os.CreateTemp("", "test.key") 57 assert.Nil(t, err) 58 defer os.Remove(keyF.Name()) 59 60 // failed pub write 61 ob.Reset() 62 eb.Reset() 63 args = []string{"-out-pub", "/do/not/write/pleasepub", "-out-key", keyF.Name()} 64 assert.EqualError(t, keygen(args, ob, eb), "error while writing out-pub: open /do/not/write/pleasepub: "+NoSuchDirError) 65 assert.Equal(t, "", ob.String()) 66 assert.Equal(t, "", eb.String()) 67 68 // create temp pub file 69 pubF, err := os.CreateTemp("", "test.pub") 70 assert.Nil(t, err) 71 defer os.Remove(pubF.Name()) 72 73 // test proper keygen 74 ob.Reset() 75 eb.Reset() 76 args = []string{"-out-pub", pubF.Name(), "-out-key", keyF.Name()} 77 assert.Nil(t, keygen(args, ob, eb)) 78 assert.Equal(t, "", ob.String()) 79 assert.Equal(t, "", eb.String()) 80 81 // read cert and key files 82 rb, _ := os.ReadFile(keyF.Name()) 83 lKey, b, err := cert.UnmarshalX25519PrivateKey(rb) 84 assert.Len(t, b, 0) 85 assert.Nil(t, err) 86 assert.Len(t, lKey, 32) 87 88 rb, _ = os.ReadFile(pubF.Name()) 89 lPub, b, err := cert.UnmarshalX25519PublicKey(rb) 90 assert.Len(t, b, 0) 91 assert.Nil(t, err) 92 assert.Len(t, lPub, 32) 93 }