forked from sourcegraph/checkup
-
Notifications
You must be signed in to change notification settings - Fork 0
/
s3.go
227 lines (199 loc) · 5.79 KB
/
s3.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
package checkup
import (
"bytes"
"encoding/json"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/client"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/aws/aws-sdk-go/service/s3"
)
// S3 is a way to store checkup results in an S3 bucket.
type S3 struct {
AccessKeyID string `json:"access_key_id"`
SecretAccessKey string `json:"secret_access_key"`
Region string `json:"region,omitempty"`
Bucket string `json:"bucket"`
// Check files older than CheckExpiry will be
// deleted on calls to Maintain(). If this is
// the zero value, no old check files will be
// deleted.
CheckExpiry time.Duration `json:"check_expiry,omitempty"`
}
// Store stores results on S3 according to the configuration in s.
func (s S3) Store(results []Result) error {
jsonBytes, err := json.Marshal(results)
if err != nil {
return err
}
svc := newS3(session.New(), &aws.Config{
Credentials: credentials.NewStaticCredentials(s.AccessKeyID, s.SecretAccessKey, ""),
Region: &s.Region,
})
params := &s3.PutObjectInput{
Bucket: &s.Bucket,
Key: GenerateFilename(),
Body: bytes.NewReader(jsonBytes),
}
_, err = svc.PutObject(params)
return err
}
// Maintain deletes check files that are older than s.CheckExpiry.
func (s S3) Maintain() error {
if s.CheckExpiry == 0 {
return nil
}
svc := newS3(session.New(), &aws.Config{
Credentials: credentials.NewStaticCredentials(s.AccessKeyID, s.SecretAccessKey, ""),
Region: &s.Region,
})
var marker *string
for {
listParams := &s3.ListObjectsInput{
Bucket: &s.Bucket,
Marker: marker,
}
listResp, err := svc.ListObjects(listParams)
if err != nil {
return err
}
var objsToDelete []*s3.ObjectIdentifier
for _, o := range listResp.Contents {
if o == nil || o.LastModified == nil {
continue
}
if time.Since(*o.LastModified) > s.CheckExpiry {
objsToDelete = append(objsToDelete, &s3.ObjectIdentifier{Key: o.Key})
}
}
if len(objsToDelete) == 0 {
break
}
delParams := &s3.DeleteObjectsInput{
Bucket: &s.Bucket,
Delete: &s3.Delete{
Objects: objsToDelete,
Quiet: aws.Bool(true),
},
}
_, err = svc.DeleteObjects(delParams)
if err != nil {
return err
}
if !*listResp.IsTruncated {
break
}
marker = listResp.Contents[len(listResp.Contents)-1].Key
}
return nil
}
// Provision creates a new IAM user in the account specified
// by s, and configures a bucket according to the values in
// s. The credentials in s must have the IAMFullAccess and
// AmazonS3FullAccess permissions in order to succeed.
//
// The name of the created IAM user is "checkup-monitor-s3-public".
// It will have read-only permission to S3.
//
// Provision need only be called once per status page (bucket),
// not once per endpoint.
func (s S3) Provision() (ProvisionInfo, error) {
const iamUser = "checkup-monitor-s3-public"
var info ProvisionInfo
// default region (required, but regions don't apply to S3, kinda weird)
if s.Region == "" {
s.Region = "us-east-1"
}
svcIam := iam.New(session.New(), &aws.Config{
Credentials: credentials.NewStaticCredentials(s.AccessKeyID, s.SecretAccessKey, ""),
Region: &s.Region,
})
// Create a new user, just for reading the check files
resp, err := svcIam.CreateUser(&iam.CreateUserInput{
UserName: aws.String(iamUser),
})
if err != nil {
return info, err
}
info.Username = *resp.User.UserName
info.UserID = *resp.User.UserId
// Restrict the user to only reading S3 buckets
_, err = svcIam.AttachUserPolicy(&iam.AttachUserPolicyInput{
PolicyArn: aws.String("arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess"),
UserName: aws.String(iamUser),
})
if err != nil {
return info, err
}
// Give the user a key (this will become public as it is read-only)
resp3, err := svcIam.CreateAccessKey(&iam.CreateAccessKeyInput{
UserName: aws.String(iamUser),
})
if err != nil {
return info, err
}
info.PublicAccessKeyID = *resp3.AccessKey.AccessKeyId
info.PublicAccessKey = *resp3.AccessKey.SecretAccessKey
// Prepare to talk to S3
svcS3 := s3.New(session.New(), &aws.Config{
Credentials: credentials.NewStaticCredentials(s.AccessKeyID, s.SecretAccessKey, ""),
Region: &s.Region,
})
// Create a bucket to hold all the checks
_, err = svcS3.CreateBucket(&s3.CreateBucketInput{
Bucket: &s.Bucket,
})
if err != nil {
return info, err
}
// Configure its CORS policy to allow reading from status pages
_, err = svcS3.PutBucketCors(&s3.PutBucketCorsInput{
Bucket: &s.Bucket,
CORSConfiguration: &s3.CORSConfiguration{
CORSRules: []*s3.CORSRule{
{
AllowedOrigins: []*string{aws.String("*")},
AllowedMethods: []*string{aws.String("GET"), aws.String("HEAD")},
ExposeHeaders: []*string{aws.String("ETag")},
AllowedHeaders: []*string{aws.String("*")},
MaxAgeSeconds: aws.Int64(3000),
},
},
},
})
if err != nil {
return info, err
}
// Set its policy to allow getting objects
_, err = svcS3.PutBucketPolicy(&s3.PutBucketPolicyInput{
Bucket: &s.Bucket,
Policy: aws.String(`{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "PublicReadGetObject",
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::` + s.Bucket + `/*"
}
]
}`),
})
if err != nil {
return info, err
}
return info, nil
}
// newS3 calls s3.New(), but may be replaced for mocking in tests.
var newS3 = func(p client.ConfigProvider, cfgs ...*aws.Config) s3svc {
return s3.New(p, cfgs...)
}
// s3svc is used for mocking the s3.S3 type.
type s3svc interface {
PutObject(*s3.PutObjectInput) (*s3.PutObjectOutput, error)
ListObjects(*s3.ListObjectsInput) (*s3.ListObjectsOutput, error)
DeleteObjects(*s3.DeleteObjectsInput) (*s3.DeleteObjectsOutput, error)
}