-
Notifications
You must be signed in to change notification settings - Fork 6
/
attach_policy.go
74 lines (64 loc) · 1.7 KB
/
attach_policy.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
package s3
import (
"encoding/json"
"fmt"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/s3"
)
func AttachPolicy(bucket string, svc *s3.S3) error {
publicRead := map[string]interface{}{
"Version": "2012-10-17",
"Statement": []map[string]interface{}{
{
"Sid": "PublicReadGetObject",
"Effect": "Allow",
"Principal": "*",
"Action": []string{
"s3:GetObject",
},
"Resource": []string{
fmt.Sprintf("arn:aws:s3:::%s/*", bucket),
},
},
},
}
policy, err := json.Marshal(publicRead)
if err != nil {
return err
}
_, err = svc.PutBucketPolicy(&s3.PutBucketPolicyInput{
Bucket: aws.String(bucket),
Policy: aws.String(string(policy)),
})
if err != nil {
return err
}
fmt.Printf("Successfully set bucket %q's policy\n", bucket)
return nil
}
func GetPolicy(bucket string, svc *s3.S3) (bool, error) {
result, err := svc.GetBucketPolicy(&s3.GetBucketPolicyInput{
Bucket: aws.String(bucket),
})
if err != nil {
// Special error handling for the when the bucket doesn't
// exists so we can give a more direct error message from the CLI.
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case s3.ErrCodeNoSuchBucket:
return false, fmt.Errorf("Bucket %q does not exist.", bucket)
case "NoSuchBucketPolicy":
return false, fmt.Errorf("Bucket %q does not have a policy.", bucket)
}
}
return false, fmt.Errorf("Unable to get bucket %q policy, %v.", bucket, err)
}
isPublic := strings.Contains(result.String(), "PublicReadGetObject")
fmt.Println("isPublic", isPublic)
if !isPublic {
return false, fmt.Errorf("Bucket is not Public")
}
return true, nil
}