Debian Codegraph @

integration/hcvault/hcvault_aead_test.go

raw
1 // Copyright 2019 Google Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 package hcvault_test
15
16 import (
17 "bytes"
18 "crypto/tls"
19 "crypto/x509"
20 "encoding/base64"
21 "encoding/json"
22 "fmt"
23 "net/http"
24 "net/http/httptest"
25 "strings"
26 "testing"
27
28 vault_api "github.com/hashicorp/vault/api"
29 "github.com/tink-crypto/tink-go-hcvault/v2/integration/hcvault"
30 )
31
32 const (
33 keyURITmpl = "%s/transit/keys/key-1"
34 token = "mytoken"
35 )
36
37 func TestVaultNewAEAD_EncryptDecrypt(t *testing.T) {
38 server, _, tlsConfig := newServer(t)
39 defer server.Close()
40
41 client := newVaultAPIClient(t, server.URL, token, tlsConfig)
42
43 aead, err := hcvault.NewAEAD("/transit/keys/key-1", client.Logical())
44 if err != nil {
45 t.Fatalf("hcvault.NewAEAD() err = %v, want nil", err)
46 }
47
48 plaintext := []byte("plaintext")
49 associatedData := []byte("associatedData")
50 ciphertext, err := aead.Encrypt(plaintext, associatedData)
51 if err != nil {
52 t.Fatalf("aead.Encrypt(plaintext, associatedData) err = %v, want nil", err)
53 }
54 gotPlaintext, err := aead.Decrypt(ciphertext, associatedData)
55 if err != nil {
56 t.Fatalf("aead.Decrypt(ciphertext, associatedData) err = %v, want nil", err)
57 }
58 if !bytes.Equal(gotPlaintext, plaintext) {
59 t.Errorf("aead.Decrypt(ciphertext, associatedData) = %s, want %s", gotPlaintext, plaintext)
60 }
61
62 otherAssociatedData := []byte("otherAssociatedData")
63 _, err = aead.Decrypt(ciphertext, otherAssociatedData)
64 if err == nil {
65 t.Error("aead.Decrypt(ciphertext, otherAssociatedData) err = nil, want error")
66 }
67 }
68
69 func TestVaultNewClientWithAEADOptions_EncryptDecrypt(t *testing.T) {
70 server, uriPrefix, tlsConfig := newServer(t)
71 defer server.Close()
72
73 client := newVaultAPIClient(t, server.URL, token, tlsConfig)
74
75 keyURI := uriPrefix + "/transit/keys/key-1"
76 tinkClient, err := hcvault.NewClientWithAEADOptions(keyURI, client.Logical())
77 if err != nil {
78 t.Fatalf("hcvault.NewClientWithAEADOptions() err = %v, want nil", err)
79 }
80 aead, err := tinkClient.GetAEAD(keyURI)
81 if err != nil {
82 t.Fatalf("tinkClient.GetAEAD() err = %v, want nil", err)
83 }
84
85 plaintext := []byte("plaintext")
86 associatedData := []byte("associatedData")
87 ciphertext, err := aead.Encrypt(plaintext, associatedData)
88 if err != nil {
89 t.Fatalf("aead.Encrypt(plaintext, associatedData) err = %v, want nil", err)
90 }
91 gotPlaintext, err := aead.Decrypt(ciphertext, associatedData)
92 if err != nil {
93 t.Fatalf("aead.Decrypt(ciphertext, associatedData) err = %v, want nil", err)
94 }
95 if !bytes.Equal(gotPlaintext, plaintext) {
96 t.Fatalf("aead.Decrypt(ciphertext, associatedData) = %s, want %s", gotPlaintext, plaintext)
97 }
98
99 otherAssociatedData := []byte("otherAssociatedData")
100 _, err = aead.Decrypt(ciphertext, otherAssociatedData)
101 if err == nil {
102 t.Error("aead.Decrypt(ciphertext, otherAssociatedData) err = nil, want error")
103 }
104 }
105
106 func TestVaultNewAEAD_DecryptWithFixedCiphertext(t *testing.T) {
107 server, _, tlsConfig := newServer(t)
108 defer server.Close()
109
110 client := newVaultAPIClient(t, server.URL, token, tlsConfig)
111
112 aead, err := hcvault.NewAEAD("/transit/keys/key-1", client.Logical())
113 if err != nil {
114 t.Fatalf("hcvault.NewAEAD() err = %v, want nil", err)
115 }
116
117 // associatedData is passed as "context" parameter to vault decrypt.
118 plaintext := []byte("plaintext")
119 associatedData := []byte("associatedData")
120 ciphertext := fakeEncrypt(plaintext, associatedData, nil)
121
122 gotPlaintext, err := aead.Decrypt(ciphertext, associatedData)
123 if err != nil {
124 t.Fatalf("aead.Decrypt(ciphertext, associatedData) err = %v, want nil", err)
125 }
126 if !bytes.Equal(gotPlaintext, plaintext) {
127 t.Fatalf("aead.Decrypt(ciphertext, associatedData) = %s, want %s", gotPlaintext, associatedData)
128 }
129 }
130
131 func TestVaultNewAEADWithLegacyContextParamater_isCompatible(t *testing.T) {
132 server, uriPrefix, tlsConfig := newServer(t)
133 defer server.Close()
134
135 client := newVaultAPIClient(t, server.URL, token, tlsConfig)
136
137 // Create AEAD with NewAEAD using WithLegacyContextParamater.
138 aead1, err := hcvault.NewAEAD("/transit/keys/key-1", client.Logical(), hcvault.WithLegacyContextParamater())
139 if err != nil {
140 t.Fatalf("hcvault.NewAEAD() err = %v, want nil", err)
141 }
142
143 keyURI := uriPrefix + "/transit/keys/key-1"
144
145 // Create AEAD with hcvault.NewClientWithAEADOptions using WithLegacyContextParamater and GetAEAD.
146 hcvaultClient2, err := hcvault.NewClientWithAEADOptions(
147 uriPrefix, client.Logical(), hcvault.WithLegacyContextParamater())
148 if err != nil {
149 t.Fatalf("hcvault.NewClientWithAEADOptions() err = %v, want nil", err)
150 }
151 aead2, err := hcvaultClient2.GetAEAD(keyURI)
152 if err != nil {
153 t.Fatalf("hcvaultClient2.GetAEAD(%q) err = %v, want nil", keyURI, err)
154 }
155
156 // Create AEAD with hcvault.NewClient and GetAEAD.
157 hcvaultClient3, err := hcvault.NewClient(uriPrefix, tlsConfig, token)
158 if err != nil {
159 t.Fatalf("hcvault.NewClient() err = %v, want nil", err)
160 }
161 aead3, err := hcvaultClient3.GetAEAD(keyURI)
162 if err != nil {
163 t.Fatalf("hcvaultClient3.GetAEAD(%q) err = %v, want nil", keyURI, err)
164 }
165
166 plaintext := []byte("plaintext")
167 associatedData := []byte("associatedData")
168
169 ciphertext2, err := aead2.Encrypt(plaintext, associatedData)
170 if err != nil {
171 t.Fatalf("aead2.Encrypt(plaintext, associatedData) err = %v, want nil", err)
172 }
173 gotPlaintext1, err := aead1.Decrypt(ciphertext2, associatedData)
174 if err != nil {
175 t.Fatalf("aead1.Decrypt(ciphertext2, associatedData) err = %v, want nil", err)
176 }
177 if !bytes.Equal(gotPlaintext1, plaintext) {
178 t.Fatalf("aead1.Decrypt(ciphertext2, associatedData) = %s, want %s", gotPlaintext1, plaintext)
179 }
180
181 ciphertext3, err := aead3.Encrypt(plaintext, associatedData)
182 if err != nil {
183 t.Fatalf("aead2.Encrypt(plaintext, associatedData) err = %v, want nil", err)
184 }
185 gotPlaintext2, err := aead2.Decrypt(ciphertext3, associatedData)
186 if err != nil {
187 t.Fatalf("aead2.Decrypt(ciphertext3, associatedData) err = %v, want nil", err)
188 }
189 if !bytes.Equal(gotPlaintext2, plaintext) {
190 t.Fatalf("aead2.Decrypt(ciphertext3, associatedData) = %s, want %s", gotPlaintext2, plaintext)
191 }
192
193 ciphertext1, err := aead1.Encrypt(plaintext, associatedData)
194 if err != nil {
195 t.Fatalf("aead2.Encrypt(plaintext, associatedData) err = %v, want nil", err)
196 }
197 gotPlaintext3, err := aead3.Decrypt(ciphertext1, associatedData)
198 if err != nil {
199 t.Fatalf("aead2.Decrypt(ciphertext1, associatedData) err = %v, want nil", err)
200 }
201 if !bytes.Equal(gotPlaintext3, plaintext) {
202 t.Fatalf("aead2.Decrypt(ciphertext1, associatedData) = %s, want %s", gotPlaintext2, plaintext)
203 }
204 }
205
206 func TestVaultClientAEAD_EncryptDecrypt(t *testing.T) {
207 server, uriPrefix, tlsConfig := newServer(t)
208 defer server.Close()
209
210 client, err := hcvault.NewClient(uriPrefix, tlsConfig, token)
211 if err != nil {
212 t.Fatalf("hcvault.NewClient() err = %v, want nil", err)
213 }
214
215 keyURI := fmt.Sprintf(keyURITmpl, uriPrefix)
216 aead, err := client.GetAEAD(keyURI)
217 if err != nil {
218 t.Fatalf("client.GetAEAD(%q) err = %v, want nil", keyURI, err)
219 }
220 plaintext := []byte("plaintext")
221 context := []byte("context")
222 ciphertext, err := aead.Encrypt(plaintext, context)
223 if err != nil {
224 t.Fatalf("aead.Encrypt(plaintext, context) err = %v, want nil", err)
225 }
226 gotPlaintext, err := aead.Decrypt(ciphertext, context)
227 if err != nil {
228 t.Fatalf("aead.Decrypt(ciphertext, context) err = %v, want nil", err)
229 }
230 if !bytes.Equal(gotPlaintext, plaintext) {
231 t.Fatalf("aead.Decrypt(ciphertext, context) = %s, want %s", gotPlaintext, plaintext)
232 }
233
234 invalidContext := []byte("invalidContext")
235 _, err = aead.Decrypt(ciphertext, invalidContext)
236 if err == nil {
237 t.Error("aead.Decrypt(ciphertext, invalidContext) err = nil, want error")
238 }
239 }
240
241 func TestVaultClientAEAD_DecryptWithFixedCiphertext(t *testing.T) {
242 server, uriPrefix, tlsConfig := newServer(t)
243 defer server.Close()
244
245 client, err := hcvault.NewClient(uriPrefix, tlsConfig, token)
246 if err != nil {
247 t.Fatalf("hcvault.NewClient() err = %v, want nil", err)
248 }
249
250 keyURI := fmt.Sprintf(keyURITmpl, uriPrefix)
251 aead, err := client.GetAEAD(keyURI)
252 if err != nil {
253 t.Fatalf("client.GetAEAD(%q) err = %v, want nil", keyURI, err)
254 }
255 // associatedData is passed as "context" parameter to vault decrypt.
256 plaintext := []byte("plaintext")
257 context := []byte("context")
258 ciphertext := fakeEncrypt(plaintext, nil, context)
259 gotPlaintext, err := aead.Decrypt(ciphertext, context)
260 if err != nil {
261 t.Fatalf("aead.Decrypt(ciphertext, context) err = %v, want nil", err)
262 }
263 if !bytes.Equal(gotPlaintext, plaintext) {
264 t.Fatalf("aead.Decrypt(ciphertext, context) = %s, want %s", gotPlaintext, plaintext)
265 }
266 }
267
268 func TestGetAEADFailWithBadKeyURI(t *testing.T) {
269 server, uriPrefix, tlsConfig := newServer(t)
270 defer server.Close()
271
272 client, err := hcvault.NewClient(uriPrefix, tlsConfig, token)
273 if err != nil {
274 t.Fatalf("hcvault.NewClient() err = %v, want nil", err)
275 }
276
277 for _, test := range []struct {
278 name string
279 keyURI string
280 }{
281 {
282 name: "empty",
283 keyURI: fmt.Sprintf("%s/", uriPrefix),
284 },
285 {
286 name: "without slash",
287 keyURI: fmt.Sprintf("%s/badKeyUri", uriPrefix),
288 },
289 {
290 name: "with one slash",
291 keyURI: fmt.Sprintf("%s/bad/KeyUri", uriPrefix),
292 },
293 {
294 name: "with three slash",
295 keyURI: fmt.Sprintf("%s/one/two/three/four", uriPrefix),
296 },
297 } {
298 t.Run(test.name, func(t *testing.T) {
299 if _, err := client.GetAEAD(test.keyURI); err == nil {
300 t.Errorf("client.GetAEAD(%q) err = nil, want error", test.keyURI)
301 }
302 })
303 }
304 }
305
306 // newVaultAPIClient creates a new vault API client
307 func newVaultAPIClient(t *testing.T, url string, token string, tlsConfig *tls.Config) *vault_api.Client {
308 t.Helper()
309 httpClient := vault_api.DefaultConfig().HttpClient
310 transport := httpClient.Transport.(*http.Transport)
311 transport.TLSClientConfig = tlsConfig.Clone()
312 cfg := &vault_api.Config{
313 Address: url,
314 HttpClient: httpClient,
315 }
316 client, err := vault_api.NewClient(cfg)
317 if err != nil {
318 t.Fatal(err)
319 }
320 client.SetToken(token)
321 return client
322 }
323
324 type closeFunc func() error
325
326 // newServer returns a fake, TLS-enabled Vault server, an "hcvault://" URI
327 // prefix for accessing it, and a TLS configuration which trusts the servers
328 // certificate.
329 //
330 // Once finished with the server, it's Close() method should be called.
331 //
332 // The URL and TLS configuration can be passed to hcvault.NewClient().
333 //
334 // The URL can also be used to construct valid key URIs for the server.
335 func newServer(t *testing.T) (server *httptest.Server, uriPrefix string, clientTLSConfig *tls.Config) {
336 server = httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
337 switch r.RequestURI {
338
339 // Encrypt
340 case "/v1/transit/encrypt/key-1":
341 decoder := json.NewDecoder(r.Body)
342 var encReq = make(map[string]string)
343 if err := decoder.Decode(&encReq); err != nil {
344 http.Error(w, fmt.Sprintf("Cannot decode encryption request: %s", err), 400)
345 return
346 }
347 plaintext, err := base64.StdEncoding.DecodeString(encReq["plaintext"])
348 if err != nil {
349 http.Error(w, "plaintext must be base64 encoded", 400)
350 return
351 }
352 context, err := base64.StdEncoding.DecodeString(encReq["context"])
353 if err != nil {
354 http.Error(w, "context must be base64 encoded", 400)
355 return
356 }
357 associatedData, err := base64.StdEncoding.DecodeString(encReq["associated_data"])
358 if err != nil {
359 http.Error(w, "associated_data must be base64 encoded", 400)
360 return
361 }
362 ciphertext := fakeEncrypt(plaintext, associatedData, context)
363 resp := map[string]any{
364 "data": map[string]string{
365 "ciphertext": string(ciphertext),
366 },
367 }
368 respBytes, err := json.Marshal(resp)
369 if err != nil {
370 t.Fatalf("Cannot encode encrypted data: %v", err)
371 }
372 if _, err := w.Write(respBytes); err != nil {
373 t.Fatalf("Cannot send encrypted data response: %v", err)
374 }
375
376 // Decrypt
377 case "/v1/transit/decrypt/key-1":
378 decoder := json.NewDecoder(r.Body)
379 var decReq = make(map[string]string)
380 if err := decoder.Decode(&decReq); err != nil {
381 http.Error(w, fmt.Sprintf("Cannot decode decryption request: %s", err), 400)
382 return
383 }
384 ciphertext := []byte(decReq["ciphertext"])
385 context, err := base64.StdEncoding.DecodeString(decReq["context"])
386 if err != nil {
387 http.Error(w, "context must be base64 encoded", 400)
388 return
389 }
390 associatedData, err := base64.StdEncoding.DecodeString(decReq["associated_data"])
391 if err != nil {
392 http.Error(w, "associated_data must be base64 encoded", 400)
393 return
394 }
395 plaintext, err := fakeDecrypt(ciphertext, associatedData, context)
396 if err != nil {
397 http.Error(w, fmt.Sprintf("Cannot decrypt ciphertext: %s", err), 400)
398 return
399 }
400 resp := map[string]any{
401 "data": map[string]string{
402 "plaintext": base64.StdEncoding.EncodeToString(plaintext),
403 },
404 }
405 respBytes, err := json.Marshal(resp)
406 if err != nil {
407 t.Fatalf("Cannot encode encrypted data: %v", err)
408 }
409 if _, err := w.Write(respBytes); err != nil {
410 t.Fatalf("Cannot send encrypted data response: %v", err)
411 }
412
413 default:
414 http.NotFound(w, r)
415 }
416 }))
417
418 uriPrefix = strings.Replace(server.URL, "https", "hcvault", 1)
419
420 certpool := x509.NewCertPool()
421 certpool.AddCert(server.Certificate())
422 clientTLSConfig = &tls.Config{RootCAs: certpool}
423
424 return server, uriPrefix, clientTLSConfig
425 }
426
427 // The ciphertext returned by HC Vault is of the form:
428 //
429 // vault:v1:<ciphertext>
430 //
431 // where ciphertext is base64-encoded. See:
432 // https://developer.hashicorp.com/vault/api-docs/secret/transit#sample-request-13
433 //
434 // The ciphertext returned by this fake implementation is of the form:
435 //
436 // enc:<context>:<associatedData>:<plaintext>
437 //
438 // where context, associatedData and plaintext are base64-encoded.
439 // It is deterministic and not secure.
440 func fakeEncrypt(plaintext, associatedData, context []byte) []byte {
441 s := fmt.Sprintf(
442 "enc:%s:%s:%s",
443 base64.StdEncoding.EncodeToString(context),
444 base64.StdEncoding.EncodeToString(associatedData),
445 base64.StdEncoding.EncodeToString(plaintext),
446 )
447 return []byte(s)
448 }
449
450 func TestFakeEncrypt(t *testing.T) {
451 want := []byte("enc:Y29udGV4dA==:YXNzb2NpYXRlZERhdGE=:cGxhaW50ZXh0")
452 got := fakeEncrypt([]byte("plaintext"), []byte("associatedData"), []byte("context"))
453 if !bytes.Equal(got, want) {
454 t.Errorf("fakeEncrypt(plaintext, associatedData, context) = %q, want %q", got, want)
455 }
456 }
457
458 func TestFakeEncryptWithoutAssociatedData(t *testing.T) {
459 want := []byte("enc:Y29udGV4dA==::cGxhaW50ZXh0")
460 got := fakeEncrypt([]byte("plaintext"), nil, []byte("context"))
461 if !bytes.Equal(got, want) {
462 t.Errorf("fakeEncrypt(plaintext, nil, context) = %q, want %q", got, want)
463 }
464 }
465
466 func TestFakeEncryptWithoutContext(t *testing.T) {
467 want := []byte("enc::YXNzb2NpYXRlZERhdGE=:cGxhaW50ZXh0")
468 got := fakeEncrypt([]byte("plaintext"), []byte("associatedData"), nil)
469 if !bytes.Equal(got, want) {
470 t.Errorf("fakeEncrypt(plaintext, associatedData, nil) = %q, want %q", got, want)
471 }
472 }
473
474 func fakeDecrypt(ciphertext, associatedData, context []byte) ([]byte, error) {
475 ct := string(ciphertext)
476 parts := strings.Split(ct, ":")
477 if len(parts) != 4 || parts[0] != "enc" {
478 return nil, fmt.Errorf("malformed ciphertext: %s", ciphertext)
479 }
480 context2, err := base64.StdEncoding.DecodeString(parts[1])
481 if err != nil {
482 return nil, err
483 }
484 if !bytes.Equal(context, context2) {
485 return nil, fmt.Errorf("invalid context: %s != %s", context2, context)
486 }
487 associatedData2, err := base64.StdEncoding.DecodeString(parts[2])
488 if err != nil {
489 return nil, err
490 }
491 if !bytes.Equal(associatedData2, associatedData) {
492 return nil, fmt.Errorf("invalid associatedData: %s != %s", associatedData2, associatedData)
493 }
494 plaintext, err := base64.StdEncoding.DecodeString(parts[3])
495 if err != nil {
496 return nil, err
497 }
498 return plaintext, nil
499 }
500
501 func TestFakeEncryptDecrypt(t *testing.T) {
502 ciphertext := fakeEncrypt([]byte("plaintext"), []byte("associatedData"), []byte("context"))
503 got, err := fakeDecrypt(ciphertext, []byte("associatedData"), []byte("context"))
504 if err != nil {
505 t.Errorf("fakeDecrypt() err = %v, want nil", err)
506 }
507 if want := []byte("plaintext"); !bytes.Equal(got, want) {
508 t.Errorf("fakeDecrypt() = %q, want %q", got, want)
509 }
510 }