func testDecryptPasswordAndTest(nProfile, nAccessKey, key string) resource.TestCheckFunc { return func(s *terraform.State) error { profileResource, ok := s.RootModule().Resources[nProfile] if !ok { return fmt.Errorf("Not found: %s", nProfile) } password, ok := profileResource.Primary.Attributes["encrypted_password"] if !ok { return errors.New("No password in state") } accessKeyResource, ok := s.RootModule().Resources[nAccessKey] if !ok { return fmt.Errorf("Not found: %s", nAccessKey) } accessKeyId := accessKeyResource.Primary.ID secretAccessKey, ok := accessKeyResource.Primary.Attributes["secret"] if !ok { return errors.New("No secret access key in state") } decryptedPassword, err := pgpkeys.DecryptBytes(password, key) if err != nil { return fmt.Errorf("Error decrypting password: %s", err) } iamAsCreatedUserSession := session.New(&aws.Config{ Region: aws.String("us-west-2"), Credentials: credentials.NewStaticCredentials(accessKeyId, secretAccessKey, ""), }) _, err = iamAsCreatedUserSession.Config.Credentials.Get() if err != nil { return fmt.Errorf("Error getting session credentials: %s", err) } return resource.Retry(2*time.Minute, func() *resource.RetryError { iamAsCreatedUser := iam.New(iamAsCreatedUserSession) _, err = iamAsCreatedUser.ChangePassword(&iam.ChangePasswordInput{ OldPassword: aws.String(decryptedPassword.String()), NewPassword: aws.String(generatePassword(20)), }) if err != nil { if awserr, ok := err.(awserr.Error); ok && awserr.Code() == "InvalidClientTokenId" { return resource.RetryableError(err) } return resource.NonRetryableError(fmt.Errorf("Error changing decrypted password: %s", err)) } return nil }) } }
func testDecryptSecretKeyAndTest(nAccessKey, key string) resource.TestCheckFunc { return func(s *terraform.State) error { keyResource, ok := s.RootModule().Resources[nAccessKey] if !ok { return fmt.Errorf("Not found: %s", nAccessKey) } password, ok := keyResource.Primary.Attributes["encrypted_secret"] if !ok { return errors.New("No password in state") } // We can't verify that the decrypted password is correct, because we don't // have it. We can verify that decrypting it does not error _, err := pgpkeys.DecryptBytes(password, key) if err != nil { return fmt.Errorf("Error decrypting password: %s", err) } return nil } }
func testCore_GenerateRoot_Update_PGP_Common(t *testing.T, c *Core, keys [][]byte) { // Start a root generation err := c.GenerateRootInit("", pgpkeys.TestPubKey1) if err != nil { t.Fatalf("err: %v", err) } // Fetch new config with generated nonce rkconf, err := c.GenerateRootConfiguration() if err != nil { t.Fatalf("err: %v", err) } if rkconf == nil { t.Fatalf("bad: no root generation config received") } // Provide the keys var result *GenerateRootResult for _, key := range keys { result, err = c.GenerateRootUpdate(key, rkconf.Nonce) if err != nil { t.Fatalf("err: %v", err) } } if result == nil { t.Fatalf("Bad, result is nil") } encodedRootToken := result.EncodedRootToken // Should be no progress num, err := c.GenerateRootProgress() if err != nil { t.Fatalf("err: %v", err) } if num != 0 { t.Fatalf("bad: %d", num) } // Should be no config conf, err := c.GenerateRootConfiguration() if err != nil { t.Fatalf("err: %v", err) } if conf != nil { t.Fatalf("bad: %v", conf) } ptBuf, err := pgpkeys.DecryptBytes(encodedRootToken, pgpkeys.TestPrivKey1) if err != nil { t.Fatal(err) } if ptBuf == nil { t.Fatal("Got nil plaintext key") } token := ptBuf.String() // Ensure that the token is a root token te, err := c.tokenStore.Lookup(token) if err != nil { t.Fatalf("err: %v", err) } if te == nil { t.Fatalf("token was nil") } if te.ID != token || te.Parent != "" || len(te.Policies) != 1 || te.Policies[0] != "root" { t.Fatalf("bad: %#v", *te) } }
func TestSysGenerateRoot_Update_PGP(t *testing.T) { core, master, token := vault.TestCoreUnsealed(t) ln, addr := TestServer(t, core) defer ln.Close() TestServerAuth(t, addr, token) resp := testHttpPut(t, token, addr+"/v1/sys/generate-root/attempt", map[string]interface{}{ "pgp_key": pgpkeys.TestPubKey1, }) testResponseStatus(t, resp, 200) // We need to get the nonce first before we update resp, err := http.Get(addr + "/v1/sys/generate-root/attempt") if err != nil { t.Fatalf("err: %s", err) } 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": "816938b8a29146fbe245dd29e7cbaf8e011db793", } 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) } decodedTokenBuf, err := pgpkeys.DecryptBytes(actual["encoded_root_token"].(string), pgpkeys.TestPrivKey1) if err != nil { t.Fatal(err) } if decodedTokenBuf == nil { t.Fatal("decoded root token buffer is nil") } newRootToken := decodedTokenBuf.String() 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_PGP(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, }, } tempDir, pubFiles, err := getPubKeyFiles(t) if err != nil { t.Fatal(err) } defer os.RemoveAll(tempDir) // Init the attempt args := []string{ "-address", addr, "-init", "-pgp-key", pubFiles[0], } 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]) ptBuf, err := pgpkeys.DecryptBytes(encodedToken, pgpkeys.TestPrivKey1) if err != nil { t.Fatal(err) } if ptBuf == nil { t.Fatal("returned plain text buffer is nil") } token := ptBuf.String() 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) } }