github.com/opentofu/opentofu@v1.7.1/internal/encryption/keyprovider/pbkdf2/config_test.go (about) 1 // Copyright (c) The OpenTofu Authors 2 // SPDX-License-Identifier: MPL-2.0 3 // Copyright (c) 2023 HashiCorp, Inc. 4 // SPDX-License-Identifier: MPL-2.0 5 6 package pbkdf2_test 7 8 import ( 9 "testing" 10 11 "github.com/opentofu/opentofu/internal/encryption/keyprovider/pbkdf2" 12 ) 13 14 func TestHashFunctionName_Validate(t *testing.T) { 15 tc := map[string]struct { 16 hashFunctionName pbkdf2.HashFunctionName 17 valid bool 18 }{ 19 "empty": { 20 hashFunctionName: "", 21 valid: false, 22 }, 23 "sha256": { 24 hashFunctionName: pbkdf2.SHA256HashFunctionName, 25 valid: true, 26 }, 27 "sha0": { 28 hashFunctionName: "sha0", 29 valid: false, 30 }, 31 } 32 33 for name, testCase := range tc { 34 t.Run(name, func(t *testing.T) { 35 err := testCase.hashFunctionName.Validate() 36 if testCase.valid && err != nil { 37 t.Fatalf("unexpected error: %v", err) 38 } else if !testCase.valid && err == nil { 39 t.Fatalf("expected error") 40 } 41 }) 42 } 43 } 44 45 func generateFixedStringHelper(length int) string { 46 result := "" 47 for i := 0; i < length; i++ { 48 result += "a" 49 } 50 return result 51 } 52 53 func TestConfig_Build(t *testing.T) { 54 knownGood := func() *pbkdf2.Config { 55 return pbkdf2.New().TypedConfig().WithPassphrase(generateFixedStringHelper(pbkdf2.MinimumPassphraseLength)) 56 } 57 tc := map[string]struct { 58 config *pbkdf2.Config 59 valid bool 60 }{ 61 "empty": { 62 config: &pbkdf2.Config{}, 63 valid: false, 64 }, 65 "default": { 66 // Missing passphrase 67 config: pbkdf2.New().ConfigStruct().(*pbkdf2.Config), 68 valid: false, 69 }, 70 "default-short-passphrase": { 71 config: pbkdf2.New().TypedConfig().WithPassphrase(generateFixedStringHelper(pbkdf2.MinimumPassphraseLength - 1)), 72 valid: false, 73 }, 74 "default-good-passphrase": { 75 config: knownGood(), 76 valid: true, 77 }, 78 "invalid-key-length": { 79 config: knownGood().WithKeyLength(0), 80 valid: false, 81 }, 82 "invalid-iterations": { 83 config: knownGood().WithIterations(0), 84 valid: false, 85 }, 86 "low-iterations": { 87 config: knownGood().WithIterations(pbkdf2.MinimumIterations - 1), 88 valid: false, 89 }, 90 "invalid-salt-length": { 91 config: knownGood().WithSaltLength(0), 92 valid: false, 93 }, 94 "invalid-hash-function": { 95 config: knownGood().WithHashFunction(""), 96 valid: false, 97 }, 98 } 99 for name, testCase := range tc { 100 t.Run(name, func(t *testing.T) { 101 _, _, err := testCase.config.Build() 102 if testCase.valid && err != nil { 103 t.Fatalf("unexpected error: %v", err) 104 } else if !testCase.valid && err == nil { 105 t.Fatalf("expected error") 106 } 107 }) 108 } 109 }