-
Notifications
You must be signed in to change notification settings - Fork 99
/
aws.go
80 lines (69 loc) · 2.4 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
package aws
import (
"context"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/kms"
awskmstype "github.com/aws/aws-sdk-go-v2/service/kms/types"
awsutils "github.com/berachain/offchain-sdk/types/aws"
"github.com/berachain/offchain-sdk/types/kms/types"
)
// KeyManagementSystem is a wrapper around the AWS KMS client to provide
// additional functionality.
type KeyManagementSystem struct {
// awsClient is the underlying AWS KMS client instance.
client *awsClient
}
// NewKeyManagementSystem creates a new KeyManagementSystem instance.
func NewKeyManagementSystemFromConfig(cfg aws.Config) *KeyManagementSystem {
return &KeyManagementSystem{
client: newAwsClient(kms.NewFromConfig(cfg)),
}
}
// NewKeyManagementSystem creates a new KeyManagementSystem instance with the
// provided AWS region and credentials.
func NewKeyManagementSystem(region, accessKeyID, secretKey string) *KeyManagementSystem {
// Load the default AWS configuration.
awsCfg, _ := config.LoadDefaultConfig(
context.Background(), func(cfg *config.LoadOptions) error {
// Set the AWS region.
cfg.Region = region
// Set the AWS credentials.
cfg.Credentials = awsutils.NewCredentialsProvider(
accessKeyID, secretKey,
)
// Return nil since no error occurred.
return nil
})
// Return a new KeyManagementSystem instance created from the AWS KMS client.
return NewKeyManagementSystemFromConfig(awsCfg)
}
// GenerateKey uses the AWS KMS to generate a new key.
func (awsKms *KeyManagementSystem) GenerateKey(ctx context.Context) (string, error) {
input := &kms.CreateKeyInput{
KeySpec: awskmstype.KeySpecEccSecgP256k1,
KeyUsage: awskmstype.KeyUsageTypeSignVerify,
}
result, err := awsKms.client.CreateKey(ctx, input)
if err != nil {
return "", err
}
return *result.KeyMetadata.KeyId, nil
}
// ListKeysByID retrieves all keys managed by the AWS KMS.
func (awsKms *KeyManagementSystem) ListKeysByID(ctx context.Context) ([]string, error) {
input := &kms.ListKeysInput{}
result, err := awsKms.client.ListKeys(ctx, input)
if err != nil {
return nil, err
}
keys := make([]string, 0, len(result.Keys))
for i, key := range result.Keys {
keys[i] = *key.KeyId
}
return keys, nil
}
// GetSigner returns a TxSigner instance that uses the AWS KMS.
func (awsKms *KeyManagementSystem) GetSigner(id string) (types.TxSigner, error) {
return newSigner(awsKms.client, id)
}