Debian Codegraph @

s3/util.go

raw
1 package s3
2
3 import (
4 "crypto/hmac"
5 "crypto/sha256"
6 "encoding/hex"
7 "encoding/xml"
8 "fmt"
9 "io"
10 "net/http"
11 "net/url"
12 "sort"
13 "strconv"
14 "strings"
15 )
16
17 const (
18 // SHA-256 hash of the empty string, used as the payload hash for bodiless requests
19 emptyPayloadHash = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
20
21 // Sent as the payload hash for streaming uploads where the body is not buffered in memory
22 unsignedPayload = "UNSIGNED-PAYLOAD"
23
24 // maxResponseBytes caps the size of S3 response bodies we read into memory
25 maxResponseBytes = 2 * 1024 * 1024
26
27 // partSize is the size of each part for multipart uploads (5 MB). This is also the threshold
28 // above which PutObject switches from a simple PUT to multipart upload. S3 requires a minimum
29 // part size of 5 MB for all parts except the last.
30 partSize = 5 * 1024 * 1024
31
32 // maxSinglePutSize is the maximum size for a single PUT upload (5 GB).
33 // Objects larger than this must use multipart upload.
34 maxSinglePutSize = 5 * 1024 * 1024 * 1024
35
36 // maxPages is the max number of pages to iterate through when listing objects
37 maxPages = 500
38
39 // maxDeleteBatchSize is the maximum number of keys per S3 DeleteObjects call
40 maxDeleteBatchSize = 1000
41 )
42
43 // ParseURL parses an S3 URL of the form:
44 //
45 // s3://ACCESS_KEY:SECRET_KEY@BUCKET[/PREFIX]?region=REGION[&endpoint=ENDPOINT][&disable_http2=true]
46 //
47 // When endpoint is specified, path-style addressing is enabled automatically.
48 // When disable_http2=true is set, the client forces HTTP/1.1 to work around
49 // HTTP/2 stream errors with some S3-compatible providers (e.g. DigitalOcean Spaces).
50 func ParseURL(s3URL string) (*Config, error) {
51 u, err := url.Parse(s3URL)
52 if err != nil {
53 return nil, fmt.Errorf("s3: invalid URL: %w", err)
54 }
55 if u.Scheme != "s3" {
56 return nil, fmt.Errorf("s3: URL scheme must be 's3', got '%s'", u.Scheme)
57 }
58 if u.Host == "" {
59 return nil, fmt.Errorf("s3: bucket name must be specified as host")
60 }
61 bucket := u.Host
62 prefix := strings.TrimPrefix(u.Path, "/")
63 accessKey := u.User.Username()
64 secretKey, _ := u.User.Password()
65 if accessKey == "" || secretKey == "" {
66 return nil, fmt.Errorf("s3: access key and secret key must be specified in URL")
67 }
68 region := u.Query().Get("region")
69 if region == "" {
70 return nil, fmt.Errorf("s3: region query parameter is required")
71 }
72 endpointParam := u.Query().Get("endpoint")
73 var scheme string
74 var endpoint string
75 var pathStyle bool
76 if endpointParam != "" {
77 // Custom endpoint: derive the scheme from the prefix and strip it to extract host[:port].
78 // Default to https for backward compatibility, including bare "host:port" endpoints (no
79 // scheme) -- url.Parse would otherwise misread the host before the port colon as the scheme.
80 scheme = "https"
81 if strings.HasPrefix(endpointParam, "http://") {
82 scheme = "http"
83 }
84 ep := strings.TrimRight(endpointParam, "/")
85 ep = strings.TrimPrefix(ep, "https://")
86 ep = strings.TrimPrefix(ep, "http://")
87 endpoint = ep
88 pathStyle = true
89 } else {
90 scheme = "https"
91 endpoint = fmt.Sprintf("s3.%s.amazonaws.com", region)
92 pathStyle = false
93 }
94 disableHTTP2, _ := strconv.ParseBool(u.Query().Get("disable_http2"))
95 return &Config{
96 Scheme: scheme,
97 Endpoint: endpoint,
98 PathStyle: pathStyle,
99 Bucket: bucket,
100 Prefix: prefix,
101 Region: region,
102 AccessKey: accessKey,
103 SecretKey: secretKey,
104 DisableHTTP2: disableHTTP2,
105 }, nil
106 }
107
108 // parseError reads an S3 error response and returns an *errorResponse.
109 func parseError(resp *http.Response) error {
110 body, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBytes))
111 if err != nil {
112 return fmt.Errorf("error reading S3 error response: %w", err)
113 }
114 return parseErrorFromBytes(resp.StatusCode, body)
115 }
116
117 func parseErrorFromBytes(statusCode int, body []byte) error {
118 errResp := &errorResponse{
119 StatusCode: statusCode,
120 Body: string(body),
121 }
122 // Try to parse XML error; if it fails, we still have StatusCode and Body
123 _ = xml.Unmarshal(body, errResp)
124 return errResp
125 }
126
127 // canonicalURI returns the URI-encoded path for the canonical request. Each path segment is
128 // percent-encoded per RFC 3986; forward slashes are preserved.
129 func canonicalURI(u *url.URL) string {
130 p := u.Path
131 if p == "" {
132 return "/"
133 }
134 segments := strings.Split(p, "/")
135 for i, seg := range segments {
136 segments[i] = uriEncode(seg)
137 }
138 return strings.Join(segments, "/")
139 }
140
141 // canonicalQueryString builds the query string for the canonical request. Keys and values
142 // are URI-encoded per RFC 3986 (using %20, not +) and sorted lexically by key.
143 func canonicalQueryString(values url.Values) string {
144 if len(values) == 0 {
145 return ""
146 }
147 keys := make([]string, 0, len(values))
148 for k := range values {
149 keys = append(keys, k)
150 }
151 sort.Strings(keys)
152 var pairs []string
153 for _, k := range keys {
154 ek := uriEncode(k)
155 vs := make([]string, len(values[k]))
156 copy(vs, values[k])
157 sort.Strings(vs)
158 for _, v := range vs {
159 pairs = append(pairs, ek+"="+uriEncode(v))
160 }
161 }
162 return strings.Join(pairs, "&")
163 }
164
165 // uriEncode percent-encodes a string per RFC 3986, encoding everything except unreserved
166 // characters (A-Z a-z 0-9 - _ . ~).
167 func uriEncode(s string) string {
168 var buf strings.Builder
169 for i := 0; i < len(s); i++ {
170 b := s[i]
171 if (b >= 'A' && b <= 'Z') || (b >= 'a' && b <= 'z') || (b >= '0' && b <= '9') ||
172 b == '-' || b == '_' || b == '.' || b == '~' {
173 buf.WriteByte(b)
174 } else {
175 fmt.Fprintf(&buf, "%%%02X", b)
176 }
177 }
178 return buf.String()
179 }
180
181 func isHTTPSuccess(resp *http.Response) bool {
182 return resp.StatusCode/100 == 2
183 }
184
185 func sha256Hex(data []byte) string {
186 h := sha256.Sum256(data)
187 return hex.EncodeToString(h[:])
188 }
189
190 func hmacSHA256(key, data []byte) []byte {
191 h := hmac.New(sha256.New, key)
192 h.Write(data)
193 return h.Sum(nil)
194 }