-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathaws_bundle_client.go
88 lines (68 loc) · 2.13 KB
/
aws_bundle_client.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
package openpolicyagent
import (
"bytes"
"context"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/hexa-org/policy-mapper/providers/aws/awscommon"
"github.com/hexa-org/policy-mapper/providers/openpolicyagent/compressionsupport"
"net/http"
"os"
"path/filepath"
)
const BundleTypeAws string = "aws-s3"
type AWSBundleClient struct {
bucketName string
objectName string
httpClient *s3.Client
}
func NewAWSBundleClient(bucketName, objectName string, key []byte, opts awscommon.AWSClientOptions) (*AWSBundleClient, error) {
if len(bucketName) == 0 || len(objectName) == 0 {
return nil, fmt.Errorf("required config: bucket_name, object_name")
}
cfg, err := awscommon.GetAwsClientConfig(key, opts)
if err != nil {
return nil, err
}
s3Client := s3.NewFromConfig(cfg)
bundleClient := &AWSBundleClient{
bucketName: bucketName,
objectName: objectName,
httpClient: s3Client,
}
return bundleClient, nil
}
func (a *AWSBundleClient) Type() string {
return BundleTypeAws
}
func (a *AWSBundleClient) GetDataFromBundle(path string) ([]byte, error) {
resp, err := a.httpClient.GetObject(context.Background(),
&s3.GetObjectInput{Bucket: aws.String(a.bucketName), Key: aws.String(a.objectName)})
if err != nil {
return nil, fmt.Errorf("unable to read bundle object from AWS S3 bucket: %w", err)
}
defer resp.Body.Close()
gz, gzipErr := compressionsupport.UnGzip(resp.Body)
if gzipErr != nil {
return nil, gzipErr
}
tarErr := compressionsupport.UnTarToPath(bytes.NewReader(gz), path)
if tarErr != nil {
return nil, tarErr
}
return os.ReadFile(filepath.Join(path, "/bundle/data.json"))
}
func (a *AWSBundleClient) PostBundle(bundle []byte) (int, error) {
_, err := a.httpClient.PutObject(context.Background(),
&s3.PutObjectInput{
Bucket: aws.String(a.bucketName),
Key: aws.String(a.objectName),
Body: bytes.NewReader(bundle),
ContentType: aws.String(http.DetectContentType(bundle)),
})
if err != nil {
return http.StatusInternalServerError, fmt.Errorf("unable to write bundle object to AWS S3 bucket: %w", err)
}
return http.StatusCreated, nil
}