func TestSysGenerateRoot_ReAttemptUpdate(t *testing.T) {
	core, _, token := vault.TestCoreUnsealed(t)
	ln, addr := TestServer(t, core)
	defer ln.Close()
	TestServerAuth(t, addr, token)

	otpBytes, err := vault.GenerateRandBytes(16)
	if err != nil {
		t.Fatal(err)
	}
	otp := base64.StdEncoding.EncodeToString(otpBytes)
	resp := testHttpPut(t, token, addr+"/v1/sys/generate-root/attempt", map[string]interface{}{
		"otp": otp,
	})
	testResponseStatus(t, resp, 200)

	resp = testHttpDelete(t, token, addr+"/v1/sys/generate-root/attempt")
	testResponseStatus(t, resp, 204)

	resp = testHttpPut(t, token, addr+"/v1/sys/generate-root/attempt", map[string]interface{}{
		"pgp_key": pgpkeys.TestPubKey1,
	})

	testResponseStatus(t, resp, 200)
}
func TestGenerateRoot_status(t *testing.T) {
	core, key, _ := vault.TestCoreUnsealed(t)
	ln, addr := http.TestServer(t, core)
	defer ln.Close()

	ui := new(cli.MockUi)
	c := &GenerateRootCommand{
		Key: hex.EncodeToString(key),
		Meta: Meta{
			Ui: ui,
		},
	}

	otpBytes, err := vault.GenerateRandBytes(16)
	if err != nil {
		t.Fatal(err)
	}
	otp := base64.StdEncoding.EncodeToString(otpBytes)

	args := []string{"-address", addr, "-init", "-otp", otp}
	if code := c.Run(args); code != 0 {
		t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String())
	}

	args = []string{"-address", addr, "-status"}
	if code := c.Run(args); code != 0 {
		t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String())
	}

	if !strings.Contains(string(ui.OutputWriter.Bytes()), "Started: true") {
		t.Fatalf("bad: %s", ui.OutputWriter.String())
	}
}
func TestSysGenerateRootAttempt_Setup_OTP(t *testing.T) {
	core, _, token := vault.TestCoreUnsealed(t)
	ln, addr := TestServer(t, core)
	defer ln.Close()
	TestServerAuth(t, addr, token)

	otpBytes, err := vault.GenerateRandBytes(16)
	if err != nil {
		t.Fatal(err)
	}
	otp := base64.StdEncoding.EncodeToString(otpBytes)

	resp := testHttpPut(t, token, addr+"/v1/sys/generate-root/attempt", map[string]interface{}{
		"otp": otp,
	})
	testResponseStatus(t, resp, 204)

	resp = testHttpGet(t, token, addr+"/v1/sys/generate-root/attempt")

	var actual map[string]interface{}
	expected := map[string]interface{}{
		"started":            true,
		"progress":           float64(0),
		"required":           float64(1),
		"complete":           false,
		"encoded_root_token": "",
		"pgp_fingerprint":    "",
	}
	testResponseStatus(t, resp, 200)
	testResponseBody(t, resp, &actual)
	expected["nonce"] = actual["nonce"]
	if !reflect.DeepEqual(actual, expected) {
		t.Fatalf("\nexpected: %#v\nactual: %#v", expected, actual)
	}
}
func TestSysGenerateRoot_badKey(t *testing.T) {
	core, _, token := vault.TestCoreUnsealed(t)
	ln, addr := TestServer(t, core)
	defer ln.Close()
	TestServerAuth(t, addr, token)

	otpBytes, err := vault.GenerateRandBytes(16)
	if err != nil {
		t.Fatal(err)
	}
	otp := base64.StdEncoding.EncodeToString(otpBytes)

	resp := testHttpPut(t, token, addr+"/v1/sys/generate-root/update", map[string]interface{}{
		"key": "0123",
		"otp": otp,
	})
	testResponseStatus(t, resp, 400)
}
func TestGenerateRoot_Cancel(t *testing.T) {
	core, key, _ := vault.TestCoreUnsealed(t)
	ln, addr := http.TestServer(t, core)
	defer ln.Close()

	ui := new(cli.MockUi)
	c := &GenerateRootCommand{
		Key: hex.EncodeToString(key),
		Meta: Meta{
			Ui: ui,
		},
	}

	otpBytes, err := vault.GenerateRandBytes(16)
	if err != nil {
		t.Fatal(err)
	}
	otp := base64.StdEncoding.EncodeToString(otpBytes)

	args := []string{"-address", addr, "-init", "-otp", otp}
	if code := c.Run(args); code != 0 {
		t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String())
	}

	args = []string{"-address", addr, "-cancel"}
	if code := c.Run(args); code != 0 {
		t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String())
	}

	config, err := core.GenerateRootConfiguration()
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	if config != nil {
		t.Fatal("should not have a config for root generation")
	}
}
func TestSysGenerateRoot_Update_OTP(t *testing.T) {
	core, master, token := vault.TestCoreUnsealed(t)
	ln, addr := TestServer(t, core)
	defer ln.Close()
	TestServerAuth(t, addr, token)

	otpBytes, err := vault.GenerateRandBytes(16)
	if err != nil {
		t.Fatal(err)
	}
	otp := base64.StdEncoding.EncodeToString(otpBytes)

	resp := testHttpPut(t, token, addr+"/v1/sys/generate-root/attempt", map[string]interface{}{
		"otp": otp,
	})
	var rootGenerationStatus map[string]interface{}
	testResponseStatus(t, resp, 200)
	testResponseBody(t, resp, &rootGenerationStatus)

	resp = testHttpPut(t, token, addr+"/v1/sys/generate-root/update", map[string]interface{}{
		"nonce": rootGenerationStatus["nonce"].(string),
		"key":   hex.EncodeToString(master),
	})

	var actual map[string]interface{}
	expected := map[string]interface{}{
		"complete":        true,
		"nonce":           rootGenerationStatus["nonce"].(string),
		"progress":        float64(1),
		"required":        float64(1),
		"started":         true,
		"pgp_fingerprint": "",
	}
	testResponseStatus(t, resp, 200)
	testResponseBody(t, resp, &actual)

	if actual["encoded_root_token"] == nil {
		t.Fatalf("no encoded root token found in response")
	}
	expected["encoded_root_token"] = actual["encoded_root_token"]

	if !reflect.DeepEqual(actual, expected) {
		t.Fatalf("\nexpected: %#v\nactual: %#v", expected, actual)
	}

	decodedToken, err := xor.XORBase64(otp, actual["encoded_root_token"].(string))
	if err != nil {
		t.Fatal(err)
	}
	newRootToken, err := uuid.FormatUUID(decodedToken)
	if err != nil {
		t.Fatal(err)
	}

	actual = map[string]interface{}{}
	expected = map[string]interface{}{
		"id":           newRootToken,
		"display_name": "root",
		"meta":         interface{}(nil),
		"num_uses":     float64(0),
		"policies":     []interface{}{"root"},
		"orphan":       true,
		"creation_ttl": float64(0),
		"ttl":          float64(0),
		"path":         "auth/token/root",
		"role":         "",
	}

	resp = testHttpGet(t, newRootToken, addr+"/v1/auth/token/lookup-self")
	testResponseStatus(t, resp, 200)
	testResponseBody(t, resp, &actual)

	expected["creation_time"] = actual["data"].(map[string]interface{})["creation_time"]
	expected["accessor"] = actual["data"].(map[string]interface{})["accessor"]

	if !reflect.DeepEqual(actual["data"], expected) {
		t.Fatalf("\nexpected: %#v\nactual: %#v", expected, actual["data"])
	}
}
func TestGenerateRoot_OTP(t *testing.T) {
	core, ts, key, _ := vault.TestCoreWithTokenStore(t)
	ln, addr := http.TestServer(t, core)
	defer ln.Close()

	ui := new(cli.MockUi)
	c := &GenerateRootCommand{
		Key: hex.EncodeToString(key),
		Meta: Meta{
			Ui: ui,
		},
	}

	// Generate an OTP
	otpBytes, err := vault.GenerateRandBytes(16)
	if err != nil {
		t.Fatal(err)
	}
	otp := base64.StdEncoding.EncodeToString(otpBytes)

	// Init the attempt
	args := []string{
		"-address", addr,
		"-init",
		"-otp", otp,
	}
	if code := c.Run(args); code != 0 {
		t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String())
	}

	config, err := core.GenerateRootConfiguration()
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	c.Nonce = config.Nonce

	// Provide the key
	args = []string{
		"-address", addr,
	}
	if code := c.Run(args); code != 0 {
		t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String())
	}

	beforeNAfter := strings.Split(ui.OutputWriter.String(), "Encoded root token: ")
	if len(beforeNAfter) != 2 {
		t.Fatalf("did not find encoded root token in %s", ui.OutputWriter.String())
	}
	encodedToken := strings.TrimSpace(beforeNAfter[1])

	decodedToken, err := xor.XORBase64(encodedToken, otp)
	if err != nil {
		t.Fatal(err)
	}

	token, err := uuid.FormatUUID(decodedToken)
	if err != nil {
		t.Fatal(err)
	}

	req := logical.TestRequest(t, logical.ReadOperation, "lookup-self")
	req.ClientToken = token

	resp, err := ts.HandleRequest(req)
	if err != nil {
		t.Fatalf("error running token lookup-self: %v", err)
	}
	if resp == nil {
		t.Fatalf("got nil resp with token lookup-self")
	}
	if resp.Data == nil {
		t.Fatalf("got nil resp.Data with token lookup-self")
	}

	if resp.Data["orphan"].(bool) != true ||
		resp.Data["ttl"].(int64) != 0 ||
		resp.Data["num_uses"].(int) != 0 ||
		resp.Data["meta"].(map[string]string) != nil ||
		len(resp.Data["policies"].([]string)) != 1 ||
		resp.Data["policies"].([]string)[0] != "root" {
		t.Fatalf("bad: %#v", resp.Data)
	}

	// Clear the output and run a decode to verify we get the same result
	ui.OutputWriter.Reset()
	args = []string{
		"-address", addr,
		"-decode", encodedToken,
		"-otp", otp,
	}
	if code := c.Run(args); code != 0 {
		t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String())
	}
	beforeNAfter = strings.Split(ui.OutputWriter.String(), "Root token: ")
	if len(beforeNAfter) != 2 {
		t.Fatalf("did not find decoded root token in %s", ui.OutputWriter.String())
	}

	outToken := strings.TrimSpace(beforeNAfter[1])
	if outToken != token {
		t.Fatalf("tokens do not match:\n%s\n%s", token, outToken)
	}
}