diff --git a/README.md b/README.md index a157766..8e063ca 100644 --- a/README.md +++ b/README.md @@ -108,9 +108,12 @@ order. Exit code is non-zero if any channel fails; failures on one channel don't stop the others. `retries` (under `defaults` or per channel; `--retries` overrides both, -default 0) retries temporary failures: network errors, HTTP 429/5xx and -SMTP 4xx replies. Backoff doubles from 1s up to 30s, and each attempt gets -the full timeout. Exec channels are never retried. +default 0) retries failures where nothing was delivered: connection +failures, HTTP 429/502/503/504 and SMTP 4xx replies. Timeouts after a request +was sent, HTTP 500 and exec failures are never retried, so a retry cannot +duplicate a notification. Backoff doubles from 1s up to 30s, and each +attempt gets the full timeout. Cross-host HTTP redirects are refused, since +they would forward headers and the body to another server. ## Adding a provider type diff --git a/internal/cli/cli.go b/internal/cli/cli.go index ba39b70..cbe5041 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -48,7 +48,7 @@ func Run(args []string, stdin *os.File, stdout, stderr io.Writer) error { subject = fs.String("subject", "", "subject override") tmplPath = fs.String("template", "", "body template file override (relative to template_dir or absolute)") timeout = fs.Duration("timeout", 0, "send timeout per attempt (default: defaults.timeout from config, else 30s)") - retries = fs.Int("retries", 0, "retry temporary failures (network errors, HTTP 429/5xx, SMTP 4xx) up to N times (default: channel or defaults.retries)") + retries = fs.Int("retries", 0, "retry temporary failures (connection failures, HTTP 429/502/503/504, SMTP 4xx) up to N times (default: channel or defaults.retries)") dryRun = fs.Bool("dry-run", false, "render everything and print what would be sent, without sending") list = fs.Bool("list", false, "list configured channels and exit") verbose = fs.Bool("verbose", false, "verbose output") diff --git a/internal/provider/http.go b/internal/provider/http.go index 4620943..9e7f304 100644 --- a/internal/provider/http.go +++ b/internal/provider/http.go @@ -3,8 +3,10 @@ package provider import ( "context" "crypto/tls" + "errors" "fmt" "io" + "net" "net/http" "net/url" "sort" @@ -179,12 +181,25 @@ func (h *httpSender) Describe(msg Message) string { } func (h *httpSender) client() *http.Client { - if !h.cfg.InsecureSkipVerify { - return http.DefaultClient + tr := http.DefaultTransport + if h.cfg.InsecureSkipVerify { + t := http.DefaultTransport.(*http.Transport).Clone() + t.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} + tr = t } - tr := http.DefaultTransport.(*http.Transport).Clone() - tr.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} - return &http.Client{Transport: tr} + return &http.Client{Transport: tr, CheckRedirect: sameHostRedirect} +} + +// sameHostRedirect follows redirects only within the original host: on +// 307/308 Go re-sends the body and custom headers, which may carry secrets. +func sameHostRedirect(req *http.Request, via []*http.Request) error { + if req.URL.Host != via[0].URL.Host { + return fmt.Errorf("refusing redirect to another host (%s)", req.URL.Host) + } + if len(via) >= 10 { + return errors.New("stopped after 10 redirects") + } + return nil } func (h *httpSender) Send(ctx context.Context, msg Message) error { @@ -196,7 +211,12 @@ func (h *httpSender) Send(ctx context.Context, msg Message) error { resp, err := h.client().Do(req) if err != nil { - return Temporary(fmt.Errorf("http request: %w", err)) + err = fmt.Errorf("http request: %w", err) + var opErr *net.OpError + if errors.As(err, &opErr) && opErr.Op == "dial" { + return Temporary(err) + } + return err } defer resp.Body.Close() respBody, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<10)) @@ -214,7 +234,8 @@ func (h *httpSender) Send(ctx context.Context, msg Message) error { } if !ok { err := fmt.Errorf("http: unexpected status %d: %s", resp.StatusCode, truncate(string(respBody), 300)) - if resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= 500 { + switch resp.StatusCode { + case http.StatusTooManyRequests, http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout: return Temporary(err) } return err diff --git a/internal/provider/http_test.go b/internal/provider/http_test.go index 6a8d72a..354be6c 100644 --- a/internal/provider/http_test.go +++ b/internal/provider/http_test.go @@ -2,11 +2,14 @@ package provider import ( "context" + "fmt" "io" "net/http" "net/http/httptest" "strings" + "sync/atomic" "testing" + "time" "github.com/suprbdev/noty/internal/render" ) @@ -290,7 +293,7 @@ func TestLooksLikeJSON(t *testing.T) { } func TestHTTPTemporaryErrors(t *testing.T) { - for status, want := range map[int]bool{503: true, 500: true, 429: true, 404: false, 400: false} { + for status, want := range map[int]bool{429: true, 502: true, 503: true, 504: true, 500: false, 404: false, 400: false} { var cap capture srv := serve(t, status, &cap) s, _ := New("http", chanNode(t, "type: http\nurl: "+srv.URL), &render.Renderer{}) @@ -306,3 +309,54 @@ func TestHTTPTemporaryErrors(t *testing.T) { t.Errorf("connection failure should be temporary: %v", err) } } + +func TestHTTPTimeoutIsNotTemporary(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + select { + case <-r.Context().Done(): + case <-time.After(2 * time.Second): + } + })) + t.Cleanup(srv.Close) + s, _ := New("http", chanNode(t, "type: http\nurl: "+srv.URL), &render.Renderer{}) + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + err := s.Send(ctx, testMsg("x")) + if err == nil || IsTemporary(err) { + t.Errorf("a timeout after the request was sent must not be retried (may duplicate): %v", err) + } +} + +func TestHTTPRedirects(t *testing.T) { + var other capture + otherSrv := serve(t, 200, &other) + var hops atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hops.Add(1) + switch r.URL.Path { + case "/away": + http.Redirect(w, r, otherSrv.URL+"/stolen", http.StatusTemporaryRedirect) + case "/move": + http.Redirect(w, r, "/here", http.StatusTemporaryRedirect) + default: + w.WriteHeader(200) + } + })) + t.Cleanup(srv.Close) + + cfg := "type: http\nurl: %s\nheaders:\n X-Api-Key: secret\n" + s, _ := New("http", chanNode(t, fmt.Sprintf(cfg, srv.URL+"/away")), &render.Renderer{}) + err := s.Send(context.Background(), testMsg("x")) + if err == nil || !strings.Contains(err.Error(), "another host") { + t.Errorf("cross-host redirect should be refused, got %v", err) + } + if other.method != "" { + t.Errorf("redirect target received the request (X-Api-Key=%q)", other.header.Get("X-Api-Key")) + } + + hops.Store(0) + s, _ = New("http", chanNode(t, fmt.Sprintf(cfg, srv.URL+"/move")), &render.Renderer{}) + if err := s.Send(context.Background(), testMsg("x")); err != nil || hops.Load() != 2 { + t.Errorf("same-host redirect should be followed: err=%v hops=%d", err, hops.Load()) + } +} diff --git a/internal/provider/smtp.go b/internal/provider/smtp.go index 8df6c34..f5fb059 100644 --- a/internal/provider/smtp.go +++ b/internal/provider/smtp.go @@ -170,19 +170,21 @@ func randomID() string { return hex.EncodeToString(id[:]) } -// smtpTemporary marks network errors and transient (4xx) SMTP replies as -// retryable. -func smtpTemporary(err error) error { +// smtpTemporary marks transient (4xx) SMTP replies as retryable, and network +// errors too unless they happened while the end of DATA was being +// acknowledged, when the server may already have accepted the message. +func smtpTemporary(err error, ambiguous bool) error { var te *textproto.Error var ne net.Error - if errors.As(err, &te) && te.Code >= 400 && te.Code < 500 || errors.As(err, &ne) { + if errors.As(err, &te) && te.Code >= 400 && te.Code < 500 || !ambiguous && errors.As(err, &ne) { return Temporary(err) } return err } func (s *smtpSender) Send(ctx context.Context, msg Message) (err error) { - defer func() { err = smtpTemporary(err) }() + ambiguous := false + defer func() { err = smtpTemporary(err, ambiguous) }() to, err := parseAddrs(s.recipients(msg)) if err != nil { return fmt.Errorf("smtp: to: %w", err) @@ -248,10 +250,12 @@ func (s *smtpSender) Send(ctx context.Context, msg Message) (err error) { if _, err := w.Write(s.message(msg, to)); err != nil { return fmt.Errorf("smtp write: %w", err) } + ambiguous = true if err := w.Close(); err != nil { return fmt.Errorf("smtp close data: %w", err) } - return c.Quit() + _ = c.Quit() + return nil } // loginAuth implements the SMTP LOGIN mechanism. Like smtp.PlainAuth it diff --git a/internal/provider/smtp_test.go b/internal/provider/smtp_test.go index 87b5832..51db53c 100644 --- a/internal/provider/smtp_test.go +++ b/internal/provider/smtp_test.go @@ -94,7 +94,7 @@ type smtpSession struct { // fakeSMTP accepts one plaintext SMTP session on a loopback port and reports // the commands and DATA payload it received. -func fakeSMTP(t *testing.T) (int, <-chan smtpSession) { +func fakeSMTP(t *testing.T, dropAfterData bool) (int, <-chan smtpSession) { t.Helper() ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { @@ -127,6 +127,9 @@ func fakeSMTP(t *testing.T) (int, <-chan smtpSession) { b, _ := tp.ReadDotBytes() sess.data = string(b) _ = tp.PrintfLine("250 queued") + if dropAfterData { + return + } case "AUTH": for _, prompt := range []string{"VXNlcm5hbWU6", "UGFzc3dvcmQ6"} { _ = tp.PrintfLine("334 %s", prompt) @@ -150,7 +153,7 @@ func fakeSMTP(t *testing.T) (int, <-chan smtpSession) { } func TestSMTPSend(t *testing.T) { - port, done := fakeSMTP(t) + port, done := fakeSMTP(t, false) cfg := fmt.Sprintf(`type: smtp host: 127.0.0.1 port: %d @@ -215,7 +218,7 @@ bcc: [audit@example.com] } func TestSMTPAuthLogin(t *testing.T) { - port, done := fakeSMTP(t) + port, done := fakeSMTP(t, false) cfg := fmt.Sprintf("type: smtp\nhost: 127.0.0.1\nport: %d\ntls: none\nauth: LOGIN\nusername: user@example.com\npassword: hunter2\nfrom: a@example.com\nto: [b@example.com]\n", port) s, err := New("smtp", chanNode(t, cfg), &render.Renderer{}) if err != nil { @@ -252,20 +255,40 @@ func TestLoginAuthRefusesPlaintext(t *testing.T) { } func TestSMTPTemporary(t *testing.T) { - if !IsTemporary(smtpTemporary(fmt.Errorf("rcpt: %w", &textproto.Error{Code: 451, Msg: "try later"}))) { - t.Error("4xx reply should be temporary") + for _, ambiguous := range []bool{false, true} { + if !IsTemporary(smtpTemporary(fmt.Errorf("rcpt: %w", &textproto.Error{Code: 451, Msg: "try later"}), ambiguous)) { + t.Error("4xx reply should be temporary") + } } - if IsTemporary(smtpTemporary(&textproto.Error{Code: 550, Msg: "no such user"})) { + if IsTemporary(smtpTemporary(&textproto.Error{Code: 550, Msg: "no such user"}, false)) { t.Error("5xx reply should be permanent") } - if IsTemporary(smtpTemporary(errors.New("smtp: no recipients"))) { + if IsTemporary(smtpTemporary(errors.New("smtp: no recipients"), false)) { t.Error("config errors should be permanent") } - if smtpTemporary(nil) != nil { + if smtpTemporary(nil, false) != nil { t.Error("nil must stay nil") } _, err := net.Dial("tcp", "127.0.0.1:1") - if err != nil && !IsTemporary(smtpTemporary(err)) { + if err != nil && !IsTemporary(smtpTemporary(err, false)) { t.Errorf("network error should be temporary: %v", err) } + if err != nil && IsTemporary(smtpTemporary(err, true)) { + t.Errorf("network error while DATA is acknowledged must not be retried: %v", err) + } +} + +func TestSMTPQuitErrorAfterAcceptedData(t *testing.T) { + port, done := fakeSMTP(t, true) + cfg := fmt.Sprintf("type: smtp\nhost: 127.0.0.1\nport: %d\ntls: none\nfrom: a@example.com\nto: [b@example.com]\n", port) + s, err := New("smtp", chanNode(t, cfg), &render.Renderer{}) + if err != nil { + t.Fatal(err) + } + msg := testMsg("x") + msg.To = nil + if err := s.Send(context.Background(), msg); err != nil { + t.Errorf("message was accepted; a failed QUIT must not fail (and retry) the send: %v", err) + } + <-done } diff --git a/noty.example.yaml b/noty.example.yaml index ab1dfc2..0a05796 100644 --- a/noty.example.yaml +++ b/noty.example.yaml @@ -8,7 +8,7 @@ defaults: channel: slack # used when --channel is not passed subject: "Notification from {{ .Hostname }}" timeout: 30s - retries: 0 # retry network errors, HTTP 429/5xx, SMTP 4xx + retries: 0 # retry connection failures, HTTP 429/502/503/504, SMTP 4xx # Global template variables, available as {{ .Vars.key }} in every template. vars: