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" } ```
This commit is contained in:
parent
c658a0fd33
commit
cc35ddbe0f
1 changed files with 12 additions and 4 deletions
16
main.go
16
main.go
|
@ -3,13 +3,14 @@ package main
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/prometheus/alertmanager/template"
|
|
||||||
"github.com/prometheus/common/model"
|
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"github.com/prometheus/alertmanager/template"
|
||||||
|
"github.com/prometheus/common/model"
|
||||||
|
|
||||||
"golang.org/x/exp/maps"
|
"golang.org/x/exp/maps"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -57,16 +58,23 @@ func WebhookHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
// Tags
|
// Tags
|
||||||
req.Header.Set("Tags", strings.Join(maps.Values(alert.Labels), ","))
|
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)
|
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)
|
log.Printf("Sending to %s failed: %s\n", req.RemoteAddr, err)
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if resp.StatusCode != 200 {
|
||||||
|
log.Printf("Failed to send notification: %v\n", resp)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
w.WriteHeader(http.StatusOK)
|
w.WriteHeader(http.StatusOK)
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue