forked from rhnvrm/simples3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtagging.go
More file actions
309 lines (258 loc) · 7.22 KB
/
tagging.go
File metadata and controls
309 lines (258 loc) · 7.22 KB
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
// LICENSE BSD-2-Clause-FreeBSD
// Copyright (c) 2018, Rohan Verma <hello@rohanverma.net>
package simples3
import (
"bytes"
"crypto/md5"
"crypto/sha256"
"encoding/base64"
"encoding/xml"
"fmt"
"io"
"net/http"
"net/url"
)
// Tag represents a single S3 object tag with a key-value pair.
type Tag struct {
Key string `xml:"Key"`
Value string `xml:"Value"`
}
// tagging is the internal type for XML marshaling/unmarshaling.
type tagging struct {
XMLName xml.Name `xml:"Tagging"`
XMLNS string `xml:"xmlns,attr,omitempty"`
TagSet tagSet `xml:"TagSet"`
}
// tagSet is the internal type for XML marshaling/unmarshaling.
type tagSet struct {
Tags []Tag `xml:"Tag"`
}
// PutObjectTaggingInput is passed to PutObjectTagging as a parameter.
type PutObjectTaggingInput struct {
// Required: The name of the bucket
Bucket string
// Required: The object key
ObjectKey string
// Required: Tags to set on the object (max 10 tags)
Tags map[string]string
}
// GetObjectTaggingInput is passed to GetObjectTagging as a parameter.
type GetObjectTaggingInput struct {
// Required: The name of the bucket
Bucket string
// Required: The object key
ObjectKey string
}
// GetObjectTaggingOutput is returned by GetObjectTagging.
type GetObjectTaggingOutput struct {
Tags map[string]string
}
// DeleteObjectTaggingInput is passed to DeleteObjectTagging as a parameter.
type DeleteObjectTaggingInput struct {
// Required: The name of the bucket
Bucket string
// Required: The object key
ObjectKey string
}
// PutObjectTagging sets tags on an existing S3 object.
// Replaces all existing tags with the provided tags.
// S3 allows up to 10 tags per object.
func (s3 *S3) PutObjectTagging(input PutObjectTaggingInput) error {
// Validate required fields
if input.Bucket == "" && s3.UsePathStyle {
return fmt.Errorf("bucket name is required")
}
if input.ObjectKey == "" {
return fmt.Errorf("object key is required")
}
if len(input.Tags) == 0 {
return fmt.Errorf("at least one tag is required")
}
if len(input.Tags) > 10 {
return fmt.Errorf("cannot set more than 10 tags per object")
}
// Renew IAM token if needed
if err := s3.renewIAMToken(); err != nil {
return err
}
// Build XML request body
tagsXML := tagging{
XMLNS: "http://s3.amazonaws.com/doc/2006-03-01/",
TagSet: tagSet{
Tags: make([]Tag, 0, len(input.Tags)),
},
}
for k, v := range input.Tags {
tagsXML.TagSet.Tags = append(tagsXML.TagSet.Tags, Tag{Key: k, Value: v})
}
xmlBody, err := xml.Marshal(tagsXML)
if err != nil {
return err
}
// Calculate Content-MD5 (required by S3 for this operation)
md5Hash := md5.Sum(xmlBody)
contentMD5 := base64.StdEncoding.EncodeToString(md5Hash[:])
// Build URL with ?tagging query parameter
baseURL := s3.getURL(input.Bucket, input.ObjectKey)
parsedURL, err := url.Parse(baseURL)
if err != nil {
return err
}
query := url.Values{}
query.Set("tagging", "")
parsedURL.RawQuery = query.Encode()
// Create PUT request
req, err := http.NewRequest(http.MethodPut, parsedURL.String(), bytes.NewReader(xmlBody))
if err != nil {
return err
}
// Set ContentLength BEFORE other headers
req.ContentLength = int64(len(xmlBody))
// Calculate content SHA256 for x-amz-content-sha256 header
h := sha256.New()
h.Write(xmlBody)
req.Header.Set("x-amz-content-sha256", fmt.Sprintf("%x", h.Sum(nil)))
req.Header.Set("Content-Type", "application/xml")
req.Header.Set("Content-MD5", contentMD5)
req.Header.Set("Content-Length", fmt.Sprintf("%d", len(xmlBody)))
req.Header.Set("Host", req.URL.Host)
// Sign the request
if err := s3.signRequest(req); err != nil {
return err
}
// Execute request
client := s3.getClient()
res, err := client.Do(req)
if err != nil {
return err
}
defer func() {
res.Body.Close()
io.Copy(io.Discard, res.Body)
}()
// Read response body for error messages
body, err := io.ReadAll(res.Body)
if err != nil {
return err
}
// Handle non-OK status codes
if res.StatusCode != http.StatusOK {
return fmt.Errorf("status code: %s: %s", res.Status, string(body))
}
return nil
}
// GetObjectTagging retrieves the tags associated with an S3 object.
func (s3 *S3) GetObjectTagging(input GetObjectTaggingInput) (GetObjectTaggingOutput, error) {
// Validate required fields
if input.Bucket == "" && s3.UsePathStyle {
return GetObjectTaggingOutput{}, fmt.Errorf("bucket name is required")
}
if input.ObjectKey == "" {
return GetObjectTaggingOutput{}, fmt.Errorf("object key is required")
}
// Renew IAM token if needed
if err := s3.renewIAMToken(); err != nil {
return GetObjectTaggingOutput{}, err
}
// Build URL with ?tagging query parameter
baseURL := s3.getURL(input.Bucket, input.ObjectKey)
parsedURL, err := url.Parse(baseURL)
if err != nil {
return GetObjectTaggingOutput{}, err
}
parsedURL.RawQuery = "tagging"
// Create GET request
req, err := http.NewRequest(http.MethodGet, parsedURL.String(), nil)
if err != nil {
return GetObjectTaggingOutput{}, err
}
// Sign the request
if err := s3.signRequest(req); err != nil {
return GetObjectTaggingOutput{}, err
}
// Execute request
client := s3.getClient()
res, err := client.Do(req)
if err != nil {
return GetObjectTaggingOutput{}, err
}
defer func() {
res.Body.Close()
io.Copy(io.Discard, res.Body)
}()
// Read response body
body, err := io.ReadAll(res.Body)
if err != nil {
return GetObjectTaggingOutput{}, err
}
// Handle non-OK status codes
if res.StatusCode != http.StatusOK {
return GetObjectTaggingOutput{}, fmt.Errorf("status code: %s: %s", res.Status, string(body))
}
// Parse XML response
var result tagging
if err := xml.Unmarshal(body, &result); err != nil {
return GetObjectTaggingOutput{}, err
}
// Convert to map
output := GetObjectTaggingOutput{
Tags: make(map[string]string, len(result.TagSet.Tags)),
}
for _, tag := range result.TagSet.Tags {
output.Tags[tag.Key] = tag.Value
}
return output, nil
}
// DeleteObjectTagging removes all tags from an S3 object.
func (s3 *S3) DeleteObjectTagging(input DeleteObjectTaggingInput) error {
// Validate required fields
if input.Bucket == "" && s3.UsePathStyle {
return fmt.Errorf("bucket name is required")
}
if input.ObjectKey == "" {
return fmt.Errorf("object key is required")
}
// Renew IAM token if needed
if err := s3.renewIAMToken(); err != nil {
return err
}
// Build URL with ?tagging query parameter
baseURL := s3.getURL(input.Bucket, input.ObjectKey)
parsedURL, err := url.Parse(baseURL)
if err != nil {
return err
}
query := url.Values{}
query.Set("tagging", "")
parsedURL.RawQuery = query.Encode()
// Create DELETE request
req, err := http.NewRequest(http.MethodDelete, parsedURL.String(), nil)
if err != nil {
return err
}
// Sign the request
if err := s3.signRequest(req); err != nil {
return err
}
// Execute request
client := s3.getClient()
res, err := client.Do(req)
if err != nil {
return err
}
defer func() {
res.Body.Close()
io.Copy(io.Discard, res.Body)
}()
// Read response body for error messages
body, err := io.ReadAll(res.Body)
if err != nil {
return err
}
// Handle non-success status codes
// AWS returns 204 No Content on successful deletion
if res.StatusCode != http.StatusNoContent {
return fmt.Errorf("status code: %s: %s", res.Status, string(body))
}
return nil
}