/
dynamodb.go
287 lines (232 loc) · 7 KB
/
dynamodb.go
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
276
277
278
279
280
281
282
283
284
285
286
287
package persistencetest
import (
"context"
"os"
"strconv"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
"github.com/docker/go-connections/nat"
"github.com/testcontainers/testcontainers-go"
"github.com/godaddy/asherah/go/appencryption"
"github.com/godaddy/asherah/go/appencryption/pkg/persistence"
)
const (
IKCreated = int64(1541461381)
SKCreated = int64(1541461380)
EncryptedKeyString = "mWT/x4RvIFVFE2BEYV1IB9FMM8sWN1sK6YN5bS2UyGR+9RSZVTvp/bcQ6PycW6kxYEqrpA+aV4u04jOr"
SKKeyID = "_SK_api_ecomm"
TestKey = "some_key"
)
const (
tableName = "CustomTableName"
portProtocolDynamoDB = "8000/tcp"
maxTriesDynamoDB = 5
waitTimeDynamoDB = 10
partitionKey = "Id"
sortKey = "Created"
keyRecord = "KeyRecord"
)
type DynamoDBTestContext struct {
instant int64
disableTestContainers bool
sess *session.Session
container testcontainers.Container
dbSvc *dynamodb.DynamoDB
}
func (d *DynamoDBTestContext) NewMetastore(opts ...persistence.DynamoDBMetastoreOption) *persistence.DynamoDBMetastore {
combinedOpts := []persistence.DynamoDBMetastoreOption{
persistence.WithTableName(tableName),
}
if len(opts) > 0 {
combinedOpts = append(combinedOpts, opts...)
}
return persistence.NewDynamoDBMetastore(d.sess, combinedOpts...)
}
func (d *DynamoDBTestContext) SeedDB(t *testing.T) {
t.Helper()
t.Log("seeding dynamodb")
// Create table schema
input := &dynamodb.CreateTableInput{
AttributeDefinitions: []*dynamodb.AttributeDefinition{
{
AttributeName: aws.String(partitionKey),
AttributeType: aws.String("S"),
},
{
AttributeName: aws.String(sortKey),
AttributeType: aws.String("N"),
},
},
KeySchema: []*dynamodb.KeySchemaElement{
{
AttributeName: aws.String(partitionKey),
KeyType: aws.String("HASH"),
},
{
AttributeName: aws.String(sortKey),
KeyType: aws.String("RANGE"),
},
},
ProvisionedThroughput: &dynamodb.ProvisionedThroughput{
ReadCapacityUnits: aws.Int64(1),
WriteCapacityUnits: aws.Int64(1),
},
TableName: aws.String(tableName),
}
o, err := d.dbSvc.CreateTable(input)
if err != nil {
panic(err)
}
t.Log("table created:", o.TableDescription.TableArn, "@", o.TableDescription.CreationDateTime)
describeTableInput := &dynamodb.DescribeTableInput{TableName: aws.String(tableName)}
if err := d.dbSvc.WaitUntilTableExists(describeTableInput); err != nil {
panic(err)
}
t.Log("finished waiting for table")
// Add item to table
km := appencryption.KeyMeta{
ID: SKKeyID,
Created: SKCreated,
}
en := persistence.DynamoDBEnvelope{
Revoked: false,
Created: IKCreated,
EncryptedKey: EncryptedKeyString,
ParentKeyMeta: &km,
}
d.putItemInDynamoDB(t, d.newDynamoDBPutItemInput(en, d.instant))
}
func (d *DynamoDBTestContext) CleanDB(t *testing.T) {
t.Helper()
t.Log("cleaning db")
// Blow out the whole table so we have clean slate each time
deleteTableInput := &dynamodb.DeleteTableInput{
TableName: aws.String(tableName),
}
if _, err := d.dbSvc.DeleteTable(deleteTableInput); err != nil {
// We may have already deleted the table in some test cases
if e, ok := err.(awserr.Error); ok && e.Code() == dynamodb.ErrCodeResourceNotFoundException {
t.Logf("ignoring error on delete table: %v", e)
return
}
panic(err)
}
t.Log("waiting for table delete")
describeTableInput := &dynamodb.DescribeTableInput{TableName: aws.String(tableName)}
if err := d.dbSvc.WaitUntilTableNotExists(describeTableInput); err != nil {
panic(err)
}
t.Log("finished waiting for table delete")
}
func (d *DynamoDBTestContext) InsertTestItem(t *testing.T, instant int64) {
t.Helper()
d.putItemInDynamoDB(t, d.newDynamoDBPutItemInput(persistence.DynamoDBEnvelope{Created: instant}, instant))
}
func (d *DynamoDBTestContext) putItemInDynamoDB(t *testing.T, item *dynamodb.PutItemInput) {
t.Helper()
t.Log("putting item")
_, err := d.dbSvc.PutItem(item)
if err != nil {
panic(err)
}
}
func (d *DynamoDBTestContext) newDynamoDBPutItemInput(envelope persistence.DynamoDBEnvelope, instant int64) *dynamodb.PutItemInput {
// Get item to add in table
av, err := dynamodbattribute.MarshalMap(&envelope)
if err != nil {
panic(err)
}
input := &dynamodb.PutItemInput{
Item: map[string]*dynamodb.AttributeValue{
partitionKey: {S: aws.String(TestKey)},
sortKey: {N: aws.String(strconv.FormatInt(instant, 10))},
keyRecord: {M: av},
},
TableName: aws.String(tableName),
}
return input
}
func (d *DynamoDBTestContext) waitForDynamoDBPing(t *testing.T) {
t.Helper()
// Check if dynamodb is up and running
listTableInput := new(dynamodb.ListTablesInput)
_, err := d.dbSvc.ListTables(listTableInput)
for tries := 1; err != nil; tries++ {
t.Logf("failed to list dynamodb tables (tried %d of max %d)", tries, maxTriesDynamoDB)
if tries == maxTriesDynamoDB {
panic(err)
}
time.Sleep(waitTimeDynamoDB * time.Second)
_, err = d.dbSvc.ListTables(listTableInput)
}
t.Log("finished waiting for dynamodb")
}
func (d *DynamoDBTestContext) TearDown(t *testing.T) {
t.Helper()
t.Log("tearing down")
// Don't call terminate if we are not using test containers
if !d.disableTestContainers {
t.Log("terminating test container")
if err := d.container.Terminate(context.Background()); err != nil {
panic(err)
}
}
}
func NewDynamoDBTestContext(t *testing.T, instant int64) *DynamoDBTestContext {
t.Helper()
ctx := context.Background()
d := &DynamoDBTestContext{
instant: instant,
}
// Setup client pointing to our local dynamodb
var (
err error
host string
dynamodbNatPort nat.Port
)
if val, ok := os.LookupEnv("DISABLE_TESTCONTAINERS"); ok {
d.disableTestContainers, err = strconv.ParseBool(val)
if err != nil {
panic(err)
}
}
if d.disableTestContainers {
host = os.Getenv("DYNAMODB_HOSTNAME")
if len(host) == 0 {
host = "localhost"
}
dynamodbNatPort = portProtocolDynamoDB
} else {
request := testcontainers.ContainerRequest{
Image: "amazon/dynamodb-local:latest",
ExposedPorts: []string{portProtocolDynamoDB},
}
d.container, err = testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
ContainerRequest: request,
Started: true,
})
if err != nil {
panic(err)
}
if host, err = d.container.Host(ctx); err != nil {
panic(err)
}
if dynamodbNatPort, err = d.container.MappedPort(ctx, portProtocolDynamoDB); err != nil {
panic(err)
}
}
endpoint := "http://" + host + ":" + dynamodbNatPort.Port()
t.Logf("using dynamodb endpoint: %s", endpoint)
d.sess = session.Must(session.NewSession(&aws.Config{
Region: aws.String("us-west-2"),
Endpoint: aws.String(endpoint),
}))
d.dbSvc = dynamodb.New(d.sess)
d.waitForDynamoDBPing(t)
return d
}