🍱 clean code

This commit is contained in:
Max Lerebourg
2022-10-11 19:34:08 +02:00
parent 2e780b304d
commit d0ba71c0c8
+43 -43
View File
@@ -118,9 +118,9 @@ func New(ctx context.Context, next http.Handler, config *Config, name string) (h
} }
// ServeHTTP principal function of plugin. // ServeHTTP principal function of plugin.
func (a *Bouncer) ServeHTTP(rw http.ResponseWriter, req *http.Request) { func (bouncer *Bouncer) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if !a.enabled { if !bouncer.enabled {
a.next.ServeHTTP(rw, req) bouncer.next.ServeHTTP(rw, req)
return return
} }
@@ -128,31 +128,31 @@ func (a *Bouncer) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
remoteHost, _, err := net.SplitHostPort(req.RemoteAddr) remoteHost, _, err := net.SplitHostPort(req.RemoteAddr)
if err != nil { if err != nil {
logger(fmt.Sprintf("failed to extract ip from remote address: %v", err)) logger(fmt.Sprintf("failed to extract ip from remote address: %v", err))
a.next.ServeHTTP(rw, req) bouncer.next.ServeHTTP(rw, req)
return return
} }
if a.crowdsecMode == streamMode || a.crowdsecMode == liveMode { if bouncer.crowdsecMode == streamMode || bouncer.crowdsecMode == liveMode {
isBanned, err := getDecision(a, remoteHost) isBanned, err := getDecision(bouncer, remoteHost)
if err == nil { if err == nil {
if isBanned { if isBanned {
rw.WriteHeader(http.StatusForbidden) rw.WriteHeader(http.StatusForbidden)
} else { } else {
a.next.ServeHTTP(rw, req) bouncer.next.ServeHTTP(rw, req)
} }
return return
} }
} }
// Right here if we cannot join the stream we forbid the request to go on. // Right here if we cannot join the stream we forbid the request to go on.
if a.crowdsecMode == streamMode { if bouncer.crowdsecMode == streamMode {
if a.crowdsecStreamHealthy { if bouncer.crowdsecStreamHealthy {
a.next.ServeHTTP(rw, req) bouncer.next.ServeHTTP(rw, req)
} else { } else {
rw.WriteHeader(http.StatusForbidden) rw.WriteHeader(http.StatusForbidden)
} }
} else { } else {
handleNoStreamCache(a, rw, req, remoteHost) handleNoStreamCache(bouncer, rw, req, remoteHost)
} }
} }
@@ -189,8 +189,8 @@ func logger(str string) {
} }
func contains(source []string, target string) bool { func contains(source []string, target string) bool {
for _, a := range source { for _, item := range source {
if a == target { if item == target {
return true return true
} }
} }
@@ -199,8 +199,8 @@ func contains(source []string, target string) bool {
// Get Decision check in the cache if the IP has the banned / not banned value. // Get Decision check in the cache if the IP has the banned / not banned value.
// Otherwise return with an error to add the IP in cache if we are on. // Otherwise return with an error to add the IP in cache if we are on.
func getDecision(a *Bouncer, clientIP string) (bool, error) { func getDecision(bouncer *Bouncer, clientIP string) (bool, error) {
banned, isCached := a.cache.Get(clientIP) banned, isCached := bouncer.cache.Get(clientIP)
bannedString, isValid := banned.(string) bannedString, isValid := banned.(string)
if isCached && isValid && len(bannedString) > 0 { if isCached && isValid && len(bannedString) > 0 {
return bannedString == cacheBannedValue, nil return bannedString == cacheBannedValue, nil
@@ -208,31 +208,31 @@ func getDecision(a *Bouncer, clientIP string) (bool, error) {
return false, fmt.Errorf("no cache data") return false, fmt.Errorf("no cache data")
} }
func setDecision(a *Bouncer, clientIP string, isBanned bool, duration int64) { func setDecision(bouncer *Bouncer, clientIP string, isBanned bool, duration int64) {
if a.crowdsecMode == noneMode { if bouncer.crowdsecMode == noneMode {
return return
} }
if isBanned { if isBanned {
logger(fmt.Sprintf("%v banned", clientIP)) logger(fmt.Sprintf("%v banned", clientIP))
a.cache.Set(clientIP, cacheBannedValue, duration) bouncer.cache.Set(clientIP, cacheBannedValue, duration)
} else { } else {
a.cache.Set(clientIP, cacheNoBannedValue, duration) bouncer.cache.Set(clientIP, cacheNoBannedValue, duration)
} }
} }
func handleNoStreamCache(a *Bouncer, rw http.ResponseWriter, req *http.Request, remoteHost string) { func handleNoStreamCache(bouncer *Bouncer, rw http.ResponseWriter, req *http.Request, remoteHost string) {
// We are now in none or live mode. // We are now in none or live mode.
routeURL := url.URL{ routeURL := url.URL{
Scheme: a.crowdsecScheme, Scheme: bouncer.crowdsecScheme,
Host: a.crowdsecHost, Host: bouncer.crowdsecHost,
Path: crowdsecLapiRoute, Path: crowdsecLapiRoute,
RawQuery: fmt.Sprintf("ip=%v&banned=true", remoteHost), RawQuery: fmt.Sprintf("ip=%v&banned=true", remoteHost),
} }
body := crowdsecQuery(a, routeURL.String()) body := crowdsecQuery(bouncer, routeURL.String())
if bytes.Equal(body, []byte("null")) { if bytes.Equal(body, []byte("null")) {
setDecision(a, remoteHost, false, a.defaultDecisionTimeout) setDecision(bouncer, remoteHost, false, bouncer.defaultDecisionTimeout)
a.next.ServeHTTP(rw, req) bouncer.next.ServeHTTP(rw, req)
return return
} }
@@ -244,8 +244,8 @@ func handleNoStreamCache(a *Bouncer, rw http.ResponseWriter, req *http.Request,
return return
} }
if len(decisions) == 0 { if len(decisions) == 0 {
setDecision(a, remoteHost, false, a.defaultDecisionTimeout) setDecision(bouncer, remoteHost, false, bouncer.defaultDecisionTimeout)
a.next.ServeHTTP(rw, req) bouncer.next.ServeHTTP(rw, req)
return return
} }
rw.WriteHeader(http.StatusForbidden) rw.WriteHeader(http.StatusForbidden)
@@ -254,50 +254,50 @@ func handleNoStreamCache(a *Bouncer, rw http.ResponseWriter, req *http.Request,
logger(fmt.Sprintf("failed to parse duration: %s", err)) logger(fmt.Sprintf("failed to parse duration: %s", err))
return return
} }
setDecision(a, remoteHost, true, int64(duration.Seconds())) setDecision(bouncer, remoteHost, true, int64(duration.Seconds()))
} }
func handleStreamCache(a *Bouncer) { func handleStreamCache(bouncer *Bouncer) {
// TODO clean properly on exit. // TODO clean properly on exit.
streamRouteURL := url.URL{ streamRouteURL := url.URL{
Scheme: a.crowdsecScheme, Scheme: bouncer.crowdsecScheme,
Host: a.crowdsecHost, Host: bouncer.crowdsecHost,
Path: crowdsecLapiStreamRoute, Path: crowdsecLapiStreamRoute,
RawQuery: fmt.Sprintf("startup=%t", !a.crowdsecStreamHealthy), RawQuery: fmt.Sprintf("startup=%t", !bouncer.crowdsecStreamHealthy),
} }
body := crowdsecQuery(a, streamRouteURL.String()) body := crowdsecQuery(bouncer, streamRouteURL.String())
var stream Stream var stream Stream
err := json.Unmarshal(body, &stream) err := json.Unmarshal(body, &stream)
if err != nil { if err != nil {
logger(fmt.Sprintf("error while parsing body: %s", err)) logger(fmt.Sprintf("error while parsing body: %s", err))
a.crowdsecStreamHealthy = false bouncer.crowdsecStreamHealthy = false
return return
} }
for _, decision := range stream.New { for _, decision := range stream.New {
duration, err := time.ParseDuration(decision.Duration) duration, err := time.ParseDuration(decision.Duration)
if err == nil { if err == nil {
setDecision(a, decision.Value, true, int64(duration.Seconds())) setDecision(bouncer, decision.Value, true, int64(duration.Seconds()))
} }
} }
for _, decision := range stream.Deleted { for _, decision := range stream.Deleted {
a.cache.Del(decision.Value) bouncer.cache.Del(decision.Value)
} }
a.crowdsecStreamHealthy = true bouncer.crowdsecStreamHealthy = true
} }
func crowdsecQuery(a *Bouncer, stringURL string) []byte { func crowdsecQuery(bouncer *Bouncer, stringURL string) []byte {
var req *http.Request var req *http.Request
req, _ = http.NewRequest(http.MethodGet, stringURL, nil) req, _ = http.NewRequest(http.MethodGet, stringURL, nil)
req.Header.Add(crowdsecLapiHeader, a.crowdsecKey) req.Header.Add(crowdsecLapiHeader, bouncer.crowdsecKey)
res, err := a.client.Do(req) res, err := bouncer.client.Do(req)
if err != nil { if err != nil {
logger(fmt.Sprintf("error while fetching %v: %s", stringURL, err)) logger(fmt.Sprintf("error while fetching %v: %s", stringURL, err))
a.crowdsecStreamHealthy = false bouncer.crowdsecStreamHealthy = false
return nil return nil
} }
if res.StatusCode != http.StatusOK { if res.StatusCode != http.StatusOK {
logger(fmt.Sprintf("error while fetching %v, status code: %d", stringURL, res.StatusCode)) logger(fmt.Sprintf("error while fetching %v, status code: %d", stringURL, res.StatusCode))
a.crowdsecStreamHealthy = false bouncer.crowdsecStreamHealthy = false
return nil return nil
} }
defer func(body io.ReadCloser) { defer func(body io.ReadCloser) {
@@ -309,7 +309,7 @@ func crowdsecQuery(a *Bouncer, stringURL string) []byte {
body, err := ioutil.ReadAll(res.Body) body, err := ioutil.ReadAll(res.Body)
if err != nil { if err != nil {
logger(fmt.Sprintf("error while reading body: %s", err)) logger(fmt.Sprintf("error while reading body: %s", err))
a.crowdsecStreamHealthy = false bouncer.crowdsecStreamHealthy = false
return nil return nil
} }
return body return body