diff --git a/.gitignore b/.gitignore index 03526ef..7db9681 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ aws-s3-reverse-proxy aws-s3-reverse-proxy.tar config test.txt +cache.d/ diff --git a/cache/cache.go b/cache/cache.go new file mode 100644 index 0000000..87d935f --- /dev/null +++ b/cache/cache.go @@ -0,0 +1,271 @@ +package cache + +// This file was initially taken from https://github.com/hauke96/tiny-http-proxy/blob/master/cache.go +// some extra functionality has been added: +// Allow invalidating cahce items +// expiring cached items based on a global TTL + +import ( + "bufio" + "bytes" + "crypto/sha256" + "encoding/hex" + "fmt" + "hash" + "io" + "io/fs" + "os" + "path/filepath" + "sync" + "time" + + log "github.com/sirupsen/logrus" +) + +type Cache struct { + folder string + hash hash.Hash + knownValues map[string][]byte + busyValues map[string]*sync.Mutex + mutex *sync.Mutex + maxSize int64 + ttl time.Duration +} + +type Options struct { + Path string + MaxSize int64 + TTL time.Duration +} + +func CreateCache(opts Options) (*Cache, error) { + fileInfos, err := os.ReadDir(opts.Path) + if err != nil { + log.Warnf("Cannot open cache folder '%s': %s", opts.Path, err) + log.Infof("Create cache folder '%s'", opts.Path) + if err := os.Mkdir(opts.Path, os.ModePerm); err != nil { + return nil, err + } + } + + values := make(map[string][]byte, 0) + busy := make(map[string]*sync.Mutex, 0) + + // Go through every file an save its name in the map. The content of the file + // is loaded when needed. This makes sure that we don't have to read + // the directory content each time the user wants data that's not yet loaded. + for _, info := range fileInfos { + if !info.IsDir() { + values[info.Name()] = nil + } + } + + hash := sha256.New() + + mutex := &sync.Mutex{} + + c := &Cache{ + folder: opts.Path, + hash: hash, + knownValues: values, + busyValues: busy, + mutex: mutex, + maxSize: opts.MaxSize, + ttl: opts.TTL, + } + + go func() { + ticker := time.NewTicker(c.ttl) + defer ticker.Stop() + for range ticker.C { + files, err := c.findFilesOlderThanTTL() + if err != nil { + continue + } + for _, file := range files { + err := c.deleteFromHash(file.Name()) + if err != nil { + continue + } + } + } + }() + + return c, nil +} + +// Returns true if the resource is found, and false otherwise. If the +// resource is busy, this method will hang until the resource is free. If +// the resource is not found, a lock indicating that the resource is busy will +// be returned. Once the resource Has been put into cache the busy lock *must* +// be unlocked to allow others to access the newly cached resource +func (c *Cache) Has(key string) (*sync.Mutex, bool) { + hashValue := calcHash(key) + + c.mutex.Lock() + defer c.mutex.Unlock() + + // If the resource is busy, wait for it to be free. This is the case if + // the resource is currently being cached as a result of another request. + // Also, release the lock on the cache to allow other readers while waiting + if lock, busy := c.busyValues[hashValue]; busy { + c.mutex.Unlock() + lock.Lock() + // just waiting in case lock was previously acquired + lock.Unlock() + c.mutex.Lock() + } + + // If a resource is in the shared cache, it can't be reserved. One can simply + // access it directly from the cache + if _, found := c.knownValues[hashValue]; found { + return nil, true + } + + // The resource is not in the cache, mark the resource as busy until it has + // been cached successfully. Unlocking lock is required! + lock := new(sync.Mutex) + lock.Lock() + c.busyValues[hashValue] = lock + return lock, false +} + +func (c *Cache) Get(key string) (*io.Reader, error) { + var response io.Reader + hashValue := calcHash(key) + + // Try to get content. Error if not found. + c.mutex.Lock() + content, ok := c.knownValues[hashValue] + c.mutex.Unlock() + if !ok && len(content) > 0 { + log.Debugf("Cache doesn't know key '%s'", hashValue) + return nil, fmt.Errorf("key '%s' is not known to cache", hashValue) + } + + log.Debugf("Cache has key '%s'", hashValue) + + // Key is known, but not loaded into RAM + if content == nil { + log.Debugf("Cache item '%s' known but is not stored in memory. Using file.", hashValue) + + file, err := os.Open(filepath.Join(c.folder, hashValue)) + if err != nil { + log.Errorf("Error reading cached file '%s': %s", hashValue, err) + // forget the cached item + _ = c.deleteFromHash(hashValue) + return nil, err + } + + response = file + + log.Debugf("Create reader from file %s", hashValue) + } else { // Key is known and data is already loaded to RAM + response = bytes.NewReader(content) + log.Debugf("Create reader from %d byte large cache content", len(content)) + } + + return &response, nil +} + +func (c *Cache) Delete(key string) error { + return c.deleteFromHash(calcHash(key)) +} + +func (c *Cache) deleteFromHash(hashValue string) error { + c.mutex.Lock() + defer c.mutex.Unlock() + + // If the resource is busy, wait for it to be free. This is the case if + // the resource is currently being cached as a result of another request. + // Also, release the lock on the cache to allow other readers while waiting + if lock, busy := c.busyValues[hashValue]; busy { + c.mutex.Unlock() + lock.Lock() + // just waiting in case lock was previously acquired + lock.Unlock() + c.mutex.Lock() + } + + delete(c.busyValues, hashValue) + delete(c.knownValues, hashValue) + + return os.Remove(filepath.Join(c.folder, hashValue)) +} + +func (c *Cache) findFilesOlderThanTTL() ([]fs.DirEntry, error) { + var files []fs.DirEntry + tmpfiles, err := os.ReadDir(c.folder) + if err != nil { + return files, err + } + + for _, file := range tmpfiles { + if file.Type().IsRegular() { + info, err := file.Info() + if err != nil { + return files, err + } + if time.Since(info.ModTime()) > c.ttl { + files = append(files, file) + } + } + } + return files, err +} + +// release is an internal method which atomically caches an item and unmarks +// the item as busy, if it was busy before. The busy lock *must* be unlocked +// elsewhere! +func (c *Cache) release(hashValue string, content []byte) { + c.mutex.Lock() + delete(c.busyValues, hashValue) + c.knownValues[hashValue] = content + c.mutex.Unlock() +} + +func (c *Cache) Put(key string, content *io.Reader, contentLength int64) error { + hashValue := calcHash(key) + + // Small enough to put it into the in-memory cache + if contentLength <= c.maxSize*1024*1024 { + buffer := &bytes.Buffer{} + _, err := io.Copy(buffer, *content) + if err != nil { + return err + } + + defer c.release(hashValue, buffer.Bytes()) + log.Debugf("Added %s into in-memory cache", hashValue) + + err = os.WriteFile(filepath.Join(c.folder, hashValue), buffer.Bytes(), 0644) + if err != nil { + return err + } + log.Debugf("Wrote content of entry %s into file", hashValue) + } else { // Too large for in-memory cache, just write to file + defer c.release(hashValue, nil) + log.Debugf("Added nil-entry for %s into in-memory cache", hashValue) + + file, err := os.Create(filepath.Join(c.folder, hashValue)) + if err != nil { + return err + } + + writer := bufio.NewWriter(file) + _, err = io.Copy(writer, *content) + if err != nil { + return err + } + log.Debugf("Wrote content of entry %s into file", hashValue) + } + + log.Debugf("Cache wrote content into '%s'", hashValue) + + return nil +} + +func calcHash(data string) string { + sha := sha256.Sum256([]byte(data)) + return hex.EncodeToString(sha[:]) +} diff --git a/go.mod b/go.mod index fb830c0..ef17dfb 100644 --- a/go.mod +++ b/go.mod @@ -1,11 +1,32 @@ module github.com/Kriechi/aws-s3-reverse-proxy +go 1.20 + require ( - github.com/aws/aws-sdk-go v1.38.25 - github.com/prometheus/client_golang v1.11.1 - github.com/sirupsen/logrus v1.8.1 - github.com/stretchr/testify v1.7.0 - gopkg.in/alecthomas/kingpin.v2 v2.2.6 + github.com/alecthomas/kingpin/v2 v2.3.2 + github.com/aws/aws-sdk-go v1.44.308 + github.com/prometheus/client_golang v1.16.0 + github.com/sirupsen/logrus v1.9.3 + github.com/stretchr/testify v1.8.4 + k8s.io/utils v0.0.0-20230726121419-3b25d923346b ) -go 1.16 +require ( + github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137 // indirect + github.com/beorn7/perks v1.0.1 // indirect + github.com/cespare/xxhash/v2 v2.2.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/golang/protobuf v1.5.3 // indirect + github.com/jmespath/go-jmespath v0.4.0 // indirect + github.com/kr/text v0.2.0 // indirect + github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/prometheus/client_model v0.3.0 // indirect + github.com/prometheus/common v0.42.0 // indirect + github.com/prometheus/procfs v0.10.1 // indirect + github.com/rogpeppe/go-internal v1.11.0 // indirect + github.com/xhit/go-str2duration/v2 v2.1.0 // indirect + golang.org/x/sys v0.10.0 // indirect + google.golang.org/protobuf v1.30.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/go.sum b/go.sum index 05b177d..116daec 100644 --- a/go.sum +++ b/go.sum @@ -1,164 +1,98 @@ -cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= -github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 h1:JYp7IbQjafoB+tBA3gMyHYHrpOtNuDiK/uB5uXxq5wM= -github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= -github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= -github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= -github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d h1:UQZhZ2O0vMHr2cI+DC1Mbh0TJxzA3RcLoMsFw+aXw7E= -github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho= -github.com/aws/aws-sdk-go v1.38.25 h1:aNjeh7+MON05cZPtZ6do+KxVT67jPOSQXANA46gOQao= -github.com/aws/aws-sdk-go v1.38.25/go.mod h1:hcU610XS61/+aQV88ixoOzUoG7v3b31pl2zKMmprdro= -github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= -github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= +github.com/alecthomas/kingpin/v2 v2.3.2 h1:H0aULhgmSzN8xQ3nX1uxtdlTHYoPLu5AhHxWrKI6ocU= +github.com/alecthomas/kingpin/v2 v2.3.2/go.mod h1:0gyi0zQnjuFk8xrkNKamJoyUo382HRL7ATRpFZCw6tE= +github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137 h1:s6gZFSlWYmbqAuRjVTiNNhvNRfY2Wxp9nhfyel4rklc= +github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137/go.mod h1:OMCwj8VM1Kc9e19TLln2VL61YJF0x1XFtfdL4JdbSyE= +github.com/aws/aws-sdk-go v1.44.308 h1:XKu+76UHsD5LaiU2Zb1q42uWakw80Az7x39jJXXahos= +github.com/aws/aws-sdk-go v1.44.308/go.mod h1:aVsgQcEevwlmQ7qHE9I3h+dtQgpqhFB+i8Phjh7fkwI= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= -github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY= -github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44= +github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= -github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= -github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY= -github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= -github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= -github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= -github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= -github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= -github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= -github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= -github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= -github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= -github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= -github.com/golang/protobuf v1.4.3 h1:JjCZWpVbqXDqFVmTfYWEVTMIYrL/NPdPSCHPJ0T/raM= -github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= -github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= +github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= +github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8= github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= -github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4= -github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= -github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= -github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= -github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= -github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM= -github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= -github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= -github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= -github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= -github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= -github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= -github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= -github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= -github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= -github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= -github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= -github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= -github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/matttproud/golang_protobuf_extensions v1.0.4 h1:mmDVorXM7PCGKw94cs5zkfA9PSy5pEvNWRP0ET0TIVo= +github.com/matttproud/golang_protobuf_extensions v1.0.4/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= -github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= -github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= -github.com/prometheus/client_golang v1.11.1 h1:+4eQaD7vAZ6DsfsxB15hbE0odUjGI5ARs9yskGu1v4s= -github.com/prometheus/client_golang v1.11.1/go.mod h1:Z6t4BnS23TR94PD6BsDNk8yVqroYurpAkEiz0P2BEV0= -github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= -github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/prometheus/client_model v0.2.0 h1:uq5h0d+GuxiXLJLNABMgp2qUWDPiLvgCzz2dUR+/W/M= -github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= -github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo= -github.com/prometheus/common v0.26.0 h1:iMAkS2TDoNWnKM+Kopnx/8tnEStIfpYA0ur0xQzzhMQ= -github.com/prometheus/common v0.26.0/go.mod h1:M7rCNAaPfAosfx8veZJCuw84e35h3Cfd9VFqTh1DIvc= -github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= -github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= -github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= -github.com/prometheus/procfs v0.6.0 h1:mxy4L2jP6qMonqmq+aTtOx1ifVWUgG/TAmntgbh3xv4= -github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= -github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= -github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= -github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= -github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE= -github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= +github.com/prometheus/client_golang v1.16.0 h1:yk/hx9hDbrGHovbci4BY+pRMfSuuat626eFsHb7tmT8= +github.com/prometheus/client_golang v1.16.0/go.mod h1:Zsulrv/L9oM40tJ7T815tM89lFEugiJ9HzIqaAx4LKc= +github.com/prometheus/client_model v0.3.0 h1:UBgGFHqYdG/TPFD1B1ogZywDqEkwp3fBMvqdiQ7Xew4= +github.com/prometheus/client_model v0.3.0/go.mod h1:LDGWKZIo7rky3hgvBe+caln+Dr3dPggB5dvjtD7w9+w= +github.com/prometheus/common v0.42.0 h1:EKsfXEYo4JpWMHH5cg+KOUWeuJSov1Id8zGR8eeI1YM= +github.com/prometheus/common v0.42.0/go.mod h1:xBwqVerjNdUDjgODMpudtOMwlOwf2SaTr1yjz4b7Zbc= +github.com/prometheus/procfs v0.10.1 h1:kYK1Va/YMlutzCGazswoHKo//tZVlFpKYh+PymziUAg= +github.com/prometheus/procfs v0.10.1/go.mod h1:nwNm2aOCAYw8uTR/9bWRREkZFxAUcWzPHWJq+XBB/FM= +github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= +github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= +github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= +github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= -github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/xhit/go-str2duration/v2 v2.1.0 h1:lxklc02Drh6ynqX+DdPyp5pCKLUQpRT8bp8Ydu2Bstc= +github.com/xhit/go-str2duration/v2 v2.1.0/go.mod h1:ohY8p+0f07DiV6Em5LKB0s2YpLtXVyJfNt1+BlmyAsU= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= -golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.1.0/go.mod h1:Cx3nUiGt4eDBEyega/BKRp+/AlGL8hYe7U9odMt2Cco= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210603081109-ebe580a85c40 h1:JWgyZ1qgdTaF3N3oxC+MdTV7qvEEgHo3otj+HB5CM7Q= -golang.org/x/sys v0.0.0-20210603081109-ebe580a85c40/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.10.0 h1:SqMFp9UcQJZa+pmYuAKjd9xq1f0j5rLcDIk0mj4qAsA= +golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= -google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= -google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= -google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= -google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= -google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= -google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.26.0-rc.1 h1:7QnIQpGRHE5RnLKnESfDoxm2dTapTZua5a0kS0A+VXQ= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= -gopkg.in/alecthomas/kingpin.v2 v2.2.6 h1:jMFz6MfLP0/4fUyZle81rXUoxOBFi19VUFKVDOQfozc= -gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= +google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng= +google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= -gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU= -gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +k8s.io/utils v0.0.0-20230726121419-3b25d923346b h1:sgn3ZU783SCgtaSJjpcVVlRqd6GSnlTLKgpAAttJvpI= +k8s.io/utils v0.0.0-20230726121419-3b25d923346b/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= diff --git a/main.go b/main.go index 3ba6826..1765b6f 100644 --- a/main.go +++ b/main.go @@ -1,124 +1,18 @@ package main import ( - "fmt" - "net" "net/http" "strings" _ "net/http/pprof" + "github.com/Kriechi/aws-s3-reverse-proxy/proxy" "github.com/prometheus/client_golang/prometheus/promhttp" - - "github.com/aws/aws-sdk-go/aws/credentials" - v4 "github.com/aws/aws-sdk-go/aws/signer/v4" log "github.com/sirupsen/logrus" - "gopkg.in/alecthomas/kingpin.v2" ) -// Options for aws-s3-reverse-proxy command line arguments -type Options struct { - Debug bool - ListenAddr string - MetricsListenAddr string - PprofListenAddr string - AllowedSourceEndpoint string - AllowedSourceSubnet []string - AwsCredentials []string - Region string - UpstreamInsecure bool - UpstreamEndpoint string - CertFile string - KeyFile string -} - -// NewOptions defines and parses the raw command line arguments -func NewOptions() Options { - var opts Options - kingpin.Flag("verbose", "enable additional logging (env - VERBOSE)").Envar("VERBOSE").Short('v').BoolVar(&opts.Debug) - kingpin.Flag("listen-addr", "address:port to listen for requests on (env - LISTEN_ADDR)").Default(":8099").Envar("LISTEN_ADDR").StringVar(&opts.ListenAddr) - kingpin.Flag("metrics-listen-addr", "address:port to listen for Prometheus metrics on, empty to disable (env - METRICS_LISTEN_ADDR)").Default("").Envar("METRICS_LISTEN_ADDR").StringVar(&opts.MetricsListenAddr) - kingpin.Flag("pprof-listen-addr", "address:port to listen for pprof on, empty to disable (env - PPROF_LISTEN_ADDR)").Default("").Envar("PPROF_LISTEN_ADDR").StringVar(&opts.PprofListenAddr) - kingpin.Flag("allowed-endpoint", "allowed endpoint (Host header) to accept for incoming requests (env - ALLOWED_ENDPOINT)").Envar("ALLOWED_ENDPOINT").Required().PlaceHolder("my.host.example.com:8099").StringVar(&opts.AllowedSourceEndpoint) - kingpin.Flag("allowed-source-subnet", "allowed source IP addresses with netmask (env - ALLOWED_SOURCE_SUBNET)").Default("127.0.0.1/32").Envar("ALLOWED_SOURCE_SUBNET").StringsVar(&opts.AllowedSourceSubnet) - kingpin.Flag("aws-credentials", "set of AWS credentials (env - AWS_CREDENTIALS)").PlaceHolder("\"AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY\"").Envar("AWS_CREDENTIALS").StringsVar(&opts.AwsCredentials) - kingpin.Flag("aws-region", "send requests to this AWS S3 region (env - AWS_REGION)").Envar("AWS_REGION").Default("eu-central-1").StringVar(&opts.Region) - kingpin.Flag("upstream-insecure", "use insecure HTTP for upstream connections (env - UPSTREAM_INSECURE)").Envar("UPSTREAM_INSECURE").BoolVar(&opts.UpstreamInsecure) - kingpin.Flag("upstream-endpoint", "use this S3 endpoint for upstream connections, instead of public AWS S3 (env - UPSTREAM_ENDPOINT)").Envar("UPSTREAM_ENDPOINT").StringVar(&opts.UpstreamEndpoint) - kingpin.Flag("cert-file", "path to the certificate file (env - CERT_FILE)").Envar("CERT_FILE").Default("").StringVar(&opts.CertFile) - kingpin.Flag("key-file", "path to the private key file (env - KEY_FILE)").Envar("KEY_FILE").Default("").StringVar(&opts.KeyFile) - kingpin.Parse() - return opts -} - -// NewAwsS3ReverseProxy parses all options and creates a new HTTP Handler -func NewAwsS3ReverseProxy(opts Options) (*Handler, error) { - log.SetLevel(log.InfoLevel) - if opts.Debug { - log.SetLevel(log.DebugLevel) - } - - scheme := "https" - if opts.UpstreamInsecure { - scheme = "http" - } - - var parsedAllowedSourceSubnet []*net.IPNet - for _, sourceSubnet := range opts.AllowedSourceSubnet { - _, subnet, err := net.ParseCIDR(sourceSubnet) - if err != nil { - return nil, fmt.Errorf("Invalid allowed source subnet: %v", sourceSubnet) - } - parsedAllowedSourceSubnet = append(parsedAllowedSourceSubnet, subnet) - } - - parsedAwsCredentials := make(map[string]string) - for _, cred := range opts.AwsCredentials { - d := strings.Split(cred, ",") - if len(d) != 2 || len(d[0]) < 16 || len(d[1]) < 1 { - return nil, fmt.Errorf("Invalid AWS credentials. Did you separate them with a ',' or are they too short?") - } - parsedAwsCredentials[d[0]] = d[1] - } - - signers := make(map[string]*v4.Signer) - for accessKeyID, secretAccessKey := range parsedAwsCredentials { - signers[accessKeyID] = v4.NewSigner(credentials.NewStaticCredentialsFromCreds(credentials.Value{ - AccessKeyID: accessKeyID, - SecretAccessKey: secretAccessKey, - })) - } - - handler := &Handler{ - Debug: opts.Debug, - UpstreamScheme: scheme, - UpstreamEndpoint: opts.UpstreamEndpoint, - AllowedSourceEndpoint: opts.AllowedSourceEndpoint, - AllowedSourceSubnet: parsedAllowedSourceSubnet, - AWSCredentials: parsedAwsCredentials, - Signers: signers, - } - return handler, nil -} - func main() { - opts := NewOptions() - handler, err := NewAwsS3ReverseProxy(opts) - if err != nil { - log.Fatal(err) - } - - if len(handler.UpstreamEndpoint) > 0 { - log.Infof("Sending requests to upstream AWS S3 to endpoint %s://%s.", handler.UpstreamScheme, handler.UpstreamEndpoint) - } else { - log.Infof("Auto-detecting S3 endpoint based on region: %s://s3.{region}.amazonaws.com", handler.UpstreamScheme) - } - - for _, subnet := range handler.AllowedSourceSubnet { - log.Infof("Allowing connections from %v.", subnet) - } - log.Infof("Accepting incoming requests for this endpoint: %v", handler.AllowedSourceEndpoint) - log.Infof("Parsed %d AWS credential sets.", len(handler.AWSCredentials)) + opts := proxy.NewOptions() if len(opts.PprofListenAddr) > 0 && len(strings.Split(opts.PprofListenAddr, ":")) == 2 { // avoid leaking pprof to the main application http servers @@ -133,13 +27,18 @@ func main() { }() } - var wrappedHandler http.Handler = handler + p, err := proxy.NewAwsS3ReverseProxy(opts) + if err != nil { + log.Fatal(err) + } + + var wrappedHandler http.Handler = p if len(opts.MetricsListenAddr) > 0 && len(strings.Split(opts.MetricsListenAddr, ":")) == 2 { metricsHandler := http.NewServeMux() metricsHandler.Handle("/metrics", promhttp.Handler()) log.Infof("Listening for secure Prometheus metrics on %s", opts.MetricsListenAddr) - wrappedHandler = wrapPrometheusMetrics(handler) + wrappedHandler = proxy.WrapPrometheusMetrics(p) go func() { log.Fatal( diff --git a/handler.go b/proxy/handler.go similarity index 62% rename from handler.go rename to proxy/handler.go index 9bd8b0f..0f0caf4 100644 --- a/handler.go +++ b/proxy/handler.go @@ -1,24 +1,35 @@ -package main +package proxy import ( "bytes" "crypto/subtle" + "errors" "fmt" - "io/ioutil" + "io" "net" "net/http" "net/http/httputil" "net/url" + "os" "regexp" "strings" "time" + "github.com/Kriechi/aws-s3-reverse-proxy/cache" + "github.com/Kriechi/aws-s3-reverse-proxy/transport" + "github.com/aws/aws-sdk-go/aws/credentials" v4 "github.com/aws/aws-sdk-go/aws/signer/v4" log "github.com/sirupsen/logrus" + "k8s.io/utils/strings/slices" ) -var awsAuthorizationCredentialRegexp = regexp.MustCompile("Credential=([a-zA-Z0-9]+)/[0-9]+/([a-z]+-?[a-z]+-?[0-9]+)/s3/aws4_request") -var awsAuthorizationSignedHeadersRegexp = regexp.MustCompile("SignedHeaders=([a-zA-Z0-9;-]+)") +var ( + ErrInvalidEndpoint = errors.New("invalid endpoint specified") + ErrInvalidSubnet = errors.New("invalid allowed source subnet") + ErrInvalidCreds = errors.New("invalid AWS credentials") + awsAuthorizationCredentialRegexp = regexp.MustCompile("Credential=([a-zA-Z0-9]+)/[0-9]+/([a-z]+-?[a-z]+-?[0-9]+)/s3/aws4_request") + awsAuthorizationSignedHeadersRegexp = regexp.MustCompile("SignedHeaders=([a-zA-Z0-9;-]+)") +) // Handler is a special handler that re-signs any AWS S3 request and sends it upstream type Handler struct { @@ -32,14 +43,11 @@ type Handler struct { UpstreamEndpoint string // Allowed endpoint, i.e., Host header to accept incoming requests from - AllowedSourceEndpoint string + AllowedSourceEndpoints []string // Allowed source IPs and subnets for incoming requests AllowedSourceSubnet []*net.IPNet - // AWS Credentials, AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY - AWSCredentials map[string]string - // AWS Signature v4 Signers map[string]*v4.Signer @@ -47,6 +55,104 @@ type Handler struct { Proxy *httputil.ReverseProxy } +// NewAwsS3ReverseProxy parses all options and creates a new HTTP Handler +func NewAwsS3ReverseProxy(opts Options) (http.Handler, error) { + log.SetLevel(log.InfoLevel) + if opts.Debug { + log.SetLevel(log.DebugLevel) + } + + h, err := newHandler(&opts) + if err != nil { + return nil, err + } + + h.Proxy = httputil.NewSingleHostReverseProxy(&url.URL{Scheme: h.UpstreamScheme, Host: h.UpstreamEndpoint}) + + if opts.CachePath != "" { + tripper, err := transport.NewTriepper(cache.Options{ + Path: opts.CachePath, + MaxSize: opts.MaxCacheItemSize, + TTL: opts.CacheTTL, + }) + if err != nil { + return nil, err + } + h.Proxy.Transport = tripper + } + + return h, nil +} + +func newHandler(opts *Options) (*Handler, error) { + scheme := "https" + if opts.UpstreamInsecure { + scheme = "http" + } + + var parsedAllowedSourceSubnet []*net.IPNet + for _, sourceSubnet := range opts.AllowedSourceSubnet { + _, subnet, err := net.ParseCIDR(sourceSubnet) + if err != nil { + return nil, fmt.Errorf("%w: %v", ErrInvalidSubnet, sourceSubnet) + } + parsedAllowedSourceSubnet = append(parsedAllowedSourceSubnet, subnet) + } + + signers := make(map[string]*v4.Signer) + for _, cred := range opts.AwsCredentials { + d := strings.SplitN(cred, ",", 2) + if len(d) != 2 || len(d[0]) < 16 || len(d[1]) < 1 { + return nil, fmt.Errorf("%w; Did you separate them with a ',' or are they too short?", ErrInvalidCreds) + } + signers[d[0]] = v4.NewSigner(credentials.NewStaticCredentialsFromCreds(credentials.Value{ + AccessKeyID: d[0], + SecretAccessKey: d[1], + })) + } + + if os.Getenv("AWS_ACCESS_KEY_ID") != "" && os.Getenv("AWS_SECRET_ACCESS_KEY") != "" { + signers[os.Getenv("AWS_ACCESS_KEY_ID")] = v4.NewSigner(credentials.NewStaticCredentialsFromCreds(credentials.Value{ + AccessKeyID: os.Getenv("AWS_ACCESS_KEY_ID"), + SecretAccessKey: os.Getenv("AWS_SECRET_ACCESS_KEY"), + SessionToken: os.Getenv("AWS_SESSION_TOKEN"), + })) + } + + h := &Handler{ + Debug: opts.Debug, + UpstreamScheme: scheme, + UpstreamEndpoint: opts.UpstreamEndpoint, + AllowedSourceSubnet: parsedAllowedSourceSubnet, + Signers: signers, + } + + if len(opts.UpstreamEndpoint) > 0 { + log.Infof("Sending requests to upstream AWS S3 to endpoint %s://%s.", scheme, h.UpstreamEndpoint) + } else { + log.Infof("Auto-detecting S3 endpoint based on region: %s://s3.{region}.amazonaws.com", scheme) + } + + for _, subnet := range opts.AllowedSourceSubnet { + log.Infof("Allowing connections from %v.", subnet) + } + for _, endpoint := range opts.AllowedSourceEndpoints { + u, err := url.Parse(endpoint) + if err != nil { + return nil, err + } + host := u.Host + if host == "" && u.Path != "" { + host = u.Path + } + h.AllowedSourceEndpoints = append(h.AllowedSourceEndpoints, host) + log.Infof("Accepting incoming requests for this endpoint: %v", u.Host) + } + log.Infof("Parsed %d AWS credential sets.", len(h.Signers)) + + return h, nil +} + func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { proxyReq, err := h.buildUpstreamRequest(r) if err != nil { @@ -60,10 +166,7 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } - url := url.URL{Scheme: proxyReq.URL.Scheme, Host: proxyReq.Host} - proxy := httputil.NewSingleHostReverseProxy(&url) - proxy.FlushInterval = 1 - proxy.ServeHTTP(w, proxyReq) + h.Proxy.ServeHTTP(w, proxyReq) } func (h *Handler) sign(signer *v4.Signer, req *http.Request, region string) error { @@ -73,7 +176,7 @@ func (h *Handler) sign(signer *v4.Signer, req *http.Request, region string) erro func (h *Handler) signWithTime(signer *v4.Signer, req *http.Request, region string, signTime time.Time) error { body := bytes.NewReader([]byte{}) if req.Body != nil { - b, err := ioutil.ReadAll(req.Body) + b, err := io.ReadAll(req.Body) if err != nil { return err } @@ -94,6 +197,17 @@ func copyHeaderWithoutOverwrite(dst http.Header, src http.Header) { } } +func (h *Handler) validateSourceEndpoint(req *http.Request) error { + host := req.URL.Host + if host == "" { + host = req.Host + } + if !slices.Contains(h.AllowedSourceEndpoints, host) { + return fmt.Errorf("%w; %s is not allowed", ErrInvalidEndpoint, req.URL.Host) + } + return nil +} + func (h *Handler) validateIncomingSourceIP(req *http.Request) error { allowed := false for _, subnet := range h.AllowedSourceSubnet { @@ -117,7 +231,7 @@ func (h *Handler) validateIncomingHeaders(req *http.Request) (string, string, er authorizationHeader := req.Header["Authorization"] if len(authorizationHeader) != 1 { - return "", "", fmt.Errorf("Authorization header missing or set multiple times: %v", req) + return "", "", fmt.Errorf("authorization header missing or set multiple times: %v", req) } match := awsAuthorizationCredentialRegexp.FindStringSubmatch(authorizationHeader[0]) if len(match) != 3 { @@ -127,7 +241,7 @@ func (h *Handler) validateIncomingHeaders(req *http.Request) (string, string, er region := match[2] // Validate the received Credential (ACCESS_KEY_ID) is allowed - for accessKeyID := range h.AWSCredentials { + for accessKeyID := range h.Signers { if subtle.ConstantTimeCompare([]byte(receivedAccessKeyID), []byte(accessKeyID)) == 1 { return accessKeyID, region, nil } @@ -153,7 +267,7 @@ func (h *Handler) generateFakeIncomingRequest(signer *v4.Signer, req *http.Reque // Delete a potentially double-added header fakeReq.Header.Del("host") - fakeReq.Host = h.AllowedSourceEndpoint + fakeReq.Host = req.Host // The X-Amz-Date header contains a timestamp, such as: 20190929T182805Z signTime, err := time.Parse("20060102T150405Z", req.Header["X-Amz-Date"][0]) @@ -205,8 +319,12 @@ func (h *Handler) assembleUpstreamReq(signer *v4.Signer, req *http.Request, regi // Do validates the incoming request and create a new request for an upstream server func (h *Handler) buildUpstreamRequest(req *http.Request) (*http.Request, error) { // Ensure the request was sent from an allowed IP address - err := h.validateIncomingSourceIP(req) - if err != nil { + if err := h.validateIncomingSourceIP(req); err != nil { + return nil, err + } + + // Ensure the request was sent from an allowed endpoint + if err := h.validateSourceEndpoint(req); err != nil { return nil, err } diff --git a/handler_test.go b/proxy/handler_test.go similarity index 88% rename from handler_test.go rename to proxy/handler_test.go index 8bfc3af..f7fd2d9 100644 --- a/handler_test.go +++ b/proxy/handler_test.go @@ -1,9 +1,8 @@ -package main +package proxy import ( "bytes" "fmt" - "net" "net/http" "net/http/httptest" "net/url" @@ -20,26 +19,34 @@ import ( // log.SetOutput(ioutil.Discard) // } -func newTestProxy(t *testing.T) *Handler { +type optsFunc func(*Options) + +func newTestProxy(t *testing.T, of ...optsFunc) http.Handler { thf := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello, client") }) - return newTestProxyWithHandler(t, &thf) + return newTestProxyWithHandler(t, &thf, of...) } -func newTestProxyWithHandler(t *testing.T, thf *http.HandlerFunc) *Handler { +func newTestProxyWithHandler(t *testing.T, thf *http.HandlerFunc, of ...optsFunc) http.Handler { ts := httptest.NewServer(thf) tsURL, _ := url.Parse(ts.URL) - h, err := NewAwsS3ReverseProxy(Options{ - Debug: true, - AllowedSourceEndpoint: "foobar.example.com", - AllowedSourceSubnet: []string{"0.0.0.0/0"}, - AwsCredentials: []string{"fooooooooooooooo,bar"}, - Region: "eu-test-1", - UpstreamInsecure: true, - UpstreamEndpoint: tsURL.Host, - }) + o := Options{ + Debug: true, + AllowedSourceEndpoints: []string{"foobar.example.com"}, + AllowedSourceSubnet: []string{"0.0.0.0/0"}, + AwsCredentials: []string{"fooooooooooooooo,bar"}, + Region: "eu-test-1", + UpstreamInsecure: true, + UpstreamEndpoint: tsURL.Host, + } + + for _, f := range of { + f(&o) + } + + h, err := NewAwsS3ReverseProxy(o) assert.Nil(t, err) return h } @@ -58,7 +65,7 @@ func signRequest(r *http.Request) { AccessKeyID: "fooooooooooooooo", SecretAccessKey: "bar", })) - signer.Sign(r, body, "s3", "eu-test-1", signTime) + _, _ = signer.Sign(r, body, "s3", "eu-test-1", signTime) } func verifySignature(w http.ResponseWriter, r *http.Request) { @@ -76,7 +83,7 @@ func verifySignature(w http.ResponseWriter, r *http.Request) { AccessKeyID: "fooooooooooooooo", SecretAccessKey: "bar", })) - signer.Sign(r, body, "s3", "eu-test-1", signTime) + _, _ = signer.Sign(r, body, "s3", "eu-test-1", signTime) expectedAuthorization := r.Header["Authorization"][0] // verify signature @@ -106,7 +113,7 @@ func TestHandlerMissingAuthorization(t *testing.T) { resp := httptest.NewRecorder() h.ServeHTTP(resp, req) assert.Equal(t, 400, resp.Code) - assert.Contains(t, resp.Body.String(), "Authorization header missing or set multiple times") + assert.Contains(t, resp.Body.String(), "authorization header missing or set multiple times") } func TestHandlerMissingCredential(t *testing.T) { @@ -157,13 +164,13 @@ func TestHandlerInvalidCredential(t *testing.T) { } func TestHandlerInvalidSourceSubnet(t *testing.T) { - h := newTestProxy(t) - _, newNet, _ := net.ParseCIDR("172.27.42.0/24") - h.AllowedSourceSubnet = []*net.IPNet{newNet} + h := newTestProxy(t, func(o *Options) { + o.AllowedSourceSubnet = []string{"172.27.42.0/24"} + }) req := httptest.NewRequest(http.MethodGet, "http://foobar.example.com", nil) req.Header.Set("X-Amz-Date", "20060102T150405Z") - req.Header.Set("Authorization", "AWS4-HMAC-SHA256 Credential=XXXooooooooooooo/20060102/eu-test-1/s3/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=a0d5e0c0924c1f9298c5f2a3925e202657bf1e239a1d6856235cbe0702855334") // signature computed manually for this test case + req.Header.Set("Authorization", "AWS4-HMAC-SHA256 Credential=fooooooooooooooo/20060102/eu-test-1/s3/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=a0d5e0c0924c1f9298c5f2a3925e202657bf1e239a1d6856235cbe0702855334") // signature computed manually for this test case resp := httptest.NewRecorder() h.ServeHTTP(resp, req) assert.Equal(t, 400, resp.Code) diff --git a/metrics.go b/proxy/metrics.go similarity index 96% rename from metrics.go rename to proxy/metrics.go index d298d45..e83a5f8 100644 --- a/metrics.go +++ b/proxy/metrics.go @@ -1,4 +1,4 @@ -package main +package proxy import ( "net/http" @@ -7,7 +7,7 @@ import ( "github.com/prometheus/client_golang/prometheus/promhttp" ) -func wrapPrometheusMetrics(handler http.Handler) http.Handler { +func WrapPrometheusMetrics(handler http.Handler) http.HandlerFunc { counter := prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "s3proxy_api_requests_total", diff --git a/main_test.go b/proxy/new_test.go similarity index 56% rename from main_test.go rename to proxy/new_test.go index 1e119ef..8b06e6f 100644 --- a/main_test.go +++ b/proxy/new_test.go @@ -1,28 +1,36 @@ -package main +package proxy import ( + "errors" + "os" "testing" "github.com/stretchr/testify/assert" ) func TestParseOptions(t *testing.T) { - h, err := NewAwsS3ReverseProxy(Options{ - AllowedSourceEndpoint: "foobar.endpoint.example.com", - AllowedSourceSubnet: []string{"127.0.0.1/32", "192.168.1.0/24"}, - AwsCredentials: []string{"fooooooooooooooo,bar", "baaaaaaaaaaaaaar,baz"}, - Region: "eu-test-1", + os.Unsetenv("AWS_ACCESS_KEY_ID") + os.Unsetenv("AWS_SECRET_ACCESS_KEY") + h, err := newHandler(&Options{ + AllowedSourceEndpoints: []string{"foobar.endpoint.example.com"}, + AllowedSourceSubnet: []string{"127.0.0.1/32", "192.168.1.0/24"}, + AwsCredentials: []string{"fooooooooooooooo,bar", "baaaaaaaaaaaaaar,baz"}, + Region: "eu-test-1", }) assert.Nil(t, err) assert.Equal(t, "https", h.UpstreamScheme) assert.Equal(t, "", h.UpstreamEndpoint) - assert.Equal(t, "foobar.endpoint.example.com", h.AllowedSourceEndpoint) + assert.Equal(t, "foobar.endpoint.example.com", h.AllowedSourceEndpoints[0]) assert.Len(t, h.AllowedSourceSubnet, 2) assert.Equal(t, "127.0.0.1/32", h.AllowedSourceSubnet[0].String()) assert.Equal(t, "192.168.1.0/24", h.AllowedSourceSubnet[1].String()) - assert.Len(t, h.AWSCredentials, 2) - assert.Equal(t, "bar", h.AWSCredentials["fooooooooooooooo"]) - assert.Equal(t, "baz", h.AWSCredentials["baaaaaaaaaaaaaar"]) + assert.Len(t, h.Signers, 2) + creds, err := h.Signers["fooooooooooooooo"].Credentials.Get() + assert.Nil(t, err) + assert.Equal(t, "bar", creds.SecretAccessKey) + creds, err = h.Signers["baaaaaaaaaaaaaar"].Credentials.Get() + assert.Nil(t, err) + assert.Equal(t, "baz", creds.SecretAccessKey) assert.Len(t, h.Signers, 2) assert.Contains(t, h.Signers, "fooooooooooooooo") assert.Contains(t, h.Signers, "baaaaaaaaaaaaaar") @@ -32,47 +40,47 @@ func TestParseOptionsBrokenSubnets(t *testing.T) { _, err := NewAwsS3ReverseProxy(Options{ AllowedSourceSubnet: []string{"foobar"}, }) - assert.Contains(t, err.Error(), "Invalid allowed source subnet") + assert.True(t, errors.Is(err, ErrInvalidSubnet)) _, err = NewAwsS3ReverseProxy(Options{ AllowedSourceSubnet: []string{""}, }) - assert.Contains(t, err.Error(), "Invalid allowed source subnet") + assert.True(t, errors.Is(err, ErrInvalidSubnet)) _, err = NewAwsS3ReverseProxy(Options{ AllowedSourceSubnet: []string{"127.0.0.1/XXX"}, }) - assert.Contains(t, err.Error(), "Invalid allowed source subnet") + assert.True(t, errors.Is(err, ErrInvalidSubnet)) _, err = NewAwsS3ReverseProxy(Options{ AllowedSourceSubnet: []string{"127.0.0.1"}, }) - assert.Contains(t, err.Error(), "Invalid allowed source subnet") + assert.True(t, errors.Is(err, ErrInvalidSubnet)) _, err = NewAwsS3ReverseProxy(Options{ AllowedSourceSubnet: []string{"256.0.0.1"}, }) - assert.Contains(t, err.Error(), "Invalid allowed source subnet") + assert.True(t, errors.Is(err, ErrInvalidSubnet)) } func TestParseOptionsBrokenAWSCredentials(t *testing.T) { _, err := NewAwsS3ReverseProxy(Options{ AwsCredentials: []string{""}, }) - assert.Contains(t, err.Error(), "Invalid AWS credentials") + assert.True(t, errors.Is(err, ErrInvalidCreds)) _, err = NewAwsS3ReverseProxy(Options{ AwsCredentials: []string{"foobar"}, }) - assert.Contains(t, err.Error(), "Invalid AWS credentials") + assert.True(t, errors.Is(err, ErrInvalidCreds)) _, err = NewAwsS3ReverseProxy(Options{ AwsCredentials: []string{"foooooooooooobar"}, }) - assert.Contains(t, err.Error(), "Invalid AWS credentials") + assert.True(t, errors.Is(err, ErrInvalidCreds)) _, err = NewAwsS3ReverseProxy(Options{ AwsCredentials: []string{"foooooooooooobar,"}, }) - assert.Contains(t, err.Error(), "Invalid AWS credentials") + assert.True(t, errors.Is(err, ErrInvalidCreds)) } diff --git a/proxy/options.go b/proxy/options.go new file mode 100644 index 0000000..2b4be0a --- /dev/null +++ b/proxy/options.go @@ -0,0 +1,48 @@ +package proxy + +import ( + "time" + + "github.com/alecthomas/kingpin/v2" +) + +// Options for aws-s3-reverse-proxy command line arguments +type Options struct { + Debug bool + ListenAddr string + MetricsListenAddr string + PprofListenAddr string + AllowedSourceEndpoints []string + AllowedSourceSubnet []string + AwsCredentials []string + Region string + UpstreamInsecure bool + UpstreamEndpoint string + CertFile string + KeyFile string + MaxCacheItemSize int64 + CachePath string + CacheTTL time.Duration +} + +// NewOptions defines and parses the raw command line arguments +func NewOptions() Options { + var opts Options + kingpin.Flag("verbose", "enable additional logging (env - VERBOSE)").Envar("VERBOSE").Short('v').BoolVar(&opts.Debug) + kingpin.Flag("listen-addr", "address:port to listen for requests on (env - LISTEN_ADDR)").Default(":8099").Envar("LISTEN_ADDR").StringVar(&opts.ListenAddr) + kingpin.Flag("metrics-listen-addr", "address:port to listen for Prometheus metrics on, empty to disable (env - METRICS_LISTEN_ADDR)").Default("").Envar("METRICS_LISTEN_ADDR").StringVar(&opts.MetricsListenAddr) + kingpin.Flag("pprof-listen-addr", "address:port to listen for pprof on, empty to disable (env - PPROF_LISTEN_ADDR)").Default("").Envar("PPROF_LISTEN_ADDR").StringVar(&opts.PprofListenAddr) + kingpin.Flag("allowed-endpoint", "allowed endpoint (Host header) to accept for incoming requests (env - ALLOWED_ENDPOINT)").Envar("ALLOWED_ENDPOINT").Required().PlaceHolder("my.host.example.com:8099").StringsVar(&opts.AllowedSourceEndpoints) + kingpin.Flag("allowed-source-subnet", "allowed source IP addresses with netmask (env - ALLOWED_SOURCE_SUBNET)").Default("127.0.0.1/32").Envar("ALLOWED_SOURCE_SUBNET").StringsVar(&opts.AllowedSourceSubnet) + kingpin.Flag("aws-credentials", "set of AWS credentials (env - AWS_CREDENTIALS)").PlaceHolder("\"AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY\"").Envar("AWS_CREDENTIALS").StringsVar(&opts.AwsCredentials) + kingpin.Flag("aws-region", "send requests to this AWS S3 region (env - AWS_REGION)").Envar("AWS_REGION").Default("eu-central-1").StringVar(&opts.Region) + kingpin.Flag("upstream-insecure", "use insecure HTTP for upstream connections (env - UPSTREAM_INSECURE)").Envar("UPSTREAM_INSECURE").BoolVar(&opts.UpstreamInsecure) + kingpin.Flag("upstream-endpoint", "use this S3 endpoint for upstream connections, instead of public AWS S3 (env - UPSTREAM_ENDPOINT)").Envar("UPSTREAM_ENDPOINT").StringVar(&opts.UpstreamEndpoint) + kingpin.Flag("cert-file", "path to the certificate file (env - CERT_FILE)").Envar("CERT_FILE").Default("").StringVar(&opts.CertFile) + kingpin.Flag("key-file", "path to the private key file (env - KEY_FILE)").Envar("KEY_FILE").Default("").StringVar(&opts.KeyFile) + kingpin.Flag("max-cache-items", "max item size to cache in memory, in Mb (env MAX_CACHE_ITEMS)").Envar("MAX_CACHE_ITEMS").Default("500").Int64Var(&opts.MaxCacheItemSize) + kingpin.Flag("cache-path", "path to store the cache (env CACHE_PATH)").Envar("CACHE_PATH").Default("").StringVar(&opts.CachePath) + kingpin.Flag("cache-ttl", "how long to cache for (env CACHE_TTL)").Envar("CACHE_TTL").Default("1h").DurationVar(&opts.CacheTTL) + kingpin.Parse() + return opts +} diff --git a/transport/transport.go b/transport/transport.go new file mode 100644 index 0000000..7bf46cb --- /dev/null +++ b/transport/transport.go @@ -0,0 +1,80 @@ +package transport + +import ( + "bufio" + "bytes" + "io" + "net/http" + "net/http/httputil" + + log "github.com/sirupsen/logrus" + + "github.com/Kriechi/aws-s3-reverse-proxy/cache" +) + +type Tripper struct { + transport http.RoundTripper + client *http.Client + cache *cache.Cache +} + +func NewTriepper(opts cache.Options) (*Tripper, error) { + cache, err := cache.CreateCache(opts) + if err != nil { + return nil, err + } + + return &Tripper{ + transport: http.DefaultTransport, + client: http.DefaultClient, + cache: cache, + }, nil +} + +// Implement the RoundTripper interface +func (t *Tripper) RoundTrip(r *http.Request) (*http.Response, error) { + select { + case <-r.Context().Done(): + { + return nil, r.Context().Err() + } + default: + } + log.Infof("requested: %s", r.URL.String()) + if r.Method != http.MethodGet { + return t.transport.RoundTrip(r) + } + key := r.URL.Path + "?" + r.URL.RawQuery + // Cache miss, Load data from requested URL and add to cache + if busy, ok := t.cache.Has(key); !ok { + defer busy.Unlock() + response, err := t.client.Do(r) + if err != nil { + return nil, err + } + defer response.Body.Close() + + dump, err := httputil.DumpResponse(response, true) + if err != nil { + return nil, err + } + var reader io.Reader + reader = bytes.NewReader(dump) + + err = t.cache.Put(key, &reader, response.ContentLength) + if err != nil { + return response, err + } + return response, nil + } + + log.Info("serving from cache") + + // Cache hit, return cached response + content, err := t.cache.Get(key) + if err != nil { + return nil, err + } + + return http.ReadResponse(bufio.NewReader(*content), r) +}