From b701ba4006ce69ef6b57fb08e52c864d4b5862a8 Mon Sep 17 00:00:00 2001 From: Matt Edmonston Date: Sat, 28 Nov 2026 04:12:00 +0000 Subject: [PATCH] Export a notify package for sending from Go programs github.com/suprbdev/noty/notify loads the same YAML config as the CLI and sends messages in-process: Load/Parse, New with options for the HTTP client, exec runner, timeout, retries and clock, and Client.Send with per-channel results. Provider internals stay internal. The CLI now sends through the package, so both share one code path. CLI flags, output and exit codes are unchanged. --- README.md | 48 +++- internal/cli/cli.go | 217 +++------------- internal/cli/cli_test.go | 11 - internal/config/config.go | 36 ++- internal/provider/exec.go | 31 ++- internal/provider/http.go | 35 ++- internal/provider/provider.go | 48 +++- internal/provider/smtp.go | 3 +- notify/config.go | 91 +++++++ notify/errors.go | 62 +++++ notify/example_test.go | 104 ++++++++ notify/mask.go | 38 +++ notify/mask_test.go | 14 ++ notify/notify.go | 385 +++++++++++++++++++++++++++++ notify/notify_test.go | 448 ++++++++++++++++++++++++++++++++++ 15 files changed, 1345 insertions(+), 226 deletions(-) create mode 100644 notify/config.go create mode 100644 notify/errors.go create mode 100644 notify/example_test.go create mode 100644 notify/mask.go create mode 100644 notify/mask_test.go create mode 100644 notify/notify.go create mode 100644 notify/notify_test.go diff --git a/README.md b/README.md index 898cc23..17f17ce 100644 --- a/README.md +++ b/README.md @@ -126,6 +126,49 @@ 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. +## Go package + +`github.com/suprbdev/noty/notify` sends notifications from a Go program +with the same config format, templates, fan-out, retries and secret masking +as the CLI (which is built on it): + +``` +go get github.com/suprbdev/noty@latest +``` + +```go +cfg, err := notify.Load("/etc/myapp/noty.yaml") // or notify.Parse(data) +if err != nil { + return err // errors.Is(err, notify.ErrInvalidConfig) for config problems +} +client, err := notify.New(cfg) +if err != nil { + return err +} +res, err := client.Send(ctx, notify.Message{ + Channels: []string{"slack", "email"}, // empty: defaults.channel + Subject: "deploy finished", + Text: "api v2.4 is live", // {{ .Message }} + Vars: map[string]string{"environment": "prod"}, +}) +var sendErr *notify.SendError +if errors.As(err, &sendErr) { + // Some channels failed; the others were still attempted. + log.Printf("failed channels %v: %v", res.Failed(), err) +} +``` + +`Message` also has `To` (recipient override), `Template` (body template +file override) and `DryRun` (render and validate only; each +`ChannelResult.Description` says what would be sent). `Send` returns +`notify.ErrNoChannel` or an error wrapping `notify.ErrUnknownChannel` +before sending anything when the channels can't be resolved. + +Options: `notify.WithLookupEnv` resolves `${VAR}` through your own lookup +instead of the process environment (for `Load`/`Parse`); `WithHTTPClient`, +`WithExecRunner` (fake or restrict `exec` channels), `WithTimeout`, +`WithRetries`, `WithBackoff` and `WithClock` customise the client. + ## Adding a provider type Implement the `Sender` interface and register a factory — nothing else @@ -134,7 +177,7 @@ changes: ```go // internal/provider/carrierpigeon.go func init() { - Register("pigeon", func(node *yaml.Node, r *render.Renderer) (Sender, error) { + Register("pigeon", func(node *yaml.Node, deps Deps) (Sender, error) { var cfg pigeonConfig if err := Decode(node, "pigeon", &cfg); err != nil { return nil, err } return &pigeonSender{cfg}, nil @@ -143,7 +186,8 @@ func init() { ``` Each provider decodes its own YAML from the channel node, so new settings -never touch the core config code. `Decode` rejects keys that are neither +never touch the core config code. `deps.Renderer` templates the provider's +own fields. `Decode` rejects keys that are neither provider fields nor common channel fields, so config typos fail loudly with a line number. diff --git a/internal/cli/cli.go b/internal/cli/cli.go index ccf3474..7c14f78 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -1,4 +1,4 @@ -// Package cli wires flags, stdin, config, templates, and providers together. +// Package cli maps flags and stdin onto the notify package. package cli import ( @@ -7,17 +7,12 @@ import ( "flag" "fmt" "io" - "maps" - "net/url" "os" - "sort" "strings" - "sync" - "time" "github.com/suprbdev/noty/internal/config" "github.com/suprbdev/noty/internal/provider" - "github.com/suprbdev/noty/internal/render" + "github.com/suprbdev/noty/notify" ) type multiFlag []string @@ -27,9 +22,7 @@ func (m *multiFlag) Set(v string) error { *m = append(*m, v); return nil } // retryDelay is the backoff before retry number attempt (1-based): // 1s, 2s, 4s, ... capped at 30s. -var retryDelay = func(attempt int) time.Duration { - return min(time.Second< defaults.subject), wrapped by the channel template/inline. - base := *subject - if base == "" { - var err error - if base, err = renderer.Resolve("", cfg.Defaults.Subject, "", data); err != nil { - return "", fmt.Errorf("defaults.subject: %w", err) - } - } - data.Subject = base - subj, err := renderer.Resolve(ch.Common.SubjectTemplate, ch.Common.Subject, base, data) - if err != nil { - return "", fmt.Errorf("subject: %w", err) - } - data.Subject = subj - - // Body: --template flag > channel body_template > channel inline body > raw message. - bodyTmpl := *tmplPath - if bodyTmpl == "" { - bodyTmpl = ch.Common.BodyTemplate - } - body, err := renderer.Resolve(bodyTmpl, ch.Common.Body, msgText, data) - if err != nil { - return "", fmt.Errorf("body: %w", err) - } - - sender, err := provider.New(ch.Type, ch.Raw, renderer) - if err != nil { - return "", err - } - - msg := provider.Message{Subject: subj, Body: body, To: toFlags, Data: data} - - maxRetries := cfg.Defaults.Retries - if ch.Common.Retries != nil { - maxRetries = *ch.Common.Retries - } - if set["retries"] { - maxRetries = *retries - } - if maxRetries < 0 { - 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) - cancel() - if err == nil || attempt > maxRetries || !provider.IsTemporary(err) { - if err != nil && attempt > 1 { - err = fmt.Errorf("%w (after %d attempts)", err, attempt) - } - return "", err - } - time.Sleep(retryDelay(attempt)) + res, err := client.Send(context.Background(), notify.Message{ + Channels: chNames, + To: toFlags, + Subject: *subject, + Text: msgText, + Template: *tmplPath, + Vars: flagVars, + DryRun: *dryRun, + }) + var sendErr *notify.SendError + if err != nil && !errors.As(err, &sendErr) { + if errors.Is(err, notify.ErrUnknownChannel) { + return fmt.Errorf("%w (run --list to see channels)", err) } + return err } - type result struct { - desc string - err error - } - results := make([]result, len(chNames)) - var wg sync.WaitGroup - for i, name := range chNames { - wg.Add(1) - go func() { - defer wg.Done() - results[i].desc, results[i].err = send(name) - }() - } - wg.Wait() - - var failed []string - for i, name := range chNames { - switch r := results[i]; { - case r.err != nil: - fmt.Fprintf(stderr, "channel %q: %s\n", name, mask(r.err.Error())) - failed = append(failed, name) + for _, r := range res.Channels { + switch { + case r.Err != nil: + fmt.Fprintf(stderr, "channel %q: %s\n", r.Channel, r.Err) case *dryRun: - fmt.Fprintf(stdout, "[dry-run] channel %q:\n %s\n", name, mask(r.desc)) + fmt.Fprintf(stdout, "[dry-run] channel %q:\n %s\n", r.Channel, r.Description) case *verbose: - fmt.Fprintf(stderr, "channel %q: sent\n", name) + fmt.Fprintf(stderr, "channel %q: sent\n", r.Channel) } } - if len(failed) > 0 { + if failed := res.Failed(); len(failed) > 0 { return fmt.Errorf("failed channels: %v", failed) } return nil } -// secretMasker returns a function that replaces every value substituted -// 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 { - type pair struct{ old, ref string } - var pairs []pair - for name, v := range env { - if len(v) < 4 { - continue - } - for _, form := range []string{v, url.QueryEscape(v), url.PathEscape(v)} { - pairs = append(pairs, pair{form, "${" + name + "}"}) - } - } - if len(pairs) == 0 { - return func(s string) string { return s } - } - 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 pairs[i].old < pairs[j].old || pairs[i].old == pairs[j].old && pairs[i].ref < pairs[j].ref - }) - args := make([]string, 0, 2*len(pairs)) - for _, p := range pairs { - args = append(args, p.old, p.ref) - } - return strings.NewReplacer(args...).Replace -} - // readStdin returns piped stdin text with trailing newlines removed. A nil or // unreadable stdin and the null device yield an empty message; an interactive // terminal is an error so a forgotten -m doesn't send a blank notification. diff --git a/internal/cli/cli_test.go b/internal/cli/cli_test.go index ea045a6..a7b6f5f 100644 --- a/internal/cli/cli_test.go +++ b/internal/cli/cli_test.go @@ -425,17 +425,6 @@ func TestRunRejectsNonPositiveTimeout(t *testing.T) { } } -func TestSecretMasker(t *testing.T) { - 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" { - t.Errorf("empty masker changed input: %q", got) - } -} - func TestRunMasksEnvSecrets(t *testing.T) { t.Setenv("NOTY_TEST_TOKEN", "tok-123456") cfg := ` diff --git a/internal/config/config.go b/internal/config/config.go index 9542010..ad53dfb 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -29,7 +29,8 @@ type Config struct { // provider-specific and decoded by the provider itself. Channels map[string]Channel `yaml:"channels"` - // Path is the file the config was loaded from (not part of YAML). + // Path is the file the config was loaded from, empty when it was parsed + // from data (not part of YAML). Path string `yaml:"-"` // EnvValues maps each environment variable substituted into the config // to its value, so output can mask secrets (not part of YAML). @@ -161,8 +162,10 @@ var envPattern = regexp.MustCompile(`\$\$|\$\{([A-Za-z_][A-Za-z0-9_]*)(:-([^}]*) // parsed YAML tree, so values are never re-parsed as YAML. $$ escapes a // literal dollar sign. Unset variables without a default are collected in // missing so misconfigured secrets fail loudly instead of silently; values -// taken from the environment are recorded in used. +// taken from the environment are recorded in used. A nil lookup reads the +// process environment. type expander struct { + lookup func(string) (string, bool) missing []string used map[string]string } @@ -194,7 +197,11 @@ func (e *expander) expand(s string) string { } groups := envPattern.FindStringSubmatch(m) name, hasDefault, def := groups[1], groups[2] != "", groups[3] - if v, ok := os.LookupEnv(name); ok { + lookup := e.lookup + if lookup == nil { + lookup = os.LookupEnv + } + if v, ok := lookup(name); ok { if e.used == nil { e.used = map[string]string{} } @@ -217,20 +224,33 @@ func Load(path string) (*Config, error) { if err != nil { return nil, err } + return Parse(raw, path, nil) +} + +// Parse parses and env-expands raw config data. path is the file the data +// came from: it prefixes errors and anchors a relative template_dir. With an +// empty path errors are prefixed with "config" and template paths resolve +// against the working directory. lookup resolves ${VAR} references; nil +// means os.LookupEnv. +func Parse(raw []byte, path string, lookup func(string) (string, bool)) (*Config, error) { + name := path + if name == "" { + name = "config" + } var doc yaml.Node if err := yaml.Unmarshal(raw, &doc); err != nil { - return nil, fmt.Errorf("%s: %w", path, err) + return nil, fmt.Errorf("%s: %w", name, err) } var cfg Config if len(doc.Content) > 0 { - var e expander + e := expander{lookup: lookup} e.node(&doc) if len(e.missing) > 0 { - return nil, fmt.Errorf("%s: environment variable(s) not set: %v (use ${VAR:-default} to allow a fallback)", path, e.missing) + return nil, fmt.Errorf("%s: environment variable(s) not set: %v (use ${VAR:-default} to allow a fallback)", name, e.missing) } cfg.EnvValues = e.used if err := doc.Decode(&cfg); err != nil { - return nil, fmt.Errorf("%s: %w", path, err) + return nil, fmt.Errorf("%s: %w", name, err) } } cfg.Path = path @@ -240,7 +260,7 @@ func Load(path string) (*Config, error) { cfg.TemplateDir = filepath.Join(filepath.Dir(path), cfg.TemplateDir) } if len(cfg.Channels) == 0 { - return nil, fmt.Errorf("%s: no channels defined", path) + return nil, fmt.Errorf("%s: no channels defined", name) } return &cfg, nil } diff --git a/internal/provider/exec.go b/internal/provider/exec.go index 547cd34..55b7505 100644 --- a/internal/provider/exec.go +++ b/internal/provider/exec.go @@ -33,10 +33,11 @@ const execWaitDelay = time.Second type execSender struct { cfg execConfig r *render.Renderer + run Runner } func init() { - Register("exec", func(node *yaml.Node, r *render.Renderer) (Sender, error) { + Register("exec", func(node *yaml.Node, deps Deps) (Sender, error) { var cfg execConfig if err := Decode(node, "exec", &cfg); err != nil { return nil, err @@ -44,7 +45,11 @@ func init() { if cfg.Command == "" { return nil, fmt.Errorf("exec: 'command' is required") } - return &execSender{cfg: cfg, r: r}, nil + run := deps.Runner + if run == nil { + run = runCommand + } + return &execSender{cfg: cfg, r: deps.Renderer, run: run}, nil }) } @@ -73,9 +78,7 @@ func (e *execSender) Send(ctx context.Context, msg Message) error { if err != nil { return fmt.Errorf("exec: %w", err) } - cmd := exec.CommandContext(ctx, e.cfg.Command, args...) - cmd.WaitDelay = execWaitDelay - cmd.Env = os.Environ() + cmd := Command{Path: e.cfg.Command, Args: args, Env: os.Environ()} for k, v := range e.cfg.Env { rv, err := e.r.RenderString("env."+k, v, msg.Data) if err != nil { @@ -86,12 +89,22 @@ func (e *execSender) Send(ctx context.Context, msg Message) error { if e.cfg.StdinBody == nil || *e.cfg.StdinBody { cmd.Stdin = strings.NewReader(msg.Body) } - out, err := cmd.CombinedOutput() - if errors.Is(err, exec.ErrWaitDelay) && cmd.ProcessState != nil && cmd.ProcessState.Success() { - err = nil - } + out, err := e.run(ctx, cmd) if err != nil { return fmt.Errorf("exec %s: %w: %s", e.cfg.Command, err, truncate(string(out), 300)) } return nil } + +// runCommand is the default Runner, built on os/exec. +func runCommand(ctx context.Context, c Command) ([]byte, error) { + cmd := exec.CommandContext(ctx, c.Path, c.Args...) + cmd.WaitDelay = execWaitDelay + cmd.Env = c.Env + cmd.Stdin = c.Stdin + out, err := cmd.CombinedOutput() + if errors.Is(err, exec.ErrWaitDelay) && cmd.ProcessState != nil && cmd.ProcessState.Success() { + err = nil + } + return out, err +} diff --git a/internal/provider/http.go b/internal/provider/http.go index 199e419..e36f703 100644 --- a/internal/provider/http.go +++ b/internal/provider/http.go @@ -45,12 +45,13 @@ type httpConfig struct { } type httpSender struct { - cfg httpConfig - r *render.Renderer + cfg httpConfig + r *render.Renderer + base *http.Client } func init() { - Register("http", func(node *yaml.Node, r *render.Renderer) (Sender, error) { + Register("http", func(node *yaml.Node, deps Deps) (Sender, error) { var cfg httpConfig if err := Decode(node, "http", &cfg); err != nil { return nil, err @@ -61,7 +62,7 @@ func init() { if cfg.Method == "" { cfg.Method = http.MethodPost } - return &httpSender{cfg: cfg, r: r}, nil + return &httpSender{cfg: cfg, r: deps.Renderer, base: deps.HTTPClient}, nil }) } @@ -180,14 +181,30 @@ func (h *httpSender) Describe(msg Message) (string, error) { req.Method, u.Redacted(), strings.Join(hdrs, "; "), truncate(body, 500)), nil } +// client returns the client for one request: the configured base client +// (or a default one) with the same-host redirect policy, and certificate +// verification disabled for insecure_skip_verify when its transport is an +// *http.Transport. func (h *httpSender) client() *http.Client { - tr := http.DefaultTransport - if h.cfg.InsecureSkipVerify { - t := http.DefaultTransport.(*http.Transport).Clone() - t.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} + var c http.Client + if h.base != nil { + c = *h.base + } + tr := c.Transport + if tr == nil { + tr = http.DefaultTransport + } + if t, ok := tr.(*http.Transport); ok && h.cfg.InsecureSkipVerify { + t = t.Clone() + if t.TLSClientConfig == nil { + t.TLSClientConfig = &tls.Config{} + } + t.TLSClientConfig.InsecureSkipVerify = true tr = t } - return &http.Client{Transport: tr, CheckRedirect: sameHostRedirect} + c.Transport = tr + c.CheckRedirect = sameHostRedirect + return &c } // sameHostRedirect follows redirects only within the original host and diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 53e869b..a2aa98b 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -7,6 +7,8 @@ import ( "context" "errors" "fmt" + "io" + "net/http" "sort" "github.com/suprbdev/noty/internal/config" @@ -34,9 +36,39 @@ type Sender interface { Describe(msg Message) (string, error) } -// Factory builds a Sender from the channel's raw YAML node. The renderer is -// provided so providers can template their own fields (URLs, payloads, args). -type Factory func(node *yaml.Node, r *render.Renderer) (Sender, error) +// Factory builds a Sender from the channel's raw YAML node. The renderer in +// deps is provided so providers can template their own fields (URLs, +// payloads, args). +type Factory func(node *yaml.Node, deps Deps) (Sender, error) + +// Deps carries what a Sender needs from its environment. +type Deps struct { + // Renderer renders the provider's templated fields. + Renderer *render.Renderer + // HTTPClient, if set, supplies the transport, cookie jar, and timeout + // for http channels. Redirects always follow the http provider's + // same-host policy. + HTTPClient *http.Client + // Runner, if set, runs exec channel commands instead of os/exec. + Runner Runner +} + +// Command is a process an exec channel asks to run. +type Command struct { + // Path is the configured command name or path. + Path string + // Args are the rendered arguments, not including the command itself. + Args []string + // Env is the full environment: the process environment plus the + // channel's rendered env entries, as KEY=value. + Env []string + // Stdin is the rendered body, or nil when stdin_body is false. + Stdin io.Reader +} + +// Runner runs cmd and returns its combined stdout and stderr. It should +// stop the command when ctx is done. +type Runner func(ctx context.Context, cmd Command) ([]byte, error) var registry = map[string]Factory{} @@ -45,13 +77,19 @@ func Register(typeName string, f Factory) { registry[typeName] = f } -// New builds a Sender for the given provider type. +// New builds a Sender for the given provider type with default +// dependencies and renderer r. func New(typeName string, node *yaml.Node, r *render.Renderer) (Sender, error) { + return NewWithDeps(typeName, node, Deps{Renderer: r}) +} + +// NewWithDeps builds a Sender for the given provider type. +func NewWithDeps(typeName string, node *yaml.Node, deps Deps) (Sender, error) { f, ok := registry[typeName] if !ok { return nil, fmt.Errorf("unknown provider type %q (available: %v)", typeName, Types()) } - return f(node, r) + return f(node, deps) } // Types lists registered provider types, sorted. diff --git a/internal/provider/smtp.go b/internal/provider/smtp.go index a087e1b..d23750f 100644 --- a/internal/provider/smtp.go +++ b/internal/provider/smtp.go @@ -18,7 +18,6 @@ import ( "strings" "time" - "github.com/suprbdev/noty/internal/render" "go.yaml.in/yaml/v3" ) @@ -51,7 +50,7 @@ type smtpSender struct { } func init() { - Register("smtp", func(node *yaml.Node, _ *render.Renderer) (Sender, error) { + Register("smtp", func(node *yaml.Node, _ Deps) (Sender, error) { var cfg smtpConfig if err := Decode(node, "smtp", &cfg); err != nil { return nil, err diff --git a/notify/config.go b/notify/config.go new file mode 100644 index 0000000..9d9c967 --- /dev/null +++ b/notify/config.go @@ -0,0 +1,91 @@ +package notify + +import ( + "os" + "sort" + + "github.com/suprbdev/noty/internal/config" +) + +// Config is a parsed noty configuration, in the same YAML format the noty +// CLI reads. Create one with [Load] or [Parse]; it is immutable and safe to +// share between clients and goroutines. +type Config struct { + c *config.Config +} + +// Channel describes a configured channel. +type Channel struct { + // Name is the channel's key under channels. + Name string + // Type is the provider type: smtp, http, or exec. + Type string + // Default reports whether the channel is defaults.channel. + Default bool +} + +// ConfigOption customizes [Load] and [Parse]. +type ConfigOption func(*configOptions) + +type configOptions struct { + lookup func(string) (string, bool) +} + +// WithLookupEnv makes ${VAR} references in the config resolve through +// lookup instead of [os.LookupEnv]. lookup reports whether the variable is +// set, so ${VAR:-default} falls back only when it returns false. The env +// template function still reads the process environment. +func WithLookupEnv(lookup func(string) (string, bool)) ConfigOption { + return func(o *configOptions) { o.lookup = lookup } +} + +// Load reads and parses the config file at path. A relative template_dir, +// and template paths when template_dir is unset, resolve against the file's +// directory. Read errors are returned as is (test them with +// [errors.Is](err, [fs.ErrNotExist])); everything else wraps +// [ErrInvalidConfig]. +func Load(path string, opts ...ConfigOption) (*Config, error) { + raw, err := os.ReadFile(path) + if err != nil { + return nil, err + } + return parse(raw, path, opts) +} + +// Parse parses config data. It behaves like [Load], except that relative +// template paths resolve against the working directory and errors are +// prefixed with "config" instead of a file name. Errors wrap +// [ErrInvalidConfig]. +func Parse(data []byte, opts ...ConfigOption) (*Config, error) { + return parse(data, "", opts) +} + +func parse(data []byte, path string, opts []ConfigOption) (*Config, error) { + var o configOptions + for _, opt := range opts { + opt(&o) + } + c, err := config.Parse(data, path, o.lookup) + if err != nil { + return nil, invalidConfigError{err} + } + return &Config{c: c}, nil +} + +// Path returns the file the config was loaded from, or "" for a config +// created with [Parse]. +func (c *Config) Path() string { return c.c.Path } + +// DefaultChannel returns defaults.channel, the channel a [Message] without +// Channels is sent through, or "" when it is unset. +func (c *Config) DefaultChannel() string { return c.c.Defaults.Channel } + +// Channels returns the configured channels sorted by name. +func (c *Config) Channels() []Channel { + out := make([]Channel, 0, len(c.c.Channels)) + for name, ch := range c.c.Channels { + out = append(out, Channel{Name: name, Type: ch.Type, Default: name == c.c.Defaults.Channel}) + } + sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name }) + return out +} diff --git a/notify/errors.go b/notify/errors.go new file mode 100644 index 0000000..9b9769f --- /dev/null +++ b/notify/errors.go @@ -0,0 +1,62 @@ +package notify + +import ( + "errors" + "fmt" + "strings" +) + +var ( + // ErrInvalidConfig is wrapped by every [Load] and [Parse] error that is + // not a file read error: malformed YAML, unknown keys, missing + // environment variables, no channels, and so on. + ErrInvalidConfig = errors.New("invalid config") + // ErrNoChannel is returned by [Client.Send] when the message names no + // channels and the config has no defaults.channel. + ErrNoChannel = errors.New("no channel specified") + // ErrUnknownChannel is wrapped by the error [Client.Send] returns when + // the message names a channel the config does not define. Nothing is + // sent in that case. + ErrUnknownChannel = errors.New("unknown channel") +) + +type invalidConfigError struct{ err error } + +func (e invalidConfigError) Error() string { return e.err.Error() } +func (e invalidConfigError) Unwrap() []error { return []error{ErrInvalidConfig, e.err} } + +// SendError is returned by [Client.Send] when one or more channels failed. +// The other channels were still attempted; [Result] has every outcome. +type SendError struct { + // Failed holds the results of the failed channels, in request order. + Failed []ChannelResult +} + +// Error lists each failed channel with its error. +func (e *SendError) Error() string { + parts := make([]string, len(e.Failed)) + for i, r := range e.Failed { + parts[i] = fmt.Sprintf("channel %q: %v", r.Channel, r.Err) + } + return strings.Join(parts, "; ") +} + +// Unwrap returns the per-channel errors, so [errors.Is] and [errors.As] +// match any of them. +func (e *SendError) Unwrap() []error { + errs := make([]error, len(e.Failed)) + for i, r := range e.Failed { + errs[i] = r.Err + } + return errs +} + +// maskedError presents err with environment-sourced secrets masked while +// keeping it unwrappable. +type maskedError struct { + err error + msg string +} + +func (e maskedError) Error() string { return e.msg } +func (e maskedError) Unwrap() error { return e.err } diff --git a/notify/example_test.go b/notify/example_test.go new file mode 100644 index 0000000..8546fbf --- /dev/null +++ b/notify/example_test.go @@ -0,0 +1,104 @@ +package notify_test + +import ( + "context" + "fmt" + "io" + "log" + "net/http" + "net/http/httptest" + + "github.com/suprbdev/noty/notify" +) + +func Example() { + webhook := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + fmt.Printf("webhook received: %s\n", body) + })) + defer webhook.Close() + + cfg, err := notify.Parse([]byte(` +defaults: + channel: slack +vars: + environment: prod +channels: + slack: + type: http + url: ${SLACK_WEBHOOK_URL} + body: '{"text": {{ json (printf "[%s] %s" .Vars.environment .Message) }}}' +`), notify.WithLookupEnv(func(name string) (string, bool) { + if name == "SLACK_WEBHOOK_URL" { + return webhook.URL, true + } + return "", false + })) + if err != nil { + log.Fatal(err) + } + + client, err := notify.New(cfg) + if err != nil { + log.Fatal(err) + } + res, err := client.Send(context.Background(), notify.Message{Text: "deploy finished"}) + if err != nil { + log.Fatal(err) + } + for _, r := range res.Channels { + fmt.Printf("%s: attempts=%d err=%v\n", r.Channel, r.Attempts, r.Err) + } + // Output: + // webhook received: {"text": "[prod] deploy finished"} + // slack: attempts=1 err= +} + +func ExampleClient_Send_dryRun() { + cfg, err := notify.Parse([]byte(` +channels: + ops: + type: exec + command: /usr/local/bin/page-oncall + args: ["--severity", "{{ .Vars.severity }}", "{{ .Subject }}"] +`)) + if err != nil { + log.Fatal(err) + } + client, err := notify.New(cfg) + if err != nil { + log.Fatal(err) + } + res, err := client.Send(context.Background(), notify.Message{ + Channels: []string{"ops"}, + Subject: "db-1 unreachable", + Text: "connection refused", + Vars: map[string]string{"severity": "high"}, + DryRun: true, + }) + if err != nil { + log.Fatal(err) + } + fmt.Println(res.Channels[0].Description) + // Output: + // exec /usr/local/bin/page-oncall --severity high db-1 unreachable (stdin: 18 bytes) +} + +func ExampleConfig_Channels() { + cfg, err := notify.Parse([]byte(` +defaults: + channel: slack +channels: + slack: {type: http, url: "https://hooks.example.com/x"} + email: {type: smtp, host: smtp.example.com, from: alerts@example.com} +`)) + if err != nil { + log.Fatal(err) + } + for _, ch := range cfg.Channels() { + fmt.Println(ch.Name, ch.Type, ch.Default) + } + // Output: + // email smtp false + // slack http true +} diff --git a/notify/mask.go b/notify/mask.go new file mode 100644 index 0000000..11b7c3d --- /dev/null +++ b/notify/mask.go @@ -0,0 +1,38 @@ +package notify + +import ( + "net/url" + "sort" + "strings" +) + +// secretMasker returns a function that replaces every value substituted +// 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 { + type pair struct{ old, ref string } + var pairs []pair + for name, v := range env { + if len(v) < 4 { + continue + } + for _, form := range []string{v, url.QueryEscape(v), url.PathEscape(v)} { + pairs = append(pairs, pair{form, "${" + name + "}"}) + } + } + if len(pairs) == 0 { + return func(s string) string { return s } + } + 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 pairs[i].old < pairs[j].old || pairs[i].old == pairs[j].old && pairs[i].ref < pairs[j].ref + }) + args := make([]string, 0, 2*len(pairs)) + for _, p := range pairs { + args = append(args, p.old, p.ref) + } + return strings.NewReplacer(args...).Replace +} diff --git a/notify/mask_test.go b/notify/mask_test.go new file mode 100644 index 0000000..2df978c --- /dev/null +++ b/notify/mask_test.go @@ -0,0 +1,14 @@ +package notify + +import "testing" + +func TestSecretMasker(t *testing.T) { + 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" { + t.Errorf("empty masker changed input: %q", got) + } +} diff --git a/notify/notify.go b/notify/notify.go new file mode 100644 index 0000000..8261668 --- /dev/null +++ b/notify/notify.go @@ -0,0 +1,385 @@ +// Package notify sends notifications in-process using a noty +// configuration, with the same config format, templates, fan-out, retries, +// and secret masking as the noty CLI. +// +// Load or parse a config, build a [Client], and call [Client.Send]: +// +// cfg, err := notify.Load("/etc/myapp/noty.yaml") +// if err != nil { +// return err +// } +// client, err := notify.New(cfg) +// if err != nil { +// return err +// } +// res, err := client.Send(ctx, notify.Message{ +// Channels: []string{"slack", "email"}, +// Text: "deploy finished", +// Vars: map[string]string{"environment": "prod"}, +// }) +// +// Channels are sent concurrently and a failure on one does not stop the +// others. Send returns a [*SendError] when any channel fails, and the +// [Result] reports each channel's outcome in request order. +// +// See the noty README for the configuration reference. +package notify + +import ( + "context" + "errors" + "fmt" + "io" + "maps" + "net/http" + "os" + "sync" + "time" + + "github.com/suprbdev/noty/internal/config" + "github.com/suprbdev/noty/internal/provider" + "github.com/suprbdev/noty/internal/render" +) + +// DefaultTimeout is the per-attempt send timeout used when neither +// [WithTimeout] nor defaults.timeout sets one. +const DefaultTimeout = 30 * time.Second + +// DefaultBackoff is the default delay before retry number attempt +// (1-based): 1s, 2s, 4s, ... capped at 30s. +func DefaultBackoff(attempt int) time.Duration { + return min(time.Second< 0 { + return res, &SendError{Failed: failed} + } + return res, nil +} + +func (c *Client) send(ctx context.Context, name string, msg Message, now time.Time) ChannelResult { + res := ChannelResult{Channel: name} + done := func(err error) ChannelResult { + res.Err = err + return res + } + ch := c.cfg.Channels[name] + + vars := map[string]string{} + maps.Copy(vars, c.cfg.Vars) + maps.Copy(vars, ch.Common.Vars) + maps.Copy(vars, msg.Vars) + + data := render.Data{ + Message: msg.Text, + To: msg.To, + Channel: name, + Vars: vars, + Now: now, + Hostname: c.hostname, + } + + base := msg.Subject + if base == "" { + var err error + if base, err = c.renderer.Resolve("", c.cfg.Defaults.Subject, "", data); err != nil { + return done(fmt.Errorf("defaults.subject: %w", err)) + } + } + data.Subject = base + subj, err := c.renderer.Resolve(ch.Common.SubjectTemplate, ch.Common.Subject, base, data) + if err != nil { + return done(fmt.Errorf("subject: %w", err)) + } + data.Subject = subj + + bodyTmpl := msg.Template + if bodyTmpl == "" { + bodyTmpl = ch.Common.BodyTemplate + } + body, err := c.renderer.Resolve(bodyTmpl, ch.Common.Body, msg.Text, data) + if err != nil { + return done(fmt.Errorf("body: %w", err)) + } + + sender, err := provider.NewWithDeps(ch.Type, ch.Raw, c.deps) + if err != nil { + return done(err) + } + pm := provider.Message{Subject: subj, Body: body, To: msg.To, Data: data} + + maxRetries := c.cfg.Defaults.Retries + if ch.Common.Retries != nil { + maxRetries = *ch.Common.Retries + } + if c.retries != nil { + maxRetries = *c.retries + } + if maxRetries < 0 { + return done(fmt.Errorf("retries must be >= 0, got %d", maxRetries)) + } + + if msg.DryRun { + res.Description, err = sender.Describe(pm) + return done(err) + } + + for { + res.Attempts++ + actx, cancel := context.WithTimeout(ctx, c.timeout) + err = sender.Send(actx, pm) + cancel() + if err == nil || res.Attempts > maxRetries || !provider.IsTemporary(err) { + if err != nil && res.Attempts > 1 { + err = fmt.Errorf("%w (after %d attempts)", err, res.Attempts) + } + return done(err) + } + t := time.NewTimer(c.backoff(res.Attempts)) + select { + case <-ctx.Done(): + t.Stop() + return done(fmt.Errorf("%w (retry abandoned: %w)", err, ctx.Err())) + case <-t.C: + } + } +} diff --git a/notify/notify_test.go b/notify/notify_test.go new file mode 100644 index 0000000..e4533f9 --- /dev/null +++ b/notify/notify_test.go @@ -0,0 +1,448 @@ +package notify_test + +import ( + "context" + "errors" + "io" + "io/fs" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "reflect" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/suprbdev/noty/notify" +) + +func env(m map[string]string) notify.ConfigOption { + return notify.WithLookupEnv(func(k string) (string, bool) { + v, ok := m[k] + return v, ok + }) +} + +func mustParse(t *testing.T, src string, opts ...notify.ConfigOption) *notify.Config { + t.Helper() + cfg, err := notify.Parse([]byte(src), opts...) + if err != nil { + t.Fatal(err) + } + return cfg +} + +func mustClient(t *testing.T, cfg *notify.Config, opts ...notify.Option) *notify.Client { + t.Helper() + c, err := notify.New(cfg, opts...) + if err != nil { + t.Fatal(err) + } + return c +} + +type hook struct { + srv *httptest.Server + mu sync.Mutex + bodies []string + hits atomic.Int32 +} + +func newHook(t *testing.T, statuses ...int) *hook { + t.Helper() + h := &hook{} + h.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + h.mu.Lock() + h.bodies = append(h.bodies, string(b)) + h.mu.Unlock() + n := int(h.hits.Add(1)) + status := http.StatusOK + if len(statuses) > 0 { + status = statuses[min(n, len(statuses))-1] + } + w.WriteHeader(status) + })) + t.Cleanup(h.srv.Close) + return h +} + +type fakeExec struct { + mu sync.Mutex + cmds []notify.ExecCommand + in []string + err error +} + +func (f *fakeExec) run(_ context.Context, cmd notify.ExecCommand) ([]byte, error) { + var in []byte + if cmd.Stdin != nil { + in, _ = io.ReadAll(cmd.Stdin) + } + f.mu.Lock() + defer f.mu.Unlock() + f.cmds = append(f.cmds, cmd) + f.in = append(f.in, string(in)) + if f.err != nil { + return []byte("fake output"), f.err + } + return nil, nil +} + +const fanOutConfig = ` +defaults: + channel: hook + subject: "default subject" +vars: + environment: prod + team: ops +channels: + hook: + type: http + url: ${HOOK_URL}/notify + body: '{"text": {{ json .Message }}, "subject": {{ json .Subject }}, "env": {{ json .Vars.environment }}}' + cmd: + type: exec + command: notify-cli + args: ["--to", "{{ index .To 0 }}", "--team", "{{ .Vars.team }}"] + subject: "[{{ .Vars.environment }}] {{ .Subject }}" + body: "{{ .Subject }}: {{ .Message }}" + vars: + team: platform +` + +func TestParse(t *testing.T) { + cfg := mustParse(t, fanOutConfig, env(map[string]string{"HOOK_URL": "http://example.invalid"})) + if cfg.Path() != "" { + t.Errorf("Path = %q, want empty for parsed data", cfg.Path()) + } + if cfg.DefaultChannel() != "hook" { + t.Errorf("DefaultChannel = %q", cfg.DefaultChannel()) + } + want := []notify.Channel{{Name: "cmd", Type: "exec"}, {Name: "hook", Type: "http", Default: true}} + if got := cfg.Channels(); !reflect.DeepEqual(got, want) { + t.Errorf("Channels = %+v, want %+v", got, want) + } +} + +func TestParseLookupEnv(t *testing.T) { + t.Setenv("NOTY_PKG_TEST_URL", "http://from-process-env") + src := "channels:\n c:\n type: http\n url: ${NOTY_PKG_TEST_URL}\n" + _, err := notify.Parse([]byte(src), env(nil)) + if !errors.Is(err, notify.ErrInvalidConfig) || !strings.Contains(err.Error(), "NOTY_PKG_TEST_URL") { + t.Fatalf("injected lookup must replace the process environment, got %v", err) + } + if _, err := notify.Parse([]byte(src)); err != nil { + t.Errorf("default lookup must read the process environment: %v", err) + } + cfg := mustParse(t, "channels:\n c:\n type: http\n url: ${MISSING:-http://fallback}\n", env(nil)) + if len(cfg.Channels()) != 1 { + t.Errorf("fallback not applied") + } +} + +func TestParseInvalid(t *testing.T) { + cases := map[string]string{ + "yaml": "channels: [::", + "unknown key": "chanels:\n c:\n type: http\n", + "missing type": "channels:\n c:\n url: x\n", + "no channels": "defaults:\n channel: x\n", + "empty": "", + "missing env": "channels:\n c:\n type: http\n url: ${UNSET}\n", + "defaults typo": "defaults:\n chanel: c\nchannels:\n c:\n type: http\n", + } + for name, src := range cases { + _, err := notify.Parse([]byte(src), env(nil)) + if !errors.Is(err, notify.ErrInvalidConfig) { + t.Errorf("%s: error %v does not wrap ErrInvalidConfig", name, err) + } else if !strings.HasPrefix(err.Error(), "config: ") { + t.Errorf("%s: error %q not prefixed with config", name, err) + } + } +} + +func TestLoad(t *testing.T) { + dir := t.TempDir() + if err := os.MkdirAll(filepath.Join(dir, "tpl"), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "tpl", "body.tmpl"), []byte("templated {{ .Message }}"), 0o600); err != nil { + t.Fatal(err) + } + path := filepath.Join(dir, "noty.yaml") + src := "template_dir: tpl\nchannels:\n c:\n type: exec\n command: x\n body_template: body.tmpl\n" + if err := os.WriteFile(path, []byte(src), 0o600); err != nil { + t.Fatal(err) + } + cfg, err := notify.Load(path) + if err != nil { + t.Fatal(err) + } + if cfg.Path() != path { + t.Errorf("Path = %q, want %q", cfg.Path(), path) + } + var fake fakeExec + if _, err := mustClient(t, cfg, notify.WithExecRunner(fake.run)).Send(context.Background(), notify.Message{Channels: []string{"c"}, Text: "hi"}); err != nil { + t.Fatal(err) + } + if fake.in[0] != "templated hi" { + t.Errorf("body = %q, want template resolved relative to the config file", fake.in[0]) + } + + _, err = notify.Load(filepath.Join(dir, "absent.yaml")) + if !errors.Is(err, fs.ErrNotExist) || errors.Is(err, notify.ErrInvalidConfig) { + t.Errorf("missing file: got %v, want fs.ErrNotExist only", err) + } +} + +func TestSendFanOut(t *testing.T) { + h := newHook(t) + cfg := mustParse(t, fanOutConfig, env(map[string]string{"HOOK_URL": h.srv.URL})) + var fake fakeExec + client := mustClient(t, cfg, notify.WithExecRunner(fake.run)) + + res, err := client.Send(context.Background(), notify.Message{ + Channels: []string{"cmd", "hook"}, + To: []string{"+15550001111"}, + Subject: "disk full", + Text: "db-1 at 92%", + Vars: map[string]string{"environment": "staging"}, + }) + if err != nil { + t.Fatal(err) + } + if got := []string{res.Channels[0].Channel, res.Channels[1].Channel}; !reflect.DeepEqual(got, []string{"cmd", "hook"}) { + t.Errorf("result order = %v, want request order", got) + } + for _, r := range res.Channels { + if r.Err != nil || r.Attempts != 1 || r.Description != "" { + t.Errorf("%s: unexpected result %+v", r.Channel, r) + } + } + if want := `{"text": "db-1 at 92%", "subject": "disk full", "env": "staging"}`; len(h.bodies) != 1 || h.bodies[0] != want { + t.Errorf("http bodies = %q, want [%q]", h.bodies, want) + } + if len(fake.cmds) != 1 { + t.Fatalf("exec runs = %d, want 1", len(fake.cmds)) + } + cmd := fake.cmds[0] + if cmd.Path != "notify-cli" || !reflect.DeepEqual(cmd.Args, []string{"--to", "+15550001111", "--team", "platform"}) { + t.Errorf("command = %s %q", cmd.Path, cmd.Args) + } + if len(cmd.Env) == 0 { + t.Error("command env should include the process environment") + } + if want := "[staging] disk full: db-1 at 92%"; fake.in[0] != want { + t.Errorf("stdin = %q, want %q", fake.in[0], want) + } +} + +func TestSendDefaultChannelAndSubject(t *testing.T) { + h := newHook(t) + client := mustClient(t, mustParse(t, fanOutConfig, env(map[string]string{"HOOK_URL": h.srv.URL}))) + res, err := client.Send(context.Background(), notify.Message{Text: "hi"}) + if err != nil { + t.Fatal(err) + } + if len(res.Channels) != 1 || res.Channels[0].Channel != "hook" { + t.Errorf("default channel not used: %+v", res.Channels) + } + if want := `{"text": "hi", "subject": "default subject", "env": "prod"}`; h.bodies[0] != want { + t.Errorf("body = %q, want %q", h.bodies[0], want) + } +} + +func TestSendFailureContinues(t *testing.T) { + h := newHook(t, http.StatusInternalServerError) + cfg := mustParse(t, fanOutConfig, env(map[string]string{"HOOK_URL": h.srv.URL})) + fake := fakeExec{err: errors.New("exit status 3")} + client := mustClient(t, cfg, notify.WithExecRunner(fake.run), notify.WithRetries(3), notify.WithBackoff(func(int) time.Duration { return 0 })) + + res, err := client.Send(context.Background(), notify.Message{Channels: []string{"hook", "cmd"}, To: []string{"x"}}) + var sendErr *notify.SendError + if !errors.As(err, &sendErr) { + t.Fatalf("error %v is not a *SendError", err) + } + if got := res.Failed(); !reflect.DeepEqual(got, []string{"hook", "cmd"}) { + t.Errorf("Failed = %v", got) + } + if len(sendErr.Failed) != 2 || !strings.Contains(err.Error(), `channel "hook": http: unexpected status 500`) || !strings.Contains(err.Error(), "fake output") { + t.Errorf("error does not describe both failures: %v", err) + } + if h.hits.Load() != 1 || res.Channels[0].Attempts != 1 { + t.Errorf("HTTP 500 must not be retried: hits=%d attempts=%d", h.hits.Load(), res.Channels[0].Attempts) + } + if len(fake.cmds) != 1 { + t.Errorf("exec must still run after another channel fails") + } + + ok := newHook(t) + cfg = mustParse(t, fanOutConfig, env(map[string]string{"HOOK_URL": ok.srv.URL})) + res, err = mustClient(t, cfg).Send(context.Background(), notify.Message{Channels: []string{"cmd", "hook"}}) + if err == nil || res.Channels[0].Err == nil || res.Channels[1].Err != nil || ok.hits.Load() != 1 { + t.Errorf("render error on one channel must not stop the other: err=%v results=%+v", err, res.Channels) + } +} + +func TestSendRetries(t *testing.T) { + h := newHook(t, http.StatusServiceUnavailable, http.StatusBadGateway, http.StatusOK) + cfg := mustParse(t, "defaults:\n retries: 2\nchannels:\n hook:\n type: http\n url: ${HOOK_URL}\n", env(map[string]string{"HOOK_URL": h.srv.URL})) + var delays []int + client := mustClient(t, cfg, notify.WithBackoff(func(a int) time.Duration { delays = append(delays, a); return 0 })) + res, err := client.Send(context.Background(), notify.Message{Channels: []string{"hook"}}) + if err != nil { + t.Fatal(err) + } + if res.Channels[0].Attempts != 3 || !reflect.DeepEqual(delays, []int{1, 2}) { + t.Errorf("attempts = %d, backoff calls = %v", res.Channels[0].Attempts, delays) + } +} + +func TestSendRetryStopsWhenContextDone(t *testing.T) { + h := newHook(t, http.StatusServiceUnavailable) + cfg := mustParse(t, "channels:\n hook:\n type: http\n url: ${HOOK_URL}\n", env(map[string]string{"HOOK_URL": h.srv.URL})) + ctx, cancel := context.WithCancel(context.Background()) + client := mustClient(t, cfg, notify.WithRetries(5), notify.WithBackoff(func(int) time.Duration { cancel(); return time.Hour })) + _, err := client.Send(ctx, notify.Message{Channels: []string{"hook"}}) + if !errors.Is(err, context.Canceled) || h.hits.Load() != 1 { + t.Errorf("err = %v, hits = %d; want cancellation after one attempt", err, h.hits.Load()) + } +} + +func TestSendDryRun(t *testing.T) { + h := newHook(t) + secretURL := h.srv.URL + "/s3cr3t-path" + cfg := mustParse(t, fanOutConfig, env(map[string]string{"HOOK_URL": secretURL})) + var fake fakeExec + client := mustClient(t, cfg, notify.WithExecRunner(fake.run)) + res, err := client.Send(context.Background(), notify.Message{Channels: []string{"hook", "cmd"}, To: []string{"+1555"}, Text: "hi", DryRun: true}) + if err != nil { + t.Fatal(err) + } + if h.hits.Load() != 0 || len(fake.cmds) != 0 { + t.Fatalf("dry run sent: http hits=%d exec runs=%d", h.hits.Load(), len(fake.cmds)) + } + hook, cmd := res.Channels[0].Description, res.Channels[1].Description + if !strings.HasPrefix(hook, "POST ${HOOK_URL}/notify") || strings.Contains(hook, "s3cr3t") { + t.Errorf("hook description not masked: %q", hook) + } + if !strings.HasPrefix(cmd, "exec notify-cli --to +1555 --team platform") { + t.Errorf("cmd description = %q", cmd) + } + + _, err = mustClient(t, mustParse(t, "channels:\n c:\n type: smtp\n host: h\n from: a@b.c\n")).Send(context.Background(), notify.Message{Channels: []string{"c"}, DryRun: true}) + if err == nil || !strings.Contains(err.Error(), "no recipients") { + t.Errorf("dry run must validate like a send, got %v", err) + } +} + +func TestSendMasksErrors(t *testing.T) { + cfg := mustParse(t, "channels:\n c:\n type: exec\n command: x\n args: [\"${TOKEN}\"]\n", env(map[string]string{"TOKEN": "tok-123456"})) + cause := errors.New("boom tok-123456") + fake := fakeExec{err: cause} + _, err := mustClient(t, cfg, notify.WithExecRunner(fake.run)).Send(context.Background(), notify.Message{Channels: []string{"c"}}) + if err == nil || strings.Contains(err.Error(), "tok-123456") || !strings.Contains(err.Error(), "${TOKEN}") { + t.Errorf("secret not masked: %v", err) + } + if !errors.Is(err, cause) { + t.Errorf("masked error must still unwrap to the cause") + } +} + +func TestSendChannelErrors(t *testing.T) { + var fake fakeExec + cfg := mustParse(t, "channels:\n c:\n type: exec\n command: x\n") + client := mustClient(t, cfg, notify.WithExecRunner(fake.run)) + + _, err := client.Send(context.Background(), notify.Message{Channels: []string{"c", "nope"}}) + if !errors.Is(err, notify.ErrUnknownChannel) || !strings.Contains(err.Error(), `"nope"`) { + t.Errorf("got %v, want ErrUnknownChannel naming the channel", err) + } + if len(fake.cmds) != 0 { + t.Error("no channel may send when any requested channel is unknown") + } + + _, err = client.Send(context.Background(), notify.Message{}) + if !errors.Is(err, notify.ErrNoChannel) { + t.Errorf("got %v, want ErrNoChannel", err) + } +} + +func TestNewTimeout(t *testing.T) { + cases := map[string]struct { + src string + opts []notify.Option + want string + }{ + "bad defaults.timeout": {src: "defaults:\n timeout: soon\n", want: "defaults.timeout"}, + "zero defaults.timeout": {src: "defaults:\n timeout: 0s\n", want: "timeout must be positive"}, + "negative option": {opts: []notify.Option{notify.WithTimeout(-time.Second)}, want: "timeout must be positive"}, + "option wins": {src: "defaults:\n timeout: soon\n", opts: []notify.Option{notify.WithTimeout(time.Second)}}, + } + for name, tc := range cases { + cfg := mustParse(t, tc.src+"channels:\n c:\n type: exec\n command: x\n") + _, err := notify.New(cfg, tc.opts...) + if tc.want == "" && err != nil || tc.want != "" && (err == nil || !strings.Contains(err.Error(), tc.want)) { + t.Errorf("%s: err = %v, want %q", name, err, tc.want) + } + } + if _, err := notify.New(nil); err == nil { + t.Error("nil config must be rejected") + } +} + +func TestSendTimeoutPerAttempt(t *testing.T) { + cfg := mustParse(t, "channels:\n c:\n type: exec\n command: x\n") + var deadline time.Duration + run := func(ctx context.Context, _ notify.ExecCommand) ([]byte, error) { + d, _ := ctx.Deadline() + deadline = time.Until(d) + return nil, nil + } + if _, err := mustClient(t, cfg, notify.WithExecRunner(run), notify.WithTimeout(time.Minute)).Send(context.Background(), notify.Message{Channels: []string{"c"}}); err != nil { + t.Fatal(err) + } + if deadline <= 50*time.Second || deadline > time.Minute { + t.Errorf("attempt deadline in %v, want about 1m", deadline) + } +} + +func TestWithClockAndTemplate(t *testing.T) { + dir := t.TempDir() + tmpl := filepath.Join(dir, "override.tmpl") + if err := os.WriteFile(tmpl, []byte(`{{ timefmt "2006-01-02 15:04" .Now }} {{ .Message }}`), 0o600); err != nil { + t.Fatal(err) + } + cfg := mustParse(t, "channels:\n c:\n type: exec\n command: x\n body: ignored\n") + var fake fakeExec + fixed := time.Date(2026, 1, 2, 3, 4, 0, 0, time.UTC) + client := mustClient(t, cfg, notify.WithExecRunner(fake.run), notify.WithClock(func() time.Time { return fixed })) + if _, err := client.Send(context.Background(), notify.Message{Channels: []string{"c"}, Text: "hi", Template: tmpl}); err != nil { + t.Fatal(err) + } + if want := "2026-01-02 03:04 hi"; fake.in[0] != want { + t.Errorf("body = %q, want %q", fake.in[0], want) + } +} + +type countingTransport struct{ n atomic.Int32 } + +func (c *countingTransport) RoundTrip(r *http.Request) (*http.Response, error) { + c.n.Add(1) + return http.DefaultTransport.RoundTrip(r) +} + +func TestWithHTTPClient(t *testing.T) { + h := newHook(t) + cfg := mustParse(t, "channels:\n hook:\n type: http\n url: ${HOOK_URL}\n", env(map[string]string{"HOOK_URL": h.srv.URL})) + tr := &countingTransport{} + if _, err := mustClient(t, cfg, notify.WithHTTPClient(&http.Client{Transport: tr})).Send(context.Background(), notify.Message{Channels: []string{"hook"}}); err != nil { + t.Fatal(err) + } + if tr.n.Load() != 1 || h.hits.Load() != 1 { + t.Errorf("custom transport not used: transport=%d server=%d", tr.n.Load(), h.hits.Load()) + } +}