-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabag_crypto_test.go
More file actions
275 lines (254 loc) · 8.31 KB
/
Copy pathdatabag_crypto_test.go
File metadata and controls
275 lines (254 loc) · 8.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
// databag_crypto_test.go
package cinc
import (
"encoding/base64"
"encoding/json"
"errors"
"reflect"
"strings"
"testing"
)
// The decrypt-compatibility fixtures below were produced by the real Chef
// gem (chef/encrypted_data_bag_item) to prove cross-compatibility with the
// canonical Ruby implementation. They were generated with:
//
// require "chef/encrypted_data_bag_item"
// secret = "opensesame-super-secret-key"
// Chef::EncryptedDataBagItem::Encryptor::Version1Encryptor.new(value, secret).for_encrypted_item
// # (and Version2Encryptor / Version3Encryptor)
//
// The base64 fields carry Chef/Ruby's "\n"-every-60-chars-plus-trailing-"\n"
// wrapping verbatim, which exercises the whitespace-stripping read path.
const compatSecret = "opensesame-super-secret-key"
// Chef Version1Encryptor.new("hello world", secret).
const fixtureV1String = `{
"encrypted_data": "MSa0fay80/gnrXL5WOHWRnI2/mFrc5VCp2VsCDJaMTk=\n",
"iv": "s2ElSTGBePtOJxPuaOdazA==\n",
"version": 1,
"cipher": "aes-256-cbc"
}`
// Chef Version2Encryptor.new("hello world", secret).
const fixtureV2String = `{
"encrypted_data": "YPayJpcFtqEphi40tnv8QWBwcvpakdxfctIeGOnakHE=\n",
"hmac": "2SRvwbdKdRejpDkWZfpmrzsG09Cj3QwijFlWMIN3Glw=\n",
"iv": "YMv0tjSdxQDOXjTHVFa/ew==\n",
"version": 2,
"cipher": "aes-256-cbc"
}`
// Chef Version3Encryptor.new("hello world", secret).
const fixtureV3String = `{
"encrypted_data": "tmPS0vwip+VU5tXd23ekJIGw0CrikuoKeZGm1mqD\n",
"iv": "ckznCKqh5nUXxHXB\n",
"auth_tag": "M5LttZ2UqwNvEWLVRwbAeA==\n",
"version": 3,
"cipher": "aes-256-gcm"
}`
// Chef Version3Encryptor.new(42, secret) — proves non-string round-trip.
const fixtureV3Int = `{
"encrypted_data": "RDTRDMZq/w2pFJMvRuuvNFCfaw==\n",
"iv": "tdMv/vRnp4Xryjas\n",
"auth_tag": "5z/jdDZ1Q0pw1XVACDpXeQ==\n",
"version": 3,
"cipher": "aes-256-gcm"
}`
// Chef Version3Encryptor.new({"a"=>1,"b"=>[true,false,"x"]}, secret).
const fixtureV3Obj = `{
"encrypted_data": "eisqM7r0KvjJ8dp4hNnN8maGjkSJl4bpAp097ljk2vwY2LceD9RIYbY6l1rK\n",
"iv": "4DBfruCypGNoY7Qq\n",
"auth_tag": "ECi58KYM0A1UwCSFMD3Itw==\n",
"version": 3,
"cipher": "aes-256-gcm"
}`
func mustWrapper(t *testing.T, raw string) any {
t.Helper()
var w any
if err := json.Unmarshal([]byte(raw), &w); err != nil {
t.Fatalf("decode wrapper: %v", err)
}
return w
}
// flipFirstB64Byte decodes a (possibly newline-wrapped) base64 string, flips
// a bit in its first byte, and re-encodes it as clean standard base64.
func flipFirstB64Byte(t *testing.T, s string) string {
t.Helper()
clean := strings.Join(strings.Fields(s), "")
raw, err := base64.StdEncoding.DecodeString(clean)
if err != nil {
t.Fatalf("decode b64: %v", err)
}
if len(raw) == 0 {
t.Fatal("empty ciphertext")
}
raw[0] ^= 0x01
return base64.StdEncoding.EncodeToString(raw)
}
func TestDataBagItem_EncryptDecrypt_RoundTrip(t *testing.T) {
secret := []byte("a-much-longer-test-secret-value")
orig := DataBagItem{
"id": "creds",
"str": "s3cret-password",
"num": float64(42),
"flag": true,
"nested": map[string]any{"host": "db.local", "port": float64(5432)},
"list": []any{"a", float64(1), false},
}
enc, err := orig.Encrypt(secret)
if err != nil {
t.Fatalf("Encrypt: %v", err)
}
// Receiver must not be mutated.
if _, ok := orig["str"].(string); !ok || orig["str"] != "s3cret-password" {
t.Fatalf("Encrypt mutated the receiver: %+v", orig)
}
// id stays cleartext.
if enc["id"] != "creds" {
t.Errorf("encrypted id = %v, want cleartext \"creds\"", enc["id"])
}
// Every non-id value must look encrypted, not equal to the plaintext.
if enc["str"] == "s3cret-password" {
t.Errorf("str was not encrypted")
}
if !enc.IsEncrypted() {
t.Errorf("Encrypt output should report IsEncrypted() == true")
}
dec, err := enc.Decrypt(secret)
if err != nil {
t.Fatalf("Decrypt: %v", err)
}
if !reflect.DeepEqual(map[string]any(dec), map[string]any(orig)) {
t.Errorf("round-trip mismatch:\n got %+v\nwant %+v", dec, orig)
}
}
func TestDataBagItem_Encrypt_RequiresID(t *testing.T) {
secret := []byte("secret")
for _, item := range []DataBagItem{
{},
{"k": "v"},
{"id": ""},
{"id": 42},
} {
if _, err := item.Encrypt(secret); err == nil {
t.Errorf("Encrypt(%+v) should fail without a non-empty string id", item)
}
}
}
func TestDataBagItem_Encrypt_WritesVersion3(t *testing.T) {
secret := []byte("secret")
enc, err := DataBagItem{"id": "x", "v": "value"}.Encrypt(secret)
if err != nil {
t.Fatalf("Encrypt: %v", err)
}
w, ok := enc["v"].(map[string]any)
if !ok {
t.Fatalf("wrapper not a JSON object: %T", enc["v"])
}
if v, _ := w["version"].(float64); v != 3 {
t.Errorf("version = %v, want 3", w["version"])
}
if w["cipher"] != "aes-256-gcm" {
t.Errorf("cipher = %v, want aes-256-gcm", w["cipher"])
}
if w["auth_tag"] == nil || w["iv"] == nil || w["encrypted_data"] == nil {
t.Errorf("v3 wrapper missing fields: %+v", w)
}
}
func TestDataBagItem_Decrypt_ChefCompat(t *testing.T) {
secret := []byte(compatSecret)
tests := []struct {
name string
wrapper string
want any
}{
{"v1-string", fixtureV1String, "hello world"},
{"v2-string", fixtureV2String, "hello world"},
{"v3-string", fixtureV3String, "hello world"},
{"v3-int", fixtureV3Int, float64(42)},
{"v3-obj", fixtureV3Obj, map[string]any{"a": float64(1), "b": []any{true, false, "x"}}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
item := DataBagItem{"id": "fix", "value": mustWrapper(t, tt.wrapper)}
dec, err := item.Decrypt(secret)
if err != nil {
t.Fatalf("Decrypt: %v", err)
}
if !reflect.DeepEqual(dec["value"], tt.want) {
t.Errorf("value = %#v, want %#v", dec["value"], tt.want)
}
if dec["id"] != "fix" {
t.Errorf("id = %v, want cleartext", dec["id"])
}
})
}
}
func TestDataBagItem_Decrypt_WrongSecret(t *testing.T) {
// v3 fixture decrypted with the wrong secret must be an auth error.
item := DataBagItem{"id": "fix", "value": mustWrapper(t, fixtureV3String)}
_, err := item.Decrypt([]byte("totally-wrong-secret"))
if err == nil {
t.Fatal("expected an error decrypting with the wrong secret")
}
if !errors.Is(err, ErrDataBagAuth) {
t.Errorf("err = %v, want ErrDataBagAuth chain", err)
}
}
func TestDataBagItem_Decrypt_V2TamperedHMAC(t *testing.T) {
w := mustWrapper(t, fixtureV2String).(map[string]any)
w["hmac"] = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
item := DataBagItem{"id": "fix", "value": w}
_, err := item.Decrypt([]byte(compatSecret))
if err == nil {
t.Fatal("expected an error on tampered v2 hmac")
}
if !errors.Is(err, ErrDataBagAuth) {
t.Errorf("err = %v, want ErrDataBagAuth chain", err)
}
}
func TestDataBagItem_Decrypt_V3TamperedCiphertext(t *testing.T) {
enc, err := DataBagItem{"id": "x", "v": "value"}.Encrypt([]byte("secret"))
if err != nil {
t.Fatalf("Encrypt: %v", err)
}
w := enc["v"].(map[string]any)
// Flip a byte in the ciphertext by re-encoding tampered bytes.
w["encrypted_data"] = flipFirstB64Byte(t, w["encrypted_data"].(string))
if _, err := enc.Decrypt([]byte("secret")); !errors.Is(err, ErrDataBagAuth) {
t.Errorf("tampered v3 ciphertext err = %v, want ErrDataBagAuth", err)
}
}
func TestDataBagItem_Decrypt_NotAWrapper(t *testing.T) {
// A plain (un-encrypted) item should give a clear, non-auth error.
item := DataBagItem{"id": "x", "password": "plaintext"}
_, err := item.Decrypt([]byte("secret"))
if err == nil {
t.Fatal("expected an error decrypting a non-encrypted item")
}
if errors.Is(err, ErrDataBagAuth) {
t.Errorf("non-wrapper should not be an auth error: %v", err)
}
if !errors.Is(err, ErrNotEncrypted) {
t.Errorf("err = %v, want ErrNotEncrypted chain", err)
}
}
func TestDataBagItem_IsEncrypted(t *testing.T) {
v3 := mustWrapper(t, fixtureV3String)
tests := []struct {
name string
item DataBagItem
want bool
}{
{"empty", DataBagItem{}, false},
{"only-id", DataBagItem{"id": "x"}, false},
{"plaintext", DataBagItem{"id": "x", "p": "secret"}, false},
{"one-wrapper", DataBagItem{"id": "x", "p": v3}, true},
{"mixed", DataBagItem{"id": "x", "p": v3, "q": "plaintext"}, false},
{"id-plus-wrapper", DataBagItem{"id": "x", "a": mustWrapper(t, fixtureV1String), "b": mustWrapper(t, fixtureV2String)}, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.item.IsEncrypted(); got != tt.want {
t.Errorf("IsEncrypted() = %v, want %v", got, tt.want)
}
})
}
}