~bfiedler/go-threema

ref: bb62b75c1a842a28507a18394bd9bbc826394449 go-threema/cmd/am-hook/main.go -rw-r--r-- 4.7 KiB
bb62b75c — Ben Fiedler am-hook: Add version indicator 1 year, 8 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
// An Alertmanager-compatible webhook server, which bridges results to Threema
//
// Due to Threema messages costing credits to send, the implementation limits itself to
// to four requests/day with a maximum burst of 10.
package main

import (
	"encoding/hex"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"
	"strings"
	"time"

	"github.com/prometheus/alertmanager/template"
	"github.com/prometheus/common/model"
	"github.com/spf13/pflag"
	"golang.org/x/time/rate"

	"git.sr.ht/~bfiedler/go-threema/client"
)

var (
	c   client.Client
	pk  client.PrivateKey
	lim *rate.Limiter

	id          = pflag.String("id", os.Getenv("THREEMA_CLI_ID"), "Threema ID to use, required. Can also be set using the environment variable THREEMA_CLI_ID")
	apiSecret   = pflag.String("api-secret", os.Getenv("THREEMA_CLI_API_SECRET"), "API secret, required. Can also be set using the environment variable THREEMA_CLI_API_SECRET")
	mode        = pflag.String("mode", os.Getenv("THREEMA_CLI_MODE"), "Mode to use (simple/e2e). Defaults to simple, only relevant for sending messages. Can also be set using the environment variable THREEMA_CLI_MODE")
	privateKey  = pflag.String("private-key", os.Getenv("THREEMA_CLI_PRIVATE_KEY"), "Hex-encoded private key to derive shared keys for sent messages. Required if mode is e2e. Can also be set using the environment variable THREEMA_CLI_PRIVATE_KEY")
	recipientID = pflag.String("recipient-id", os.Getenv("THREEMA_CLI_RECIPIENT_ID"), "Threema ID send messages to, required. Can also be set using the environment variable THREEMA_CLI_RECIPIENT_ID")

	alertRate = rate.Every(24 * time.Hour / 4) // Refill four tokens per day

	Commit = "unknown"
)

func main() {
	fmt.Printf("Starting am-hook (commit %s)\n", Commit)

	pflag.Parse()
	checkFlags()

	var err error
	switch *mode {
	case "simple":
		c, err = client.NewSimpleClient(*id, *apiSecret)
	case "e2e":
		c, err = client.NewE2EClient(*id, *apiSecret, pk)
	}
	if err != nil {
		log.Fatalf("could not create client: %v", err)
	}

	lim = rate.NewLimiter(alertRate, 10)
	err = http.ListenAndServe("localhost:8999", http.HandlerFunc(handle))
	if err != nil {
		log.Fatal(err)
	}
}

func checkFlags() {
	fatal := false
	if *id == "" {
		log.Printf("flag id missing, this is required")
		fatal = true
	}

	if *recipientID == "" {
		log.Printf("flag recipientID missing, this is required")
		fatal = true
	}

	if *apiSecret == "" {
		log.Printf("flag apiSecret missing, this is required")
		fatal = true
	}

	if *mode == "" {
		log.Printf("mode missing, defaulting to 'simple'")
		*mode = "simple"
	}

	switch *mode {
	case "simple":
		// intentionally left blank
	case "e2e":
		if *privateKey == "" {
			log.Printf("private key missing, this is requried for mode 'e2e'")
			fatal = true
		} else {
			decodedLen := hex.DecodedLen(len(*privateKey))
			if decodedLen != len(pk) {
				log.Fatalf("private key length error, expected: %v, got: %v", len(pk), decodedLen)
			}

			_, err := hex.Decode(pk[:], []byte(*privateKey))
			if err != nil {
				log.Fatalf("could not decode private key: %v", err)
			}
		}
	default:
		log.Printf("unknown mode, valid modes are 'simple' and 'e2e': %v", *mode)
		fatal = true
	}

	if fatal {
		log.Printf("fatal configuration error")
		os.Exit(1)
	}
}

func handle(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()

	if !lim.Allow() {
		// we have exceeded the number of possible messages
		http.Error(w, "rate limited", http.StatusTooManyRequests)
	}

	d := json.NewDecoder(r.Body)
	var data template.Data
	err := d.Decode(&data)
	if err != nil {
		http.Error(w, "could not decode json body", http.StatusInternalServerError)
		return
	}
	http.Error(w, "ok", http.StatusOK)

	var sb strings.Builder
	for _, alert := range data.Alerts {
		msg := formatAlert(&alert)
		if msg.Len() > client.MaxTextMessageBytes {
			log.Printf("message is longer than maximum allowed message size, sending truncated message")
			writeMessage(sb.String()[:3400] + "..._message truncated_")
		}

		if msg.Len()+sb.Len() > client.MaxTextMessageBytes {
			writeMessage(sb.String())
			sb.Reset()
		}

		sb.WriteString(msg.String())
	}

	writeMessage(sb.String())
}

func writeMessage(msg string) {
	err := c.SendTextMessage(*recipientID, msg)
	if err != nil {
		log.Printf("error sending message: %v", err)
	}
}

func formatAlert(a *template.Alert) strings.Builder {
	var sb strings.Builder
	fmt.Fprintln(&sb, "*"+strings.ToUpper(a.Status)+"*")
	fmt.Fprintln(&sb, "*"+a.Labels[model.AlertNameLabel]+"*")

	msg, ok := a.Annotations["message"]
	if ok && msg != "" {
		fmt.Fprintln(&sb, msg)
	}

	if a.Status == string(model.AlertFiring) {
		fmt.Fprintf(&sb, "since %s\n", a.StartsAt.Format("02 Jan 15:04"))
	} else {
		fmt.Fprintf(&sb, "ended %s\n", a.EndsAt.Format("02 Jan 15:04"))
		fmt.Fprintf(&sb, "duration %s\n", a.EndsAt.Sub(a.StartsAt))
	}

	return sb
}