From cc35ddbe0f5a176a0d347d3c1f1e03303a8f15ca Mon Sep 17 00:00:00 2001 From: Jaseem Abid Date: Fri, 10 Feb 2023 19:30:03 +0000 Subject: [PATCH] Enable basic auth only if username/password is set Empty password leads to an authorization error, which isn't ideal. Also log the response in case its an error, I think this would be handy in case the upstream starts misbehaving. By default won't add to log noise. Example: ``` curl -s -u ':' -d "test" ntfy.sh/test | jq . { "code": 40101, "http": 401, "error": "unauthorized", "link": "https://ntfy.sh/docs/publish/#authentication" } ``` --- main.go | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/main.go b/main.go index 0d9c478..82b7534 100644 --- a/main.go +++ b/main.go @@ -3,13 +3,14 @@ package main import ( "encoding/json" "fmt" - "github.com/prometheus/alertmanager/template" - "github.com/prometheus/common/model" "log" "net/http" "os" "strings" + "github.com/prometheus/alertmanager/template" + "github.com/prometheus/common/model" + "golang.org/x/exp/maps" ) @@ -57,16 +58,23 @@ func WebhookHandler(w http.ResponseWriter, r *http.Request) { // Tags req.Header.Set("Tags", strings.Join(maps.Values(alert.Labels), ",")) - req.SetBasicAuth(os.Getenv("NTFY_USER"), os.Getenv("NTFY_PASS")) + username, password := os.Getenv("NTFY_USER"), os.Getenv("NTFY_PASS") + if username != "" && password != "" { + req.SetBasicAuth(username, password) + } log.Printf("Sending request: %v\n", req) - if _, err := http.DefaultClient.Do(req); err != nil { + resp, err := http.DefaultClient.Do(req) + if err != nil { log.Printf("Sending to %s failed: %s\n", req.RemoteAddr, err) w.WriteHeader(http.StatusBadRequest) return } + if resp.StatusCode != 200 { + log.Printf("Failed to send notification: %v\n", resp) + } } w.WriteHeader(http.StatusOK)