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
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@ go build -o noty .
stdin, args are templates.
- **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.
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`.
- **Templates live outside the binary** as plain files (Go `text/template`
syntax), resolved relative to `template_dir`, or inline in the config.

Expand Down
31 changes: 29 additions & 2 deletions internal/cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ func Run(args []string, stdin *os.File, stdout, stderr io.Writer) error {

hostname, _ := os.Hostname()
renderer := &render.Renderer{TemplateDir: cfg.TemplateDir}
mask := secretMasker(cfg.EnvValues)

send := func(name string) (string, error) {
ch := cfg.Channels[name]
Expand Down Expand Up @@ -261,10 +262,10 @@ func Run(args []string, stdin *os.File, stdout, stderr io.Writer) error {
for i, name := range chNames {
switch r := results[i]; {
case r.err != nil:
fmt.Fprintf(stderr, "channel %q: %v\n", name, r.err)
fmt.Fprintf(stderr, "channel %q: %s\n", name, mask(r.err.Error()))
failed = append(failed, name)
case *dryRun:
fmt.Fprintf(stdout, "[dry-run] channel %q:\n %s\n", name, r.desc)
fmt.Fprintf(stdout, "[dry-run] channel %q:\n %s\n", name, mask(r.desc))
case *verbose:
fmt.Fprintf(stderr, "channel %q: sent\n", name)
}
Expand All @@ -276,6 +277,32 @@ func Run(args []string, stdin *os.File, stdout, stderr io.Writer) error {
return nil
}

// 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.
func secretMasker(env map[string]string) func(string) string {
names := make([]string, 0, len(env))
for name, v := range env {
if len(v) >= 4 {
names = append(names, name)
}
}
if len(names) == 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]])
}
return names[i] < names[j]
})
pairs := make([]string, 0, 2*len(names))
for _, name := range names {
pairs = append(pairs, env[name], "${"+name+"}")
}
return strings.NewReplacer(pairs...).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.
Expand Down
41 changes: 41 additions & 0 deletions internal/cli/cli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -424,3 +424,44 @@ func TestRunRejectsNonPositiveTimeout(t *testing.T) {
t.Errorf("defaults.timeout 0s should be rejected, got %v", err)
}
}

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 {
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 := `
channels:
hook:
type: http
url: http://127.0.0.1:1/hooks/${NOTY_TEST_TOKEN}
cmd:
type: exec
command: /bin/sh
args: ["-c", "echo $0; exit 1", "${NOTY_TEST_TOKEN}"]
`
path := filepath.Join(t.TempDir(), "noty.yaml")
if err := os.WriteFile(path, []byte(cfg), 0o600); err != nil {
t.Fatal(err)
}
var stdout, stderr bytes.Buffer
if err := Run([]string{"-c", path, "-m", "hi", "--channel", "hook,cmd", "--dry-run"}, nil, &stdout, &stderr); err != nil {
t.Fatal(err)
}
_ = Run([]string{"-c", path, "-m", "hi", "--channel", "hook,cmd"}, nil, &stdout, &stderr)
out := stdout.String() + stderr.String()
if strings.Contains(out, "tok-123456") {
t.Errorf("secret leaked:\n%s", out)
}
if strings.Count(out, "${NOTY_TEST_TOKEN}") < 4 {
t.Errorf("expected masked references in dry-run and both errors:\n%s", out)
}
}
42 changes: 27 additions & 15 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ type Config struct {

// Path is the file the config was loaded from (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).
EnvValues map[string]string `yaml:"-"`
}

// Defaults holds fallback values.
Expand Down Expand Up @@ -132,13 +135,19 @@ func CheckKeys(node *yaml.Node, structs ...any) error {
// envPattern matches $$, ${VAR}, and ${VAR:-default}.
var envPattern = regexp.MustCompile(`\$\$|\$\{([A-Za-z_][A-Za-z0-9_]*)(:-([^}]*))?\}`)

// expandEnv replaces ${VAR} and ${VAR:-default} in every scalar of the
// expander replaces ${VAR} and ${VAR:-default} in every scalar of the
// parsed YAML tree, so values are never re-parsed as YAML. $$ escapes a
// literal dollar sign. Unset variables without a default are collected into
// missing so misconfigured secrets fail loudly instead of silently.
func expandEnv(n *yaml.Node, missing *[]string) {
// 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.
type expander struct {
missing []string
used map[string]string
}

func (e *expander) node(n *yaml.Node) {
if n.Kind == yaml.ScalarNode {
if v := expandString(n.Value, missing); v != n.Value {
if v := e.expand(n.Value); v != n.Value {
n.Value = v
if n.Style == 0 {
n.Tag = ""
Expand All @@ -149,13 +158,11 @@ func expandEnv(n *yaml.Node, missing *[]string) {
}
}
for _, c := range n.Content {
expandEnv(c, missing)
e.node(c)
}
}

// expandString expands environment references in s, appending the names of
// unset variables without a default to missing (each name once).
func expandString(s string, missing *[]string) string {
func (e *expander) expand(s string) string {
if !strings.Contains(s, "$") {
return s
}
Expand All @@ -166,13 +173,17 @@ func expandString(s string, missing *[]string) string {
groups := envPattern.FindStringSubmatch(m)
name, hasDefault, def := groups[1], groups[2] != "", groups[3]
if v, ok := os.LookupEnv(name); ok {
if e.used == nil {
e.used = map[string]string{}
}
e.used[name] = v
return v
}
if hasDefault {
return def
}
if !slices.Contains(*missing, name) {
*missing = append(*missing, name)
if !slices.Contains(e.missing, name) {
e.missing = append(e.missing, name)
}
return m
})
Expand All @@ -190,11 +201,12 @@ func Load(path string) (*Config, error) {
}
var cfg Config
if len(doc.Content) > 0 {
var missing []string
expandEnv(&doc, &missing)
if len(missing) > 0 {
return nil, fmt.Errorf("%s: environment variable(s) not set: %v (use ${VAR:-default} to allow a fallback)", path, missing)
var e expander
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)
}
cfg.EnvValues = e.used
if err := doc.Decode(&cfg); err != nil {
return nil, fmt.Errorf("%s: %w", path, err)
}
Expand Down
12 changes: 8 additions & 4 deletions internal/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,12 @@ func TestExpandString(t *testing.T) {
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
var missing []string
if got := expandString(tc.in, &missing); got != tc.want {
var e expander
if got := e.expand(tc.in); got != tc.want {
t.Errorf("got %q, want %q", got, tc.want)
}
if !reflect.DeepEqual(missing, tc.missing) {
t.Errorf("missing = %v, want %v", missing, tc.missing)
if !reflect.DeepEqual(e.missing, tc.missing) {
t.Errorf("missing = %v, want %v", e.missing, tc.missing)
}
})
}
Expand Down Expand Up @@ -76,6 +76,10 @@ channels:
if got.Null != "NULL" {
t.Errorf("null = %q, want %q (env values must never decode as YAML null)", got.Null, "NULL")
}
want := map[string]string{"NOTY_TEST_SECRET": secret, "NOTY_TEST_PORT": "2525", "NOTY_TEST_NULL": "NULL"}
if !reflect.DeepEqual(cfg.EnvValues, want) {
t.Errorf("EnvValues = %v, want %v", cfg.EnvValues, want)
}
if got.Port != 2525 {
t.Errorf("port = %d, want 2525 (plain scalars must keep resolving as YAML types)", got.Port)
}
Expand Down
Loading