github.com/khulnasoft-lab/defsec@v1.0.5-0.20230827010352-5e9f46893d95/internal/adapters/cloud/aws/kms/adapt.go (about)

     1  package kms
     2  
     3  import (
     4  	api "github.com/aws/aws-sdk-go-v2/service/kms"
     5  	"github.com/aws/aws-sdk-go-v2/service/kms/types"
     6  	"github.com/khulnasoft-lab/defsec/internal/adapters/cloud/aws"
     7  	"github.com/khulnasoft-lab/defsec/pkg/concurrency"
     8  	"github.com/khulnasoft-lab/defsec/pkg/providers/aws/kms"
     9  	"github.com/khulnasoft-lab/defsec/pkg/state"
    10  	defsecTypes "github.com/khulnasoft-lab/defsec/pkg/types"
    11  )
    12  
    13  type adapter struct {
    14  	*aws.RootAdapter
    15  	api *api.Client
    16  }
    17  
    18  func init() {
    19  	aws.RegisterServiceAdapter(&adapter{})
    20  }
    21  
    22  func (a *adapter) Provider() string {
    23  	return "aws"
    24  }
    25  
    26  func (a *adapter) Name() string {
    27  	return "kms"
    28  }
    29  
    30  func (a *adapter) Adapt(root *aws.RootAdapter, state *state.State) error {
    31  
    32  	a.RootAdapter = root
    33  	a.api = api.NewFromConfig(root.SessionConfig())
    34  	var err error
    35  
    36  	state.AWS.KMS.Keys, err = a.getKeys()
    37  	if err != nil {
    38  		return err
    39  	}
    40  
    41  	return nil
    42  }
    43  
    44  func (a *adapter) getKeys() ([]kms.Key, error) {
    45  
    46  	a.Tracker().SetServiceLabel("Discovering keys...")
    47  
    48  	var apiKeys []types.KeyListEntry
    49  	var input api.ListKeysInput
    50  	for {
    51  		output, err := a.api.ListKeys(a.Context(), &input)
    52  		if err != nil {
    53  			return nil, err
    54  		}
    55  		apiKeys = append(apiKeys, output.Keys...)
    56  		a.Tracker().SetTotalResources(len(apiKeys))
    57  		if output.NextMarker == nil {
    58  			break
    59  		}
    60  		input.Marker = output.NextMarker
    61  	}
    62  
    63  	a.Tracker().SetServiceLabel("Adapting keys...")
    64  	return concurrency.Adapt(apiKeys, a.RootAdapter, a.adaptKey), nil
    65  }
    66  
    67  func (a *adapter) adaptKey(apiKey types.KeyListEntry) (*kms.Key, error) {
    68  
    69  	metadata := a.CreateMetadataFromARN(*apiKey.KeyArn)
    70  
    71  	output, err := a.api.DescribeKey(a.Context(), &api.DescribeKeyInput{
    72  		KeyId: apiKey.KeyId,
    73  	})
    74  	if err != nil {
    75  		return nil, err
    76  	}
    77  
    78  	return &kms.Key{
    79  		Metadata:        metadata,
    80  		Usage:           defsecTypes.String(string(output.KeyMetadata.KeyUsage), metadata),
    81  		RotationEnabled: defsecTypes.Bool(output.KeyMetadata.ValidTo != nil, metadata),
    82  	}, nil
    83  }