s3storage.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. package storage
  2. // Fork from Thanos S3 Bucket support to reuse configuration options
  3. // Licensed under the Apache License 2.0
  4. // https://github.com/thanos-io/thanos/blob/main/pkg/objstore/s3/s3.go
  5. import (
  6. "bytes"
  7. "context"
  8. "io"
  9. "net/http"
  10. "os"
  11. "strings"
  12. "time"
  13. "github.com/opencost/opencost/core/pkg/log"
  14. "github.com/aws/aws-sdk-go-v2/aws"
  15. awsconfig "github.com/aws/aws-sdk-go-v2/config"
  16. "github.com/minio/minio-go/v7"
  17. "github.com/minio/minio-go/v7/pkg/credentials"
  18. "github.com/minio/minio-go/v7/pkg/encrypt"
  19. "github.com/pkg/errors"
  20. "gopkg.in/yaml.v2"
  21. )
  22. type ctxKey int
  23. const (
  24. // SSEKMS is the name of the SSE-KMS method for objectstore encryption.
  25. SSEKMS = "SSE-KMS"
  26. // SSEC is the name of the SSE-C method for objstore encryption.
  27. SSEC = "SSE-C"
  28. // SSES3 is the name of the SSE-S3 method for objstore encryption.
  29. SSES3 = "SSE-S3"
  30. // sseConfigKey is the context key to override SSE config. This feature is used by downstream
  31. // projects (eg. Cortex) to inject custom SSE config on a per-request basis. Future work or
  32. // refactoring can introduce breaking changes as far as the functionality is preserved.
  33. // NOTE: we're using a context value only because it's a very specific S3 option. If SSE will
  34. // be available to wider set of backends we should probably add a variadic option to Get() and Upload().
  35. sseConfigKey = ctxKey(0)
  36. )
  37. var defaultS3Config = S3Config{
  38. PutUserMetadata: map[string]string{},
  39. HTTPConfig: HTTPConfig{
  40. IdleConnTimeout: 90 * time.Second,
  41. ResponseHeaderTimeout: 2 * time.Minute,
  42. TLSHandshakeTimeout: 10 * time.Second,
  43. ExpectContinueTimeout: 1 * time.Second,
  44. MaxIdleConns: 100,
  45. MaxIdleConnsPerHost: 100,
  46. MaxConnsPerHost: 0,
  47. DisableCompression: true,
  48. },
  49. PartSize: 1024 * 1024 * 64, // 64MB.
  50. }
  51. // Config stores the configuration for s3 bucket.
  52. type S3Config struct {
  53. Bucket string `yaml:"bucket"`
  54. Endpoint string `yaml:"endpoint"`
  55. Region string `yaml:"region"`
  56. AWSSDKAuth bool `yaml:"aws_sdk_auth"`
  57. AccessKey string `yaml:"access_key"`
  58. Insecure bool `yaml:"insecure"`
  59. SignatureV2 bool `yaml:"signature_version2"`
  60. SecretKey string `yaml:"secret_key"`
  61. PutUserMetadata map[string]string `yaml:"put_user_metadata"`
  62. HTTPConfig HTTPConfig `yaml:"http_config"`
  63. TraceConfig TraceConfig `yaml:"trace"`
  64. ListObjectsVersion string `yaml:"list_objects_version"`
  65. // PartSize used for multipart upload. Only used if uploaded object size is known and larger than configured PartSize.
  66. // NOTE we need to make sure this number does not produce more parts than 10 000.
  67. PartSize uint64 `yaml:"part_size"`
  68. SSEConfig SSEConfig `yaml:"sse_config"`
  69. STSEndpoint string `yaml:"sts_endpoint"`
  70. }
  71. // SSEConfig deals with the configuration of SSE for Minio. The following options are valid:
  72. // kmsencryptioncontext == https://docs.aws.amazon.com/kms/latest/developerguide/services-s3.html#s3-encryption-context
  73. type SSEConfig struct {
  74. Type string `yaml:"type"`
  75. KMSKeyID string `yaml:"kms_key_id"`
  76. KMSEncryptionContext map[string]string `yaml:"kms_encryption_context"`
  77. EncryptionKey string `yaml:"encryption_key"`
  78. }
  79. type TraceConfig struct {
  80. Enable bool `yaml:"enable"`
  81. }
  82. // S3Storage provides storage via S3
  83. type S3Storage struct {
  84. name string
  85. client *minio.Client
  86. defaultSSE encrypt.ServerSide
  87. putUserMetadata map[string]string
  88. partSize uint64
  89. listObjectsV1 bool
  90. }
  91. // parseConfig unmarshals a buffer into a Config with default HTTPConfig values.
  92. func parseS3Config(conf []byte) (S3Config, error) {
  93. config := defaultS3Config
  94. if err := yaml.Unmarshal(conf, &config); err != nil {
  95. return S3Config{}, err
  96. }
  97. return config, nil
  98. }
  99. // NewBucket returns a new Bucket using the provided s3 config values.
  100. func NewS3Storage(conf []byte) (*S3Storage, error) {
  101. config, err := parseS3Config(conf)
  102. if err != nil {
  103. return nil, err
  104. }
  105. return NewS3StorageWith(config)
  106. }
  107. // NewBucketWithConfig returns a new Bucket using the provided s3 config values.
  108. func NewS3StorageWith(config S3Config) (*S3Storage, error) {
  109. var chain []credentials.Provider
  110. wrapCredentialsProvider := func(p credentials.Provider) credentials.Provider { return p }
  111. if config.SignatureV2 {
  112. wrapCredentialsProvider = func(p credentials.Provider) credentials.Provider {
  113. return &overrideSignerType{Provider: p, signerType: credentials.SignatureV2}
  114. }
  115. }
  116. if err := validate(config); err != nil {
  117. return nil, err
  118. }
  119. if config.AWSSDKAuth {
  120. chain = []credentials.Provider{
  121. wrapCredentialsProvider(&awsAuth{Region: config.Region}),
  122. }
  123. } else if config.AccessKey != "" {
  124. chain = []credentials.Provider{wrapCredentialsProvider(&credentials.Static{
  125. Value: credentials.Value{
  126. AccessKeyID: config.AccessKey,
  127. SecretAccessKey: config.SecretKey,
  128. SignerType: credentials.SignatureV4,
  129. },
  130. })}
  131. } else {
  132. chain = []credentials.Provider{
  133. wrapCredentialsProvider(&credentials.EnvAWS{}),
  134. wrapCredentialsProvider(&credentials.FileAWSCredentials{}),
  135. wrapCredentialsProvider(&credentials.IAM{
  136. Client: &http.Client{
  137. Transport: http.DefaultTransport,
  138. },
  139. Endpoint: config.STSEndpoint,
  140. }),
  141. }
  142. }
  143. rt, err := config.HTTPConfig.GetHTTPTransport()
  144. if err != nil {
  145. return nil, err
  146. }
  147. client, err := minio.New(config.Endpoint, &minio.Options{
  148. Creds: credentials.NewChainCredentials(chain),
  149. Secure: !config.Insecure,
  150. Region: config.Region,
  151. Transport: rt,
  152. })
  153. if err != nil {
  154. return nil, errors.Wrap(err, "initialize s3 client")
  155. }
  156. var sse encrypt.ServerSide
  157. if config.SSEConfig.Type != "" {
  158. switch config.SSEConfig.Type {
  159. case SSEKMS:
  160. // If the KMSEncryptionContext is a nil map the header that is
  161. // constructed by the encrypt.ServerSide object will be base64
  162. // encoded "nil" which is not accepted by AWS.
  163. if config.SSEConfig.KMSEncryptionContext == nil {
  164. config.SSEConfig.KMSEncryptionContext = make(map[string]string)
  165. }
  166. sse, err = encrypt.NewSSEKMS(config.SSEConfig.KMSKeyID, config.SSEConfig.KMSEncryptionContext)
  167. if err != nil {
  168. return nil, errors.Wrap(err, "initialize s3 client SSE-KMS")
  169. }
  170. case SSEC:
  171. key, err := os.ReadFile(config.SSEConfig.EncryptionKey)
  172. if err != nil {
  173. return nil, err
  174. }
  175. sse, err = encrypt.NewSSEC(key)
  176. if err != nil {
  177. return nil, errors.Wrap(err, "initialize s3 client SSE-C")
  178. }
  179. case SSES3:
  180. sse = encrypt.NewSSE()
  181. default:
  182. sseErrMsg := errors.Errorf("Unsupported type %q was provided. Supported types are SSE-S3, SSE-KMS, SSE-C", config.SSEConfig.Type)
  183. return nil, errors.Wrap(sseErrMsg, "Initialize s3 client SSE Config")
  184. }
  185. }
  186. if config.ListObjectsVersion != "" && config.ListObjectsVersion != "v1" && config.ListObjectsVersion != "v2" {
  187. return nil, errors.Errorf("Initialize s3 client list objects version: Unsupported version %q was provided. Supported values are v1, v2", config.ListObjectsVersion)
  188. }
  189. bkt := &S3Storage{
  190. name: config.Bucket,
  191. client: client,
  192. defaultSSE: sse,
  193. putUserMetadata: config.PutUserMetadata,
  194. partSize: config.PartSize,
  195. listObjectsV1: config.ListObjectsVersion == "v1",
  196. }
  197. return bkt, nil
  198. }
  199. // String returns the bucket name for s3.
  200. func (s3 *S3Storage) String() string {
  201. return s3.name
  202. }
  203. // StorageType returns a string identifier for the type of storage used by the implementation.
  204. func (s3 *S3Storage) StorageType() StorageType {
  205. return StorageTypeBucketS3
  206. }
  207. // validate checks to see the config options are set.
  208. func validate(conf S3Config) error {
  209. if conf.Endpoint == "" {
  210. return errors.New("no s3 endpoint in config file")
  211. }
  212. if conf.AWSSDKAuth && conf.AccessKey != "" {
  213. return errors.New("aws_sdk_auth and access_key are mutually exclusive configurations")
  214. }
  215. if conf.AccessKey == "" && conf.SecretKey != "" {
  216. return errors.New("no s3 acccess_key specified while secret_key is present in config file; either both should be present in config or envvars/IAM should be used.")
  217. }
  218. if conf.AccessKey != "" && conf.SecretKey == "" {
  219. return errors.New("no s3 secret_key specified while access_key is present in config file; either both should be present in config or envvars/IAM should be used.")
  220. }
  221. if conf.SSEConfig.Type == SSEC && conf.SSEConfig.EncryptionKey == "" {
  222. return errors.New("encryption_key must be set if sse_config.type is set to 'SSE-C'")
  223. }
  224. if conf.SSEConfig.Type == SSEKMS && conf.SSEConfig.KMSKeyID == "" {
  225. return errors.New("kms_key_id must be set if sse_config.type is set to 'SSE-KMS'")
  226. }
  227. return nil
  228. }
  229. // FullPath returns the storage working path combined with the path provided
  230. func (s3 *S3Storage) FullPath(name string) string {
  231. name = trimLeading(name)
  232. return name
  233. }
  234. // Get returns a reader for the given object name.
  235. func (s3 *S3Storage) Read(name string) ([]byte, error) {
  236. name = trimLeading(name)
  237. log.Tracef("S3Storage::Read(%s)", name)
  238. ctx := context.Background()
  239. return s3.getRange(ctx, name, 0, -1)
  240. }
  241. // Exists checks if the given object exists.
  242. func (s3 *S3Storage) Exists(name string) (bool, error) {
  243. name = trimLeading(name)
  244. log.Tracef("S3Storage::Exists(%s)", name)
  245. ctx := context.Background()
  246. _, err := s3.client.StatObject(ctx, s3.name, name, minio.StatObjectOptions{})
  247. if err != nil {
  248. if s3.isDoesNotExist(err) {
  249. return false, nil
  250. }
  251. return false, errors.Wrap(err, "stat s3 object")
  252. }
  253. return true, nil
  254. }
  255. // Upload the contents of the reader as an object into the bucket.
  256. func (s3 *S3Storage) Write(name string, data []byte) error {
  257. name = trimLeading(name)
  258. log.Tracef("S3Storage::Write(%s)", name)
  259. ctx := context.Background()
  260. sse, err := s3.getServerSideEncryption(ctx)
  261. if err != nil {
  262. return err
  263. }
  264. var size int64 = int64(len(data))
  265. // Set partSize to 0 to write files in one go. This prevents chunking of
  266. // upload into multiple parts, which requires additional memory for buffering
  267. // the sub-parts. To remain consistent with other storage implementations,
  268. // we would rather attempt to lower cost fast upload and fast-fail.
  269. var partSize uint64 = 0
  270. r := bytes.NewReader(data)
  271. _, err = s3.client.PutObject(ctx, s3.name, name, r, int64(size), minio.PutObjectOptions{
  272. PartSize: partSize,
  273. ServerSideEncryption: sse,
  274. UserMetadata: s3.putUserMetadata,
  275. })
  276. if err != nil {
  277. return errors.Wrap(err, "upload s3 object")
  278. }
  279. return nil
  280. }
  281. // Attributes returns information about the specified object.
  282. func (s3 *S3Storage) Stat(name string) (*StorageInfo, error) {
  283. name = trimLeading(name)
  284. log.Tracef("S3Storage::Stat(%s)", name)
  285. ctx := context.Background()
  286. objInfo, err := s3.client.StatObject(ctx, s3.name, name, minio.StatObjectOptions{})
  287. if err != nil {
  288. if s3.isDoesNotExist(err) {
  289. return nil, DoesNotExistError
  290. }
  291. return nil, err
  292. }
  293. return &StorageInfo{
  294. Name: trimName(name),
  295. Size: objInfo.Size,
  296. ModTime: objInfo.LastModified,
  297. }, nil
  298. }
  299. // Delete removes the object with the given name.
  300. func (s3 *S3Storage) Remove(name string) error {
  301. name = trimLeading(name)
  302. log.Tracef("S3Storage::Remove(%s)", name)
  303. ctx := context.Background()
  304. return s3.client.RemoveObject(ctx, s3.name, name, minio.RemoveObjectOptions{})
  305. }
  306. func (s3 *S3Storage) List(path string) ([]*StorageInfo, error) {
  307. path = trimLeading(path)
  308. log.Tracef("S3Storage::List(%s)", path)
  309. ctx := context.Background()
  310. // Ensure the object name actually ends with a dir suffix. Otherwise we'll just iterate the
  311. // object itself as one prefix item.
  312. if path != "" {
  313. path = strings.TrimSuffix(path, DirDelim) + DirDelim
  314. }
  315. opts := minio.ListObjectsOptions{
  316. Prefix: path,
  317. Recursive: false,
  318. UseV1: s3.listObjectsV1,
  319. }
  320. var stats []*StorageInfo
  321. for object := range s3.client.ListObjects(ctx, s3.name, opts) {
  322. // Catch the error when failed to list objects.
  323. if object.Err != nil {
  324. return nil, object.Err
  325. }
  326. // The s3 client can also return the directory itself in the ListObjects call above.
  327. if object.Key == path {
  328. continue
  329. }
  330. name := trimName(object.Key)
  331. // This sometimes happens with empty buckets.
  332. if name == "" {
  333. continue
  334. }
  335. stats = append(stats, &StorageInfo{
  336. Name: name,
  337. Size: object.Size,
  338. ModTime: object.LastModified,
  339. })
  340. }
  341. return stats, nil
  342. }
  343. func (s3 *S3Storage) ListDirectories(path string) ([]*StorageInfo, error) {
  344. path = trimLeading(path)
  345. log.Tracef("S3Storage::List(%s)", path)
  346. ctx := context.Background()
  347. if path != "" {
  348. path = strings.TrimSuffix(path, DirDelim) + DirDelim
  349. }
  350. opts := minio.ListObjectsOptions{
  351. Prefix: path,
  352. Recursive: false,
  353. UseV1: s3.listObjectsV1,
  354. }
  355. var stats []*StorageInfo
  356. for object := range s3.client.ListObjects(ctx, s3.name, opts) {
  357. if object.Err != nil {
  358. return nil, object.Err
  359. }
  360. if object.Key == "" {
  361. continue
  362. }
  363. if object.Key == path {
  364. continue
  365. }
  366. // If trim removes the entire name, it's a directory, ergo we list it
  367. if trimName(object.Key) == "" {
  368. stats = append(stats, &StorageInfo{
  369. Name: object.Key,
  370. Size: object.Size,
  371. ModTime: object.LastModified,
  372. })
  373. }
  374. }
  375. return stats, nil
  376. }
  377. // getServerSideEncryption returns the SSE to use.
  378. func (s3 *S3Storage) getServerSideEncryption(ctx context.Context) (encrypt.ServerSide, error) {
  379. if value := ctx.Value(sseConfigKey); value != nil {
  380. if sse, ok := value.(encrypt.ServerSide); ok {
  381. return sse, nil
  382. }
  383. return nil, errors.New("invalid SSE config override provided in the context")
  384. }
  385. return s3.defaultSSE, nil
  386. }
  387. // isDoesNotExist returns true if error means that object key is not found.
  388. func (s3 *S3Storage) isDoesNotExist(err error) bool {
  389. return minio.ToErrorResponse(errors.Cause(err)).Code == "NoSuchKey"
  390. }
  391. // isObjNotFound returns true if the error means that the object was not found
  392. func (s3 *S3Storage) isObjNotFound(err error) bool {
  393. return minio.ToErrorResponse(errors.Cause(err)).Code == "NotFoundObject"
  394. }
  395. func (s3 *S3Storage) getRange(ctx context.Context, name string, off, length int64) ([]byte, error) {
  396. sse, err := s3.getServerSideEncryption(ctx)
  397. if err != nil {
  398. return nil, err
  399. }
  400. opts := &minio.GetObjectOptions{ServerSideEncryption: sse}
  401. if length != -1 {
  402. if err := opts.SetRange(off, off+length-1); err != nil {
  403. return nil, err
  404. }
  405. } else if off > 0 {
  406. if err := opts.SetRange(off, 0); err != nil {
  407. return nil, err
  408. }
  409. }
  410. r, err := s3.client.GetObject(ctx, s3.name, name, *opts)
  411. if err != nil {
  412. if s3.isObjNotFound(err) {
  413. return nil, DoesNotExistError
  414. }
  415. return nil, err
  416. }
  417. defer r.Close()
  418. // NotFoundObject error is revealed only after first Read. This does the initial GetRequest. Prefetch this here
  419. // for convenience.
  420. if _, err := r.Read(nil); err != nil {
  421. if s3.isObjNotFound(err) {
  422. return nil, DoesNotExistError
  423. }
  424. return nil, errors.Wrap(err, "Read from S3 failed")
  425. }
  426. return io.ReadAll(r)
  427. }
  428. // awsAuth retrieves credentials from the aws-sdk-go.
  429. type awsAuth struct {
  430. Region string
  431. creds aws.Credentials
  432. }
  433. // Retrieve retrieves the keys from the environment.
  434. func (a *awsAuth) Retrieve() (credentials.Value, error) {
  435. cfg, err := awsconfig.LoadDefaultConfig(context.TODO(), awsconfig.WithRegion(a.Region))
  436. if err != nil {
  437. return credentials.Value{}, errors.Wrap(err, "load AWS SDK config")
  438. }
  439. creds, err := cfg.Credentials.Retrieve(context.TODO())
  440. if err != nil {
  441. return credentials.Value{}, errors.Wrap(err, "retrieve AWS SDK credentials")
  442. }
  443. a.creds = creds
  444. return credentials.Value{
  445. AccessKeyID: creds.AccessKeyID,
  446. SecretAccessKey: creds.SecretAccessKey,
  447. SessionToken: creds.SessionToken,
  448. SignerType: credentials.SignatureV4,
  449. }, nil
  450. }
  451. func (a *awsAuth) RetrieveWithCredContext(ctx *credentials.CredContext) (credentials.Value, error) {
  452. return a.Retrieve()
  453. }
  454. // IsExpired returns if the credentials have been retrieved.
  455. func (a *awsAuth) IsExpired() bool {
  456. return a.creds.Expired()
  457. }
  458. type overrideSignerType struct {
  459. credentials.Provider
  460. signerType credentials.SignatureType
  461. }
  462. func (s *overrideSignerType) Retrieve() (credentials.Value, error) {
  463. v, err := s.Provider.Retrieve()
  464. if err != nil {
  465. return v, err
  466. }
  467. if !v.SignerType.IsAnonymous() {
  468. v.SignerType = s.signerType
  469. }
  470. return v, nil
  471. }
  472. func (s *overrideSignerType) RetrieveWithCredContext(ctx *credentials.CredContext) (credentials.Value, error) {
  473. v, err := s.Provider.RetrieveWithCredContext(ctx)
  474. if err != nil {
  475. return v, err
  476. }
  477. if !v.SignerType.IsAnonymous() {
  478. v.SignerType = s.signerType
  479. }
  480. return v, nil
  481. }