-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathaws.go
551 lines (490 loc) · 12.5 KB
/
aws.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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
/* ****************************************************************************
* Copyright 2020 51 Degrees Mobile Experts Limited (51degrees.com)
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
* ***************************************************************************/
package swift
import (
"errors"
"fmt"
"sync"
"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"
)
// AWS is a implementation of sws.Store for AWS DynamoDB.
type AWS struct {
name string
timestamp time.Time // The last time the maps were refreshed
svc *dynamodb.DynamoDB // Reference to the creators table
common
}
// NodeItem is the dynamodb table item representation of a node
type NodeItem struct {
Network string // The name of the network the node belongs to
Domain string // The domain name associated with the node
Created time.Time // The time that the node was created
Starts time.Time // The time that the node goes online
Expires int64 `json:"expires"` // The time that the node will retire from the network
Role int // The role the node has in the network
ScramblerKey string // Secret used to scramble data with fixed nonce
CookieDomain string // The domain to use with cookies
}
// SecretItem is the dynamodb table item representation of a secret
type SecretItem struct {
Domain string
TimeStamp time.Time
Expires int64 `json:"expires"`
ScramblerKey string
}
// NewAWS creates a new instance of the AWS structure
func NewAWS() (*AWS, error) {
var a AWS
var s *session.Session
a.name = "AWS DynamoDB Store"
// Configure session with credentials from .aws/credentials or env and
// region from .aws/config or env
s = session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
if s == nil {
return nil, errors.New("AWS session is nil")
}
a.svc = dynamodb.New(s)
_, err := a.awsCreateTables()
if err != nil {
return nil, err
}
a.mutex = &sync.Mutex{}
err = a.refresh()
if err != nil {
return nil, err
}
return &a, nil
}
func (a *AWS) awsCreateTables() (bool, error) {
// Create nodes table
_, err := a.createNodesTable()
nodesExisted, err := a.checkTableExists(err)
if err != nil {
return false, err
}
// Create secrets table
_, err = a.createSecretsTable()
secretsExisted, err := a.checkTableExists(err)
if err != nil {
return false, err
}
if !nodesExisted {
// Wait for nodes table to be created
err = a.waitUntilTableActive(nodesTableName)
if err != nil {
return false, err
}
// Set TTL on nodes table expires attribute
err = a.setTableTTL(nodesTableName)
if err != nil {
return false, err
}
}
if !secretsExisted {
// Wait for secrets table to be created
err = a.waitUntilTableActive(secretsTableName)
if err != nil {
return false, err
}
// Set TTL on secrets table expires attribute
err = a.setTableTTL(secretsTableName)
if err != nil {
return false, err
}
}
return true, nil
}
func (a *AWS) checkTableExists(err error) (bool, error) {
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case dynamodb.ErrCodeTableAlreadyExistsException:
return true, nil
case dynamodb.ErrCodeResourceInUseException:
return true, nil
default:
return false, err
}
} else {
return false, err
}
}
return false, nil
}
func (a *AWS) waitUntilTableActive(tableName string) error {
for {
input := &dynamodb.DescribeTableInput{
TableName: aws.String(tableName),
}
result, err := a.svc.DescribeTable(input)
if err != nil {
return err
}
if *result.Table.TableStatus == "ACTIVE" {
break
}
}
return nil
}
func (a *AWS) setTableTTL(tableName string) error {
ttlInput := &dynamodb.UpdateTimeToLiveInput{
TableName: aws.String(tableName),
TimeToLiveSpecification: &dynamodb.TimeToLiveSpecification{
AttributeName: aws.String(expiresFieldName),
Enabled: aws.Bool(true),
},
}
_, err := a.svc.UpdateTimeToLive(ttlInput)
if err != nil {
return err
}
return nil
}
func (a *AWS) createNodesTable() (*dynamodb.CreateTableOutput, error) {
// Create nodes table
nodesTableInput := &dynamodb.CreateTableInput{
AttributeDefinitions: []*dynamodb.AttributeDefinition{
{
AttributeName: aws.String(networkFieldName),
AttributeType: aws.String("S"),
},
{
AttributeName: aws.String(domainFieldName),
AttributeType: aws.String("S"),
},
{
AttributeName: aws.String(expiresFieldName),
AttributeType: aws.String("N"),
},
},
KeySchema: []*dynamodb.KeySchemaElement{
{
AttributeName: aws.String(networkFieldName),
KeyType: aws.String("HASH"),
},
{
AttributeName: aws.String(domainFieldName),
KeyType: aws.String("RANGE"),
},
},
LocalSecondaryIndexes: []*dynamodb.LocalSecondaryIndex{
{
IndexName: aws.String("Expires-index"),
KeySchema: []*dynamodb.KeySchemaElement{
{
AttributeName: aws.String(networkFieldName),
KeyType: aws.String("HASH"),
},
{
AttributeName: aws.String(expiresFieldName),
KeyType: aws.String("RANGE"),
},
},
Projection: &dynamodb.Projection{
ProjectionType: aws.String("KEYS_ONLY"),
},
},
},
BillingMode: aws.String("PAY_PER_REQUEST"),
TableName: aws.String(nodesTableName),
}
return a.svc.CreateTable(nodesTableInput)
}
func (a *AWS) createSecretsTable() (*dynamodb.CreateTableOutput, error) {
// Create secrets table
secretsTableInput := &dynamodb.CreateTableInput{
AttributeDefinitions: []*dynamodb.AttributeDefinition{
{
AttributeName: aws.String(domainFieldName),
AttributeType: aws.String("S"),
},
{
AttributeName: aws.String(scramblerKeyFieldName),
AttributeType: aws.String("S"),
},
{
AttributeName: aws.String(expiresFieldName),
AttributeType: aws.String("N"),
},
{
AttributeName: aws.String(cookieDomainFieldName),
AttributeType: aws.String("S"),
},
},
KeySchema: []*dynamodb.KeySchemaElement{
{
AttributeName: aws.String(domainFieldName),
KeyType: aws.String("HASH"),
},
{
AttributeName: aws.String(scramblerKeyFieldName),
KeyType: aws.String("RANGE"),
},
},
LocalSecondaryIndexes: []*dynamodb.LocalSecondaryIndex{
{
IndexName: aws.String("Expires-index"),
KeySchema: []*dynamodb.KeySchemaElement{
{
AttributeName: aws.String(domainFieldName),
KeyType: aws.String("HASH"),
},
{
AttributeName: aws.String(expiresFieldName),
KeyType: aws.String("RANGE"),
},
},
Projection: &dynamodb.Projection{
ProjectionType: aws.String("KEYS_ONLY"),
},
},
},
BillingMode: aws.String("PAY_PER_REQUEST"),
TableName: aws.String(secretsTableName),
}
return a.svc.CreateTable(secretsTableInput)
}
func (a *AWS) getName() string {
return a.name
}
func (a *AWS) getReadOnly() bool {
return false
}
// GetNode takes a domain name and returns the associated node. If a node
// does not exist then nil is returned.
func (a *AWS) getNode(domain string) (*node, error) {
n, err := a.common.getNode(domain)
if err != nil {
return nil, err
}
if n == nil {
err = a.refresh()
if err != nil {
return nil, err
}
n, err = a.common.getNode(domain)
}
return n, err
}
// GetNodes returns all the nodes associated with a network.
func (a *AWS) getNodes(network string) (*nodes, error) {
ns, err := a.common.getNodes(network)
if err != nil {
return nil, err
}
if ns == nil {
err = a.refresh()
if err != nil {
return nil, err
}
ns, err = a.common.getNodes(network)
}
return ns, err
}
// getAllNodes refreshes internal data and returns all nodes.
func (a *AWS) getAllNodes() ([]*node, error) {
err := a.refresh()
if err != nil {
return nil, err
}
return a.common.getAllNodes()
}
// iterateNodes calls the callback function for each node
func (a *AWS) iterateNodes(
callback func(n *node, s interface{}) error,
s interface{}) error {
for _, n := range a.nodes {
err := callback(n, s)
if err != nil {
return err
}
}
return nil
}
// SetNode inserts or updates the node.
func (a *AWS) setNode(n *node) error {
err := a.setNodeSecrets(n)
if err != nil {
return err
}
item := NodeItem{
n.network,
n.domain,
n.created,
n.starts,
n.expires.Unix(),
n.role,
n.getScramblerKey(),
n.cookieDomain}
av, err := dynamodbattribute.MarshalMap(item)
if err != nil {
fmt.Println("Got error marshalling new creator item:")
return err
}
input := &dynamodb.PutItemInput{
Item: av,
TableName: aws.String(nodesTableName),
}
_, err = a.svc.PutItem(input)
if err != nil {
fmt.Println("Got error calling PutItem:")
return err
}
return nil
}
func (a *AWS) refresh() error {
nets := make(map[string]*nodes)
// Fetch the nodes and then add the secrets.
ns, err := a.fetchNodes()
if err != nil {
return err
}
err = a.addSecrets(ns)
if err != nil {
return err
}
// Create a map of networks from the nodes found.
for _, v := range ns {
net := nets[v.network]
if net == nil {
net = &nodes{}
net.dict = make(map[string]*node)
nets[v.network] = net
}
net.all = append(net.all, v)
net.dict[v.domain] = v
}
// Finally sort the nodes by hash values and whether they are active.
for _, net := range nets {
net.order()
}
// In a single atomic operation update the reference to the networks and
// nodes.
a.mutex.Lock()
a.nodes = ns
a.networks = nets
a.mutex.Unlock()
return nil
}
func (a *AWS) fetchNodes() (map[string]*node, error) {
var err error
ns := make(map[string]*node)
// Fetch all the records from the nodes table in Dynamo.
params := &dynamodb.ScanInput{
TableName: aws.String(nodesTableName),
}
result, err := a.svc.Scan(params)
if err != nil {
fmt.Println("Query API call failed:")
fmt.Println((err.Error()))
return nil, err
}
// Iterate over the records creating nodes and adding them to the networks
// map.
for _, i := range result.Items {
ni := NodeItem{}
err = dynamodbattribute.UnmarshalMap(i, &ni)
if err != nil {
fmt.Println("Got error un-marshalling:")
fmt.Println(err.Error())
return nil, err
}
ns[ni.Domain], err = newNode(
ni.Network,
ni.Domain,
ni.Created,
ni.Starts,
time.Unix(ni.Expires, 0).UTC(),
ni.Role,
ni.ScramblerKey,
ni.CookieDomain)
if err != nil {
return nil, err
}
}
return ns, err
}
func (a *AWS) addSecrets(ns map[string]*node) error {
// Fetch all the records from the secrets table in DynamoDB.
params := &dynamodb.ScanInput{
TableName: aws.String(secretsTableName),
}
result, err := a.svc.Scan(params)
if err != nil {
fmt.Println("Query API call failed:")
fmt.Println((err.Error()))
return err
}
// Iterate over the secrets adding them to nodes.
for _, i := range result.Items {
secretItem := SecretItem{}
err = dynamodbattribute.UnmarshalMap(i, &secretItem)
if err != nil {
fmt.Println("Got error un-marshalling:")
fmt.Println(err.Error())
return err
}
s, err := newSecretFromKey(secretItem.ScramblerKey, secretItem.TimeStamp)
if err != nil {
return err
}
if ns[secretItem.Domain] != nil {
ns[secretItem.Domain].addSecret(s)
}
}
// Sort the secrets so the most recent is at the start of the array.
for _, n := range ns {
n.sortSecrets()
}
return nil
}
func (a *AWS) setNodeSecrets(n *node) error {
var pi []*dynamodb.WriteRequest
for _, s := range n.secrets {
item := SecretItem{
n.domain,
s.timeStamp,
n.expires.Unix(),
s.key}
av, err := dynamodbattribute.MarshalMap(item)
if err != nil {
fmt.Println("Got error marshalling new creator item:")
return err
}
pi = append(pi, &dynamodb.WriteRequest{
PutRequest: &dynamodb.PutRequest{
Item: av,
},
})
}
input := &dynamodb.BatchWriteItemInput{
RequestItems: map[string][]*dynamodb.WriteRequest{
secretsTableName: pi,
},
}
_, err := a.svc.BatchWriteItem(input)
if err != nil {
return err
}
return nil
}