ntfy: Support authentication via access-tokens

Implements: https://todo.xenrox.net/~xenrox/ntfy-alertmanager/14
This commit is contained in:
Thorben Günther 2023-02-21 11:50:50 +01:00
parent 37714a4a64
commit 41fb0f7766
No known key found for this signature in database
GPG key ID: 415CD778D8C5AFED
3 changed files with 23 additions and 5 deletions

View file

@ -67,9 +67,12 @@ resolved {
ntfy { ntfy {
# URL of the ntfy topic - required # URL of the ntfy topic - required
topic https://ntfy.sh/alertmanager-alerts topic https://ntfy.sh/alertmanager-alerts
# ntfy access control (https://ntfy.sh/docs/config/#access-control) # ntfy authentication via Basic Auth (https://docs.ntfy.sh/publish/#username-password)
user user user user
password pass password pass
# ntfy authentication via access tokens (https://docs.ntfy.sh/publish/#access-tokens)
# Either access-token or a user/password combination can be used - not both.
access-token foobar
} }
alertmanager { alertmanager {

View file

@ -1,6 +1,7 @@
package main package main
import ( import (
"errors"
"fmt" "fmt"
"strings" "strings"
"time" "time"
@ -30,9 +31,10 @@ type config struct {
} }
type ntfyConfig struct { type ntfyConfig struct {
Topic string Topic string
User string User string
Password string Password string
AccessToken string
} }
type labels struct { type labels struct {
@ -212,6 +214,17 @@ func readConfig(path string) (*config, error) {
} }
} }
d = ntfyDir.Children.Get("access-token")
if d != nil {
if err := d.ParseParams(&config.ntfy.AccessToken); err != nil {
return nil, err
}
}
if config.ntfy.User != "" && config.ntfy.AccessToken != "" {
return nil, errors.New("ntfy: cannot use both an access-token and a user/password at the same time")
}
cacheDir := cfg.Get("cache") cacheDir := cfg.Get("cache")
if cacheDir != nil { if cacheDir != nil {

View file

@ -244,10 +244,12 @@ func (rcv *receiver) publish(n *notification) error {
return err return err
} }
// Basic auth // ntfy authentication
if rcv.cfg.ntfy.Password != "" && rcv.cfg.ntfy.User != "" { if rcv.cfg.ntfy.Password != "" && rcv.cfg.ntfy.User != "" {
auth := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", rcv.cfg.ntfy.User, rcv.cfg.ntfy.Password))) auth := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", rcv.cfg.ntfy.User, rcv.cfg.ntfy.Password)))
req.Header.Set("Authorization", fmt.Sprintf("Basic %s", auth)) req.Header.Set("Authorization", fmt.Sprintf("Basic %s", auth))
} else if rcv.cfg.ntfy.AccessToken != "" {
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", rcv.cfg.ntfy.AccessToken))
} }
req.Header.Set("X-Title", n.title) req.Header.Set("X-Title", n.title)