1package gcpckms 2 3import ( 4 "os" 5 "reflect" 6 "testing" 7 8 log "github.com/hashicorp/go-hclog" 9 "github.com/hashicorp/vault/sdk/helper/logging" 10 context "golang.org/x/net/context" 11) 12 13const ( 14 // These values need to match the values from the hc-value-testing project 15 gcpckmsTestProjectID = "hc-vault-testing" 16 gcpckmsTestLocationID = "global" 17 gcpckmsTestKeyRing = "vault-test-keyring" 18 gcpckmsTestCryptoKey = "vault-test-key" 19) 20 21func TestGCPCKMSSeal(t *testing.T) { 22 // Do an error check before env vars are set 23 s := NewSeal(logging.NewVaultLogger(log.Trace)) 24 _, err := s.SetConfig(nil) 25 if err == nil { 26 t.Fatal("expected error when GCPCKMSSeal required values are not provided") 27 } 28 29 // Now test for cases where CKMS values are provided 30 checkAndSetEnvVars(t) 31 32 configCases := map[string]map[string]string{ 33 "env_var": nil, 34 "config": map[string]string{ 35 "credentials": os.Getenv("GOOGLE_APPLICATION_CREDENTIALS"), 36 }, 37 } 38 39 for name, config := range configCases { 40 t.Run(name, func(t *testing.T) { 41 s := NewSeal(logging.NewVaultLogger(log.Trace)) 42 _, err := s.SetConfig(config) 43 if err != nil { 44 t.Fatalf("error setting seal config: %v", err) 45 } 46 }) 47 } 48} 49 50func TestGCPCKMSSeal_Lifecycle(t *testing.T) { 51 checkAndSetEnvVars(t) 52 53 s := NewSeal(logging.NewVaultLogger(log.Trace)) 54 _, err := s.SetConfig(nil) 55 if err != nil { 56 t.Fatalf("error setting seal config: %v", err) 57 } 58 59 // Test Encrypt and Decrypt calls 60 input := []byte("foo") 61 swi, err := s.Encrypt(context.Background(), input) 62 if err != nil { 63 t.Fatalf("err: %s", err.Error()) 64 } 65 66 pt, err := s.Decrypt(context.Background(), swi) 67 if err != nil { 68 t.Fatalf("err: %s", err.Error()) 69 } 70 71 if !reflect.DeepEqual(input, pt) { 72 t.Fatalf("expected %s, got %s", input, pt) 73 } 74} 75 76// checkAndSetEnvVars check and sets the required env vars. It will skip tests that are 77// not ran as acceptance tests since they require calling to external APIs. 78func checkAndSetEnvVars(t *testing.T) { 79 t.Helper() 80 81 // Skip tests if we are not running acceptance tests 82 if os.Getenv("VAULT_ACC") == "" { 83 t.SkipNow() 84 } 85 86 if os.Getenv("GOOGLE_APPLICATION_CREDENTIALS") == "" && os.Getenv(EnvGCPCKMSSealCredsPath) == "" { 87 t.Fatal("unable to get GCP credentials via environment variables") 88 } 89 90 if os.Getenv(EnvGCPCKMSSealProject) == "" { 91 os.Setenv(EnvGCPCKMSSealProject, gcpckmsTestProjectID) 92 } 93 94 if os.Getenv(EnvGCPCKMSSealLocation) == "" { 95 os.Setenv(EnvGCPCKMSSealLocation, gcpckmsTestLocationID) 96 } 97 98 if os.Getenv(EnvGCPCKMSSealKeyRing) == "" { 99 os.Setenv(EnvGCPCKMSSealKeyRing, gcpckmsTestKeyRing) 100 } 101 102 if os.Getenv(EnvGCPCKMSSealCryptoKey) == "" { 103 os.Setenv(EnvGCPCKMSSealCryptoKey, gcpckmsTestCryptoKey) 104 } 105} 106