From 41fb0f7766bf02d1914904b2c2239044d5172a61 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thorben=20G=C3=BCnther?= Date: Tue, 21 Feb 2023 11:50:50 +0100 Subject: [PATCH] ntfy: Support authentication via access-tokens Implements: https://todo.xenrox.net/~xenrox/ntfy-alertmanager/14 --- README.md | 5 ++++- config.go | 19 ++++++++++++++++--- main.go | 4 +++- 3 files changed, 23 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 5df21ed..776d0a0 100644 --- a/README.md +++ b/README.md @@ -67,9 +67,12 @@ resolved { ntfy { # URL of the ntfy topic - required 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 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 { diff --git a/config.go b/config.go index 929c588..c4d0109 100644 --- a/config.go +++ b/config.go @@ -1,6 +1,7 @@ package main import ( + "errors" "fmt" "strings" "time" @@ -30,9 +31,10 @@ type config struct { } type ntfyConfig struct { - Topic string - User string - Password string + Topic string + User string + Password string + AccessToken string } 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") if cacheDir != nil { diff --git a/main.go b/main.go index 8c2d3f7..c7cd73e 100644 --- a/main.go +++ b/main.go @@ -244,10 +244,12 @@ func (rcv *receiver) publish(n *notification) error { return err } - // Basic auth + // ntfy authentication 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))) 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)