diff --git a/README.md b/README.md index 7a7b7cb..898cc23 100644 --- a/README.md +++ b/README.md @@ -38,8 +38,10 @@ go build -o noty . - **Secrets stay in the environment.** Use `${VAR}` anywhere in the config; loading fails loudly if a variable is unset. `${VAR:-default}` allows a fallback, `$$` escapes a literal dollar. `--dry-run` output and error - messages show every value taken from the environment as `${VAR}`, and - header/query/form fields named like credentials as `REDACTED`. + messages show values substituted via `${VAR}` (4+ bytes, raw or + URL-escaped) as `${VAR}`, and header/query/form fields named like + credentials as `REDACTED`. Values read with the `env` template function + are not masked. - **Templates live outside the binary** as plain files (Go `text/template` syntax), resolved relative to `template_dir`, or inline in the config. @@ -116,12 +118,13 @@ 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 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. +default 0) retries failures that normally mean 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, +since the notification may already have gone out. Backoff doubles from 1s +up to 30s, and each attempt gets the full timeout. HTTP redirects to another +host or from https to http are refused, since they would forward headers +and the body. ## Adding a provider type diff --git a/internal/cli/cli.go b/internal/cli/cli.go index b4545d6..ccf3474 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -8,6 +8,7 @@ import ( "fmt" "io" "maps" + "net/url" "os" "sort" "strings" @@ -214,10 +215,6 @@ func Run(args []string, stdin *os.File, stdout, stderr io.Writer) error { msg := provider.Message{Subject: subj, Body: body, To: toFlags, Data: data} - if *dryRun { - return sender.Describe(msg), nil - } - maxRetries := cfg.Defaults.Retries if ch.Common.Retries != nil { maxRetries = *ch.Common.Retries @@ -229,6 +226,10 @@ func Run(args []string, stdin *os.File, stdout, stderr io.Writer) error { return "", fmt.Errorf("retries must be >= 0, got %d", maxRetries) } + if *dryRun { + return sender.Describe(msg) + } + for attempt := 1; ; attempt++ { ctx, cancel := context.WithTimeout(context.Background(), to) err = sender.Send(ctx, msg) @@ -278,29 +279,34 @@ func Run(args []string, stdin *os.File, stdout, stderr io.Writer) error { } // secretMasker returns a function that replaces every value substituted -// from the environment with its ${NAME} reference. Values shorter than four -// bytes are left alone so common substrings aren't masked. +// from the environment, raw or URL query/path-escaped, with its ${NAME} +// reference. Values shorter than four bytes are left alone so common +// substrings aren't masked. func secretMasker(env map[string]string) func(string) string { - names := make([]string, 0, len(env)) + type pair struct{ old, ref string } + var pairs []pair for name, v := range env { - if len(v) >= 4 { - names = append(names, name) + if len(v) < 4 { + continue + } + for _, form := range []string{v, url.QueryEscape(v), url.PathEscape(v)} { + pairs = append(pairs, pair{form, "${" + name + "}"}) } } - if len(names) == 0 { + if len(pairs) == 0 { return func(s string) string { return s } } - sort.Slice(names, func(i, j int) bool { - if len(env[names[i]]) != len(env[names[j]]) { - return len(env[names[i]]) > len(env[names[j]]) + sort.Slice(pairs, func(i, j int) bool { + if len(pairs[i].old) != len(pairs[j].old) { + return len(pairs[i].old) > len(pairs[j].old) } - return names[i] < names[j] + return pairs[i].old < pairs[j].old || pairs[i].old == pairs[j].old && pairs[i].ref < pairs[j].ref }) - pairs := make([]string, 0, 2*len(names)) - for _, name := range names { - pairs = append(pairs, env[name], "${"+name+"}") + args := make([]string, 0, 2*len(pairs)) + for _, p := range pairs { + args = append(args, p.old, p.ref) } - return strings.NewReplacer(pairs...).Replace + return strings.NewReplacer(args...).Replace } // readStdin returns piped stdin text with trailing newlines removed. A nil or diff --git a/internal/cli/cli_test.go b/internal/cli/cli_test.go index a735a59..ea045a6 100644 --- a/internal/cli/cli_test.go +++ b/internal/cli/cli_test.go @@ -426,9 +426,9 @@ func TestRunRejectsNonPositiveTimeout(t *testing.T) { } func TestSecretMasker(t *testing.T) { - mask := secretMasker(map[string]string{"SHORT": "abc", "TOKEN": "s3cr3t", "LONG": "s3cr3t-and-more"}) - got := mask("abc s3cr3t s3cr3t-and-more") - if want := "abc ${TOKEN} ${LONG}"; got != want { + mask := secretMasker(map[string]string{"SHORT": "abc", "TOKEN": "s3cr3t", "LONG": "s3cr3t-and-more", "ESC": "ab+cd/ef=="}) + got := mask("abc s3cr3t s3cr3t-and-more ab%2Bcd%2Fef%3D%3D ab+cd%2Fef==") + if want := "abc ${TOKEN} ${LONG} ${ESC} ${ESC}"; got != want { t.Errorf("mask = %q, want %q", got, want) } if got := secretMasker(nil)("unchanged"); got != "unchanged" { @@ -465,3 +465,19 @@ channels: t.Errorf("expected masked references in dry-run and both errors:\n%s", out) } } + +func TestRunDryRunValidatesLikeSend(t *testing.T) { + cases := map[string]string{ + "negative retries": "defaults:\n retries: -1\nchannels:\n c:\n type: exec\n command: \"true\"\n", + "invalid recipient": "channels:\n c:\n type: smtp\n host: h\n from: a@b.c\n to: [\"not an address\"]\n", + } + for name, cfg := range cases { + path := filepath.Join(t.TempDir(), "noty.yaml") + if err := os.WriteFile(path, []byte(cfg), 0o600); err != nil { + t.Fatal(err) + } + if err := run("-c", path, "-m", "x", "--channel", "c", "--dry-run"); err == nil { + t.Errorf("%s: --dry-run must fail like a real send", name) + } + } +} diff --git a/internal/config/config.go b/internal/config/config.go index 9fd1ad1..9542010 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -101,8 +101,9 @@ func (d *Defaults) UnmarshalYAML(node *yaml.Node) error { // CheckKeys returns an error naming the first key of the mapping node that // is not a yaml field of any of the given structs (values or pointers), so -// typos fail loudly instead of being silently ignored. Non-mapping nodes are -// left for Decode to report. +// typos fail loudly instead of being silently ignored. Keys pulled in with a +// YAML merge (<<) are checked too. Non-mapping nodes are left for Decode to +// report. func CheckKeys(node *yaml.Node, structs ...any) error { if node.Kind != yaml.MappingNode { return nil @@ -124,12 +125,33 @@ func CheckKeys(node *yaml.Node, structs ...any) error { known[name] = true } } - for i := 0; i+1 < len(node.Content); i += 2 { - if k := node.Content[i]; !known[k.Value] { - return fmt.Errorf("line %d: unknown field %q", k.Line, k.Value) + var check func(n *yaml.Node) error + check = func(n *yaml.Node) error { + if n.Kind == yaml.AliasNode { + n = n.Alias } + switch n.Kind { + case yaml.SequenceNode: + for _, c := range n.Content { + if err := check(c); err != nil { + return err + } + } + case yaml.MappingNode: + for i := 0; i+1 < len(n.Content); i += 2 { + k := n.Content[i] + if k.ShortTag() == "!!merge" { + if err := check(n.Content[i+1]); err != nil { + return err + } + } else if !known[k.Value] { + return fmt.Errorf("line %d: unknown field %q", k.Line, k.Value) + } + } + } + return nil } - return nil + return check(node) } // envPattern matches $$, ${VAR}, and ${VAR:-default}. diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 794013d..84965d9 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -6,6 +6,8 @@ import ( "reflect" "strings" "testing" + + "go.yaml.in/yaml/v3" ) func TestExpandString(t *testing.T) { @@ -219,3 +221,24 @@ func TestDefaultPathsSkipWorkingDirectory(t *testing.T) { } } } + +func TestCheckKeysFollowsMerges(t *testing.T) { + type fields struct { + Type string `yaml:"type"` + URL string `yaml:"url"` + Body string `yaml:"body"` + } + parse := func(src string) *yaml.Node { + var doc yaml.Node + if err := yaml.Unmarshal([]byte(src), &doc); err != nil { + t.Fatal(err) + } + return doc.Content[0].Content[3] + } + if err := CheckKeys(parse("base: &b {type: http, url: x}\nalt: {<<: *b, body: y}\n"), fields{}); err != nil { + t.Errorf("merge key must be accepted: %v", err) + } + if err := CheckKeys(parse("base: &b {type: http, ur: x}\nalt: {<<: [*b], body: y}\n"), fields{}); err == nil || !strings.Contains(err.Error(), `"ur"`) { + t.Errorf("unknown key inside merged mapping must be reported, got %v", err) + } +} diff --git a/internal/provider/exec.go b/internal/provider/exec.go index fa12227..547cd34 100644 --- a/internal/provider/exec.go +++ b/internal/provider/exec.go @@ -60,12 +60,12 @@ func (e *execSender) renderArgs(msg Message) ([]string, error) { return out, nil } -func (e *execSender) Describe(msg Message) string { +func (e *execSender) Describe(msg Message) (string, error) { args, err := e.renderArgs(msg) if err != nil { - return fmt.Sprintf("exec (error rendering args: %v)", err) + return "", fmt.Errorf("exec: %w", err) } - return fmt.Sprintf("exec %s %s (stdin: %d bytes)", e.cfg.Command, strings.Join(args, " "), len(msg.Body)) + return fmt.Sprintf("exec %s %s (stdin: %d bytes)", e.cfg.Command, strings.Join(args, " "), len(msg.Body)), nil } func (e *execSender) Send(ctx context.Context, msg Message) error { diff --git a/internal/provider/exec_test.go b/internal/provider/exec_test.go index 420334f..d657730 100644 --- a/internal/provider/exec_test.go +++ b/internal/provider/exec_test.go @@ -95,7 +95,7 @@ args: ["{{ .Subject }}"] if err != nil { t.Fatal(err) } - out := s.Describe(testMsg("body")) + out := describe(t, s, testMsg("body")) if !strings.Contains(out, "echo subj") { t.Errorf("Describe should show rendered command line: %q", out) } diff --git a/internal/provider/http.go b/internal/provider/http.go index 9e7f304..199e419 100644 --- a/internal/provider/http.go +++ b/internal/provider/http.go @@ -131,7 +131,7 @@ const redacted = "REDACTED" // it carries a credential. func sensitive(name string) bool { n := strings.ToLower(name) - for _, s := range []string{"auth", "key", "token", "secret", "password"} { + for _, s := range []string{"auth", "key", "token", "secret", "pass", "cookie", "session", "signature", "credential"} { if strings.Contains(n, s) { return true } @@ -150,10 +150,10 @@ func redactValues(vals url.Values) url.Values { return out } -func (h *httpSender) Describe(msg Message) string { +func (h *httpSender) Describe(msg Message) (string, error) { req, body, err := h.build(msg) if err != nil { - return fmt.Sprintf("http (error building request: %v)", err) + return "", fmt.Errorf("http: %w", err) } if len(h.cfg.Form) > 0 { vals, _ := h.form(msg) @@ -177,7 +177,7 @@ func (h *httpSender) Describe(msg Message) string { hdrs[i] = k + ": " + v } return fmt.Sprintf("%s %s\n headers: %s\n body: %s", - req.Method, u.Redacted(), strings.Join(hdrs, "; "), truncate(body, 500)) + req.Method, u.Redacted(), strings.Join(hdrs, "; "), truncate(body, 500)), nil } func (h *httpSender) client() *http.Client { @@ -190,12 +190,16 @@ func (h *httpSender) client() *http.Client { 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. +// sameHostRedirect follows redirects only within the original host and +// never from https to http: on 307/308 Go re-sends the body and 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 via[0].URL.Scheme == "https" && req.URL.Scheme != "https" { + return fmt.Errorf("refusing redirect from https to %s", req.URL.Scheme) + } if len(via) >= 10 { return errors.New("stopped after 10 redirects") } diff --git a/internal/provider/http_test.go b/internal/provider/http_test.go index 354be6c..17e35b8 100644 --- a/internal/provider/http_test.go +++ b/internal/provider/http_test.go @@ -212,7 +212,7 @@ headers: if err != nil { t.Fatal(err) } - out := s.Describe(testMsg("body")) + out := describe(t, s, testMsg("body")) if strings.Contains(out, "supersecret") || strings.Contains(out, "alsosecret") { t.Errorf("secrets leaked in dry-run output:\n%s", out) } @@ -236,7 +236,7 @@ form: if err != nil { t.Fatal(err) } - out := s.Describe(testMsg("body")) + out := describe(t, s, testMsg("body")) if strings.Contains(out, "qsecret") || strings.Contains(out, "formsecret") { t.Errorf("secrets leaked in dry-run output:\n%s", out) } @@ -253,7 +253,7 @@ func TestHTTPDescribeHeaderOrder(t *testing.T) { if err != nil { t.Fatal(err) } - if out := s.Describe(testMsg("plain")); !strings.Contains(out, "headers: X-A: a; X-B: b; X-C: c") { + if out := describe(t, s, testMsg("plain")); !strings.Contains(out, "headers: X-A: a; X-B: b; X-C: c") { t.Errorf("headers not sorted:\n%s", out) } } @@ -360,3 +360,30 @@ func TestHTTPRedirects(t *testing.T) { t.Errorf("same-host redirect should be followed: err=%v hops=%d", err, hops.Load()) } } + +func TestSameHostRedirectRefusesDowngrade(t *testing.T) { + via := []*http.Request{httptest.NewRequest("POST", "https://h.example/a", nil)} + if err := sameHostRedirect(httptest.NewRequest("POST", "http://h.example/b", nil), via); err == nil { + t.Error("https to http redirect must be refused") + } + if err := sameHostRedirect(httptest.NewRequest("POST", "https://h.example/b", nil), via); err != nil { + t.Errorf("same-host https redirect should be followed: %v", err) + } + via = []*http.Request{httptest.NewRequest("POST", "http://h.example/a", nil)} + if err := sameHostRedirect(httptest.NewRequest("POST", "https://h.example/b", nil), via); err != nil { + t.Errorf("http to https upgrade should be followed: %v", err) + } +} + +func TestSensitiveNames(t *testing.T) { + for _, name := range []string{"Authorization", "X-Api-Key", "token", "client_secret", "passwd", "Cookie", "session_id", "X-Signature", "credentials"} { + if !sensitive(name) { + t.Errorf("%q should be treated as sensitive", name) + } + } + for _, name := range []string{"Content-Type", "message", "title", "To"} { + if sensitive(name) { + t.Errorf("%q should not be treated as sensitive", name) + } + } +} diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 41c5f70..53e869b 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -28,8 +28,10 @@ type Sender interface { // Send delivers the message. Implementations should honor ctx // cancellation and wrap failures worth retrying with Temporary. Send(ctx context.Context, msg Message) error - // Describe returns a human-readable summary used by --dry-run. - Describe(msg Message) string + // Describe returns a human-readable summary used by --dry-run. It reports + // the configuration and rendering errors Send would fail with, without + // any network or process activity. + Describe(msg Message) (string, error) } // Factory builds a Sender from the channel's raw YAML node. The renderer is diff --git a/internal/provider/provider_test.go b/internal/provider/provider_test.go index d97f6f3..97b4617 100644 --- a/internal/provider/provider_test.go +++ b/internal/provider/provider_test.go @@ -19,6 +19,15 @@ func chanNode(t *testing.T, src string) *yaml.Node { return doc.Content[0] } +func describe(t *testing.T, s Sender, msg Message) string { + t.Helper() + out, err := s.Describe(msg) + if err != nil { + t.Fatal(err) + } + return out +} + func TestRegistryTypes(t *testing.T) { types := Types() for _, want := range []string{"exec", "http", "smtp"} { diff --git a/internal/provider/smtp.go b/internal/provider/smtp.go index f5fb059..a087e1b 100644 --- a/internal/provider/smtp.go +++ b/internal/provider/smtp.go @@ -122,17 +122,29 @@ func joinAddrs(addrs []*mail.Address) string { return strings.Join(parts, ", ") } -func (s *smtpSender) recipients(msg Message) []string { - to := msg.To +// recipients returns the parsed --to addresses, else the configured ones. +func (s *smtpSender) recipients(msg Message) ([]*mail.Address, error) { + list := msg.To + if len(list) == 0 { + list = s.cfg.To + } + to, err := parseAddrs(list) + if err != nil { + return nil, fmt.Errorf("smtp: to: %w", err) + } if len(to) == 0 { - to = s.cfg.To + return nil, fmt.Errorf("smtp: no recipients (set 'to' in config or pass --to)") } - return to + return to, nil } -func (s *smtpSender) Describe(msg Message) string { - return fmt.Sprintf("smtp %s (%s) from=%s to=%v subject=%q body=%d bytes", - net.JoinHostPort(s.cfg.Host, strconv.Itoa(s.cfg.Port)), s.cfg.TLS, s.cfg.From, s.recipients(msg), msg.Subject, len(msg.Body)) +func (s *smtpSender) Describe(msg Message) (string, error) { + to, err := s.recipients(msg) + if err != nil { + return "", err + } + return fmt.Sprintf("smtp %s (%s) from=%s to=%s subject=%q body=%d bytes", + net.JoinHostPort(s.cfg.Host, strconv.Itoa(s.cfg.Port)), s.cfg.TLS, s.from, joinAddrs(to), msg.Subject, len(msg.Body)), nil } // message renders the RFC 5322 message: headers plus a quoted-printable body, @@ -185,12 +197,9 @@ func smtpTemporary(err error, ambiguous bool) error { func (s *smtpSender) Send(ctx context.Context, msg Message) (err error) { ambiguous := false defer func() { err = smtpTemporary(err, ambiguous) }() - to, err := parseAddrs(s.recipients(msg)) + to, err := s.recipients(msg) if err != nil { - return fmt.Errorf("smtp: to: %w", err) - } - if len(to) == 0 { - return fmt.Errorf("smtp: no recipients (set 'to' in config or pass --to)") + return err } all := append(append(append([]*mail.Address{}, to...), s.cc...), s.bcc...) diff --git a/internal/provider/smtp_test.go b/internal/provider/smtp_test.go index 51db53c..d39765d 100644 --- a/internal/provider/smtp_test.go +++ b/internal/provider/smtp_test.go @@ -30,7 +30,7 @@ func TestSMTPDefaults(t *testing.T) { if err != nil { t.Fatal(err) } - out := s.Describe(testMsg("body")) + out := describe(t, s, mailMsg()) if !strings.Contains(out, "mail.example.com:587") { t.Errorf("default port 587 expected: %q", out) } @@ -49,13 +49,13 @@ func TestSMTPRecipientOverride(t *testing.T) { // --to flag wins. msg := testMsg("x") msg.To = []string{"flag@example.com"} - if out := s.Describe(msg); !strings.Contains(out, "flag@example.com") { + if out := describe(t, s, msg); !strings.Contains(out, "flag@example.com") { t.Errorf("flag recipients should override config: %q", out) } // Config to used when no flag. msg.To = nil - if out := s.Describe(msg); !strings.Contains(out, "config@example.com") { + if out := describe(t, s, msg); !strings.Contains(out, "config@example.com") { t.Errorf("config recipients expected: %q", out) } } @@ -70,7 +70,7 @@ func TestSMTPTLSValidation(t *testing.T) { if err != nil { t.Fatal(err) } - if out := s.Describe(testMsg("x")); !strings.Contains(out, "h:465 (tls)") { + if out := describe(t, s, mailMsg()); !strings.Contains(out, "h:465 (tls)") { t.Errorf("implicit TLS should default to port 465: %q", out) } } @@ -292,3 +292,23 @@ func TestSMTPQuitErrorAfterAcceptedData(t *testing.T) { } <-done } + +func mailMsg() Message { + msg := testMsg("body") + msg.To = []string{"rcpt@example.com"} + return msg +} + +func TestSMTPDescribeValidatesRecipients(t *testing.T) { + s, err := New("smtp", chanNode(t, "type: smtp\nhost: h\nfrom: a@b.c"), &render.Renderer{}) + if err != nil { + t.Fatal(err) + } + for _, to := range [][]string{nil, {"not an address"}} { + msg := testMsg("x") + msg.To = to + if _, err := s.Describe(msg); err == nil { + t.Errorf("to=%q: dry-run must report what Send would reject", to) + } + } +}