s3.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package loader
  2. import (
  3. "fmt"
  4. "io"
  5. "os"
  6. "strings"
  7. "time"
  8. "github.com/goamz/goamz/aws"
  9. "github.com/goamz/goamz/s3"
  10. )
  11. // S3 implements interface Loader, so it can be used in an mitmengine.Config struct when getting a
  12. // mitmengine.Processor.
  13. type S3 struct {
  14. bucket *s3.Bucket
  15. }
  16. // NewS3Instance creates S3 struct using configs loaded from environment variables
  17. func NewS3Instance() (*S3, error) {
  18. accessKey, ok := os.LookupEnv("AWS_ACCESS_KEY_ID")
  19. if !ok {
  20. return nil, fmt.Errorf("environment variable '%s' not set", "AWS_ACCESS_KEY_ID")
  21. }
  22. secretKey, ok := os.LookupEnv("AWS_SECRET_ACCESS_KEY")
  23. if !ok {
  24. return nil, fmt.Errorf("environment variable '%s' not set", "AWS_SECRET_ACCESS_KEY")
  25. }
  26. endpoint, ok := os.LookupEnv("AWS_ENDPOINT")
  27. if !ok {
  28. return nil, fmt.Errorf("environment variable '%s' not set", "AWS_ENDPOINT")
  29. }
  30. bucketName, ok := os.LookupEnv("AWS_BUCKET_NAME")
  31. if !ok {
  32. return nil, fmt.Errorf("environment variable '%s' not set", "AWS_BUCKET_NAME")
  33. }
  34. auth, err := aws.GetAuth(strings.TrimSpace(string(accessKey)), strings.TrimSpace(string(secretKey)), "", time.Time{})
  35. if err != nil {
  36. return nil, fmt.Errorf("aws.GetAuth(): '%v'", err)
  37. }
  38. region := aws.Region{
  39. S3BucketEndpoint: fmt.Sprintf("https://%s.%s", bucketName, endpoint),
  40. }
  41. // use the bucket to pull fingerprint files
  42. mitmBucket := s3.New(auth, region).Bucket(bucketName)
  43. if mitmBucket == nil {
  44. return nil, fmt.Errorf("no bucket '%s' found at bucket endpoint '%s'", bucketName, endpoint)
  45. }
  46. return &S3{
  47. bucket: mitmBucket,
  48. }, nil
  49. }
  50. // LoadFile implements the LoadFile function specified in Loader interface, as defined in loader.go
  51. func (s3Instance *S3) LoadFile(fileName string) (io.ReadCloser, error) {
  52. reader, err := s3Instance.bucket.GetReader(fileName)
  53. if err != nil {
  54. return nil, fmt.Errorf("could not read %s: %s", fileName, err)
  55. }
  56. return reader, nil
  57. }