| 1 |
package s3 |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"context" |
| 6 |
"crypto/md5" //nolint:gosec // MD5 is required by the S3 protocol for Content-MD5 headers |
| 7 |
"crypto/tls" |
| 8 |
"encoding/base64" |
| 9 |
"encoding/xml" |
| 10 |
"errors" |
| 11 |
"fmt" |
| 12 |
"io" |
| 13 |
"net/http" |
| 14 |
"net/url" |
| 15 |
"strings" |
| 16 |
"time" |
| 17 |
|
| 18 |
"heckel.io/ntfy/v2/log" |
| 19 |
) |
| 20 |
|
| 21 |
const ( |
| 22 |
tagS3Client = "s3_client" |
| 23 |
) |
| 24 |
|
| 25 |
// Client is a minimal S3-compatible client. It supports PutObject, GetObject, DeleteObjects, |
| 26 |
// and ListObjectsV2 operations using AWS Signature V4 signing. The bucket and optional key prefix |
| 27 |
// are fixed at construction time. All operations target the same bucket and prefix. |
| 28 |
// |
| 29 |
// The following IAM policy is required for AWS S3: |
| 30 |
// |
| 31 |
// { |
| 32 |
// "Version": "2012-10-17", |
| 33 |
// "Statement": [ |
| 34 |
// { |
| 35 |
// "Effect": "Allow", |
| 36 |
// "Action": [ |
| 37 |
// "s3:ListBucket", |
| 38 |
// "s3:ListBucketMultipartUploads" |
| 39 |
// ], |
| 40 |
// "Resource": "arn:aws:s3:::BUCKET_NAME" |
| 41 |
// }, |
| 42 |
// { |
| 43 |
// "Effect": "Allow", |
| 44 |
// "Action": [ |
| 45 |
// "s3:GetObject", |
| 46 |
// "s3:PutObject", |
| 47 |
// "s3:DeleteObject", |
| 48 |
// "s3:AbortMultipartUpload" |
| 49 |
// ], |
| 50 |
// "Resource": "arn:aws:s3:::BUCKET_NAME/*" |
| 51 |
// } |
| 52 |
// ] |
| 53 |
// } |
| 54 |
// |
| 55 |
// Fields must not be modified after the Client is passed to any method or goroutine. |
| 56 |
type Client struct { |
| 57 |
config *Config |
| 58 |
http *http.Client |
| 59 |
} |
| 60 |
|
| 61 |
// New creates a new S3 client from the given Config. |
| 62 |
func New(config *Config) *Client { |
| 63 |
httpClient := config.HTTPClient |
| 64 |
if httpClient == nil { |
| 65 |
if config.DisableHTTP2 { |
| 66 |
httpClient = newHTTP1Client() |
| 67 |
} else { |
| 68 |
httpClient = http.DefaultClient |
| 69 |
} |
| 70 |
} |
| 71 |
return &Client{ |
| 72 |
config: config, |
| 73 |
http: httpClient, |
| 74 |
} |
| 75 |
} |
| 76 |
|
| 77 |
// PutObject uploads body to the given key. The key is automatically prefixed with the client's |
| 78 |
// configured prefix. |
| 79 |
// |
| 80 |
// If untrustedLength is between 1 and 5 GB, the body is streamed directly to S3 via a |
| 81 |
// single PUT request without buffering. The read is limited to untrustedLength bytes; |
| 82 |
// any extra data in the body is ignored. If the body is shorter than claimed, the upload fails. |
| 83 |
// |
| 84 |
// Otherwise (untrustedLength <= 0 or > 5 GB), the first 5 MB are buffered to decide |
| 85 |
// between a simple PUT and multipart upload. |
| 86 |
// |
| 87 |
// See https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutObject.html |
| 88 |
// and https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateMultipartUpload.html |
| 89 |
func (c *Client) PutObject(ctx context.Context, key string, body io.Reader, untrustedLength int64) error { |
| 90 |
if untrustedLength > 0 && untrustedLength <= maxSinglePutSize { |
| 91 |
// Stream directly: Content-Length is known (but untrusted). LimitReader ensures we send at most |
| 92 |
// untrustedLength bytes, and any extra data in body is ignored. |
| 93 |
return c.putObject(ctx, key, io.LimitReader(body, untrustedLength), untrustedLength) |
| 94 |
} |
| 95 |
// Buffered path: read first 5 MB to decide simple vs multipart |
| 96 |
first := make([]byte, partSize) |
| 97 |
n, err := io.ReadFull(body, first) |
| 98 |
if errors.Is(err, io.ErrUnexpectedEOF) || err == io.EOF { |
| 99 |
return c.putObject(ctx, key, bytes.NewReader(first[:n]), int64(n)) |
| 100 |
} else if err != nil { |
| 101 |
return fmt.Errorf("error reading object %s from client: %w", key, err) |
| 102 |
} |
| 103 |
return c.putObjectMultipart(ctx, key, io.MultiReader(bytes.NewReader(first), body)) |
| 104 |
} |
| 105 |
|
| 106 |
// putObject uploads a body with known size using a simple PUT with UNSIGNED-PAYLOAD. |
| 107 |
func (c *Client) putObject(ctx context.Context, key string, body io.Reader, size int64) error { |
| 108 |
log.Tag(tagS3Client).Debug("Uploading object %s (%d bytes)", key, size) |
| 109 |
req, err := http.NewRequestWithContext(ctx, http.MethodPut, c.config.ObjectURL(key), body) |
| 110 |
if err != nil { |
| 111 |
return fmt.Errorf("creating upload request object %s failed: %w", key, err) |
| 112 |
} |
| 113 |
req.ContentLength = size |
| 114 |
c.signV4(req, unsignedPayload) |
| 115 |
resp, err := c.http.Do(req) |
| 116 |
if err != nil { |
| 117 |
return fmt.Errorf("uploading object %s failed: %w", key, err) |
| 118 |
} |
| 119 |
defer resp.Body.Close() |
| 120 |
if !isHTTPSuccess(resp) { |
| 121 |
return parseError(resp) |
| 122 |
} |
| 123 |
return nil |
| 124 |
} |
| 125 |
|
| 126 |
// GetObject downloads an object. The key is automatically prefixed with the client's configured |
| 127 |
// prefix. The caller must close the returned ReadCloser. |
| 128 |
// |
| 129 |
// See https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html |
| 130 |
func (c *Client) GetObject(ctx context.Context, key string) (io.ReadCloser, int64, error) { |
| 131 |
log.Tag(tagS3Client).Debug("Fetching object %s", key) |
| 132 |
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.config.ObjectURL(key), nil) |
| 133 |
if err != nil { |
| 134 |
return nil, 0, fmt.Errorf("error creating HTTP GET request for %s: %w", key, err) |
| 135 |
} |
| 136 |
c.signV4(req, emptyPayloadHash) |
| 137 |
resp, err := c.http.Do(req) |
| 138 |
if err != nil { |
| 139 |
return nil, 0, fmt.Errorf("error fetching object %s: %w", key, err) |
| 140 |
} else if !isHTTPSuccess(resp) { |
| 141 |
err := parseError(resp) |
| 142 |
resp.Body.Close() |
| 143 |
return nil, 0, err |
| 144 |
} |
| 145 |
return resp.Body, resp.ContentLength, nil |
| 146 |
} |
| 147 |
|
| 148 |
// ListObjectsV2 returns all objects under the client's configured prefix by paginating through |
| 149 |
// ListObjectsV2 results automatically. Keys in the returned objects have the prefix stripped, |
| 150 |
// so they match the keys used with PutObject/GetObject/DeleteObjects. It stops after 10,000 |
| 151 |
// pages as a safety valve. |
| 152 |
// |
| 153 |
// See https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListObjectsV2.html |
| 154 |
func (c *Client) ListObjectsV2(ctx context.Context) ([]*Object, error) { |
| 155 |
var all []*Object |
| 156 |
var token string |
| 157 |
for page := 0; page < maxPages; page++ { |
| 158 |
result, err := c.listObjectsV2(ctx, token) |
| 159 |
if err != nil { |
| 160 |
return nil, err |
| 161 |
} |
| 162 |
for _, obj := range result.Contents { |
| 163 |
var lastModified time.Time |
| 164 |
if obj.LastModified != "" { |
| 165 |
lastModified, _ = time.Parse(time.RFC3339, obj.LastModified) |
| 166 |
} |
| 167 |
all = append(all, &Object{ |
| 168 |
Key: c.config.StripPrefix(obj.Key), |
| 169 |
Size: obj.Size, |
| 170 |
LastModified: lastModified, |
| 171 |
}) |
| 172 |
} |
| 173 |
if !result.IsTruncated { |
| 174 |
return all, nil |
| 175 |
} |
| 176 |
token = result.NextContinuationToken |
| 177 |
} |
| 178 |
return nil, fmt.Errorf("listing objects exceeded %d pages", maxPages) |
| 179 |
} |
| 180 |
|
| 181 |
// listObjectsV2 performs a single ListObjectsV2 request using the client's configured prefix. |
| 182 |
func (c *Client) listObjectsV2(ctx context.Context, continuationToken string) (*listObjectsV2Result, error) { |
| 183 |
if continuationToken == "" { |
| 184 |
log.Tag(tagS3Client).Debug("Listing remote objects") |
| 185 |
} else { |
| 186 |
log.Tag(tagS3Client).Debug("Listing remote objects, continuing with token '%s'", continuationToken) |
| 187 |
} |
| 188 |
query := url.Values{"list-type": {"2"}} |
| 189 |
if prefix := c.config.ListPrefix(); prefix != "" { |
| 190 |
query.Set("prefix", prefix) |
| 191 |
} |
| 192 |
if continuationToken != "" { |
| 193 |
query.Set("continuation-token", continuationToken) |
| 194 |
} |
| 195 |
respBody, err := c.do(ctx, "ListObjects", http.MethodGet, c.config.BucketURL()+"?"+query.Encode(), nil, nil) |
| 196 |
if err != nil { |
| 197 |
return nil, err |
| 198 |
} |
| 199 |
var result listObjectsV2Result |
| 200 |
if err := xml.Unmarshal(respBody, &result); err != nil { |
| 201 |
return nil, fmt.Errorf("failed to unmarshal list object response: %w", err) |
| 202 |
} |
| 203 |
return &result, nil |
| 204 |
} |
| 205 |
|
| 206 |
// DeleteObjects removes multiple objects in a single batch request. Keys are automatically |
| 207 |
// prefixed with the client's configured prefix. S3 supports up to 1000 keys per call; the |
| 208 |
// caller is responsible for batching if needed. |
| 209 |
// |
| 210 |
// Even when S3 returns HTTP 200, individual keys may fail. If any per-key errors are present |
| 211 |
// in the response, they are returned as a combined error. |
| 212 |
// |
| 213 |
// See https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteObjects.html |
| 214 |
func (c *Client) DeleteObjects(ctx context.Context, keys []string) error { |
| 215 |
// S3 DeleteObjects supports up to 1000 keys per call |
| 216 |
for i := 0; i < len(keys); i += maxDeleteBatchSize { |
| 217 |
end := i + maxDeleteBatchSize |
| 218 |
if end > len(keys) { |
| 219 |
end = len(keys) |
| 220 |
} |
| 221 |
if err := c.deleteObjects(ctx, keys[i:end]); err != nil { |
| 222 |
return err |
| 223 |
} |
| 224 |
} |
| 225 |
return nil |
| 226 |
} |
| 227 |
|
| 228 |
func (c *Client) deleteObjects(ctx context.Context, keys []string) error { |
| 229 |
log.Tag(tagS3Client).Debug("Deleting %d object(s)", len(keys)) |
| 230 |
req := &deleteObjectsRequest{ |
| 231 |
Quiet: true, |
| 232 |
} |
| 233 |
for _, key := range keys { |
| 234 |
req.Objects = append(req.Objects, &deleteObject{Key: c.config.ObjectKey(key)}) |
| 235 |
} |
| 236 |
body, err := xml.Marshal(req) |
| 237 |
if err != nil { |
| 238 |
return fmt.Errorf("error marshalling XML for deleting objects: %w", err) |
| 239 |
} |
| 240 |
|
| 241 |
// Content-MD5 is required by the S3 protocol for DeleteObjects requests. |
| 242 |
md5Sum := md5.Sum(body) //nolint:gosec |
| 243 |
headers := map[string]string{ |
| 244 |
"Content-MD5": base64.StdEncoding.EncodeToString(md5Sum[:]), |
| 245 |
} |
| 246 |
reqURL := c.config.BucketURL() + "?delete" |
| 247 |
respBody, err := c.do(ctx, "DeleteObjects", http.MethodPost, reqURL, body, headers) |
| 248 |
if err != nil { |
| 249 |
return fmt.Errorf("error deleting objects: %w", err) |
| 250 |
} |
| 251 |
|
| 252 |
// S3 may return HTTP 200 with per-key errors in the response body |
| 253 |
var result deleteObjectsResult |
| 254 |
if err := xml.Unmarshal(respBody, &result); err != nil { |
| 255 |
return nil // If we can't parse, assume success (Quiet mode returns empty body on success) |
| 256 |
} |
| 257 |
if len(result.Errors) > 0 { |
| 258 |
var msgs []string |
| 259 |
for _, e := range result.Errors { |
| 260 |
msgs = append(msgs, fmt.Sprintf("%s: %s", e.Key, e.Message)) |
| 261 |
} |
| 262 |
return fmt.Errorf("error deleting objects, partial failure: %s", strings.Join(msgs, "; ")) |
| 263 |
} |
| 264 |
return nil |
| 265 |
} |
| 266 |
|
| 267 |
// do creates a signed request, executes it, reads the response body, and checks for errors. |
| 268 |
// If body is nil, the request is sent with an empty payload. If body is non-nil, it is sent |
| 269 |
// with a computed SHA-256 payload hash and Content-Type: application/xml. |
| 270 |
func (c *Client) do(ctx context.Context, op, method, reqURL string, body []byte, headers map[string]string) ([]byte, error) { |
| 271 |
log.Tag(tagS3Client).Trace("Performing request %s %s %s (body: %d bytes)", op, method, reqURL, len(body)) |
| 272 |
var reader io.Reader |
| 273 |
var hash string |
| 274 |
if body != nil { |
| 275 |
reader = bytes.NewReader(body) |
| 276 |
hash = sha256Hex(body) |
| 277 |
} else { |
| 278 |
hash = emptyPayloadHash |
| 279 |
} |
| 280 |
req, err := http.NewRequestWithContext(ctx, method, reqURL, reader) |
| 281 |
if err != nil { |
| 282 |
return nil, fmt.Errorf("s3: %s request: %w", op, err) |
| 283 |
} |
| 284 |
if body != nil { |
| 285 |
req.ContentLength = int64(len(body)) |
| 286 |
req.Header.Set("Content-Type", "application/xml") |
| 287 |
} else { |
| 288 |
req.ContentLength = 0 |
| 289 |
} |
| 290 |
for k, v := range headers { |
| 291 |
req.Header.Set(k, v) |
| 292 |
} |
| 293 |
c.signV4(req, hash) |
| 294 |
resp, err := c.http.Do(req) |
| 295 |
if err != nil { |
| 296 |
return nil, fmt.Errorf("s3: %s: %w", op, err) |
| 297 |
} |
| 298 |
respBody, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBytes)) |
| 299 |
resp.Body.Close() |
| 300 |
if err != nil { |
| 301 |
return nil, fmt.Errorf("s3: %s read: %w", op, err) |
| 302 |
} |
| 303 |
if !isHTTPSuccess(resp) { |
| 304 |
return nil, parseErrorFromBytes(resp.StatusCode, respBody) |
| 305 |
} |
| 306 |
return respBody, nil |
| 307 |
} |
| 308 |
|
| 309 |
// newHTTP1Client creates an HTTP client that forces HTTP/1.1 by disabling HTTP/2 |
| 310 |
// ALPN negotiation. This works around HTTP/2 stream errors with some S3-compatible |
| 311 |
// providers (e.g. DigitalOcean Spaces) that can cause non-retryable failures on |
| 312 |
// streaming uploads when the server resets the stream mid-transfer. |
| 313 |
// See https://github.com/rclone/rclone/issues/4673, https://github.com/golang/go/issues/42777 |
| 314 |
func newHTTP1Client() *http.Client { |
| 315 |
return &http.Client{ |
| 316 |
Transport: &http.Transport{ |
| 317 |
TLSClientConfig: &tls.Config{ |
| 318 |
MinVersion: tls.VersionTLS12, |
| 319 |
}, |
| 320 |
ForceAttemptHTTP2: false, |
| 321 |
TLSNextProto: make(map[string]func(string, *tls.Conn) http.RoundTripper), |
| 322 |
}, |
| 323 |
} |
| 324 |
} |