github.com/khulnasoft-lab/kube-bench@v0.2.1-0.20240330183753-9df52345ae58/internal/findings/publisher.go (about)

     1  package findings
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/aws/aws-sdk-go-v2/service/securityhub"
     7  	"github.com/aws/aws-sdk-go-v2/service/securityhub/types"
     8  	"github.com/pkg/errors"
     9  )
    10  
    11  // A Publisher represents an object that publishes finds to AWS Security Hub.
    12  type Publisher struct {
    13  	client securityhub.Client // AWS Security Hub Service Client
    14  }
    15  
    16  // A PublisherOutput represents an object that contains information about the service call.
    17  type PublisherOutput struct {
    18  	// The number of findings that failed to import.
    19  	//
    20  	// FailedCount is a required field
    21  	FailedCount int32
    22  
    23  	// The list of findings that failed to import.
    24  	FailedFindings []types.ImportFindingsError
    25  
    26  	// The number of findings that were successfully imported.
    27  	//
    28  	// SuccessCount is a required field
    29  	SuccessCount int32
    30  }
    31  
    32  // New creates a new Publisher.
    33  func New(client securityhub.Client) *Publisher {
    34  	return &Publisher{
    35  		client: client,
    36  	}
    37  }
    38  
    39  // PublishFinding publishes findings to AWS Security Hub Service
    40  func (p *Publisher) PublishFinding(finding []types.AwsSecurityFinding) (*PublisherOutput, error) {
    41  	o := PublisherOutput{}
    42  	i := securityhub.BatchImportFindingsInput{}
    43  	i.Findings = finding
    44  	var errs error
    45  
    46  	// Split the slice into batches of 100 finding.
    47  	batch := 100
    48  
    49  	for i := 0; i < len(finding); i += batch {
    50  		i := securityhub.BatchImportFindingsInput{}
    51  		i.Findings = finding
    52  		r, err := p.client.BatchImportFindings(context.Background(), &i) // Process the batch.
    53  		if err != nil {
    54  			errs = errors.Wrap(err, "finding publish failed")
    55  		}
    56  		if r != nil {
    57  			if r.FailedCount != 0 {
    58  				o.FailedCount += r.FailedCount
    59  			}
    60  			if r.SuccessCount != 0 {
    61  				o.SuccessCount += r.SuccessCount
    62  			}
    63  			o.FailedFindings = append(o.FailedFindings, r.FailedFindings...)
    64  		}
    65  	}
    66  	return &o, errs
    67  }