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: 11 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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

Expand Down
42 changes: 24 additions & 18 deletions internal/cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"fmt"
"io"
"maps"
"net/url"
"os"
"sort"
"strings"
Expand Down Expand Up @@ -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
Expand All @@ -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)
Expand Down Expand Up @@ -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
Expand Down
22 changes: 19 additions & 3 deletions internal/cli/cli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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" {
Expand Down Expand Up @@ -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)
}
}
}
34 changes: 28 additions & 6 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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}.
Expand Down
23 changes: 23 additions & 0 deletions internal/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import (
"reflect"
"strings"
"testing"

"go.yaml.in/yaml/v3"
)

func TestExpandString(t *testing.T) {
Expand Down Expand Up @@ -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)
}
}
6 changes: 3 additions & 3 deletions internal/provider/exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion internal/provider/exec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
16 changes: 10 additions & 6 deletions internal/provider/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand All @@ -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)
Expand All @@ -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 {
Expand All @@ -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")
}
Expand Down
33 changes: 30 additions & 3 deletions internal/provider/http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand All @@ -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)
}
Expand All @@ -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)
}
}
Expand Down Expand Up @@ -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)
}
}
}
6 changes: 4 additions & 2 deletions internal/provider/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 9 additions & 0 deletions internal/provider/provider_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"} {
Expand Down
Loading
Loading