Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions internal/check/check_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,16 @@ package check
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"

"github.com/NotAFlightRisk/patchcall/internal/match"
"github.com/NotAFlightRisk/patchcall/internal/notify"
)

Expand Down Expand Up @@ -95,6 +98,22 @@ func TestRunAlertsOncePerAdvisory(t *testing.T) {
}
}

func TestMessageFitsNtfyAndCountsWhatItLeftOut(t *testing.T) {
hits := make([]match.Hit, 40)
for i := range hits {
hits[i] = match.Hit{Advisory: match.Advisory{ID: fmt.Sprintf("GHSA-%d", i), Severity: "low",
Summary: strings.Repeat("ünïcödé ", 25)}}
}
m := (&Checker{}).message(App{}, hits)
lines := strings.Split(m.Body, "\n")
shown := len(lines) - 3
more := fmt.Sprintf("And %d more on the page.", len(hits)-shown)
if len(m.Body) >= 4096 || lines[len(lines)-1] != more || len(m.Advisories) != len(hits) {
t.Errorf("body = %d bytes ending %q, advisories = %d", len(m.Body), lines[len(lines)-1],
len(m.Advisories))
}
}

func TestRunRetriesAnAlertThatDidntGoOut(t *testing.T) {
fx := newFixture(t)
fx.refuse = true
Expand Down
25 changes: 17 additions & 8 deletions internal/check/report.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"cmp"
"fmt"
"io"
"slices"
"strings"
"text/tabwriter"
"time"
Expand All @@ -27,6 +28,9 @@ const (
Untracked Status = "untracked"
)

// ntfy refuses a message of 4 KB or more, so the rest wait on the page
const alertBytes = 3000

var urgency = map[Status]int{Affected: 0, Unavailable: 1, Unmapped: 2, Unknown: 2, Stale: 3,
Watch: 4, Clear: 5, Quiet: 6, Untracked: 7}

Expand Down Expand Up @@ -80,20 +84,25 @@ func byUrgency(a, b App) int {
}

func (c *Checker) message(app App, fresh []match.Hit) notify.Message {
urgent := false
lines := []string{fmt.Sprintf("%d new advisor%s. Move to %s.", len(fresh),
plural(len(fresh), "y", "ies"), app.MoveTo), ""}
for _, hit := range fresh {
line := fmt.Sprintf("%s %s: %s", strings.ToUpper(hit.Severity), hit.ID, hit.Summary)
urgent := slices.ContainsFunc(fresh, func(hit match.Hit) bool {
return hit.KEV || match.Rank(hit.Severity) >= match.Rank("high")
})
body := fmt.Sprintf("%d new advisor%s. Move to %s.\n", len(fresh),
plural(len(fresh), "y", "ies"), app.MoveTo)
for i, hit := range fresh {
line := fmt.Sprintf("\n%s %s: %s", strings.ToUpper(hit.Severity), hit.ID, hit.Summary)
if hit.KEV {
line += " (actively exploited)"
}
lines = append(lines, line)
urgent = urgent || hit.KEV || match.Rank(hit.Severity) >= match.Rank("high")
if len(body)+len(line) > alertBytes {
body += fmt.Sprintf("\nAnd %d more on the page.", len(fresh)-i)
break
}
body += line
}
return notify.Message{
Title: fmt.Sprintf("%s %s needs patching", app.Name, app.Version),
Body: strings.Join(lines, "\n"),
Body: body,
URL: cmp.Or(c.opts.PublicURL, fresh[0].URL),
Urgent: urgent,
App: app.Name,
Expand Down
12 changes: 8 additions & 4 deletions internal/notify/mail.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package notify

import (
"cmp"
"context"
"crypto/tls"
"fmt"
"mime"
Expand All @@ -13,7 +14,7 @@ import (
)

// mail sends over smtp:// (STARTTLS when offered) or smtps://, logging in if the URL has a user
func mail(cfg Config, m Message) error {
func mail(ctx context.Context, cfg Config, m Message) error {
server, err := url.Parse(cfg.SMTPURL)
if err != nil {
return err
Expand All @@ -23,18 +24,21 @@ func mail(cfg Config, m Message) error {
dialer := &net.Dialer{Timeout: 30 * time.Second}
var conn net.Conn
if server.Scheme == "smtps" {
conn, err = tls.DialWithDialer(dialer, "tcp", net.JoinHostPort(host, cmp.Or(port, "465")), secure)
conn, err = (&tls.Dialer{NetDialer: dialer, Config: secure}).
DialContext(ctx, "tcp", net.JoinHostPort(host, cmp.Or(port, "465")))
} else {
conn, err = dialer.Dial("tcp", net.JoinHostPort(host, cmp.Or(port, "587")))
conn, err = dialer.DialContext(ctx, "tcp", net.JoinHostPort(host, cmp.Or(port, "587")))
}
if err != nil {
return err
}
defer conn.Close()
defer context.AfterFunc(ctx, func() { conn.Close() })()
conn.SetDeadline(time.Now().Add(time.Minute))
client, err := smtp.NewClient(conn, host)
if err != nil {
return err
}
defer client.Close()
if ok, _ := client.Extension("STARTTLS"); ok && server.Scheme != "smtps" {
if err := client.StartTLS(secure); err != nil {
return err
Expand Down
5 changes: 3 additions & 2 deletions internal/notify/notify.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ func New(cfg Config, client *http.Client) *Notifier {
if err != nil {
return err
}
topic.Path = strings.TrimRight(topic.Path, "/")
base := *topic
base.Path = path.Dir(topic.Path)
priority := 3
Expand Down Expand Up @@ -89,8 +90,8 @@ func New(cfg Config, client *http.Client) *Notifier {
return n.post(ctx, cfg.AppriseURL, "", "",
map[string]string{"title": m.Title, "body": m.Body, "type": "warning"})
})
add("email", cfg.SMTPURL, func(_ context.Context, m Message) error {
return mail(cfg, m)
add("email", cfg.SMTPURL, func(ctx context.Context, m Message) error {
return mail(ctx, cfg, m)
})
return n
}
Expand Down
17 changes: 16 additions & 1 deletion internal/notify/notify_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ package notify
import (
"context"
"encoding/json"
"net"
"net/http"
"net/http/httptest"
"testing"
"time"
)

type captured struct {
Expand All @@ -21,7 +23,7 @@ func TestSendShapesEachChannelsPayload(t *testing.T) {
got = append(got, c)
}))
defer server.Close()
n := New(Config{NtfyURL: server.URL + "/alerts", NtfyToken: "tk", GotifyURL: server.URL + "/gotify/",
n := New(Config{NtfyURL: server.URL + "/alerts/", NtfyToken: "tk", GotifyURL: server.URL + "/gotify/",
GotifyToken: "gk", AppriseURL: server.URL + "/notify/home"}, server.Client())
if err := n.Send(context.Background(), Message{Title: "Immich needs patching", Body: "Move to 3", Urgent: true}); err != nil {
t.Fatal(err)
Expand Down Expand Up @@ -53,3 +55,16 @@ func TestSendKeepsGoingPastABrokenChannel(t *testing.T) {
t.Error("the webhook should still have been sent")
}
}

func TestMailGivesUpOnAServerThatNeverGreets(t *testing.T) {
silent, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer silent.Close()
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
if err := mail(ctx, Config{SMTPURL: "smtp://" + silent.Addr().String()}, Message{}); err == nil {
t.Error("want an error once the context ends")
}
}
Loading