Compare commits

..

No commits in common. "main" and "0.1.5" have entirely different histories.
main ... 0.1.5

17 changed files with 56 additions and 346 deletions

View file

@ -1,8 +0,0 @@
/.direnv
/.git
/k8s
/flake.*
/LICENSE
/dist
/renovate.json
/skaffold.yaml

View file

@ -14,10 +14,10 @@ jobs:
build: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v3
- name: Set up Go - name: Set up Go
uses: actions/setup-go@v5 uses: actions/setup-go@v4
with: with:
go-version: '1.21' go-version: '1.21'

View file

@ -1,4 +1,4 @@
FROM golang:1.22-bookworm as builder FROM golang:1.21-bookworm as builder
WORKDIR /app WORKDIR /app

View file

@ -1,48 +1,3 @@
# ntfy-bridge # ntfy-bridge
Bridge for various implementations to publish to ntfy. Bridge for various implementations to publish to ntfy.
## Installation
Using go:
```sh
go install forge.babariviere.com/babariviere/ntfy-bridge@latest
```
Or using docker:
```sh
docker pull forge.babariviere.com/babariviere/ntfy-bridge:latest
```
Binaries are also avaiable in the [release section](https://forge.babariviere.com/babariviere/ntfy-bridge/releases).
## Usage
First, you need to create a configuration file. A sample one is provided [here](./config.example.scfg).
For now, we have these handler types:
- `flux`: handle notification from [Flux](https://fluxcd.io)
- `discord_embed`: handle preformated notification from discord embeds (see [embed object](https://discord.com/developers/docs/resources/channel#embed-object))
- `alertmanager`: handle notification from alertmanager using [webhook_config](https://prometheus.io/docs/alerting/latest/configuration/#webhook_config)
Once you have created your config file, you can either put it in these directories:
- `/etc/ntfy-bridge/config.scfg`
- `$HOME/.ntfy-bridge/config.scfg`
- `$HOME/.config/ntfy-bridge/config.scfg`
- `config.scfg` (current directory)
Then, you can simply run the binary with either the native binary:
```sh
./ntfy-bridge
```
Or via docker:
```sh
docker run -v config.scfg:/etc/ntfy-bridge/config.scfg -p 8080 forge.babariviere.com/babariviere/ntfy-bridge:latest
```
Sample config for kubernetes can be found in [./k8s/](./k8s/) directory.

View file

@ -1,70 +0,0 @@
package bridge
import (
"encoding/json"
"log/slog"
"net/http"
"strings"
"time"
)
type AlertmanagerEvent struct {
Receiver string `json:"receiver"`
Status string `json:"status"`
Alerts []struct {
Status string `json:"status"`
Labels map[string]string `json:"labels"`
Annotations map[string]string `json:"annotations"`
StartsAt time.Time `json:"startsAt"`
EndsAt time.Time `json:"endsAt"`
GeneratorURL string `json:"generatorURL"`
Fingerprint string `json:"fingerprint"`
} `json:"alerts"`
GroupLabels map[string]string `json:"groupLabels"`
CommonLabels map[string]string `json:"commonLabels"`
CommonAnnotations map[string]string `json:"commonAnnotations"`
ExternalURL string `json:"externalURL"`
Version string `json:"version"`
GroupKey string `json:"groupKey"`
TruncatedAlerts int `json:"truncatedAlerts"`
}
type AlertmanagerHandler struct{}
func NewAlertmanagerHandler() AlertmanagerHandler {
return AlertmanagerHandler{}
}
func (d AlertmanagerHandler) ProduceNotifications(r *http.Request) ([]Notification, error) {
l := slog.With(slog.String("handler", "alertmanager"))
dec := json.NewDecoder(r.Body)
defer r.Body.Close()
var event AlertmanagerEvent
if err := dec.Decode(&event); err != nil {
l.Error("invalid message format", "error", err)
return nil, err
}
notifications := make([]Notification, 0, len(event.Alerts))
for _, alert := range event.Alerts {
if alert.Annotations["summary"] == "" {
continue
}
var not Notification
not.Title = "[" + strings.ToUpper(event.Status) + "] " + alert.Annotations["summary"]
not.Body = alert.Annotations["description"]
if runbook := alert.Annotations["runbook_url"]; runbook != "" {
not.Actions = append(not.Actions, NewViewAction("Runbook", runbook))
}
if event.Status == "resolved" {
not.Tags = []string{"resolved"}
}
notifications = append(notifications, not)
}
return notifications, nil
}

View file

@ -4,6 +4,7 @@ import (
"encoding/base64" "encoding/base64"
"encoding/json" "encoding/json"
"errors" "errors"
"io"
"log/slog" "log/slog"
"net/http" "net/http"
"strconv" "strconv"
@ -11,7 +12,7 @@ import (
) )
type Handler interface { type Handler interface {
ProduceNotifications(r *http.Request) ([]Notification, error) FormatNotification(r io.Reader) (Notification, error)
} }
type NotificationError struct { type NotificationError struct {
@ -19,37 +20,11 @@ type NotificationError struct {
Error string `json:"error"` Error string `json:"error"`
} }
type NotificationAction struct {
Action string
Label string
Params []string
}
func NewViewAction(label, url string, params ...string) NotificationAction {
return NotificationAction{
Action: "view",
Label: label,
Params: append([]string{url}, params...),
}
}
func (n NotificationAction) Format() string {
var sb strings.Builder
sb.WriteString(n.Action + ", " + n.Label)
if len(n.Params) > 0 {
sb.WriteString(", " + strings.Join(n.Params, ", "))
}
return sb.String()
}
type Notification struct { type Notification struct {
Title string Title string
Body string Body string
Priority int Priority int
Tags []string Tags []string
Actions []NotificationAction
IsMarkdown bool IsMarkdown bool
topic string topic string
@ -92,15 +67,6 @@ func (n Notification) Send(base string) error {
req.Header.Set("Authorization", n.auth.bearer()) req.Header.Set("Authorization", n.auth.bearer())
} }
if len(n.Actions) > 0 {
actions := make([]string, len(n.Actions))
for i, act := range n.Actions {
actions[i] = act.Format()
}
req.Header.Set("Actions", strings.Join(actions, "; "))
}
resp, err := http.DefaultClient.Do(req) resp, err := http.DefaultClient.Do(req)
if err != nil { if err != nil {
return err return err
@ -162,30 +128,31 @@ func (b Bridge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return return
} }
nots, err := b.h.ProduceNotifications(r) not, err := b.h.FormatNotification(r.Body)
defer r.Body.Close()
if err != nil { if err != nil {
slog.Error("failed to format notification") slog.Error("failed to format notification")
w.WriteHeader(http.StatusBadRequest) w.WriteHeader(http.StatusBadRequest)
return return
} }
if len(nots) == 0 { // If notification is empty, that means it should be ignored.
slog.Debug("no notification produced") // TODO: maybe return an error instead of empty notification
w.WriteHeader(http.StatusNoContent) if not.IsEmpty() {
w.WriteHeader(http.StatusOK)
return return
} }
for _, not := range nots { not.topic = b.topic
not.topic = b.topic not.auth = b.auth
not.auth = b.auth if err = not.Send(b.baseURL); err != nil {
if err = not.Send(b.baseURL); err != nil { slog.Error("unable to send notification", "error", err)
slog.Error("unable to send notification", "error", err) w.WriteHeader(http.StatusInternalServerError)
w.WriteHeader(http.StatusInternalServerError) return
return
}
} }
slog.Debug("notifications sent with success", "sent", len(nots)) slog.Debug("notification sent with success")
w.WriteHeader(http.StatusNoContent) w.WriteHeader(http.StatusOK)
} }

View file

@ -1,74 +0,0 @@
package bridge
import (
"encoding/json"
"log/slog"
"net/http"
"strings"
)
type DiscordMessage struct {
Content string `json:"content"`
Embeds []struct {
Title string `json:"title"`
Description string `json:"description"`
URL string `json:"url"`
Footer struct {
Text string `json:"text"`
} `json:"footer"`
Author struct {
Name string `json:"name"`
URL string `json:"url"`
} `json:"author"`
} `json:"embeds"`
}
type DiscordEmbedHandler struct{}
func NewDiscordEmbedHandler() DiscordEmbedHandler {
return DiscordEmbedHandler{}
}
func (d DiscordEmbedHandler) ProduceNotifications(r *http.Request) ([]Notification, error) {
l := slog.With(slog.String("handler", "discord_embed"))
dec := json.NewDecoder(r.Body)
defer r.Body.Close()
var not DiscordMessage
if err := dec.Decode(&not); err != nil {
l.Error("invalid message format", "error", err)
return nil, err
}
notifications := make([]Notification, len(not.Embeds))
for i, embed := range not.Embeds {
not := notifications[i]
not.Title = embed.Title
not.IsMarkdown = true
if embed.URL != "" {
not.Actions = []NotificationAction{NewViewAction("Open in Browser", embed.URL)}
}
var body strings.Builder
body.WriteString(embed.Description)
if embed.Author.Name != "" {
body.WriteString("\n\n**Author**\n")
body.WriteString(embed.Author.Name)
if embed.Author.URL != "" {
body.WriteString(" (" + embed.Author.URL + ")")
}
}
if embed.Footer.Text != "" {
body.WriteString("\n\n" + embed.Footer.Text)
}
not.Body = body.String()
notifications[i] = not
}
return notifications, nil
}

View file

@ -3,32 +3,26 @@ package bridge
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io"
"log/slog" "log/slog"
"net/http"
"strings" "strings"
"time" "time"
) )
type fluxInvolvedObject struct {
Kind string `json:"kind"`
Namespace string `json:"namespace"`
Name string `json:"name"`
UID string `json:"uid"`
APIVersion string `json:"apiVersion"`
ResourceVersion string `json:"resourceVersion"`
}
func (f fluxInvolvedObject) String() string {
return strings.ToLower(f.Kind) + "/" + f.Namespace + "." + f.Name
}
type FluxNotification struct { type FluxNotification struct {
InvolvedObject fluxInvolvedObject `json:"involvedObject"` InvolvedObject struct {
Severity string `json:"severity"` Kind string `json:"kind"`
Timestamp time.Time `json:"timestamp"` Namespace string `json:"namespace"`
Message string `json:"message"` Name string `json:"name"`
Reason string `json:"reason"` UID string `json:"uid"`
Metadata struct { APIVersion string `json:"apiVersion"`
ResourceVersion string `json:"resourceVersion"`
} `json:"involvedObject"`
Severity string `json:"severity"`
Timestamp time.Time `json:"timestamp"`
Message string `json:"message"`
Reason string `json:"reason"`
Metadata struct {
CommitStatus string `json:"commit_status"` CommitStatus string `json:"commit_status"`
Revision string `json:"revision"` Revision string `json:"revision"`
Summary string `json:"summary"` Summary string `json:"summary"`
@ -37,51 +31,37 @@ type FluxNotification struct {
ReportingInstance string `json:"reportingInstance"` ReportingInstance string `json:"reportingInstance"`
} }
type FluxHandler struct { type FluxHandler struct{}
// Register all modifications of reconciliations
reconciliations map[string]bool
}
func NewFluxHandler() FluxHandler { func NewFluxHandler() FluxHandler {
return FluxHandler{ return FluxHandler{}
reconciliations: make(map[string]bool),
}
} }
func (f FluxHandler) ProduceNotifications(r *http.Request) ([]Notification, error) { func (f FluxHandler) FormatNotification(r io.Reader) (Notification, error) {
l := slog.With(slog.String("handler", "flux")) l := slog.With(slog.String("handler", "flux"))
dec := json.NewDecoder(r.Body) dec := json.NewDecoder(r)
defer r.Body.Close()
var not FluxNotification var not FluxNotification
if err := dec.Decode(&not); err != nil { if err := dec.Decode(&not); err != nil {
l.Error("invalid message format", "error", err) l.Error("invalid message format in flux", "error", err)
return nil, err return Notification{}, err
} }
obj := not.InvolvedObject.String()
if not.Reason == "ReconciliationSucceeded" { if not.Reason == "ReconciliationSucceeded" {
if ok := f.reconciliations[obj]; !ok { // Filter out spammy ReconciliationSucceeded notification
// Filter out spammy ReconciliationSucceeded notification return Notification{}, nil
return nil, nil
}
// we will print the object so skip it next time it spam
f.reconciliations[obj] = false
} else {
// object has been modified, we can print it next time
f.reconciliations[obj] = true
} }
title := fmt.Sprintf("[%s] %s %s", not.Severity, not.Reason, obj) title := fmt.Sprintf("[%s] %s %s/%s.%s", not.Severity, not.Reason,
strings.ToLower(not.InvolvedObject.Kind), not.InvolvedObject.Namespace, not.InvolvedObject.Name)
body := not.Message + "\n\n**revision**\n" + not.Metadata.Revision body := not.Message + "\n\n**revision**\n" + not.Metadata.Revision
l.Debug("flux notification", slog.Group("notification", l.Debug("flux notification", slog.Group("notification",
slog.String("title", title), slog.String("title", title),
slog.String("body", body))) slog.String("body", body)))
return []Notification{{ return Notification{
Title: title, Title: title,
Body: body, Body: body,
IsMarkdown: true, IsMarkdown: true,
}}, nil }, nil
} }

View file

@ -23,12 +23,3 @@ handler "/flux" {
# type "alertmanager" # type "alertmanager"
# topic "/infra" # topic "/infra"
# } # }
# Handle discord type messages. This is meant for
# webhook that doesn't support generic one's.
# Instead, we convert discord messages to ntfy message.
# See: https://discord.com/developers/docs/resources/channel#message-object
handler "/discord-like" {
type "discord_embed" # handle message with `embeds` content
topic "discord-like"
}

View file

@ -11,18 +11,12 @@ type HandlerType int
const ( const (
HandlerFlux HandlerType = iota + 1 HandlerFlux HandlerType = iota + 1
HandlerDiscordEmbed
HandlerAlertmanager
) )
func (h HandlerType) String() string { func (h HandlerType) String() string {
switch h { switch h {
case HandlerFlux: case HandlerFlux:
return "flux" return "flux"
case HandlerDiscordEmbed:
return "discord_embed"
case HandlerAlertmanager:
return "alertmanager"
} }
panic("unreachable") panic("unreachable")
} }
@ -154,10 +148,6 @@ func readHandlerType(d *scfg.Directive) (HandlerType, error) {
switch ty { switch ty {
case "flux": case "flux":
return HandlerFlux, nil return HandlerFlux, nil
case "discord_embed":
return HandlerDiscordEmbed, nil
case "alertmanager":
return HandlerAlertmanager, nil
default: default:
return 0, fmt.Errorf("invalid handler type %q", ty) return 0, fmt.Errorf("invalid handler type %q", ty)
} }

2
go.mod
View file

@ -1,5 +1,5 @@
module forge.babariviere.com/babariviere/ntfy-bridge module forge.babariviere.com/babariviere/ntfy-bridge
go 1.21 go 1.20
require git.sr.ht/~emersion/go-scfg v0.0.0-20230828131541-76adf4aeafd7 require git.sr.ht/~emersion/go-scfg v0.0.0-20230828131541-76adf4aeafd7

View file

@ -6,27 +6,17 @@ metadata:
data: data:
config.scfg: | config.scfg: |
http-address 0.0.0.0:8080 http-address 0.0.0.0:8080
log-level debug log-level info
log-format text log-format text
ntfy { ntfy {
server http://ntfy-http:80 server http://ntfy:80
} }
handler "/flux" { handler "/flux" {
type "flux" type "flux"
topic "flux" topic "flux"
} }
handler "/forgejo" {
type "discord_embed"
topic "forgejo"
}
handler "/alerts" {
type "alertmanager"
topic "infra"
}
--- ---
apiVersion: apps/v1 apiVersion: apps/v1
kind: Deployment kind: Deployment
@ -64,6 +54,6 @@ spec:
ports: ports:
- port: 8080 - port: 8080
name: http name: http
type: ClusterIP type: LoadBalancer
selector: selector:
app: bridge app: bridge

View file

@ -13,7 +13,7 @@ kind: Secret
metadata: metadata:
name: ntfy-bridge-dev-address name: ntfy-bridge-dev-address
stringData: stringData:
address: "http://bridge:8080/flux" address: "http://bridge.ntfy-bridge-dev.svc.cluster.local:8080/flux"
--- ---
apiVersion: notification.toolkit.fluxcd.io/v1beta2 apiVersion: notification.toolkit.fluxcd.io/v1beta2
kind: Alert kind: Alert

11
main.go
View file

@ -74,18 +74,11 @@ func main() {
switch handler.Type { switch handler.Type {
case config.HandlerFlux: case config.HandlerFlux:
h = bridge.NewFluxHandler() h = bridge.NewFluxHandler()
case config.HandlerDiscordEmbed:
h = bridge.NewDiscordEmbedHandler()
case config.HandlerAlertmanager:
h = bridge.NewAlertmanagerHandler()
} }
slog.Debug("Registering bridge", "route", route, "handler", handler.Type) slog.Debug("Registering bridge", "route", route, "handler", handler.Type)
topic := handler.Topic // TODO: use default topic if topic == ""
if topic == "" { bridge := bridge.NewBridge(cfg.Ntfy.Server, handler.Topic, h)
topic = cfg.Ntfy.DefaultTopic
}
bridge := bridge.NewBridge(cfg.Ntfy.Server, topic, h)
if !auth.IsEmpty() { if !auth.IsEmpty() {
bridge.WithAuth(auth) bridge.WithAuth(auth)
} }

View file

@ -1,4 +1,4 @@
FROM alpine:3.19 as alpine FROM alpine:3.18 as alpine
RUN apk add -U --no-cache ca-certificates RUN apk add -U --no-cache ca-certificates
FROM scratch FROM scratch

View file

@ -2,9 +2,6 @@
"$schema": "https://docs.renovatebot.com/renovate-schema.json", "$schema": "https://docs.renovatebot.com/renovate-schema.json",
"extends": [ "extends": [
"config:recommended", "config:recommended",
":dependencyDashboard", ":dependencyDashboard"
":automergeMinor",
":automergePatch",
":maintainLockFilesWeekly"
] ]
} }

View file

@ -6,7 +6,6 @@ build:
artifacts: artifacts:
- image: forge.babariviere.com/babariviere/ntfy-bridge - image: forge.babariviere.com/babariviere/ntfy-bridge
buildpacks: buildpacks:
local: {}
manifests: manifests:
kustomize: kustomize:
paths: paths: