From 50690d1ac7d135577efb278ae8f01b034f81f942 Mon Sep 17 00:00:00 2001 From: maxlerebourg Date: Sat, 4 Mar 2023 11:51:54 +0100 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20handle=20redis=20password=20(#87)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * ✨ handle redis password * 🍱 fix version --- bouncer.go | 8 ++- go.mod | 2 +- go.sum | 4 +- pkg/cache/cache.go | 4 +- pkg/configuration/configuration.go | 2 + .../maxlerebourg/simpleredis/README.md | 29 ++++++++- .../maxlerebourg/simpleredis/simpleredis.go | 64 +++++++++++++------ vendor/modules.txt | 2 +- 8 files changed, 86 insertions(+), 29 deletions(-) diff --git a/bouncer.go b/bouncer.go index c2b416c..9353a63 100644 --- a/bouncer.go +++ b/bouncer.go @@ -141,13 +141,12 @@ func New(ctx context.Context, next http.Handler, config *configuration.Config, n }, cacheClient: &cache.Client{}, } - bouncer.cacheClient.New(config.RedisCacheEnabled, config.RedisCacheHost) + bouncer.cacheClient.New(config.RedisCacheEnabled, config.RedisCacheHost, config.RedisCachePass) //nolint:nestif if (config.CrowdsecMode == configuration.StreamMode || config.CrowdsecMode == configuration.AloneMode) && ticker == nil { if config.CrowdsecMode == configuration.AloneMode { - err = getToken(bouncer) - if err != nil { + if err := getToken(bouncer); err != nil { logger.Error(fmt.Sprintf("New:getToken %s", err.Error())) return nil, err } @@ -366,6 +365,9 @@ func handleStreamCache(bouncer *Bouncer) error { logger.Debug("handleStreamCache:alreadyUpdated") return nil } + if err.Error() != cache.CacheMiss { + return err + } bouncer.cacheClient.SetDecision(cacheTimeoutKey, false, bouncer.updateInterval-1) streamRouteURL := url.URL{ Scheme: bouncer.crowdsecScheme, diff --git a/go.mod b/go.mod index 0840a70..04f2937 100644 --- a/go.mod +++ b/go.mod @@ -4,5 +4,5 @@ go 1.19 require ( github.com/leprosus/golang-ttl-map v1.1.7 - github.com/maxlerebourg/simpleredis v1.0.3 + github.com/maxlerebourg/simpleredis v1.0.5 ) diff --git a/go.sum b/go.sum index 170d15e..53f61ad 100644 --- a/go.sum +++ b/go.sum @@ -1,4 +1,4 @@ github.com/leprosus/golang-ttl-map v1.1.7 h1:cF4AAFDDnJTFSV+/42sKLhmMluvLdRlCGS2UaifH6UM= github.com/leprosus/golang-ttl-map v1.1.7/go.mod h1:4QWHJPeVBbrkhOhXdhCv9IEiyj/YzkO04/iexy4vSe0= -github.com/maxlerebourg/simpleredis v1.0.3 h1:VhXq9bVytWDqD/TS/GjHKayvQb/VUeEql5F+yUbdOiI= -github.com/maxlerebourg/simpleredis v1.0.3/go.mod h1:/DH8zOK6kDskSqoX/m5CJJdNGfkIQZd/ERBJgytDDSk= +github.com/maxlerebourg/simpleredis v1.0.5 h1:1ubyIpTgIb+dadpILivAxuhZTHOOapEHRhcMakveuYY= +github.com/maxlerebourg/simpleredis v1.0.5/go.mod h1:/DH8zOK6kDskSqoX/m5CJJdNGfkIQZd/ERBJgytDDSk= diff --git a/pkg/cache/cache.go b/pkg/cache/cache.go index bae9e14..a2c0b3f 100644 --- a/pkg/cache/cache.go +++ b/pkg/cache/cache.go @@ -82,9 +82,9 @@ type Client struct { } // New Initialize cache client. -func (client *Client) New(isRedis bool, host string) { +func (client *Client) New(isRedis bool, host string, pass string) { if isRedis { - redis.Init(host) + redis.Init(host, pass) client.cache = &redisCache{} } else { client.cache = &localCache{} diff --git a/pkg/configuration/configuration.go b/pkg/configuration/configuration.go index f01c826..8c62d1e 100644 --- a/pkg/configuration/configuration.go +++ b/pkg/configuration/configuration.go @@ -55,6 +55,7 @@ type Config struct { ClientTrustedIPs []string `json:"clientTrustedIps,omitempty"` RedisCacheEnabled bool `json:"redisCacheEnabled,omitempty"` RedisCacheHost string `json:"redisCacheHost,omitempty"` + RedisCachePass string `json:"redisCachePass,omitempty"` } func contains(source []string, target string) bool { @@ -83,6 +84,7 @@ func New() *Config { ClientTrustedIPs: []string{}, RedisCacheEnabled: false, RedisCacheHost: "redis:6379", + RedisCachePass: "", } } diff --git a/vendor/github.com/maxlerebourg/simpleredis/README.md b/vendor/github.com/maxlerebourg/simpleredis/README.md index 9675434..30fd3fe 100644 --- a/vendor/github.com/maxlerebourg/simpleredis/README.md +++ b/vendor/github.com/maxlerebourg/simpleredis/README.md @@ -1,2 +1,29 @@ # simpleredis -Minimal go redis with only get, set and delete operation +Minimal go redis with only `get`, `set` and `delete` operation. +With **NO** extern dependencies. + +## Example +```go +import simpleredis "github.com/maxlerebourg/simpleredis" + +var redis simpleredis.SimpleRedis + +redis.Init("redis:6379", "") // redisHost, redisPass + +err := redis.Set("test", []bytes("whatever"), 60), // Set key "test" with "whatever" for 60 seconds +if err != nil { + ... +} +val, err := redis.Get("test") // get key test +if err != nil { + // err could be only redis:unreachable, redis:miss or redis:timeout available in simpleredis.RedisUnreachable + ... +} +err = redis.Del("test") +if err != nil { + ... +} +``` + +## Author +Max Lerebourg @ [Primadviz.com](https://primadviz.com) \ No newline at end of file diff --git a/vendor/github.com/maxlerebourg/simpleredis/simpleredis.go b/vendor/github.com/maxlerebourg/simpleredis/simpleredis.go index fcad152..ec21873 100644 --- a/vendor/github.com/maxlerebourg/simpleredis/simpleredis.go +++ b/vendor/github.com/maxlerebourg/simpleredis/simpleredis.go @@ -17,10 +17,11 @@ const ( RedisUnreachable = "redis:unreachable" RedisMiss = "redis:miss" RedisTimeout = "redis:timeout" + RedisNoAuth = "redis:noauth" ) -// A RedisCmd is used to communicate with redis at low level using commands. -type RedisCmd struct { +// A redisCmd is used to communicate with redis at low level using commands. +type redisCmd struct { Command string Name string Data []byte @@ -30,7 +31,8 @@ type RedisCmd struct { // A SimpleRedis is used to communicate with redis. type SimpleRedis struct { - redisHost string + host string + pass string } func genRedisArray(params ...[]byte) []byte { @@ -49,11 +51,11 @@ func send(wr *textproto.Writer, method string, data []byte) { } } -func askRedis(hostnamePort string, cmd RedisCmd, channel chan RedisCmd) { +func askRedis(sr *SimpleRedis, cmd redisCmd, channel chan redisCmd) { dialer := net.Dialer{Timeout: 2 * time.Second} - conn, err := dialer.Dial("tcp", hostnamePort) + conn, err := dialer.Dial("tcp", sr.host) if err != nil { - channel <- RedisCmd{Error: fmt.Errorf(RedisUnreachable)} + channel <- redisCmd{Error: fmt.Errorf(RedisUnreachable)} return } defer func() { @@ -65,6 +67,25 @@ func askRedis(hostnamePort string, cmd RedisCmd, channel chan RedisCmd) { writer := textproto.NewWriter(bufio.NewWriter(conn)) reader := textproto.NewReader(bufio.NewReader(conn)) + if sr.pass != "" { + data := genRedisArray([]byte("AUTH"), []byte(sr.pass)) + send(writer, "auth", data) + for { + select { + case <-time.After(time.Second * 1): + channel <- redisCmd{Error: fmt.Errorf(RedisTimeout)} + return + default: + read, _ := reader.ReadLineBytes() + if string(read) != "+OK" { + channel <- redisCmd{Error: fmt.Errorf(RedisNoAuth)} + return + } + break + } + } + } + switch cmd.Command { case "SET": data := genRedisArray([]byte("SET"), []byte(cmd.Name), cmd.Data, []byte("EX"), []byte(fmt.Sprintf("%d", cmd.Duration))) @@ -78,16 +99,20 @@ func askRedis(hostnamePort string, cmd RedisCmd, channel chan RedisCmd) { for { select { case <-time.After(time.Second * 1): - channel <- RedisCmd{Error: fmt.Errorf(RedisTimeout)} + channel <- redisCmd{Error: fmt.Errorf(RedisTimeout)} return default: read, _ := reader.ReadLineBytes() - if string(read) != "$1" { - channel <- RedisCmd{Error: fmt.Errorf(RedisMiss)} + str := string(read) + if strings.Contains(str, "-NOAUTH") { + channel <- redisCmd{Error: fmt.Errorf(RedisNoAuth)} + return + } else if str != "$1" { + channel <- redisCmd{Error: fmt.Errorf(RedisMiss)} return } read, _ = reader.ReadLineBytes() - channel <- RedisCmd{Data: read} + channel <- redisCmd{Data: read} return } } @@ -95,18 +120,19 @@ func askRedis(hostnamePort string, cmd RedisCmd, channel chan RedisCmd) { } // Init sets the redisHost used to connect to redis. -func (sr *SimpleRedis) Init(redisHost string) { - sr.redisHost = redisHost +func (sr *SimpleRedis) Init(host string, pass string) { + sr.host = host + sr.pass = pass } // Get fetches the value for key name in redis. func (sr *SimpleRedis) Get(name string) ([]byte, error) { - redisCmd := RedisCmd{ + cmd := redisCmd{ Command: "GET", Name: name, } - channel := make(chan RedisCmd) - go askRedis(sr.redisHost, redisCmd, channel) + channel := make(chan redisCmd) + go askRedis(sr, cmd, channel) resp := <-channel if resp.Error != nil { return nil, resp.Error @@ -116,22 +142,22 @@ func (sr *SimpleRedis) Get(name string) ([]byte, error) { // Set updates the value for key name in redis with value data for duration. func (sr *SimpleRedis) Set(name string, data []byte, duration int64) error { - redisCmd := RedisCmd{ + cmd := redisCmd{ Command: "SET", Name: name, Data: data, Duration: duration, } - go askRedis(sr.redisHost, redisCmd, nil) + go askRedis(sr, cmd, nil) return nil } // Del removes the key name in redis. func (sr *SimpleRedis) Del(name string) error { - redisCmd := RedisCmd{ + cmd := redisCmd{ Command: "DEL", Name: name, } - go askRedis(sr.redisHost, redisCmd, nil) + go askRedis(sr, cmd, nil) return nil } diff --git a/vendor/modules.txt b/vendor/modules.txt index 1ecfcb3..7045931 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1,6 +1,6 @@ # github.com/leprosus/golang-ttl-map v1.1.7 ## explicit; go 1.15 github.com/leprosus/golang-ttl-map -# github.com/maxlerebourg/simpleredis v1.0.3 +# github.com/maxlerebourg/simpleredis v1.0.5 ## explicit; go 1.19 github.com/maxlerebourg/simpleredis