File: encryption_client_v2_test.go

package info (click to toggle)
golang-github-aws-aws-sdk-go 1.44.133-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bookworm-proposed-updates
  • size: 245,296 kB
  • sloc: makefile: 120
file content (212 lines) | stat: -rw-r--r-- 6,258 bytes parent folder | download | duplicates (2)
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
//go:build go1.7
// +build go1.7

package s3crypto

import (
	"bytes"
	"encoding/hex"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"reflect"
	"strings"
	"testing"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/request"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/awstesting/unit"
	"github.com/aws/aws-sdk-go/service/kms"
	"github.com/aws/aws-sdk-go/service/s3"
)

func sessionWithLogCheck(message string) (*session.Session, *bool) {
	gotWarning := false

	u := unit.Session.Copy(&aws.Config{Logger: aws.LoggerFunc(func(i ...interface{}) {
		if len(i) == 0 {
			return
		}
		s, ok := i[0].(string)
		if !ok {
			return
		}
		if s == message {
			gotWarning = true
		}
	})})

	return u, &gotWarning
}

func TestNewEncryptionClientV2(t *testing.T) {
	tUnit, gotWarning := sessionWithLogCheck(customTypeWarningMessage)

	mcb := AESGCMContentCipherBuilderV2(NewKMSContextKeyGenerator(nil, "id", nil))
	v2, err := NewEncryptionClientV2(tUnit, mcb)
	if err != nil {
		t.Fatalf("expected no error, got %v", err)
	}
	if v2 == nil {
		t.Fatal("expected client to not be nil")
	}

	if *gotWarning {
		t.Errorf("expected no warning for aws provided custom cipher builder")
	}

	if !reflect.DeepEqual(mcb, v2.options.ContentCipherBuilder) {
		t.Errorf("content cipher builder did not match provided value")
	}

	_, ok := v2.options.SaveStrategy.(HeaderV2SaveStrategy)
	if !ok {
		t.Errorf("expected default save strategy to be s3 header strategy")
	}

	if v2.options.S3Client == nil {
		t.Errorf("expected s3 client not be nil")
	}

	if e, a := DefaultMinFileSize, v2.options.MinFileSize; int64(e) != a {
		t.Errorf("expected %v, got %v", e, a)
	}

	if e, a := "", v2.options.TempFolderPath; e != a {
		t.Errorf("expected %v, got %v", e, a)
	}
}

func TestNewEncryptionClientV2_NonDefaults(t *testing.T) {
	tUnit, gotWarning := sessionWithLogCheck(customTypeWarningMessage)

	s3Client := s3.New(tUnit)

	mcb := mockCipherBuilderV2{}
	v2, err := NewEncryptionClientV2(tUnit, nil, func(clientOptions *EncryptionClientOptions) {
		clientOptions.S3Client = s3Client
		clientOptions.ContentCipherBuilder = mcb
		clientOptions.TempFolderPath = "/mock/path"
		clientOptions.MinFileSize = 42
		clientOptions.SaveStrategy = S3SaveStrategy{}
	})
	if err != nil {
		t.Fatalf("expected no error, got %v", err)
	}
	if v2 == nil {
		t.Fatal("expected client to not be nil")
	}

	if !*gotWarning {
		t.Errorf("expected warning for custom provided content cipher builder")
	}

	if !reflect.DeepEqual(mcb, v2.options.ContentCipherBuilder) {
		t.Errorf("content cipher builder did not match provided value")
	}

	_, ok := v2.options.SaveStrategy.(S3SaveStrategy)
	if !ok {
		t.Errorf("expected default save strategy to be s3 header strategy")
	}

	if v2.options.S3Client != s3Client {
		t.Errorf("expected s3 client not be nil")
	}

	if e, a := 42, v2.options.MinFileSize; int64(e) != a {
		t.Errorf("expected %v, got %v", e, a)
	}

	if e, a := "/mock/path", v2.options.TempFolderPath; e != a {
		t.Errorf("expected %v, got %v", e, a)
	}
}

// cdgWithStaticTestIV is a test structure that wraps a CipherDataGeneratorWithCEKAlg and stubs in a static IV
// so that encryption tests can be guaranteed to be consistent.
type cdgWithStaticTestIV struct {
	IV []byte
	CipherDataGeneratorWithCEKAlg
}

// isAWSFixture will avoid the warning log message when doing tests that need to mock the IV
func (k cdgWithStaticTestIV) isAWSFixture() bool {
	return true
}

func (k cdgWithStaticTestIV) GenerateCipherDataWithCEKAlg(ctx aws.Context, keySize, ivSize int, cekAlg string) (CipherData, error) {
	cipherData, err := k.CipherDataGeneratorWithCEKAlg.GenerateCipherDataWithCEKAlg(ctx, keySize, ivSize, cekAlg)
	if err == nil {
		cipherData.IV = k.IV
	}
	return cipherData, err
}

func TestEncryptionClientV2_PutObject_KMSCONTEXT_AESGCM(t *testing.T) {
	ts := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
		fmt.Fprintln(writer, `{"CiphertextBlob":"8gSzlk7giyfFbLPUVgoVjvQebI1827jp8lDkO+n2chsiSoegx1sjm8NdPk0Bl70I","KeyId":"test-key-id","Plaintext":"lP6AbIQTmptyb/+WQq+ubDw+w7na0T1LGSByZGuaono="}`)
	}))

	sess := unit.Session.Copy()
	kmsClient := kms.New(sess.Copy(&aws.Config{Endpoint: &ts.URL}))

	var md MaterialDescription
	iv, _ := hex.DecodeString("ae325acae2bfd5b9c3d0b813")
	kmsWithStaticIV := cdgWithStaticTestIV{
		IV:                            iv,
		CipherDataGeneratorWithCEKAlg: NewKMSContextKeyGenerator(kmsClient, "test-key-id", md),
	}
	contentCipherBuilderV2 := AESGCMContentCipherBuilderV2(kmsWithStaticIV)
	client, err := NewEncryptionClientV2(sess, contentCipherBuilderV2)
	if err != nil {
		t.Fatalf("expected no error, got %v", err)
	}

	req, _ := client.PutObjectRequest(&s3.PutObjectInput{
		Bucket: aws.String("test-bucket"),
		Key:    aws.String("test-key"),
		Body: func() io.ReadSeeker {
			content, _ := hex.DecodeString("8f2c59c6dbfcacf356f3da40788cbde67ca38161a4702cbcf757af663e1c24a600001b2f500417dbf5a050f57db6737422b2ed6a44c75e0d")
			return bytes.NewReader(content)
		}(),
	})

	req.Handlers.Send.Clear()
	req.Handlers.Send.PushFront(func(r *request.Request) {
		all, err := ioutil.ReadAll(r.Body)
		if err != nil {
			t.Fatalf("expected no error, got %v", err)
		}

		expected, _ := hex.DecodeString("4cd8e95a1c9b8b19640e02838b02c8c09e66250703a602956695afbc23cbb8647d51645955ab63b89733d0766f9a264adb88571b1d467b734ff72eb73d31de9a83670d59688c54ea")

		if !bytes.Equal(all, expected) {
			t.Error("encrypted bytes did not match expected")
		}

		req.HTTPResponse = &http.Response{
			Status:     http.StatusText(200),
			StatusCode: http.StatusOK,
			Body:       aws.ReadSeekCloser(bytes.NewReader([]byte{})),
		}
	})
	err = req.Send()
	if err != nil {
		t.Errorf("expected no error, got %v", err)
	}
}

func TestNewEncryptionClientV2_FailsOnIncompatibleFixtures(t *testing.T) {
	sess := unit.Session.Copy()
	_, err := NewEncryptionClientV2(sess, AESGCMContentCipherBuilder(NewKMSKeyGenerator(kms.New(sess), "cmkId")))
	if err == nil {
		t.Fatal("expected to fail, but got nil")
	}
	if !strings.Contains(err.Error(), "attempted to use deprecated or incompatible cipher builder") {
		t.Errorf("expected to get error for using dperecated cipher builder")
	}
}