diff --git a/internal/check/check_test.go b/internal/check/check_test.go index 4352455..05b8d3b 100644 --- a/internal/check/check_test.go +++ b/internal/check/check_test.go @@ -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" ) @@ -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 diff --git a/internal/check/report.go b/internal/check/report.go index 1204785..eac59b7 100644 --- a/internal/check/report.go +++ b/internal/check/report.go @@ -4,6 +4,7 @@ import ( "cmp" "fmt" "io" + "slices" "strings" "text/tabwriter" "time" @@ -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} @@ -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, diff --git a/internal/notify/mail.go b/internal/notify/mail.go index a966a97..5258ccf 100644 --- a/internal/notify/mail.go +++ b/internal/notify/mail.go @@ -2,6 +2,7 @@ package notify import ( "cmp" + "context" "crypto/tls" "fmt" "mime" @@ -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 @@ -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 diff --git a/internal/notify/notify.go b/internal/notify/notify.go index 53f13f3..acf5945 100644 --- a/internal/notify/notify.go +++ b/internal/notify/notify.go @@ -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 @@ -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 } diff --git a/internal/notify/notify_test.go b/internal/notify/notify_test.go index f2a0b77..6eb26f9 100644 --- a/internal/notify/notify_test.go +++ b/internal/notify/notify_test.go @@ -3,9 +3,11 @@ package notify import ( "context" "encoding/json" + "net" "net/http" "net/http/httptest" "testing" + "time" ) type captured struct { @@ -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) @@ -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") + } +}