Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add: create kms-key #204

Merged
merged 1 commit into from
Jul 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions cmd/create/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"github.com/awslabs/eksdemo/pkg/resource/dns_record"
"github.com/awslabs/eksdemo/pkg/resource/ec2/instance"
"github.com/awslabs/eksdemo/pkg/resource/fargate_profile"
kmskey "github.com/awslabs/eksdemo/pkg/resource/kms/key"
"github.com/awslabs/eksdemo/pkg/resource/log_group"
"github.com/awslabs/eksdemo/pkg/resource/nodegroup"
"github.com/awslabs/eksdemo/pkg/resource/organization"
Expand Down Expand Up @@ -44,6 +45,7 @@ func NewCreateCmd() *cobra.Command {
cmd.AddCommand(dns_record.NewResource().NewCreateCmd())
cmd.AddCommand(fargate_profile.NewResource().NewCreateCmd())
cmd.AddCommand(instance.NewResource().NewCreateCmd())
cmd.AddCommand(kmskey.NewResource().NewCreateCmd())
cmd.AddCommand(NewKyvernoCmd())
cmd.AddCommand(NewCreateAliasCmds(kyvernoPolicies, "kyverno-")...)
cmd.AddCommand(log_group.NewResource().NewCreateCmd())
Expand Down
4 changes: 2 additions & 2 deletions cmd/get/get.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import (
"github.com/awslabs/eksdemo/pkg/resource/iam_policy"
"github.com/awslabs/eksdemo/pkg/resource/iam_role"
"github.com/awslabs/eksdemo/pkg/resource/internet_gateway"
"github.com/awslabs/eksdemo/pkg/resource/kms_key"
kmskey "github.com/awslabs/eksdemo/pkg/resource/kms/key"
"github.com/awslabs/eksdemo/pkg/resource/listener"
"github.com/awslabs/eksdemo/pkg/resource/listener_rule"
"github.com/awslabs/eksdemo/pkg/resource/load_balancer"
Expand Down Expand Up @@ -100,7 +100,7 @@ func NewGetCmd() *cobra.Command {
cmd.AddCommand(iam_policy.NewResource().NewGetCmd())
cmd.AddCommand(iam_role.NewResource().NewGetCmd())
cmd.AddCommand(internet_gateway.NewResource().NewGetCmd())
cmd.AddCommand(kms_key.NewResource().NewGetCmd())
cmd.AddCommand(kmskey.NewResource().NewGetCmd())
cmd.AddCommand(listener.NewResource().NewGetCmd())
cmd.AddCommand(listener_rule.NewResource().NewGetCmd())
cmd.AddCommand(load_balancer.NewResource().NewGetCmd())
Expand Down
45 changes: 33 additions & 12 deletions pkg/aws/kms.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,39 @@ func NewKMSClient() *KMSClient {
return &KMSClient{kms.NewFromConfig(GetConfig())}
}

func (c *KMSClient) CreateAlias(aliasName, keyID string) error {
_, err := c.Client.CreateAlias(context.Background(), &kms.CreateAliasInput{
AliasName: aws.String(aliasName),
TargetKeyId: aws.String(keyID),
})

return err
}

func (c *KMSClient) CreateKey() (*types.KeyMetadata, error) {
result, err := c.Client.CreateKey(context.Background(), &kms.CreateKeyInput{
KeySpec: types.KeySpecSymmetricDefault,
})

if err != nil {
return nil, err
}

return result.KeyMetadata, nil
}

func (c *KMSClient) DescribeKey(keyID string) (*types.KeyMetadata, error) {
result, err := c.Client.DescribeKey(context.Background(), &kms.DescribeKeyInput{
KeyId: aws.String(keyID),
})

if err != nil {
return nil, err
}

return result.KeyMetadata, nil
}

func (c *KMSClient) ListAliases() ([]types.AliasListEntry, error) {
keys := []types.AliasListEntry{}
pageNum := 0
Expand Down Expand Up @@ -51,15 +84,3 @@ func (c *KMSClient) ListKeys() ([]types.KeyListEntry, error) {

return keys, nil
}

func (c *KMSClient) DescribeKey(keyId string) (*types.KeyMetadata, error) {
result, err := c.Client.DescribeKey(context.Background(), &kms.DescribeKeyInput{
KeyId: aws.String(keyId),
})

if err != nil {
return nil, err
}

return result.KeyMetadata, nil
}
2 changes: 1 addition & 1 deletion pkg/resource/amp_workspace/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ func (m *Manager) Create(options resource.Options) error {
if err != nil {
return err
}
fmt.Printf("done\nCreated AMP Workspace Id: %s\n", *result.WorkspaceId)
fmt.Printf("done\nCreated AMP Workspace Id: %s\n", awssdk.ToString(result.WorkspaceId))

return nil
}
Expand Down
12 changes: 12 additions & 0 deletions pkg/resource/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package resource

import "fmt"

// TODO: phase this out. Doesn't work with errors.As
type NotFoundError string

func (e NotFoundError) Error() string {
Expand All @@ -25,3 +26,14 @@ type NotFoundByNameError struct {
func (e *NotFoundByNameError) Error() string {
return fmt.Sprintf("%s with name %q not found", e.Type, e.Name)
}

// TODO: This error could potentially replace NotFoundByIDError and NotFoundByNameError
type NotFoundByError struct {
Type string
Name string
Value string
}

func (e *NotFoundByError) Error() string {
return fmt.Sprintf("%s with %s %q not found", e.Type, e.Name, e.Value)
}
12 changes: 9 additions & 3 deletions pkg/resource/kms_key/get.go → pkg/resource/kms/key/get.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
package kms_key
package key

import (
"fmt"
"os"
"sort"

awssdk "github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/kms/types"
Expand Down Expand Up @@ -31,7 +32,7 @@ func (g *Getter) Init() {
}

func (g *Getter) Get(alias string, output printer.Output, options resource.Options) error {
kmsOptions, ok := options.(*KmsKeyOptions)
kmsOptions, ok := options.(*Options)
if !ok {
return fmt.Errorf("internal error, unable to cast options to KmsKeyOptions")
}
Expand Down Expand Up @@ -85,6 +86,11 @@ func (g *Getter) GetAllKeys() ([]*KMSKey, error) {
keys = append(keys, key)
}

// Show recently created Keys at the end of the list
sort.Slice(keys, func(i, j int) bool {
return keys[i].Key.CreationDate.Before(awssdk.ToTime(keys[j].Key.CreationDate))
})

return keys, nil
}

Expand All @@ -109,7 +115,7 @@ func (g *Getter) GetByAlias(aliasName string) (*KMSKey, error) {
return &KMSKey{filterAliasesByKeyId(aliases, keyId), key}, nil
}

return nil, resource.NotFoundError(fmt.Sprintf("kms-key alias %q not found", aliasName))
return nil, &resource.NotFoundByError{Type: "kms-key", Name: "alias", Value: aliasName}
}

func filterAliasesByKeyId(aliases []types.AliasListEntry, id string) []types.AliasListEntry {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,23 +1,28 @@
package kms_key
package key

import (
"github.com/awslabs/eksdemo/pkg/cmd"
"github.com/awslabs/eksdemo/pkg/resource"
)

func NewResource() *resource.Resource {
res := &resource.Resource{
options, getFlags := newOptions()

return &resource.Resource{
Command: cmd.Command{
Name: "kms-key",
Description: "KMS Key",
Aliases: []string{"kms-keys", "kmskeys", "kmskey", "kms"},
Args: []string{"ALIAS"},
CreateArgs: []string{"ALIAS"},
},

GetFlags: getFlags,

Getter: &Getter{},
}

res.Options, res.GetFlags = newOptions()
Manager: &Manager{},

return res
Options: options,
}
}
86 changes: 86 additions & 0 deletions pkg/resource/kms/key/manager.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package key

import (
"errors"
"fmt"

awssdk "github.com/aws/aws-sdk-go-v2/aws"
"github.com/awslabs/eksdemo/pkg/aws"
"github.com/awslabs/eksdemo/pkg/resource"
"github.com/spf13/cobra"
)

type Manager struct {
DryRun bool
kmsClient *aws.KMSClient
kmsGetter *Getter
}

func (m *Manager) Init() {
if m.kmsClient == nil {
m.kmsClient = aws.NewKMSClient()
}
m.kmsGetter = NewGetter(m.kmsClient)
}

func (m *Manager) Create(options resource.Options) error {
alias := options.Common().Name

_, err := m.kmsGetter.GetByAlias(alias)

// Return if the KMS alias already exists
if err == nil {
fmt.Printf("KMS Key with alias %q already exists\n", alias)
return nil
}

// Return the error if it's anything other than resource not found
var notFoundErr *resource.NotFoundByError
if !errors.As(err, &notFoundErr) {
return err
}

fullAliasName := fmt.Sprintf("alias/%s", alias)

if m.DryRun {
return m.dryRun(fullAliasName)
}

fmt.Printf("Creating KMS Key with Alias %q...", alias)

keyMeta, err := m.kmsClient.CreateKey()
if err != nil {
return err
}

keyID := awssdk.ToString(keyMeta.KeyId)

err = m.kmsClient.CreateAlias(fullAliasName, keyID)
if err != nil {
return fmt.Errorf("failed to create alias for key %q: %w", keyID, err)
}
fmt.Printf("done\nCreated KMS Key Id: %s\n", keyID)

return nil
}

func (m *Manager) Delete(_ resource.Options) error {
return fmt.Errorf("feature not supported")
}

func (m *Manager) SetDryRun() {
m.DryRun = true
}

func (m *Manager) Update(_ resource.Options, _ *cobra.Command) error {
return fmt.Errorf("feature not supported")
}

func (m *Manager) dryRun(aliasName string) error {
fmt.Printf("\nKMS Key Manager Dry Run:\n")
fmt.Printf("KMS API Call %q with no request parameters\n", "CreateKey")
fmt.Printf("KMS API Call %q with parameters:\n", "CreateAlias")
fmt.Printf("\tAliasName: %q\n", aliasName)
fmt.Printf("\tTargetKeyId: <Key Id returned from CreateKey call>\n")
return nil
}
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
package kms_key
package key

import (
"github.com/awslabs/eksdemo/pkg/cmd"
"github.com/awslabs/eksdemo/pkg/resource"
)

type KmsKeyOptions struct {
type Options struct {
resource.CommonOptions
}

func newOptions() (options *KmsKeyOptions, getFlags cmd.Flags) {
options = &KmsKeyOptions{
func newOptions() (options *Options, getFlags cmd.Flags) {
options = &Options{
CommonOptions: resource.CommonOptions{
ClusterFlagDisabled: true,
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package kms_key
package key

import (
"fmt"
Expand Down