s3.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. package s3
  2. import (
  3. "context"
  4. "errors"
  5. "io"
  6. "net/http"
  7. "strconv"
  8. "strings"
  9. "sync"
  10. "time"
  11. s3Crypto "github.com/aws/amazon-s3-encryption-client-go/v3/client"
  12. s3CryptoMaterials "github.com/aws/amazon-s3-encryption-client-go/v3/materials"
  13. "github.com/aws/aws-sdk-go-v2/aws"
  14. awsHttp "github.com/aws/aws-sdk-go-v2/aws/transport/http"
  15. awsConfig "github.com/aws/aws-sdk-go-v2/config"
  16. "github.com/aws/aws-sdk-go-v2/credentials/stscreds"
  17. "github.com/aws/aws-sdk-go-v2/service/kms"
  18. "github.com/aws/aws-sdk-go-v2/service/s3"
  19. "github.com/aws/aws-sdk-go-v2/service/sts"
  20. "github.com/imgproxy/imgproxy/v3/config"
  21. "github.com/imgproxy/imgproxy/v3/ierrors"
  22. defaultTransport "github.com/imgproxy/imgproxy/v3/transport"
  23. "github.com/imgproxy/imgproxy/v3/transport/common"
  24. )
  25. type s3Client interface {
  26. GetObject(ctx context.Context, input *s3.GetObjectInput, opts ...func(*s3.Options)) (*s3.GetObjectOutput, error)
  27. }
  28. // transport implements RoundTripper for the 's3' protocol.
  29. type transport struct {
  30. clientOptions []func(*s3.Options)
  31. defaultClient s3Client
  32. defaultConfig aws.Config
  33. clientsByRegion map[string]s3Client
  34. clientsByBucket map[string]s3Client
  35. mu sync.RWMutex
  36. }
  37. func New() (http.RoundTripper, error) {
  38. conf, err := awsConfig.LoadDefaultConfig(context.Background())
  39. if err != nil {
  40. return nil, ierrors.Wrap(err, 0, ierrors.WithPrefix("can't load AWS S3 config"))
  41. }
  42. trans, err := defaultTransport.New(false)
  43. if err != nil {
  44. return nil, err
  45. }
  46. conf.HTTPClient = &http.Client{Transport: trans}
  47. if len(config.S3Region) != 0 {
  48. conf.Region = config.S3Region
  49. }
  50. if len(conf.Region) == 0 {
  51. conf.Region = "us-west-1"
  52. }
  53. if len(config.S3AssumeRoleArn) != 0 {
  54. creds := stscreds.NewAssumeRoleProvider(sts.NewFromConfig(conf), config.S3AssumeRoleArn, func(o *stscreds.AssumeRoleOptions) {
  55. if len(config.S3AssumeRoleExternalID) != 0 {
  56. o.ExternalID = aws.String(config.S3AssumeRoleExternalID)
  57. }
  58. })
  59. conf.Credentials = creds
  60. }
  61. clientOptions := []func(*s3.Options){}
  62. if len(config.S3Endpoint) != 0 {
  63. endpoint := config.S3Endpoint
  64. if !strings.HasPrefix(endpoint, "http://") && !strings.HasPrefix(endpoint, "https://") {
  65. endpoint = "http://" + endpoint
  66. }
  67. clientOptions = append(clientOptions, func(o *s3.Options) {
  68. o.BaseEndpoint = aws.String(endpoint)
  69. o.UsePathStyle = config.S3EndpointUsePathStyle
  70. })
  71. }
  72. client, err := createClient(conf, clientOptions)
  73. if err != nil {
  74. return nil, ierrors.Wrap(err, 0, ierrors.WithPrefix("can't create S3 client"))
  75. }
  76. return &transport{
  77. clientOptions: clientOptions,
  78. defaultClient: client,
  79. defaultConfig: conf,
  80. clientsByRegion: map[string]s3Client{conf.Region: client},
  81. clientsByBucket: make(map[string]s3Client),
  82. }, nil
  83. }
  84. func (t *transport) RoundTrip(req *http.Request) (*http.Response, error) {
  85. bucket, key, query := common.GetBucketAndKey(req.URL)
  86. if len(bucket) == 0 || len(key) == 0 {
  87. body := strings.NewReader("Invalid S3 URL: bucket name or object key is empty")
  88. return &http.Response{
  89. StatusCode: http.StatusNotFound,
  90. Proto: "HTTP/1.0",
  91. ProtoMajor: 1,
  92. ProtoMinor: 0,
  93. Header: http.Header{"Content-Type": {"text/plain"}},
  94. ContentLength: int64(body.Len()),
  95. Body: io.NopCloser(body),
  96. Close: false,
  97. Request: req,
  98. }, nil
  99. }
  100. input := &s3.GetObjectInput{
  101. Bucket: aws.String(bucket),
  102. Key: aws.String(key),
  103. }
  104. if len(query) > 0 {
  105. input.VersionId = aws.String(query)
  106. }
  107. statusCode := http.StatusOK
  108. if r := req.Header.Get("Range"); len(r) != 0 {
  109. input.Range = aws.String(r)
  110. } else {
  111. if config.ETagEnabled {
  112. if ifNoneMatch := req.Header.Get("If-None-Match"); len(ifNoneMatch) > 0 {
  113. input.IfNoneMatch = aws.String(ifNoneMatch)
  114. }
  115. }
  116. if config.LastModifiedEnabled {
  117. if ifModifiedSince := req.Header.Get("If-Modified-Since"); len(ifModifiedSince) > 0 {
  118. parsedIfModifiedSince, err := time.Parse(http.TimeFormat, ifModifiedSince)
  119. if err == nil {
  120. input.IfModifiedSince = &parsedIfModifiedSince
  121. }
  122. }
  123. }
  124. }
  125. client := t.getBucketClient(bucket)
  126. output, err := client.GetObject(req.Context(), input)
  127. defer func() {
  128. if err != nil && output != nil && output.Body != nil {
  129. output.Body.Close()
  130. }
  131. }()
  132. if err != nil {
  133. // Check if the error is the region mismatch error.
  134. // If so, create a new client with the correct region and retry the request.
  135. if region := regionFromError(err); len(region) != 0 {
  136. client, err = t.createBucketClient(bucket, region)
  137. if err != nil {
  138. return handleError(req, err)
  139. }
  140. output, err = client.GetObject(req.Context(), input)
  141. }
  142. }
  143. if err != nil {
  144. return handleError(req, err)
  145. }
  146. contentLength := int64(-1)
  147. if output.ContentLength != nil {
  148. contentLength = *output.ContentLength
  149. }
  150. if config.S3DecryptionClientEnabled {
  151. if unencryptedContentLength := output.Metadata["X-Amz-Meta-X-Amz-Unencrypted-Content-Length"]; len(unencryptedContentLength) != 0 {
  152. cl, err := strconv.ParseInt(unencryptedContentLength, 10, 64)
  153. if err != nil {
  154. handleError(req, err)
  155. }
  156. contentLength = cl
  157. }
  158. }
  159. header := make(http.Header)
  160. if contentLength > 0 {
  161. header.Set("Content-Length", strconv.FormatInt(contentLength, 10))
  162. }
  163. if output.ContentType != nil {
  164. header.Set("Content-Type", *output.ContentType)
  165. }
  166. if output.ContentEncoding != nil {
  167. header.Set("Content-Encoding", *output.ContentEncoding)
  168. }
  169. if output.CacheControl != nil {
  170. header.Set("Cache-Control", *output.CacheControl)
  171. }
  172. if output.ExpiresString != nil {
  173. header.Set("Expires", *output.ExpiresString)
  174. }
  175. if output.ETag != nil {
  176. header.Set("ETag", *output.ETag)
  177. }
  178. if output.LastModified != nil {
  179. header.Set("Last-Modified", output.LastModified.Format(http.TimeFormat))
  180. }
  181. if output.AcceptRanges != nil {
  182. header.Set("Accept-Ranges", *output.AcceptRanges)
  183. }
  184. if output.ContentRange != nil {
  185. header.Set("Content-Range", *output.ContentRange)
  186. statusCode = http.StatusPartialContent
  187. }
  188. return &http.Response{
  189. StatusCode: statusCode,
  190. Proto: "HTTP/1.0",
  191. ProtoMajor: 1,
  192. ProtoMinor: 0,
  193. Header: header,
  194. ContentLength: contentLength,
  195. Body: output.Body,
  196. Close: true,
  197. Request: req,
  198. }, nil
  199. }
  200. func (t *transport) getBucketClient(bucket string) s3Client {
  201. var client s3Client
  202. func() {
  203. t.mu.RLock()
  204. defer t.mu.RUnlock()
  205. client = t.clientsByBucket[bucket]
  206. }()
  207. if client != nil {
  208. return client
  209. }
  210. return t.defaultClient
  211. }
  212. func (t *transport) createBucketClient(bucket, region string) (s3Client, error) {
  213. t.mu.Lock()
  214. defer t.mu.Unlock()
  215. // Check again if someone did this before us
  216. if client := t.clientsByBucket[bucket]; client != nil {
  217. return client, nil
  218. }
  219. if client := t.clientsByRegion[region]; client != nil {
  220. t.clientsByBucket[bucket] = client
  221. return client, nil
  222. }
  223. conf := t.defaultConfig.Copy()
  224. conf.Region = region
  225. client, err := createClient(conf, t.clientOptions)
  226. if err != nil {
  227. return nil, ierrors.Wrap(err, 0, ierrors.WithPrefix("can't create regional S3 client"))
  228. }
  229. t.clientsByRegion[region] = client
  230. t.clientsByBucket[bucket] = client
  231. return client, nil
  232. }
  233. func createClient(conf aws.Config, opts []func(*s3.Options)) (s3Client, error) {
  234. client := s3.NewFromConfig(conf, opts...)
  235. if config.S3DecryptionClientEnabled {
  236. kmsClient := kms.NewFromConfig(conf)
  237. keyring := s3CryptoMaterials.NewKmsDecryptOnlyAnyKeyKeyring(kmsClient)
  238. cmm, err := s3CryptoMaterials.NewCryptographicMaterialsManager(keyring)
  239. if err != nil {
  240. return nil, err
  241. }
  242. return s3Crypto.New(client, cmm)
  243. } else {
  244. return client, nil
  245. }
  246. }
  247. func regionFromError(err error) string {
  248. var rerr *awsHttp.ResponseError
  249. if !errors.As(err, &rerr) {
  250. return ""
  251. }
  252. if rerr.Response == nil || rerr.Response.StatusCode != 301 {
  253. return ""
  254. }
  255. return rerr.Response.Header.Get("X-Amz-Bucket-Region")
  256. }
  257. func handleError(req *http.Request, err error) (*http.Response, error) {
  258. var rerr *awsHttp.ResponseError
  259. if !errors.As(err, &rerr) {
  260. return nil, ierrors.Wrap(err, 0)
  261. }
  262. if rerr.Response == nil || rerr.Response.StatusCode < 100 || rerr.Response.StatusCode == 301 {
  263. return nil, ierrors.Wrap(err, 0)
  264. }
  265. return &http.Response{
  266. StatusCode: rerr.Response.StatusCode,
  267. Proto: "HTTP/1.0",
  268. ProtoMajor: 1,
  269. ProtoMinor: 0,
  270. Header: http.Header{"Content-Type": {"text/plain"}},
  271. ContentLength: int64(len(err.Error())),
  272. Body: io.NopCloser(strings.NewReader(err.Error())),
  273. Close: false,
  274. Request: req,
  275. }, nil
  276. }