open-vault/command/operator_generate_root_test.go

559 lines
12 KiB
Go
Raw Normal View History

//go:build !race
CLI Enhancements (#3897) * Use Colored UI if stdout is a tty * Add format options to operator unseal * Add format test on operator unseal * Add -no-color output flag, and use BasicUi if no-color flag is provided * Move seal status formatting logic to OutputSealStatus * Apply no-color to warnings from DeprecatedCommands as well * Add OutputWithFormat to support arbitrary data, add format option to auth list * Add ability to output arbitrary list data on TableFormatter * Clear up switch logic on format * Add format option for list-related commands * Add format option to rest of commands that returns a client API response * Remove initOutputYAML and initOutputJSON, and use OutputWithFormat instead * Remove outputAsYAML and outputAsJSON, and use OutputWithFormat instead * Remove -no-color flag, use env var exclusively to toggle colored output * Fix compile * Remove -no-color flag in main.go * Add missing FlagSetOutputFormat * Fix generate-root/decode test * Migrate init functions to main.go * Add no-color flag back as hidden * Handle non-supported data types for TableFormatter.OutputList * Pull formatting much further up to remove the need to use c.flagFormat (#3950) * Pull formatting much further up to remove the need to use c.flagFormat Also remove OutputWithFormat as the logic can cause issues. * Use const for env var * Minor updates * Remove unnecessary check * Fix SSH output and some tests * Fix tests * Make race detector not run on generate root since it kills Travis these days * Update docs * Update docs * Address review feedback * Handle --format as well as -format
2018-02-12 23:12:16 +00:00
2017-09-05 04:01:55 +00:00
package command
import (
2018-09-18 03:03:00 +00:00
"encoding/base64"
2017-09-05 04:01:55 +00:00
"io"
CLI Enhancements (#3897) * Use Colored UI if stdout is a tty * Add format options to operator unseal * Add format test on operator unseal * Add -no-color output flag, and use BasicUi if no-color flag is provided * Move seal status formatting logic to OutputSealStatus * Apply no-color to warnings from DeprecatedCommands as well * Add OutputWithFormat to support arbitrary data, add format option to auth list * Add ability to output arbitrary list data on TableFormatter * Clear up switch logic on format * Add format option for list-related commands * Add format option to rest of commands that returns a client API response * Remove initOutputYAML and initOutputJSON, and use OutputWithFormat instead * Remove outputAsYAML and outputAsJSON, and use OutputWithFormat instead * Remove -no-color flag, use env var exclusively to toggle colored output * Fix compile * Remove -no-color flag in main.go * Add missing FlagSetOutputFormat * Fix generate-root/decode test * Migrate init functions to main.go * Add no-color flag back as hidden * Handle non-supported data types for TableFormatter.OutputList * Pull formatting much further up to remove the need to use c.flagFormat (#3950) * Pull formatting much further up to remove the need to use c.flagFormat Also remove OutputWithFormat as the logic can cause issues. * Use const for env var * Minor updates * Remove unnecessary check * Fix SSH output and some tests * Fix tests * Make race detector not run on generate root since it kills Travis these days * Update docs * Update docs * Address review feedback * Handle --format as well as -format
2018-02-12 23:12:16 +00:00
"os"
2017-09-05 04:01:55 +00:00
"regexp"
"strings"
"testing"
"github.com/hashicorp/vault/sdk/helper/xor"
2018-09-18 03:03:00 +00:00
"github.com/hashicorp/vault/vault"
2017-09-05 04:01:55 +00:00
"github.com/mitchellh/cli"
)
2017-09-08 02:03:12 +00:00
func testOperatorGenerateRootCommand(tb testing.TB) (*cli.MockUi, *OperatorGenerateRootCommand) {
2017-09-05 04:01:55 +00:00
tb.Helper()
ui := cli.NewMockUi()
2017-09-08 02:03:12 +00:00
return ui, &OperatorGenerateRootCommand{
2017-09-05 04:01:55 +00:00
BaseCommand: &BaseCommand{
UI: ui,
},
}
}
2017-09-08 02:03:12 +00:00
func TestOperatorGenerateRootCommand_Run(t *testing.T) {
2017-09-05 04:01:55 +00:00
t.Parallel()
cases := []struct {
name string
args []string
out string
code int
}{
{
"init_invalid_otp",
[]string{
"-init",
"-otp", "not-a-valid-otp",
},
2018-09-18 03:03:00 +00:00
"OTP string is wrong length",
2018-08-22 18:37:40 +00:00
2,
2017-09-05 04:01:55 +00:00
},
{
"init_pgp_multi",
[]string{
"-init",
"-pgp-key", "keybase:hashicorp",
"-pgp-key", "keybase:jefferai",
},
"can only be specified once",
1,
},
{
"init_pgp_multi_inline",
[]string{
"-init",
"-pgp-key", "keybase:hashicorp,keybase:jefferai",
},
"can only specify one pgp key",
1,
},
{
"init_pgp_otp",
[]string{
"-init",
"-pgp-key", "keybase:hashicorp",
"-otp", "abcd1234",
},
"cannot specify both -otp and -pgp-key",
1,
},
}
t.Run("validations", func(t *testing.T) {
t.Parallel()
for _, tc := range cases {
tc := tc
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
client, closer := testVaultServer(t)
defer closer()
2017-09-08 02:03:12 +00:00
ui, cmd := testOperatorGenerateRootCommand(t)
cmd.client = client
2017-09-05 04:01:55 +00:00
code := cmd.Run(tc.args)
if code != tc.code {
2018-08-22 18:37:40 +00:00
t.Errorf("%s: expected %d to be %d", tc.name, code, tc.code)
2017-09-05 04:01:55 +00:00
}
combined := ui.OutputWriter.String() + ui.ErrorWriter.String()
if !strings.Contains(combined, tc.out) {
2018-08-22 18:37:40 +00:00
t.Errorf("%s: expected %q to contain %q", tc.name, combined, tc.out)
2017-09-05 04:01:55 +00:00
}
})
}
})
t.Run("generate_otp", func(t *testing.T) {
t.Parallel()
client, closer := testVaultServer(t)
defer closer()
2018-08-22 18:37:40 +00:00
_, cmd := testOperatorGenerateRootCommand(t)
cmd.client = client
2017-09-05 04:01:55 +00:00
code := cmd.Run([]string{
"-generate-otp",
})
if exp := 0; code != exp {
t.Errorf("expected %d to be %d", code, exp)
}
})
t.Run("decode", func(t *testing.T) {
t.Parallel()
2018-09-18 03:03:00 +00:00
encoded := "Bxg9JQQqOCNKBRICNwMIRzo2J3cWCBRi"
otp := "3JhHkONiyiaNYj14nnD9xZQS"
2017-09-05 04:01:55 +00:00
client, closer := testVaultServer(t)
defer closer()
2017-09-08 02:03:12 +00:00
ui, cmd := testOperatorGenerateRootCommand(t)
cmd.client = client
2017-09-05 04:01:55 +00:00
CLI Enhancements (#3897) * Use Colored UI if stdout is a tty * Add format options to operator unseal * Add format test on operator unseal * Add -no-color output flag, and use BasicUi if no-color flag is provided * Move seal status formatting logic to OutputSealStatus * Apply no-color to warnings from DeprecatedCommands as well * Add OutputWithFormat to support arbitrary data, add format option to auth list * Add ability to output arbitrary list data on TableFormatter * Clear up switch logic on format * Add format option for list-related commands * Add format option to rest of commands that returns a client API response * Remove initOutputYAML and initOutputJSON, and use OutputWithFormat instead * Remove outputAsYAML and outputAsJSON, and use OutputWithFormat instead * Remove -no-color flag, use env var exclusively to toggle colored output * Fix compile * Remove -no-color flag in main.go * Add missing FlagSetOutputFormat * Fix generate-root/decode test * Migrate init functions to main.go * Add no-color flag back as hidden * Handle non-supported data types for TableFormatter.OutputList * Pull formatting much further up to remove the need to use c.flagFormat (#3950) * Pull formatting much further up to remove the need to use c.flagFormat Also remove OutputWithFormat as the logic can cause issues. * Use const for env var * Minor updates * Remove unnecessary check * Fix SSH output and some tests * Fix tests * Make race detector not run on generate root since it kills Travis these days * Update docs * Update docs * Address review feedback * Handle --format as well as -format
2018-02-12 23:12:16 +00:00
// Simulate piped output to print raw output
old := os.Stdout
_, w, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
os.Stdout = w
2017-09-05 04:01:55 +00:00
code := cmd.Run([]string{
"-decode", encoded,
"-otp", otp,
})
if exp := 0; code != exp {
t.Errorf("expected %d to be %d", code, exp)
}
CLI Enhancements (#3897) * Use Colored UI if stdout is a tty * Add format options to operator unseal * Add format test on operator unseal * Add -no-color output flag, and use BasicUi if no-color flag is provided * Move seal status formatting logic to OutputSealStatus * Apply no-color to warnings from DeprecatedCommands as well * Add OutputWithFormat to support arbitrary data, add format option to auth list * Add ability to output arbitrary list data on TableFormatter * Clear up switch logic on format * Add format option for list-related commands * Add format option to rest of commands that returns a client API response * Remove initOutputYAML and initOutputJSON, and use OutputWithFormat instead * Remove outputAsYAML and outputAsJSON, and use OutputWithFormat instead * Remove -no-color flag, use env var exclusively to toggle colored output * Fix compile * Remove -no-color flag in main.go * Add missing FlagSetOutputFormat * Fix generate-root/decode test * Migrate init functions to main.go * Add no-color flag back as hidden * Handle non-supported data types for TableFormatter.OutputList * Pull formatting much further up to remove the need to use c.flagFormat (#3950) * Pull formatting much further up to remove the need to use c.flagFormat Also remove OutputWithFormat as the logic can cause issues. * Use const for env var * Minor updates * Remove unnecessary check * Fix SSH output and some tests * Fix tests * Make race detector not run on generate root since it kills Travis these days * Update docs * Update docs * Address review feedback * Handle --format as well as -format
2018-02-12 23:12:16 +00:00
w.Close()
os.Stdout = old
2018-09-18 03:03:00 +00:00
expected := "4RUmoevJ3lsLni9sTXcNnRE1"
2017-09-05 04:01:55 +00:00
combined := ui.OutputWriter.String() + ui.ErrorWriter.String()
if combined != expected {
t.Errorf("expected %q to be %q", combined, expected)
}
})
t.Run("decode_from_stdin", func(t *testing.T) {
t.Parallel()
encoded := "Bxg9JQQqOCNKBRICNwMIRzo2J3cWCBRi"
otp := "3JhHkONiyiaNYj14nnD9xZQS"
client, closer := testVaultServer(t)
defer closer()
stdinR, stdinW := io.Pipe()
go func() {
stdinW.Write([]byte(encoded))
stdinW.Close()
}()
ui, cmd := testOperatorGenerateRootCommand(t)
cmd.client = client
cmd.testStdin = stdinR
// Simulate piped output to print raw output
old := os.Stdout
_, w, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
os.Stdout = w
code := cmd.Run([]string{
"-decode", "-", // read from stdin
"-otp", otp,
})
if exp := 0; code != exp {
t.Errorf("expected %d to be %d", code, exp)
}
w.Close()
os.Stdout = old
expected := "4RUmoevJ3lsLni9sTXcNnRE1"
combined := ui.OutputWriter.String() + ui.ErrorWriter.String()
if combined != expected {
t.Errorf("expected %q to be %q", combined, expected)
}
})
t.Run("decode_from_stdin_empty", func(t *testing.T) {
t.Parallel()
encoded := ""
otp := "3JhHkONiyiaNYj14nnD9xZQS"
client, closer := testVaultServer(t)
defer closer()
stdinR, stdinW := io.Pipe()
go func() {
stdinW.Write([]byte(encoded))
stdinW.Close()
}()
ui, cmd := testOperatorGenerateRootCommand(t)
cmd.client = client
cmd.testStdin = stdinR
// Simulate piped output to print raw output
old := os.Stdout
_, w, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
os.Stdout = w
code := cmd.Run([]string{
"-decode", "-", // read from stdin
"-otp", otp,
})
if exp := 1; code != exp {
t.Errorf("expected %d to be %d", code, exp)
}
w.Close()
os.Stdout = old
expected := "Missing encoded value"
combined := ui.OutputWriter.String() + ui.ErrorWriter.String()
if !strings.Contains(combined, expected) {
t.Errorf("expected %q to contain %q", combined, expected)
}
})
2017-09-05 04:01:55 +00:00
t.Run("cancel", func(t *testing.T) {
t.Parallel()
client, closer := testVaultServer(t)
defer closer()
// Initialize a generation
2018-10-23 06:34:02 +00:00
if _, err := client.Sys().GenerateRootInit("", ""); err != nil {
2017-09-05 04:01:55 +00:00
t.Fatal(err)
}
2017-09-08 02:03:12 +00:00
ui, cmd := testOperatorGenerateRootCommand(t)
2017-09-05 04:01:55 +00:00
cmd.client = client
code := cmd.Run([]string{
"-cancel",
})
if exp := 0; code != exp {
t.Errorf("expected %d to be %d", code, exp)
}
expected := "Success! Root token generation canceled"
combined := ui.OutputWriter.String() + ui.ErrorWriter.String()
if !strings.Contains(combined, expected) {
t.Errorf("expected %q to contain %q", combined, expected)
}
status, err := client.Sys().GenerateRootStatus()
if err != nil {
t.Fatal(err)
}
if status.Started {
t.Errorf("expected status to be canceled: %#v", status)
}
})
t.Run("init_otp", func(t *testing.T) {
t.Parallel()
client, closer := testVaultServer(t)
defer closer()
2017-09-08 02:03:12 +00:00
ui, cmd := testOperatorGenerateRootCommand(t)
2017-09-05 04:01:55 +00:00
cmd.client = client
code := cmd.Run([]string{
"-init",
})
if exp := 0; code != exp {
t.Errorf("expected %d to be %d", code, exp)
}
expected := "Nonce"
combined := ui.OutputWriter.String() + ui.ErrorWriter.String()
if !strings.Contains(combined, expected) {
t.Errorf("expected %q to contain %q", combined, expected)
}
status, err := client.Sys().GenerateRootStatus()
if err != nil {
t.Fatal(err)
}
if !status.Started {
t.Errorf("expected status to be started: %#v", status)
}
})
t.Run("init_pgp", func(t *testing.T) {
t.Parallel()
pgpKey := "keybase:hashicorp"
pgpFingerprint := "c874011f0ab405110d02105534365d9472d7468f"
2017-09-05 04:01:55 +00:00
client, closer := testVaultServer(t)
defer closer()
2017-09-08 02:03:12 +00:00
ui, cmd := testOperatorGenerateRootCommand(t)
2017-09-05 04:01:55 +00:00
cmd.client = client
code := cmd.Run([]string{
"-init",
"-pgp-key", pgpKey,
})
if exp := 0; code != exp {
t.Errorf("expected %d to be %d", code, exp)
}
expected := "Nonce"
combined := ui.OutputWriter.String() + ui.ErrorWriter.String()
if !strings.Contains(combined, expected) {
t.Errorf("expected %q to contain %q", combined, expected)
}
status, err := client.Sys().GenerateRootStatus()
if err != nil {
t.Fatal(err)
}
if !status.Started {
t.Errorf("expected status to be started: %#v", status)
}
if status.PGPFingerprint != pgpFingerprint {
t.Errorf("expected %q to be %q", status.PGPFingerprint, pgpFingerprint)
}
})
t.Run("status", func(t *testing.T) {
t.Parallel()
client, closer := testVaultServer(t)
defer closer()
2017-09-08 02:03:12 +00:00
ui, cmd := testOperatorGenerateRootCommand(t)
2017-09-05 04:01:55 +00:00
cmd.client = client
code := cmd.Run([]string{
"-status",
})
if exp := 0; code != exp {
t.Errorf("expected %d to be %d", code, exp)
}
expected := "Nonce"
combined := ui.OutputWriter.String() + ui.ErrorWriter.String()
if !strings.Contains(combined, expected) {
t.Errorf("expected %q to contain %q", combined, expected)
}
})
t.Run("provide_arg", func(t *testing.T) {
t.Parallel()
client, keys, closer := testVaultServerUnseal(t)
defer closer()
// Initialize a generation
2018-09-18 03:03:00 +00:00
status, err := client.Sys().GenerateRootInit("", "")
2017-09-05 04:01:55 +00:00
if err != nil {
t.Fatal(err)
}
nonce := status.Nonce
2018-09-18 03:03:00 +00:00
otp := status.OTP
2017-09-05 04:01:55 +00:00
// Supply the first n-1 unseal keys
for _, key := range keys[:len(keys)-1] {
2017-09-08 02:03:12 +00:00
_, cmd := testOperatorGenerateRootCommand(t)
2017-09-05 04:01:55 +00:00
cmd.client = client
code := cmd.Run([]string{
"-nonce", nonce,
key,
})
if exp := 0; code != exp {
t.Errorf("expected %d to be %d", code, exp)
}
}
2017-09-08 02:03:12 +00:00
ui, cmd := testOperatorGenerateRootCommand(t)
2017-09-05 04:01:55 +00:00
cmd.client = client
code := cmd.Run([]string{
"-nonce", nonce,
keys[len(keys)-1], // the last unseal key
})
if exp := 0; code != exp {
t.Fatalf("expected %d to be %d, out=%q, err=%q", code, exp, ui.OutputWriter, ui.ErrorWriter)
2017-09-05 04:01:55 +00:00
}
reToken := regexp.MustCompile(`Encoded Token\s+(.+)`)
2017-09-05 04:01:55 +00:00
combined := ui.OutputWriter.String() + ui.ErrorWriter.String()
match := reToken.FindAllStringSubmatch(combined, -1)
if len(match) < 1 || len(match[0]) < 2 {
t.Fatalf("no match: %#v", match)
}
2018-09-18 03:03:00 +00:00
tokenBytes, err := base64.RawStdEncoding.DecodeString(match[0][1])
2017-09-05 04:01:55 +00:00
if err != nil {
t.Fatal(err)
}
2018-09-18 03:03:00 +00:00
token, err := xor.XORBytes(tokenBytes, []byte(otp))
2017-09-05 04:01:55 +00:00
if err != nil {
t.Fatal(err)
}
if l, exp := len(token), vault.TokenLength+vault.TokenPrefixLength; l != exp {
2017-09-05 04:01:55 +00:00
t.Errorf("expected %d to be %d: %s", l, exp, token)
}
})
t.Run("provide_stdin", func(t *testing.T) {
t.Parallel()
client, keys, closer := testVaultServerUnseal(t)
defer closer()
// Initialize a generation
2018-09-18 03:03:00 +00:00
status, err := client.Sys().GenerateRootInit("", "")
2017-09-05 04:01:55 +00:00
if err != nil {
t.Fatal(err)
}
nonce := status.Nonce
2018-09-18 03:03:00 +00:00
otp := status.OTP
2017-09-05 04:01:55 +00:00
// Supply the first n-1 unseal keys
for _, key := range keys[:len(keys)-1] {
stdinR, stdinW := io.Pipe()
go func() {
stdinW.Write([]byte(key))
stdinW.Close()
}()
2017-09-08 02:03:12 +00:00
_, cmd := testOperatorGenerateRootCommand(t)
2017-09-05 04:01:55 +00:00
cmd.client = client
cmd.testStdin = stdinR
code := cmd.Run([]string{
"-nonce", nonce,
"-",
})
if exp := 0; code != exp {
t.Errorf("expected %d to be %d", code, exp)
}
}
stdinR, stdinW := io.Pipe()
go func() {
stdinW.Write([]byte(keys[len(keys)-1])) // the last unseal key
stdinW.Close()
}()
2017-09-08 02:03:12 +00:00
ui, cmd := testOperatorGenerateRootCommand(t)
2017-09-05 04:01:55 +00:00
cmd.client = client
cmd.testStdin = stdinR
code := cmd.Run([]string{
"-nonce", nonce,
"-",
})
if exp := 0; code != exp {
t.Errorf("expected %d to be %d", code, exp)
}
reToken := regexp.MustCompile(`Encoded Token\s+(.+)`)
2017-09-05 04:01:55 +00:00
combined := ui.OutputWriter.String() + ui.ErrorWriter.String()
match := reToken.FindAllStringSubmatch(combined, -1)
if len(match) < 1 || len(match[0]) < 2 {
t.Fatalf("no match: %#v", match)
}
2018-09-18 03:03:00 +00:00
// encodedOTP := base64.RawStdEncoding.EncodeToString([]byte(otp))
// tokenBytes, err := xor.XORBase64(match[0][1], encodedOTP)
// if err != nil {
// t.Fatal(err)
// }
// token, err := uuid.FormatUUID(tokenBytes)
// if err != nil {
// t.Fatal(err)
// }
tokenBytes, err := base64.RawStdEncoding.DecodeString(match[0][1])
2017-09-05 04:01:55 +00:00
if err != nil {
t.Fatal(err)
}
2018-09-18 03:03:00 +00:00
token, err := xor.XORBytes(tokenBytes, []byte(otp))
2017-09-05 04:01:55 +00:00
if err != nil {
t.Fatal(err)
}
if l, exp := len(token), vault.TokenLength+vault.TokenPrefixLength; l != exp {
2017-09-05 04:01:55 +00:00
t.Errorf("expected %d to be %d: %s", l, exp, token)
}
})
t.Run("communication_failure", func(t *testing.T) {
t.Parallel()
client, closer := testVaultServerBad(t)
defer closer()
2017-09-08 02:03:12 +00:00
ui, cmd := testOperatorGenerateRootCommand(t)
2017-09-05 04:01:55 +00:00
cmd.client = client
code := cmd.Run([]string{
"secret/foo",
})
if exp := 2; code != exp {
t.Errorf("expected %d to be %d", code, exp)
}
expected := "Error getting root generation status: "
combined := ui.OutputWriter.String() + ui.ErrorWriter.String()
if !strings.Contains(combined, expected) {
t.Errorf("expected %q to contain %q", combined, expected)
}
})
t.Run("no_tabs", func(t *testing.T) {
t.Parallel()
2017-09-08 02:03:12 +00:00
_, cmd := testOperatorGenerateRootCommand(t)
2017-09-05 04:01:55 +00:00
assertNoTabs(t, cmd)
})
}