Add countersend test tool and project CLAUDE.md
countersend send plays mailqueuer against /in and /out, and countersend receive writes each notification to a file in place of the web app. send refuses a run that would notify unless given --allow-notify. The Makefile builds it in build, freebsd and build-linux. docs/testing-with-countersend.md has the steps. Also add CLAUDE.md and gitignore .claude/. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
54f9626121
commit
d465739f6d
@@ -2,3 +2,4 @@ bin/
|
|||||||
coverage.out
|
coverage.out
|
||||||
*.tmp
|
*.tmp
|
||||||
test_files/
|
test_files/
|
||||||
|
.claude/
|
||||||
|
|||||||
@@ -0,0 +1,61 @@
|
|||||||
|
# migadu_counters
|
||||||
|
|
||||||
|
Go daemon for real-time mail counting at Migadu. mailqueuer POSTs each recipient to `/in` or `/out`. The daemon increments daily address, domain and organisation counters in Redis and notifies
|
||||||
|
the web app when a counter reaches a warning threshold or a limit. It replaces the rspamd Lua plugin `migadu_counters.lua`, and it enforces nothing itself.
|
||||||
|
|
||||||
|
`README.md` is the contract for the API, Redis keys, config, logs and metrics. Read it there rather than from memory. The design record is in `plans/`, and open work is in `todo.md`.
|
||||||
|
|
||||||
|
## Commands
|
||||||
|
|
||||||
|
```
|
||||||
|
make build # bin/migadu_counters, bin/counterctl, bin/countersend
|
||||||
|
make test # go test -race ./...
|
||||||
|
make vet # go vet + gofmt
|
||||||
|
make test-contrib # shell test for contrib/pull-domains.sh (needs tinycdb cdb + rsync)
|
||||||
|
make freebsd # static FreeBSD amd64 binaries
|
||||||
|
```
|
||||||
|
|
||||||
|
## Layout
|
||||||
|
|
||||||
|
- `cmd/migadu_counters`: the daemon.
|
||||||
|
- `cmd/counterctl`: reads counters through `GET /counters`.
|
||||||
|
- `cmd/countersend`: standalone test tool. `send` plays mailqueuer, `receive` writes each notification to a file. Guide: `docs/testing-with-countersend.md`.
|
||||||
|
- `internal/`: `api`, `config`, `counting`, `domains`, `metrics`, `notify`, `server`, `store`, `txlog`, `watcher`.
|
||||||
|
- `contrib/`: CDB pull script and cron example.
|
||||||
|
- `review/`: past code reviews and proof tests, excluded from the gofmt check.
|
||||||
|
|
||||||
|
## Rules not to break
|
||||||
|
|
||||||
|
- Redis keys are shared with the web app: `cnt/<A|D|O>/<id>/d/<YYYY-MM-DD>/<i|o>`, DB 0, UTC day, TTL 31 days, `INCR` and `EXPIRE` in one MULTI/EXEC.
|
||||||
|
- Notifications are sent at most once and never repeated. A request that was sent but got no answer is not retried.
|
||||||
|
- Notification markers use the `ntf/` prefix because the web app scans `cnt/*<address>*`.
|
||||||
|
- Warning URLs must not use the breach URL's path, because the web app treats every call there as a breach. The daemon refuses to start if they do.
|
||||||
|
- The suffix of a `user@dom@SUFFIX` login may be a credential and is never logged or printed.
|
||||||
|
- `countersend send` refuses a run that would trigger a notification unless given `--allow-notify`. Keep that default, because real URLs email customers.
|
||||||
|
|
||||||
|
## How to work here
|
||||||
|
|
||||||
|
- Write the failing test first, then the code.
|
||||||
|
- Use the real fixture `test_files/rspamd_domains_db.cdb`. It is gitignored because it holds real customer domains, so never copy its contents into commits, docs or memory.
|
||||||
|
On a fresh clone the tests fail until it is copied from an agent host (see `README.md`).
|
||||||
|
- Run `make vet` and `make test` before reporting work as done.
|
||||||
|
- Commit or push only when asked.
|
||||||
|
|
||||||
|
## Gotchas
|
||||||
|
|
||||||
|
- SIGHUP reloads the CDB and reopens logs but does not reread the config. Notify URL changes need a restart.
|
||||||
|
- Replace the CDB with `mv`, never in place. Rewriting it truncates the inode the daemon holds open.
|
||||||
|
- FreeBSD base has no `curl` (use `fetch`), and root's shell may be csh.
|
||||||
|
- The local shell is zsh: quote URLs containing `?`, and an unquoted `$VAR` holding several words is not split.
|
||||||
|
- `golang.org/x/net` is pinned to v0.43.0.
|
||||||
|
- `cdb` (tinycdb) and `redis-server` are installed through Homebrew.
|
||||||
|
|
||||||
|
## Related repos
|
||||||
|
|
||||||
|
`../mailqueuer` (will call this daemon, no client yet), `../migadu_web3` (web app receiving the notifications), `ansible-freebsd3` (deployment role, not written yet).
|
||||||
|
|
||||||
|
## Memory
|
||||||
|
|
||||||
|
Project memory lives in `.claude/memory/`, which git ignores. Save new memories there, one fact per file with a line added to its index:
|
||||||
|
|
||||||
|
@.claude/memory/MEMORY.md
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
.PHONY: all build build-daemon build-ctl test test-contrib vet coverage freebsd build-linux clean help
|
.PHONY: all build build-daemon build-ctl build-send test test-contrib vet coverage freebsd build-linux clean help
|
||||||
|
|
||||||
# ====================================================================================
|
# ====================================================================================
|
||||||
# Variables
|
# Variables
|
||||||
@@ -9,6 +9,8 @@ CTL_BINARY ?= counterctl
|
|||||||
BIN_DIR ?= ./bin
|
BIN_DIR ?= ./bin
|
||||||
SRC = ./cmd/migadu_counters
|
SRC = ./cmd/migadu_counters
|
||||||
CTL_SRC = ./cmd/counterctl
|
CTL_SRC = ./cmd/counterctl
|
||||||
|
SEND_BINARY ?= countersend
|
||||||
|
SEND_SRC = ./cmd/countersend
|
||||||
|
|
||||||
# Version information (falls back when not in a git checkout)
|
# Version information (falls back when not in a git checkout)
|
||||||
VERSION ?= $(shell git describe --tags --always --dirty --match='v*' 2>/dev/null || echo dev)
|
VERSION ?= $(shell git describe --tags --always --dirty --match='v*' 2>/dev/null || echo dev)
|
||||||
@@ -21,8 +23,10 @@ LDFLAGS = -ldflags="${LDFLAGS_VARS}"
|
|||||||
# Cross-compilation (FreeBSD hosts run these under rc.d + daemon(8))
|
# Cross-compilation (FreeBSD hosts run these under rc.d + daemon(8))
|
||||||
FREEBSD_BINARY ?= migadu_counters-freebsd-amd64
|
FREEBSD_BINARY ?= migadu_counters-freebsd-amd64
|
||||||
CTL_FREEBSD_BINARY ?= counterctl-freebsd-amd64
|
CTL_FREEBSD_BINARY ?= counterctl-freebsd-amd64
|
||||||
|
SEND_FREEBSD_BINARY ?= countersend-freebsd-amd64
|
||||||
LINUX_BINARY ?= migadu_counters-linux-amd64
|
LINUX_BINARY ?= migadu_counters-linux-amd64
|
||||||
CTL_LINUX_BINARY ?= counterctl-linux-amd64
|
CTL_LINUX_BINARY ?= counterctl-linux-amd64
|
||||||
|
SEND_LINUX_BINARY ?= countersend-linux-amd64
|
||||||
|
|
||||||
# ====================================================================================
|
# ====================================================================================
|
||||||
# Targets
|
# Targets
|
||||||
@@ -30,7 +34,7 @@ CTL_LINUX_BINARY ?= counterctl-linux-amd64
|
|||||||
|
|
||||||
all: build
|
all: build
|
||||||
|
|
||||||
build: build-daemon build-ctl
|
build: build-daemon build-ctl build-send
|
||||||
|
|
||||||
build-daemon:
|
build-daemon:
|
||||||
@mkdir -p $(BIN_DIR)
|
@mkdir -p $(BIN_DIR)
|
||||||
@@ -40,6 +44,10 @@ build-ctl:
|
|||||||
@mkdir -p $(BIN_DIR)
|
@mkdir -p $(BIN_DIR)
|
||||||
go build $(LDFLAGS) -o $(BIN_DIR)/$(CTL_BINARY) $(CTL_SRC)
|
go build $(LDFLAGS) -o $(BIN_DIR)/$(CTL_BINARY) $(CTL_SRC)
|
||||||
|
|
||||||
|
build-send:
|
||||||
|
@mkdir -p $(BIN_DIR)
|
||||||
|
go build $(LDFLAGS) -o $(BIN_DIR)/$(SEND_BINARY) $(SEND_SRC)
|
||||||
|
|
||||||
test:
|
test:
|
||||||
go test -race ./...
|
go test -race ./...
|
||||||
|
|
||||||
@@ -59,18 +67,20 @@ freebsd:
|
|||||||
@mkdir -p $(BIN_DIR)
|
@mkdir -p $(BIN_DIR)
|
||||||
CGO_ENABLED=0 GOOS=freebsd GOARCH=amd64 go build -ldflags="${LDFLAGS_VARS}" -o $(BIN_DIR)/$(FREEBSD_BINARY) $(SRC)
|
CGO_ENABLED=0 GOOS=freebsd GOARCH=amd64 go build -ldflags="${LDFLAGS_VARS}" -o $(BIN_DIR)/$(FREEBSD_BINARY) $(SRC)
|
||||||
CGO_ENABLED=0 GOOS=freebsd GOARCH=amd64 go build -ldflags="${LDFLAGS_VARS}" -o $(BIN_DIR)/$(CTL_FREEBSD_BINARY) $(CTL_SRC)
|
CGO_ENABLED=0 GOOS=freebsd GOARCH=amd64 go build -ldflags="${LDFLAGS_VARS}" -o $(BIN_DIR)/$(CTL_FREEBSD_BINARY) $(CTL_SRC)
|
||||||
|
CGO_ENABLED=0 GOOS=freebsd GOARCH=amd64 go build -ldflags="${LDFLAGS_VARS}" -o $(BIN_DIR)/$(SEND_FREEBSD_BINARY) $(SEND_SRC)
|
||||||
|
|
||||||
build-linux:
|
build-linux:
|
||||||
@mkdir -p $(BIN_DIR)
|
@mkdir -p $(BIN_DIR)
|
||||||
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="${LDFLAGS_VARS}" -o $(BIN_DIR)/$(LINUX_BINARY) $(SRC)
|
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="${LDFLAGS_VARS}" -o $(BIN_DIR)/$(LINUX_BINARY) $(SRC)
|
||||||
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="${LDFLAGS_VARS}" -o $(BIN_DIR)/$(CTL_LINUX_BINARY) $(CTL_SRC)
|
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="${LDFLAGS_VARS}" -o $(BIN_DIR)/$(CTL_LINUX_BINARY) $(CTL_SRC)
|
||||||
|
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="${LDFLAGS_VARS}" -o $(BIN_DIR)/$(SEND_LINUX_BINARY) $(SEND_SRC)
|
||||||
|
|
||||||
clean:
|
clean:
|
||||||
rm -rf $(BIN_DIR) coverage.out
|
rm -rf $(BIN_DIR) coverage.out
|
||||||
|
|
||||||
help:
|
help:
|
||||||
@echo "Targets:"
|
@echo "Targets:"
|
||||||
@echo " build Build migadu_counters and counterctl into $(BIN_DIR)"
|
@echo " build Build migadu_counters, counterctl and countersend into $(BIN_DIR)"
|
||||||
@echo " test go test -race ./..."
|
@echo " test go test -race ./..."
|
||||||
@echo " test-contrib Shell test for contrib/pull-domains.sh"
|
@echo " test-contrib Shell test for contrib/pull-domains.sh"
|
||||||
@echo " vet go vet + gofmt check"
|
@echo " vet go vet + gofmt check"
|
||||||
|
|||||||
@@ -233,6 +233,10 @@ make test-contrib # shell test for contrib/pull-domains.sh (needs tinycdb cdb +
|
|||||||
make freebsd # static FreeBSD amd64 binaries for the Ansible role
|
make freebsd # static FreeBSD amd64 binaries for the Ansible role
|
||||||
```
|
```
|
||||||
|
|
||||||
|
To test the daemon on its server, `countersend send` posts to `/in` and `/out` as
|
||||||
|
mailqueuer will, and `countersend receive` stores each notification as a file in place of
|
||||||
|
the web app. Steps are in `docs/testing-with-countersend.md`.
|
||||||
|
|
||||||
`test_files/` is gitignored because the CDB holds real customer domains, so on
|
`test_files/` is gitignored because the CDB holds real customer domains, so on
|
||||||
a fresh clone the tests fail until you copy `rspamd_domains_db` from an agent
|
a fresh clone the tests fail until you copy `rspamd_domains_db` from an agent
|
||||||
host (`/usr/local/etc/agent/build/rspamd/`) to `test_files/rspamd_domains_db.cdb`.
|
host (`/usr/local/etc/agent/build/rspamd/`) to `test_files/rspamd_domains_db.cdb`.
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
// countersend is the test companion of migadu_counters. "send" plays
|
||||||
|
// mailqueuer (POST /in and /out), "receive" plays the web app and stores every
|
||||||
|
// notification the daemon sends as a file. See docs/testing-with-countersend.md.
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"syscall"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
exitOK = 0
|
||||||
|
exitFail = 1
|
||||||
|
exitUsage = 2
|
||||||
|
)
|
||||||
|
|
||||||
|
const usage = `Usage:
|
||||||
|
countersend send --route in|out --recipient ADDR [--auth-user ADDR] [--url URL] [--n N] [--concurrency N] ...
|
||||||
|
countersend receive [--listen ADDR] [--dir DIR]
|
||||||
|
|
||||||
|
Run "countersend send -h" or "countersend receive -h" for all options.
|
||||||
|
`
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||||
|
defer stop()
|
||||||
|
os.Exit(run(ctx, os.Args[1:], os.Stdout, os.Stderr, os.Getenv))
|
||||||
|
}
|
||||||
|
|
||||||
|
func run(ctx context.Context, args []string, stdout, stderr io.Writer, getenv func(string) string) int {
|
||||||
|
if len(args) == 0 {
|
||||||
|
fmt.Fprint(stderr, usage)
|
||||||
|
return exitUsage
|
||||||
|
}
|
||||||
|
switch args[0] {
|
||||||
|
case "send":
|
||||||
|
return runSend(args[1:], stdout, stderr, getenv)
|
||||||
|
case "receive":
|
||||||
|
return runReceive(ctx, args[1:], stdout, stderr)
|
||||||
|
default:
|
||||||
|
fmt.Fprintf(stderr, "unknown command %q\n\n%s", args[0], usage)
|
||||||
|
return exitUsage
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,212 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"io/fs"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// maxNamePart bounds a value used in a file name.
|
||||||
|
const maxNamePart = 64
|
||||||
|
|
||||||
|
// notification is the content of one stored file. Values are kept as the
|
||||||
|
// daemon sent them.
|
||||||
|
type notification struct {
|
||||||
|
ReceivedAt string `json:"received_at"`
|
||||||
|
Kind string `json:"kind"` // limit | warning
|
||||||
|
Level string `json:"level"`
|
||||||
|
ID string `json:"id"`
|
||||||
|
Flow string `json:"flow"`
|
||||||
|
Period string `json:"period"`
|
||||||
|
By string `json:"by"`
|
||||||
|
Count string `json:"count"`
|
||||||
|
Limit string `json:"limit"`
|
||||||
|
Percent string `json:"percent"`
|
||||||
|
Path string `json:"path"`
|
||||||
|
RawQuery string `json:"raw_query"`
|
||||||
|
RemoteAddr string `json:"remote_addr"`
|
||||||
|
AuthUser string `json:"auth_user"` // the basic auth user; the password is never stored
|
||||||
|
}
|
||||||
|
|
||||||
|
// receiver stands in for the web app: every GET becomes one file.
|
||||||
|
type receiver struct {
|
||||||
|
dir string
|
||||||
|
stdout, stderr io.Writer
|
||||||
|
|
||||||
|
seq atomic.Uint64
|
||||||
|
|
||||||
|
mu sync.Mutex // guards the counts and the output
|
||||||
|
counts map[string]int
|
||||||
|
failed int
|
||||||
|
}
|
||||||
|
|
||||||
|
func newReceiver(dir string, stdout, stderr io.Writer) *receiver {
|
||||||
|
return &receiver{dir: dir, stdout: stdout, stderr: stderr, counts: map[string]int{}}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *receiver) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
||||||
|
if req.Method != http.MethodGet {
|
||||||
|
w.Header().Set("Allow", http.MethodGet)
|
||||||
|
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
now := time.Now().UTC()
|
||||||
|
q := req.URL.Query()
|
||||||
|
kind := "limit"
|
||||||
|
if strings.HasSuffix(strings.TrimRight(req.URL.Path, "/"), "/warning") {
|
||||||
|
kind = "warning"
|
||||||
|
}
|
||||||
|
authUser, _, _ := req.BasicAuth()
|
||||||
|
n := notification{
|
||||||
|
ReceivedAt: now.Format(time.RFC3339Nano), Kind: kind,
|
||||||
|
Level: q.Get("level"), ID: q.Get("id"), Flow: q.Get("flow"), Period: q.Get("period"), By: q.Get("by"),
|
||||||
|
Count: q.Get("count"), Limit: q.Get("limit"), Percent: q.Get("percent"),
|
||||||
|
Path: req.URL.Path, RawQuery: req.URL.RawQuery, RemoteAddr: req.RemoteAddr, AuthUser: authUser,
|
||||||
|
}
|
||||||
|
name, err := r.store(now, n)
|
||||||
|
|
||||||
|
r.mu.Lock()
|
||||||
|
defer r.mu.Unlock()
|
||||||
|
if err != nil {
|
||||||
|
r.failed++
|
||||||
|
fmt.Fprintf(r.stderr, "could not store notification: %v\n", err)
|
||||||
|
// The daemon retries a 5xx, so this one is not lost.
|
||||||
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
r.counts[kind]++
|
||||||
|
fmt.Fprintf(r.stdout, "%s %s %s %s count=%s limit=%s -> %s\n", kind, cleanPart(n.Level), cleanPart(n.Flow), cleanPart(n.ID), cleanPart(n.Count), cleanPart(n.Limit), name)
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
}
|
||||||
|
|
||||||
|
// store writes n to a dotfile and links it to its final name, so a visible
|
||||||
|
// file is always complete and an existing one is never overwritten.
|
||||||
|
func (r *receiver) store(now time.Time, n notification) (string, error) {
|
||||||
|
data, err := json.MarshalIndent(n, "", " ")
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
tmp, err := os.CreateTemp(r.dir, ".tmp-*")
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
defer os.Remove(tmp.Name())
|
||||||
|
_, err = tmp.Write(append(data, '\n'))
|
||||||
|
if cerr := tmp.Close(); err == nil {
|
||||||
|
err = cerr
|
||||||
|
}
|
||||||
|
if err == nil {
|
||||||
|
err = os.Chmod(tmp.Name(), 0o640)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
stamp := now.Format("20060102T150405.000000Z")
|
||||||
|
for {
|
||||||
|
name := fmt.Sprintf("%s-%06d-%s-%s-%s-%s.json", stamp, r.seq.Add(1), n.Kind, cleanPart(n.Level), cleanPart(n.Flow), cleanPart(n.ID))
|
||||||
|
err := os.Link(tmp.Name(), filepath.Join(r.dir, name))
|
||||||
|
if err == nil {
|
||||||
|
return name, nil
|
||||||
|
}
|
||||||
|
if !errors.Is(err, fs.ErrExist) {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// cleanPart makes a request value safe for a file name and the terminal.
|
||||||
|
func cleanPart(s string) string {
|
||||||
|
if s == "" {
|
||||||
|
return "none"
|
||||||
|
}
|
||||||
|
if len(s) > maxNamePart {
|
||||||
|
s = s[:maxNamePart]
|
||||||
|
}
|
||||||
|
b := []byte(s)
|
||||||
|
for i, c := range b {
|
||||||
|
switch {
|
||||||
|
case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z', c >= '0' && c <= '9', c == '@', c == '.', c == '_', c == '-':
|
||||||
|
default:
|
||||||
|
b[i] = '_'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return string(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *receiver) totals() string {
|
||||||
|
r.mu.Lock()
|
||||||
|
defer r.mu.Unlock()
|
||||||
|
return fmt.Sprintf("received limit=%d warning=%d, could not store %d", r.counts["limit"], r.counts["warning"], r.failed)
|
||||||
|
}
|
||||||
|
|
||||||
|
func runReceive(ctx context.Context, args []string, stdout, stderr io.Writer) int {
|
||||||
|
fs := flag.NewFlagSet("countersend receive", flag.ContinueOnError)
|
||||||
|
fs.SetOutput(stderr)
|
||||||
|
listen := fs.String("listen", "127.0.0.1:8099", "address the daemon's notify URLs point at")
|
||||||
|
dir := fs.String("dir", "./notifications", "directory for the notification files, created if missing")
|
||||||
|
if err := fs.Parse(args); err != nil {
|
||||||
|
return exitUsage
|
||||||
|
}
|
||||||
|
if fs.NArg() != 0 || *dir == "" {
|
||||||
|
fs.Usage()
|
||||||
|
return exitUsage
|
||||||
|
}
|
||||||
|
abs, err := filepath.Abs(*dir)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintln(stderr, err)
|
||||||
|
return exitFail
|
||||||
|
}
|
||||||
|
if err := checkWritable(abs); err != nil {
|
||||||
|
fmt.Fprintf(stderr, "cannot store notifications in %s: %v\n", abs, err)
|
||||||
|
return exitFail
|
||||||
|
}
|
||||||
|
ln, err := net.Listen("tcp", *listen)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "cannot listen: %v\n", err)
|
||||||
|
return exitFail
|
||||||
|
}
|
||||||
|
rcv := newReceiver(abs, stdout, stderr)
|
||||||
|
srv := &http.Server{Handler: rcv, ReadHeaderTimeout: 5 * time.Second}
|
||||||
|
fmt.Fprintf(stdout, "listening on %s, storing notifications in %s\n", ln.Addr(), abs)
|
||||||
|
|
||||||
|
serveErr := make(chan error, 1)
|
||||||
|
go func() { serveErr <- srv.Serve(ln) }()
|
||||||
|
select {
|
||||||
|
case err := <-serveErr:
|
||||||
|
fmt.Fprintf(stderr, "server stopped: %v\n", err)
|
||||||
|
fmt.Fprintln(stdout, rcv.totals())
|
||||||
|
return exitFail
|
||||||
|
case <-ctx.Done():
|
||||||
|
}
|
||||||
|
shutdown, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
if err := srv.Shutdown(shutdown); err != nil {
|
||||||
|
fmt.Fprintf(stderr, "shutdown: %v\n", err)
|
||||||
|
}
|
||||||
|
fmt.Fprintln(stdout, rcv.totals())
|
||||||
|
return exitOK
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkWritable(dir string) error {
|
||||||
|
if err := os.MkdirAll(dir, 0o750); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
f, err := os.CreateTemp(dir, ".tmp-*")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
f.Close()
|
||||||
|
return os.Remove(f.Name())
|
||||||
|
}
|
||||||
@@ -0,0 +1,321 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/BurntSushi/toml"
|
||||||
|
|
||||||
|
"migadu_counters/internal/config"
|
||||||
|
"migadu_counters/internal/notify"
|
||||||
|
)
|
||||||
|
|
||||||
|
type syncBuffer struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
b bytes.Buffer
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *syncBuffer) Write(p []byte) (int, error) {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
return s.b.Write(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *syncBuffer) String() string {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
return s.b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
const breachQuery = "/api/limits?level=A&id=a%40yagolivas.com&flow=o&period=d&by=a%40yagolivas.com&count=20&limit=20"
|
||||||
|
|
||||||
|
func newTestReceiver(t *testing.T) (*receiver, string, *httptest.Server) {
|
||||||
|
t.Helper()
|
||||||
|
dir := filepath.Join(t.TempDir(), "notifications")
|
||||||
|
if err := os.MkdirAll(dir, 0o750); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
r := newReceiver(dir, &syncBuffer{}, &syncBuffer{})
|
||||||
|
ts := httptest.NewServer(r)
|
||||||
|
t.Cleanup(ts.Close)
|
||||||
|
return r, dir, ts
|
||||||
|
}
|
||||||
|
|
||||||
|
func entries(t *testing.T, dir string) []string {
|
||||||
|
t.Helper()
|
||||||
|
list, err := os.ReadDir(dir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
names := make([]string, 0, len(list))
|
||||||
|
for _, e := range list {
|
||||||
|
names = append(names, e.Name())
|
||||||
|
}
|
||||||
|
return names
|
||||||
|
}
|
||||||
|
|
||||||
|
func get(t *testing.T, url string) int {
|
||||||
|
t.Helper()
|
||||||
|
req, err := http.NewRequest(http.MethodGet, url, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
req.SetBasicAuth("webuser", "webpassword")
|
||||||
|
resp, err := http.DefaultClient.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
resp.Body.Close()
|
||||||
|
return resp.StatusCode
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReceive_OneRequestOneFile(t *testing.T) {
|
||||||
|
_, dir, ts := newTestReceiver(t)
|
||||||
|
if code := get(t, ts.URL+breachQuery); code != 200 {
|
||||||
|
t.Fatalf("status %d", code)
|
||||||
|
}
|
||||||
|
names := entries(t, dir)
|
||||||
|
if len(names) != 1 {
|
||||||
|
t.Fatalf("files = %v", names)
|
||||||
|
}
|
||||||
|
if !regexp.MustCompile(`^\d{8}T\d{6}\.\d{6}Z-\d{6}-limit-A-o-a@yagolivas\.com\.json$`).MatchString(names[0]) {
|
||||||
|
t.Errorf("file name = %s", names[0])
|
||||||
|
}
|
||||||
|
data, err := os.ReadFile(filepath.Join(dir, names[0]))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var n notification
|
||||||
|
if err := json.Unmarshal(data, &n); err != nil {
|
||||||
|
t.Fatalf("not JSON: %v\n%s", err, data)
|
||||||
|
}
|
||||||
|
if n.Kind != "limit" || n.Level != "A" || n.ID != hosted || n.Flow != "o" || n.Period != "d" || n.By != hosted ||
|
||||||
|
n.Count != "20" || n.Limit != "20" || n.Path != "/api/limits" || n.AuthUser != "webuser" || n.RemoteAddr == "" || n.ReceivedAt == "" ||
|
||||||
|
!strings.Contains(n.RawQuery, "level=A") {
|
||||||
|
t.Errorf("notification = %+v", n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReceive_KindFollowsPath(t *testing.T) {
|
||||||
|
_, dir, ts := newTestReceiver(t)
|
||||||
|
get(t, ts.URL+"/api/limits/warning?level=O&id=1049&flow=i&by=x&count=160&limit=200&percent=80")
|
||||||
|
names := entries(t, dir)
|
||||||
|
if len(names) != 1 || !strings.Contains(names[0], "-warning-O-i-1049.json") {
|
||||||
|
t.Fatalf("files = %v", names)
|
||||||
|
}
|
||||||
|
data, _ := os.ReadFile(filepath.Join(dir, names[0]))
|
||||||
|
var n notification
|
||||||
|
json.Unmarshal(data, &n)
|
||||||
|
if n.Kind != "warning" || n.Percent != "80" {
|
||||||
|
t.Errorf("notification = %+v", n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReceive_RepeatsAreNotMerged(t *testing.T) {
|
||||||
|
_, dir, ts := newTestReceiver(t)
|
||||||
|
get(t, ts.URL+breachQuery)
|
||||||
|
get(t, ts.URL+breachQuery)
|
||||||
|
if names := entries(t, dir); len(names) != 2 {
|
||||||
|
t.Errorf("files = %v, want 2: a repeat must stay visible", names)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReceive_ConcurrentRequestsGetDistinctCompleteFiles(t *testing.T) {
|
||||||
|
_, dir, ts := newTestReceiver(t)
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
for i := 0; i < 100; i++ {
|
||||||
|
wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
if code := get(t, ts.URL+breachQuery); code != 200 {
|
||||||
|
t.Errorf("status %d", code)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
wg.Wait()
|
||||||
|
names := entries(t, dir)
|
||||||
|
if len(names) != 100 {
|
||||||
|
t.Fatalf("%d files, want 100", len(names))
|
||||||
|
}
|
||||||
|
for _, name := range names {
|
||||||
|
if strings.HasPrefix(name, ".") {
|
||||||
|
t.Errorf("temporary file left behind: %s", name)
|
||||||
|
}
|
||||||
|
data, _ := os.ReadFile(filepath.Join(dir, name))
|
||||||
|
if !json.Valid(data) {
|
||||||
|
t.Errorf("%s is not complete JSON", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReceive_IDCannotLeaveTheDirectory(t *testing.T) {
|
||||||
|
_, dir, ts := newTestReceiver(t)
|
||||||
|
parent := filepath.Dir(dir)
|
||||||
|
get(t, ts.URL+"/api/limits?level=..%2F..&id=..%2F..%2F..%2Fetc%2Fpasswd&flow=%2Fx")
|
||||||
|
names := entries(t, dir)
|
||||||
|
if len(names) != 1 || strings.ContainsAny(names[0], "/\\") {
|
||||||
|
t.Fatalf("files = %v", names)
|
||||||
|
}
|
||||||
|
if up := entries(t, parent); len(up) != 1 {
|
||||||
|
t.Errorf("wrote outside the directory: %v", up)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReceive_LongIDIsCut(t *testing.T) {
|
||||||
|
_, dir, ts := newTestReceiver(t)
|
||||||
|
get(t, ts.URL+"/api/limits?level=A&flow=o&id="+strings.Repeat("a", 500))
|
||||||
|
names := entries(t, dir)
|
||||||
|
if len(names) != 1 || !strings.HasSuffix(names[0], "-"+strings.Repeat("a", 64)+".json") {
|
||||||
|
t.Errorf("files = %v", names)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReceive_PasswordIsNeverStored(t *testing.T) {
|
||||||
|
_, dir, ts := newTestReceiver(t)
|
||||||
|
get(t, ts.URL+breachQuery)
|
||||||
|
data, _ := os.ReadFile(filepath.Join(dir, entries(t, dir)[0]))
|
||||||
|
if bytes.Contains(data, []byte("webpassword")) {
|
||||||
|
t.Errorf("password stored:\n%s", data)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReceive_NonGetIsRefusedAndNotStored(t *testing.T) {
|
||||||
|
_, dir, ts := newTestReceiver(t)
|
||||||
|
resp, err := http.Post(ts.URL+"/api/limits", "text/plain", nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
resp.Body.Close()
|
||||||
|
if resp.StatusCode != http.StatusMethodNotAllowed {
|
||||||
|
t.Errorf("status %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
if names := entries(t, dir); len(names) != 0 {
|
||||||
|
t.Errorf("files = %v", names)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The daemon retries on 5xx, so a notification that could not be stored is not lost.
|
||||||
|
func TestReceive_UnwritableDirectoryAnswers500(t *testing.T) {
|
||||||
|
if os.Geteuid() == 0 {
|
||||||
|
t.Skip("root ignores directory permissions")
|
||||||
|
}
|
||||||
|
_, dir, ts := newTestReceiver(t)
|
||||||
|
if err := os.Chmod(dir, 0o500); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer os.Chmod(dir, 0o750)
|
||||||
|
if code := get(t, ts.URL+breachQuery); code != 500 {
|
||||||
|
t.Errorf("status %d, want 500", code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRunReceive_CreatesDirServesAndPrintsTotals(t *testing.T) {
|
||||||
|
dir := filepath.Join(t.TempDir(), "a", "b")
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
defer cancel()
|
||||||
|
var out, errb syncBuffer
|
||||||
|
done := make(chan int, 1)
|
||||||
|
go func() { done <- runReceive(ctx, []string{"--listen", "127.0.0.1:0", "--dir", dir}, &out, &errb) }()
|
||||||
|
|
||||||
|
re := regexp.MustCompile(`listening on (127\.0\.0\.1:\d+)`)
|
||||||
|
var addr string
|
||||||
|
for deadline := time.Now().Add(3 * time.Second); time.Now().Before(deadline); time.Sleep(10 * time.Millisecond) {
|
||||||
|
if m := re.FindStringSubmatch(out.String()); m != nil {
|
||||||
|
addr = m[1]
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if addr == "" {
|
||||||
|
t.Fatalf("never listened: %s %s", out.String(), errb.String())
|
||||||
|
}
|
||||||
|
get(t, "http://"+addr+breachQuery)
|
||||||
|
cancel()
|
||||||
|
select {
|
||||||
|
case code := <-done:
|
||||||
|
if code != 0 {
|
||||||
|
t.Errorf("exit %d\n%s", code, errb.String())
|
||||||
|
}
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("did not stop")
|
||||||
|
}
|
||||||
|
if names := entries(t, dir); len(names) != 1 {
|
||||||
|
t.Errorf("files = %v", names)
|
||||||
|
}
|
||||||
|
if !strings.Contains(out.String(), "limit=1") {
|
||||||
|
t.Errorf("no totals:\n%s", out.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRun_Dispatch(t *testing.T) {
|
||||||
|
var out, errb bytes.Buffer
|
||||||
|
if code := run(context.Background(), []string{"bogus"}, &out, &errb, func(string) string { return "" }); code != 2 {
|
||||||
|
t.Errorf("unknown subcommand: exit %d", code)
|
||||||
|
}
|
||||||
|
if code := run(context.Background(), nil, &out, &errb, func(string) string { return "" }); code != 2 {
|
||||||
|
t.Errorf("no subcommand: exit %d", code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// send → real daemon code → real notifier → receive → files on disk.
|
||||||
|
func TestSendThroughDaemonIntoFiles(t *testing.T) {
|
||||||
|
_, dir, sink := newTestReceiver(t)
|
||||||
|
q := "?level=$LEVEL&id=$ID&flow=$FLOW&period=$PERIOD&by=$ADDRESS&count=$COUNT&limit=$LIMIT"
|
||||||
|
breach, warn := sink.URL+"/api/limits"+q, sink.URL+"/api/limits/warning"+q+"&percent=$PERCENT"
|
||||||
|
d := startDaemon(t, ¬ify.Config{AddressURL: breach, OrgURL: breach, DomainURL: breach,
|
||||||
|
WarnAddressURL: warn, WarnOrgURL: warn, WarnDomainURL: warn, Timeout: time.Second})
|
||||||
|
|
||||||
|
// A/o=20: warn at 16, breach at 20, then nothing more.
|
||||||
|
out := []string{"--route", "out", "--auth-user", hosted, "--recipient", "x@gmail.com", "--allow-notify", "--concurrency", "4"}
|
||||||
|
if r := send(t, d.url, append(out, "--n", "25")...); r.code != 0 {
|
||||||
|
t.Fatalf("exit %d\n%s", r.code, r.all())
|
||||||
|
}
|
||||||
|
if err := d.notifier.Shutdown(context.Background()); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
glob := func(p string) int {
|
||||||
|
m, _ := filepath.Glob(filepath.Join(dir, p))
|
||||||
|
return len(m)
|
||||||
|
}
|
||||||
|
for _, p := range []string{"*-warning-A-o-a@yagolivas.com.json", "*-limit-A-o-a@yagolivas.com.json",
|
||||||
|
"*-warning-D-o-yagolivas.com.json", "*-limit-D-o-yagolivas.com.json", "*-warning-O-o-1049.json", "*-limit-O-o-1049.json"} {
|
||||||
|
if n := glob(p); n != 1 {
|
||||||
|
t.Errorf("%s: %d files, want 1; all: %v", p, n, entries(t, dir))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The [notify] block in the guide must be accepted by the daemon as written.
|
||||||
|
func TestGuideNotifyConfigIsValid(t *testing.T) {
|
||||||
|
data, err := os.ReadFile("../../docs/testing-with-countersend.md")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
m := regexp.MustCompile("(?s)```toml\n(\\[notify\\].*?)```").FindSubmatch(data)
|
||||||
|
if m == nil {
|
||||||
|
t.Fatal("no ```toml [notify] block in the guide")
|
||||||
|
}
|
||||||
|
cfg := config.Default()
|
||||||
|
if _, err := toml.Decode(string(m[1]), &cfg); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
cfg.DomainsCDB, cfg.AuthToken, cfg.Redis.WriteAddr = "x", "x", "127.0.0.1:6379"
|
||||||
|
if err := cfg.Validate(); err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
|
if w := cfg.Warnings(); len(w) != 0 {
|
||||||
|
t.Errorf("warnings: %v", w)
|
||||||
|
}
|
||||||
|
if cfg.Notify.AddressURL == "" || cfg.Notify.WarnAddressURL == "" {
|
||||||
|
t.Errorf("guide leaves URLs empty: %+v", cfg.Notify)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,591 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"crypto/rand"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"math"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"text/tabwriter"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/BurntSushi/toml"
|
||||||
|
|
||||||
|
"migadu_counters/internal/api"
|
||||||
|
"migadu_counters/internal/config"
|
||||||
|
"migadu_counters/internal/counting"
|
||||||
|
"migadu_counters/internal/domains"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
defaultWarnPercent = 80
|
||||||
|
defaultMailFromIn = "countersend@example.com"
|
||||||
|
requestTimeout = 10 * time.Second
|
||||||
|
pollInterval = 50 * time.Millisecond
|
||||||
|
// settleTime is how long to wait before the final read when no counter
|
||||||
|
// is expected to move, so nothing is there to poll for.
|
||||||
|
settleTime = 500 * time.Millisecond
|
||||||
|
)
|
||||||
|
|
||||||
|
// cliConfig mirrors the daemon config fields this tool needs; TOML ignores the
|
||||||
|
// rest, so the daemon's own config file can be used as is.
|
||||||
|
type cliConfig struct {
|
||||||
|
Addr string `toml:"addr"`
|
||||||
|
AuthToken string `toml:"auth_token"`
|
||||||
|
Notify struct {
|
||||||
|
WarnPercent *int64 `toml:"warn_percent"`
|
||||||
|
OrgURL string `toml:"org_url"`
|
||||||
|
AddressURL string `toml:"address_url"`
|
||||||
|
DomainURL string `toml:"domain_url"`
|
||||||
|
WarnOrgURL string `toml:"warn_org_url"`
|
||||||
|
WarnAddressURL string `toml:"warn_address_url"`
|
||||||
|
WarnDomainURL string `toml:"warn_domain_url"`
|
||||||
|
} `toml:"notify"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// loadConfig reads the daemon config. Without --config the default paths are
|
||||||
|
// tried; when none exists the tool still runs with --url and the token from
|
||||||
|
// the environment. found says whether a file was read.
|
||||||
|
func loadConfig(path string, haveURL bool) (cfg cliConfig, found bool, err error) {
|
||||||
|
if path == "" {
|
||||||
|
discovered, derr := config.Discover("")
|
||||||
|
if derr != nil {
|
||||||
|
if haveURL {
|
||||||
|
return cfg, false, nil
|
||||||
|
}
|
||||||
|
return cfg, false, derr
|
||||||
|
}
|
||||||
|
path = discovered
|
||||||
|
}
|
||||||
|
if _, err := toml.DecodeFile(path, &cfg); err != nil {
|
||||||
|
return cfg, false, fmt.Errorf("read config %s: %v", path, err)
|
||||||
|
}
|
||||||
|
return cfg, true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// baseURL turns the daemon's listen address into a URL: ":5555" →
|
||||||
|
// "http://localhost:5555"; a full URL is used as is.
|
||||||
|
func baseURL(addr string) string {
|
||||||
|
if addr == "" {
|
||||||
|
addr = ":5555"
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(addr, "http://") || strings.HasPrefix(addr, "https://") {
|
||||||
|
return strings.TrimRight(addr, "/")
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(addr, ":") {
|
||||||
|
addr = "localhost" + addr
|
||||||
|
}
|
||||||
|
return "http://" + addr
|
||||||
|
}
|
||||||
|
|
||||||
|
// notifyHosts lists where the configured notifications go, without URL
|
||||||
|
// credentials.
|
||||||
|
func notifyHosts(cfg cliConfig) []string {
|
||||||
|
seen := map[string]bool{}
|
||||||
|
var hosts []string
|
||||||
|
n := cfg.Notify
|
||||||
|
for _, raw := range []string{n.OrgURL, n.AddressURL, n.DomainURL, n.WarnOrgURL, n.WarnAddressURL, n.WarnDomainURL} {
|
||||||
|
u, err := url.Parse(raw)
|
||||||
|
if raw == "" || err != nil || u.Host == "" || seen[u.Host] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[u.Host] = true
|
||||||
|
hosts = append(hosts, u.Host)
|
||||||
|
}
|
||||||
|
sort.Strings(hosts)
|
||||||
|
return hosts
|
||||||
|
}
|
||||||
|
|
||||||
|
// side is one address whose counters a run moves.
|
||||||
|
type side struct {
|
||||||
|
role string // sender | recipient
|
||||||
|
addr string // normalised
|
||||||
|
flow string // i | o
|
||||||
|
before *api.CountersResponse
|
||||||
|
after *api.CountersResponse
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *side) flowName() string {
|
||||||
|
if s.flow == domains.FlowOut {
|
||||||
|
return "outgoing"
|
||||||
|
}
|
||||||
|
return "incoming"
|
||||||
|
}
|
||||||
|
|
||||||
|
func levelValue(l api.CountersLevel, flow string) (int64, *int64) {
|
||||||
|
if flow == domains.FlowOut {
|
||||||
|
return l.Out, l.OutLimit
|
||||||
|
}
|
||||||
|
return l.In, l.InLimit
|
||||||
|
}
|
||||||
|
|
||||||
|
func addressCount(r *api.CountersResponse, flow string) (int64, bool) {
|
||||||
|
if r == nil {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
for _, l := range r.Levels {
|
||||||
|
if l.Level == domains.AddressLevel {
|
||||||
|
n, _ := levelValue(l, flow)
|
||||||
|
return n, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
|
||||||
|
type client struct {
|
||||||
|
http *http.Client
|
||||||
|
base string
|
||||||
|
token string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *client) counters(address string) (*api.CountersResponse, error) {
|
||||||
|
q := url.Values{"address": {address}}
|
||||||
|
req, err := http.NewRequest(http.MethodGet, c.base+"/counters?"+q.Encode(), nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
req.Header.Set("Authorization", "Bearer "+c.token)
|
||||||
|
resp, err := c.http.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
return nil, fmt.Errorf("GET /counters answered %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
var r api.CountersResponse
|
||||||
|
if err := json.Unmarshal(body, &r); err != nil {
|
||||||
|
return nil, fmt.Errorf("GET /counters: %v", err)
|
||||||
|
}
|
||||||
|
return &r, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// readAll refreshes dest for every side and returns the first error.
|
||||||
|
func (c *client) readAll(sides []*side, dest func(*side) **api.CountersResponse) error {
|
||||||
|
var first error
|
||||||
|
for _, s := range sides {
|
||||||
|
r, err := c.counters(s.addr)
|
||||||
|
if err != nil {
|
||||||
|
if first == nil {
|
||||||
|
first = err
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
*dest(s) = r
|
||||||
|
}
|
||||||
|
return first
|
||||||
|
}
|
||||||
|
|
||||||
|
// sendStats is the outcome of the POSTs.
|
||||||
|
type sendStats struct {
|
||||||
|
status map[int]int
|
||||||
|
connErrors int
|
||||||
|
firstConnErr error
|
||||||
|
firstBadBody string
|
||||||
|
latencies []time.Duration
|
||||||
|
elapsed time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *client) post(path, runID string, n, concurrency int, body func(trace string) any) sendStats {
|
||||||
|
stats := sendStats{status: map[int]int{}}
|
||||||
|
var mu sync.Mutex
|
||||||
|
jobs := make(chan int)
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
start := time.Now()
|
||||||
|
for w := 0; w < concurrency; w++ {
|
||||||
|
wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
for i := range jobs {
|
||||||
|
code, respBody, took, err := c.postOne(path, body(fmt.Sprintf("countersend-%s-%d", runID, i)))
|
||||||
|
mu.Lock()
|
||||||
|
stats.latencies = append(stats.latencies, took)
|
||||||
|
if err != nil {
|
||||||
|
stats.connErrors++
|
||||||
|
if stats.firstConnErr == nil {
|
||||||
|
stats.firstConnErr = err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
stats.status[code]++
|
||||||
|
if code != http.StatusAccepted && stats.firstBadBody == "" {
|
||||||
|
stats.firstBadBody = respBody
|
||||||
|
}
|
||||||
|
}
|
||||||
|
mu.Unlock()
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
for i := 1; i <= n; i++ {
|
||||||
|
jobs <- i
|
||||||
|
}
|
||||||
|
close(jobs)
|
||||||
|
wg.Wait()
|
||||||
|
stats.elapsed = time.Since(start)
|
||||||
|
return stats
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *client) postOne(path string, payload any) (int, string, time.Duration, error) {
|
||||||
|
data, err := json.Marshal(payload)
|
||||||
|
if err != nil {
|
||||||
|
return 0, "", 0, err
|
||||||
|
}
|
||||||
|
req, err := http.NewRequest(http.MethodPost, c.base+path, bytes.NewReader(data))
|
||||||
|
if err != nil {
|
||||||
|
return 0, "", 0, err
|
||||||
|
}
|
||||||
|
req.Header.Set("Authorization", "Bearer "+c.token)
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
start := time.Now()
|
||||||
|
resp, err := c.http.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return 0, "", time.Since(start), err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
respBody, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
|
||||||
|
return resp.StatusCode, strings.TrimSpace(string(respBody)), time.Since(start), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func percentile(sorted []time.Duration, p float64) time.Duration {
|
||||||
|
if len(sorted) == 0 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return sorted[int(math.Ceil(p*float64(len(sorted))))-1]
|
||||||
|
}
|
||||||
|
|
||||||
|
func printStats(w io.Writer, st sendStats, n int) {
|
||||||
|
codes := make([]int, 0, len(st.status))
|
||||||
|
for c := range st.status {
|
||||||
|
codes = append(codes, c)
|
||||||
|
}
|
||||||
|
sort.Ints(codes)
|
||||||
|
parts := make([]string, 0, len(codes))
|
||||||
|
for _, c := range codes {
|
||||||
|
parts = append(parts, fmt.Sprintf("%d=%d", c, st.status[c]))
|
||||||
|
}
|
||||||
|
if len(parts) == 0 {
|
||||||
|
parts = append(parts, "none")
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, "status: %s\n", strings.Join(parts, " "))
|
||||||
|
if st.connErrors > 0 {
|
||||||
|
fmt.Fprintf(w, "connection errors: %d (first: %v)\n", st.connErrors, st.firstConnErr)
|
||||||
|
}
|
||||||
|
if st.firstBadBody != "" {
|
||||||
|
fmt.Fprintf(w, "first error reply: %s\n", st.firstBadBody)
|
||||||
|
}
|
||||||
|
sort.Slice(st.latencies, func(i, j int) bool { return st.latencies[i] < st.latencies[j] })
|
||||||
|
rate := float64(n) / st.elapsed.Seconds()
|
||||||
|
fmt.Fprintf(w, "timing: %v total, %.0f req/s, p50 %v, p99 %v\n", st.elapsed.Round(time.Microsecond), rate,
|
||||||
|
percentile(st.latencies, 0.50).Round(time.Microsecond), percentile(st.latencies, 0.99).Round(time.Microsecond))
|
||||||
|
}
|
||||||
|
|
||||||
|
// crossings describes every threshold a run of n would reach. A counter
|
||||||
|
// already past a threshold cannot cross it again and is not listed.
|
||||||
|
func crossings(sides []*side, n, percent int64) []string {
|
||||||
|
var out []string
|
||||||
|
for _, s := range sides {
|
||||||
|
if s.before == nil || !s.before.Managed {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, l := range s.before.Levels {
|
||||||
|
count, limit := levelValue(l, s.flow)
|
||||||
|
if limit == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
where := fmt.Sprintf("%s %s %s: %d + %d", l.Level, l.ID, s.flowName(), count, n)
|
||||||
|
if warn := counting.WarnThreshold(*limit, percent); warn > 0 && counting.Crossed(count+n, n, warn) {
|
||||||
|
out = append(out, fmt.Sprintf("%s reaches the warning threshold %d (limit %d)", where, warn, *limit))
|
||||||
|
}
|
||||||
|
if counting.Crossed(count+n, n, *limit) {
|
||||||
|
out = append(out, fmt.Sprintf("%s reaches the limit %d", where, *limit))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func describeHosts(found bool, hosts []string) string {
|
||||||
|
switch {
|
||||||
|
case !found:
|
||||||
|
return "notifications would go to the hosts in the daemon's config (no config was read here)"
|
||||||
|
case len(hosts) == 0:
|
||||||
|
return "no notify URL is configured, so nothing would be sent"
|
||||||
|
default:
|
||||||
|
return "notifications would go to: " + strings.Join(hosts, ", ")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func printCounters(w io.Writer, s *side) {
|
||||||
|
fmt.Fprintf(w, "%s %s, %s\n", s.role, s.addr, s.flowName())
|
||||||
|
if s.after == nil {
|
||||||
|
fmt.Fprintln(w, " counters could not be read")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
tw := tabwriter.NewWriter(w, 0, 8, 2, ' ', 0)
|
||||||
|
fmt.Fprintln(tw, " LEVEL\tID\tBEFORE\tAFTER\tCHANGE\tLIMIT")
|
||||||
|
for _, l := range s.after.Levels {
|
||||||
|
now, limit := levelValue(l, s.flow)
|
||||||
|
before, change := "-", "-"
|
||||||
|
if s.before != nil {
|
||||||
|
for _, b := range s.before.Levels {
|
||||||
|
if b.Level == l.Level {
|
||||||
|
v, _ := levelValue(b, s.flow)
|
||||||
|
before, change = fmt.Sprint(v), fmt.Sprintf("%+d", now-v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
lim := "-"
|
||||||
|
if limit != nil {
|
||||||
|
lim = fmt.Sprint(*limit)
|
||||||
|
}
|
||||||
|
fmt.Fprintf(tw, " %s\t%s\t%s\t%d\t%s\t%s\n", l.Level, l.ID, before, now, change, lim)
|
||||||
|
}
|
||||||
|
tw.Flush()
|
||||||
|
}
|
||||||
|
|
||||||
|
func runSend(args []string, stdout, stderr io.Writer, getenv func(string) string) int {
|
||||||
|
fs := flag.NewFlagSet("countersend send", flag.ContinueOnError)
|
||||||
|
fs.SetOutput(stderr)
|
||||||
|
urlFlag := fs.String("url", "", "where to send: base URL of the daemon (default: addr from the config)")
|
||||||
|
route := fs.String("route", "", "in or out")
|
||||||
|
n := fs.Int("n", 1, "number of requests")
|
||||||
|
concurrency := fs.Int("concurrency", 1, "requests in flight at once")
|
||||||
|
recipient := fs.String("recipient", "", "recipient address")
|
||||||
|
authUser := fs.String("auth-user", "", "SMTP login (--route out only)")
|
||||||
|
mailFrom := fs.String("mail-from", "", "envelope sender (default: the auth user for out, "+defaultMailFromIn+" for in)")
|
||||||
|
junk := fs.Bool("junk", false, "set junk:true (--route in only)")
|
||||||
|
configPath := fs.String("config", "", "daemon config (default: "+strings.Join(config.DefaultPaths, " or ")+")")
|
||||||
|
allowNotify := fs.Bool("allow-notify", false, "allow a run that would reach a warning threshold or a limit")
|
||||||
|
wait := fs.Duration("wait", 5*time.Second, "how long to wait for the counters to move")
|
||||||
|
if err := fs.Parse(args); err != nil {
|
||||||
|
return exitUsage
|
||||||
|
}
|
||||||
|
|
||||||
|
var problems []string
|
||||||
|
if fs.NArg() != 0 {
|
||||||
|
problems = append(problems, "unexpected arguments: "+strings.Join(fs.Args(), " "))
|
||||||
|
}
|
||||||
|
if *route != "in" && *route != "out" {
|
||||||
|
problems = append(problems, "--route must be in or out")
|
||||||
|
}
|
||||||
|
if *recipient == "" {
|
||||||
|
problems = append(problems, "--recipient is required")
|
||||||
|
}
|
||||||
|
if *route == "out" && *authUser == "" {
|
||||||
|
problems = append(problems, "--auth-user is required with --route out")
|
||||||
|
}
|
||||||
|
if *route == "in" && *authUser != "" {
|
||||||
|
problems = append(problems, "--auth-user only applies to --route out")
|
||||||
|
}
|
||||||
|
if *route == "out" && *junk {
|
||||||
|
problems = append(problems, "--junk only applies to --route in")
|
||||||
|
}
|
||||||
|
if *n < 1 {
|
||||||
|
problems = append(problems, "--n must be at least 1")
|
||||||
|
}
|
||||||
|
if *concurrency < 1 {
|
||||||
|
problems = append(problems, "--concurrency must be at least 1")
|
||||||
|
}
|
||||||
|
if len(problems) > 0 {
|
||||||
|
fmt.Fprintln(stderr, strings.Join(problems, "\n"))
|
||||||
|
return exitUsage
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg, found, err := loadConfig(*configPath, *urlFlag != "")
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "%v\nuse --config, or --url with %s set\n", err, config.EnvAuthToken)
|
||||||
|
return exitUsage
|
||||||
|
}
|
||||||
|
token := cfg.AuthToken
|
||||||
|
if v := getenv(config.EnvAuthToken); v != "" {
|
||||||
|
token = v
|
||||||
|
}
|
||||||
|
if token == "" {
|
||||||
|
fmt.Fprintf(stderr, "no auth token: set auth_token in the config or %s\n", config.EnvAuthToken)
|
||||||
|
return exitUsage
|
||||||
|
}
|
||||||
|
base := *urlFlag
|
||||||
|
if base == "" {
|
||||||
|
base = baseURL(cfg.Addr)
|
||||||
|
}
|
||||||
|
base = strings.TrimRight(base, "/")
|
||||||
|
if u, err := url.Parse(base); err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
|
||||||
|
fmt.Fprintf(stderr, "--url must be an http(s) URL, got %q\n", base)
|
||||||
|
return exitUsage
|
||||||
|
}
|
||||||
|
percent := int64(defaultWarnPercent)
|
||||||
|
if cfg.Notify.WarnPercent != nil {
|
||||||
|
percent = *cfg.Notify.WarnPercent
|
||||||
|
}
|
||||||
|
|
||||||
|
transport := http.DefaultTransport.(*http.Transport).Clone()
|
||||||
|
transport.Proxy = nil
|
||||||
|
transport.MaxIdleConnsPerHost = *concurrency
|
||||||
|
c := &client{http: &http.Client{Timeout: requestTimeout, Transport: transport}, base: base, token: token}
|
||||||
|
|
||||||
|
// Work out which counters this run moves.
|
||||||
|
var sides []*side
|
||||||
|
senderAddr := ""
|
||||||
|
if *route == "out" {
|
||||||
|
if addr, _, err := api.NormalizeAuthUser(*authUser); err == nil {
|
||||||
|
senderAddr = addr
|
||||||
|
sides = append(sides, &side{role: "sender", addr: addr, flow: domains.FlowOut})
|
||||||
|
} else {
|
||||||
|
fmt.Fprintln(stdout, "auth user is not a usable address: the sender side will not be counted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if addr, err := api.NormalizeEmail(*recipient); err == nil {
|
||||||
|
sides = append(sides, &side{role: "recipient", addr: addr, flow: domains.FlowIn})
|
||||||
|
} else {
|
||||||
|
fmt.Fprintf(stdout, "recipient %s is not a usable address: the recipient side will not be counted\n", api.SanitizeForLog(*recipient))
|
||||||
|
}
|
||||||
|
from := *mailFrom
|
||||||
|
if from == "" {
|
||||||
|
from = defaultMailFromIn
|
||||||
|
if *route == "out" {
|
||||||
|
from = senderAddr
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeErr := c.readAll(sides, func(s *side) **api.CountersResponse { return &s.before })
|
||||||
|
exempt := false
|
||||||
|
for _, s := range sides {
|
||||||
|
exempt = exempt || (s.before != nil && s.before.Exempt)
|
||||||
|
}
|
||||||
|
if addr, err := api.NormalizeEmail(from); err == nil {
|
||||||
|
r, err := c.counters(addr)
|
||||||
|
switch {
|
||||||
|
case err != nil && beforeErr == nil:
|
||||||
|
beforeErr = err
|
||||||
|
case err == nil && r.Exempt:
|
||||||
|
exempt = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
hostInfo := describeHosts(found, notifyHosts(cfg))
|
||||||
|
if beforeErr != nil && !*allowNotify {
|
||||||
|
fmt.Fprintf(stderr, "refusing to send: cannot read the counters, so cannot tell whether this run would notify anyone: %v\n", beforeErr)
|
||||||
|
fmt.Fprintf(stderr, "%s\nuse --allow-notify to send anyway\n", hostInfo)
|
||||||
|
return exitFail
|
||||||
|
}
|
||||||
|
if !exempt {
|
||||||
|
if hits := crossings(sides, int64(*n), percent); len(hits) > 0 {
|
||||||
|
if !*allowNotify {
|
||||||
|
fmt.Fprintln(stderr, "refusing to send: this run would trigger notifications:")
|
||||||
|
for _, h := range hits {
|
||||||
|
fmt.Fprintln(stderr, " "+h)
|
||||||
|
}
|
||||||
|
fmt.Fprintf(stderr, "%s\nuse --allow-notify if that is what you want\n", hostInfo)
|
||||||
|
return exitFail
|
||||||
|
}
|
||||||
|
fmt.Fprintln(stdout, "this run will trigger notifications:")
|
||||||
|
for _, h := range hits {
|
||||||
|
fmt.Fprintln(stdout, " "+h)
|
||||||
|
}
|
||||||
|
fmt.Fprintln(stdout, hostInfo)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
idBytes := make([]byte, 4)
|
||||||
|
if _, err := rand.Read(idBytes); err != nil {
|
||||||
|
fmt.Fprintln(stderr, err)
|
||||||
|
return exitFail
|
||||||
|
}
|
||||||
|
runID := hex.EncodeToString(idBytes)
|
||||||
|
path := "/" + *route
|
||||||
|
fmt.Fprintf(stdout, "POST %s%s n=%d concurrency=%d trace ids: countersend-%s-*\n", base, path, *n, *concurrency, runID)
|
||||||
|
|
||||||
|
stats := c.post(path, runID, *n, *concurrency, func(trace string) any {
|
||||||
|
if *route == "out" {
|
||||||
|
return api.OutRequest{TraceID: trace, AuthUser: *authUser, MailFrom: from, Recipient: *recipient}
|
||||||
|
}
|
||||||
|
return api.InRequest{TraceID: trace, MailFrom: from, Recipient: *recipient, Junk: *junk}
|
||||||
|
})
|
||||||
|
printStats(stdout, stats, *n)
|
||||||
|
|
||||||
|
accepted := int64(stats.status[http.StatusAccepted])
|
||||||
|
failed := accepted != int64(*n)
|
||||||
|
if failed {
|
||||||
|
fmt.Fprintf(stderr, "FAIL: %d of %d requests were not accepted\n", int64(*n)-accepted, *n)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A counter is expected to move when the daemon would count it.
|
||||||
|
var judged []*side
|
||||||
|
if !exempt && !*junk && accepted > 0 {
|
||||||
|
for _, s := range sides {
|
||||||
|
if s.before != nil && s.before.Managed {
|
||||||
|
judged = append(judged, s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
risen := func(s *side) bool {
|
||||||
|
before, ok1 := addressCount(s.before, s.flow)
|
||||||
|
after, ok2 := addressCount(s.after, s.flow)
|
||||||
|
return ok1 && ok2 && after-before >= accepted
|
||||||
|
}
|
||||||
|
afterErr := c.waitForCounters(sides, judged, risen, *wait)
|
||||||
|
|
||||||
|
for _, s := range sides {
|
||||||
|
printCounters(stdout, s)
|
||||||
|
switch {
|
||||||
|
case exempt:
|
||||||
|
fmt.Fprintln(stdout, " exempt address in this request: nothing should move")
|
||||||
|
case *junk:
|
||||||
|
fmt.Fprintln(stdout, " junk: whether this counts depends on count_junk")
|
||||||
|
case s.before != nil && !s.before.Managed:
|
||||||
|
fmt.Fprintln(stdout, " domain not hosted: nothing should move")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, s := range judged {
|
||||||
|
if !risen(s) {
|
||||||
|
before, _ := addressCount(s.before, s.flow)
|
||||||
|
after, _ := addressCount(s.after, s.flow)
|
||||||
|
fmt.Fprintf(stderr, "FAIL: %s %s counter did not rise by %d within %v (rose by %d)\n", s.role, s.addr, accepted, *wait, after-before)
|
||||||
|
failed = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if accepted > 0 && (beforeErr != nil || afterErr != nil) {
|
||||||
|
err := errors.Join(beforeErr, afterErr)
|
||||||
|
fmt.Fprintf(stderr, "FAIL: counting could not be confirmed: %v\n", err)
|
||||||
|
failed = true
|
||||||
|
}
|
||||||
|
if failed {
|
||||||
|
return exitFail
|
||||||
|
}
|
||||||
|
fmt.Fprintln(stdout, "OK")
|
||||||
|
return exitOK
|
||||||
|
}
|
||||||
|
|
||||||
|
// waitForCounters polls until every judged side has risen, or wait passes.
|
||||||
|
// Without judged sides it reads once after a short settle time.
|
||||||
|
func (c *client) waitForCounters(sides, judged []*side, risen func(*side) bool, wait time.Duration) error {
|
||||||
|
dest := func(s *side) **api.CountersResponse { return &s.after }
|
||||||
|
if len(judged) == 0 {
|
||||||
|
time.Sleep(min(wait, settleTime))
|
||||||
|
return c.readAll(sides, dest)
|
||||||
|
}
|
||||||
|
deadline := time.Now().Add(wait)
|
||||||
|
for {
|
||||||
|
err := c.readAll(sides, dest)
|
||||||
|
done := err == nil
|
||||||
|
for _, s := range judged {
|
||||||
|
done = done && risen(s)
|
||||||
|
}
|
||||||
|
if done || !time.Now().Before(deadline) {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
time.Sleep(pollInterval)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,484 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/alicebob/miniredis/v2"
|
||||||
|
|
||||||
|
"migadu_counters/internal/api"
|
||||||
|
"migadu_counters/internal/config"
|
||||||
|
"migadu_counters/internal/counting"
|
||||||
|
"migadu_counters/internal/domains"
|
||||||
|
"migadu_counters/internal/notify"
|
||||||
|
"migadu_counters/internal/server"
|
||||||
|
"migadu_counters/internal/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
testCDB = "../../test_files/rspamd_domains_db.cdb"
|
||||||
|
testToken = "s3cret-test-token"
|
||||||
|
// Real CDB row: 1049|O/i=200,O/o=20,D/i=200,D/o=20,A/i=200,A/o=20
|
||||||
|
hosted = "a@yagolivas.com"
|
||||||
|
)
|
||||||
|
|
||||||
|
type recorded struct {
|
||||||
|
Path, Auth, ContentType string
|
||||||
|
Body []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
type daemon struct {
|
||||||
|
url string
|
||||||
|
redis *miniredis.Miniredis
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
reqs []recorded
|
||||||
|
|
||||||
|
notifier *notify.Notifier
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *daemon) posts() []recorded {
|
||||||
|
d.mu.Lock()
|
||||||
|
defer d.mu.Unlock()
|
||||||
|
var out []recorded
|
||||||
|
for _, r := range d.reqs {
|
||||||
|
if r.Path == "/in" || r.Path == "/out" {
|
||||||
|
out = append(out, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *daemon) set(t *testing.T, level, id, flow string, n int) {
|
||||||
|
t.Helper()
|
||||||
|
d.redis.Set(store.Key(level, id, store.DayKey(time.Now()), flow), strconv.Itoa(n))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *daemon) get(level, id, flow string) string {
|
||||||
|
v, _ := d.redis.Get(store.Key(level, id, store.DayKey(time.Now()), flow))
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
|
||||||
|
// startDaemon runs the real server, real store and real CDB behind a recorder.
|
||||||
|
func startDaemon(t *testing.T, ncfg *notify.Config) *daemon {
|
||||||
|
t.Helper()
|
||||||
|
d := &daemon{redis: miniredis.RunT(t)}
|
||||||
|
st, err := store.New(config.RedisConfig{WriteAddr: d.redis.Addr(), ReadAddrs: []string{d.redis.Addr()}, PoolSize: 8, TimeoutMS: 2000})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { st.Close() })
|
||||||
|
db, err := domains.Open(testCDB)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { db.Close() })
|
||||||
|
|
||||||
|
exempt := map[string]bool{"support@migadu.com": true}
|
||||||
|
planner := &counting.Planner{
|
||||||
|
Lookup: counting.LookupFunc(func(name string) (*domains.Domain, error) { return db.Lookup(name) }),
|
||||||
|
Exempt: exempt, WarnPercent: 80,
|
||||||
|
}
|
||||||
|
if ncfg != nil {
|
||||||
|
d.notifier = notify.New(*ncfg, notify.Hooks{})
|
||||||
|
t.Cleanup(func() { d.notifier.Shutdown(context.Background()) })
|
||||||
|
}
|
||||||
|
srv := server.New(server.Deps{
|
||||||
|
AuthToken: testToken, Exempt: exempt, Workers: 4, QueueSize: 2000,
|
||||||
|
Counter: &counting.Counter{Planner: planner, Store: st}, Store: st,
|
||||||
|
Domains: func() *domains.DB { return db }, Notifier: d.notifier,
|
||||||
|
})
|
||||||
|
t.Cleanup(func() { srv.Drain(context.Background()) })
|
||||||
|
h := srv.Handler()
|
||||||
|
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
body, _ := io.ReadAll(r.Body)
|
||||||
|
r.Body = io.NopCloser(bytes.NewReader(body))
|
||||||
|
d.mu.Lock()
|
||||||
|
d.reqs = append(d.reqs, recorded{r.URL.Path, r.Header.Get("Authorization"), r.Header.Get("Content-Type"), body})
|
||||||
|
d.mu.Unlock()
|
||||||
|
h.ServeHTTP(w, r)
|
||||||
|
}))
|
||||||
|
t.Cleanup(ts.Close)
|
||||||
|
d.url = ts.URL
|
||||||
|
return d
|
||||||
|
}
|
||||||
|
|
||||||
|
type result struct {
|
||||||
|
code int
|
||||||
|
stdout, stderr string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r result) all() string { return r.stdout + r.stderr }
|
||||||
|
|
||||||
|
func send(t *testing.T, url string, args ...string) result {
|
||||||
|
t.Helper()
|
||||||
|
var out, errb bytes.Buffer
|
||||||
|
full := append([]string{"--url", url, "--wait", "2s"}, args...)
|
||||||
|
env := func(k string) string {
|
||||||
|
if k == config.EnvAuthToken {
|
||||||
|
return testToken
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
code := runSend(full, &out, &errb, env)
|
||||||
|
return result{code, out.String(), errb.String()}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSend_In(t *testing.T) {
|
||||||
|
d := startDaemon(t, nil)
|
||||||
|
r := send(t, d.url, "--route", "in", "--recipient", hosted, "--n", "5")
|
||||||
|
if r.code != 0 {
|
||||||
|
t.Fatalf("exit %d\n%s", r.code, r.all())
|
||||||
|
}
|
||||||
|
posts := d.posts()
|
||||||
|
if len(posts) != 5 {
|
||||||
|
t.Fatalf("sent %d requests, want 5", len(posts))
|
||||||
|
}
|
||||||
|
for _, p := range posts {
|
||||||
|
if p.Path != "/in" || p.Auth != "Bearer "+testToken || p.ContentType != "application/json" {
|
||||||
|
t.Errorf("request = %+v", p)
|
||||||
|
}
|
||||||
|
var body api.InRequest
|
||||||
|
if err := json.Unmarshal(p.Body, &body); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if body.Recipient != hosted || body.Junk || body.MailFrom != "countersend@example.com" || !strings.HasPrefix(body.TraceID, "countersend-") {
|
||||||
|
t.Errorf("body = %+v", body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if got := d.get("A", hosted, "i"); got != "5" {
|
||||||
|
t.Errorf("A/i = %q, want 5", got)
|
||||||
|
}
|
||||||
|
if !strings.Contains(r.stdout, "202") || !strings.Contains(r.stdout, "countersend-") {
|
||||||
|
t.Errorf("output:\n%s", r.stdout)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSend_Out(t *testing.T) {
|
||||||
|
d := startDaemon(t, nil)
|
||||||
|
r := send(t, d.url, "--route", "out", "--auth-user", hosted, "--recipient", "x@gmail.com", "--n", "3")
|
||||||
|
if r.code != 0 {
|
||||||
|
t.Fatalf("exit %d\n%s", r.code, r.all())
|
||||||
|
}
|
||||||
|
posts := d.posts()
|
||||||
|
if len(posts) != 3 {
|
||||||
|
t.Fatalf("sent %d requests, want 3", len(posts))
|
||||||
|
}
|
||||||
|
var body api.OutRequest
|
||||||
|
if err := json.Unmarshal(posts[0].Body, &body); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if posts[0].Path != "/out" || body.AuthUser != hosted || body.MailFrom != hosted || body.Recipient != "x@gmail.com" {
|
||||||
|
t.Errorf("path %s body %+v", posts[0].Path, body)
|
||||||
|
}
|
||||||
|
if got := d.get("A", hosted, "o"); got != "3" {
|
||||||
|
t.Errorf("A/o = %q, want 3", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSend_ConcurrencySendsExactlyN(t *testing.T) {
|
||||||
|
d := startDaemon(t, nil)
|
||||||
|
r := send(t, d.url, "--route", "in", "--recipient", hosted, "--n", "30", "--concurrency", "8")
|
||||||
|
if r.code != 0 {
|
||||||
|
t.Fatalf("exit %d\n%s", r.code, r.all())
|
||||||
|
}
|
||||||
|
posts := d.posts()
|
||||||
|
if len(posts) != 30 {
|
||||||
|
t.Fatalf("sent %d requests, want 30", len(posts))
|
||||||
|
}
|
||||||
|
seen := map[string]bool{}
|
||||||
|
for _, p := range posts {
|
||||||
|
var body api.InRequest
|
||||||
|
json.Unmarshal(p.Body, &body)
|
||||||
|
if seen[body.TraceID] {
|
||||||
|
t.Errorf("duplicate trace id %s", body.TraceID)
|
||||||
|
}
|
||||||
|
seen[body.TraceID] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSend_UsageErrors(t *testing.T) {
|
||||||
|
d := startDaemon(t, nil)
|
||||||
|
cases := map[string][]string{
|
||||||
|
"no route": {"--recipient", hosted},
|
||||||
|
"unknown route": {"--route", "sideways", "--recipient", hosted},
|
||||||
|
"no recipient": {"--route", "in"},
|
||||||
|
"out without auth": {"--route", "out", "--recipient", hosted},
|
||||||
|
"n zero": {"--route", "in", "--recipient", hosted, "--n", "0"},
|
||||||
|
"concurrency zero": {"--route", "in", "--recipient", hosted, "--concurrency", "0"},
|
||||||
|
"auth user on in": {"--route", "in", "--recipient", hosted, "--auth-user", hosted},
|
||||||
|
"junk on out": {"--route", "out", "--auth-user", hosted, "--recipient", hosted, "--junk"},
|
||||||
|
}
|
||||||
|
for name, args := range cases {
|
||||||
|
if r := send(t, d.url, args...); r.code != 2 {
|
||||||
|
t.Errorf("%s: exit %d, want 2\n%s", name, r.code, r.all())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if n := len(d.posts()); n != 0 {
|
||||||
|
t.Errorf("usage errors sent %d requests", n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSend_NoTokenIsAUsageError(t *testing.T) {
|
||||||
|
var out, errb bytes.Buffer
|
||||||
|
code := runSend([]string{"--url", "http://127.0.0.1:1", "--route", "in", "--recipient", hosted}, &out, &errb, func(string) string { return "" })
|
||||||
|
if code != 2 || !strings.Contains(errb.String(), "token") {
|
||||||
|
t.Errorf("exit %d, stderr %s", code, errb.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A/o=20 at 80% warns on reaching 16.
|
||||||
|
func TestSend_GuardJustBelowThresholdSends(t *testing.T) {
|
||||||
|
d := startDaemon(t, nil)
|
||||||
|
d.set(t, "A", hosted, "o", 10)
|
||||||
|
r := send(t, d.url, "--route", "out", "--auth-user", hosted, "--recipient", "x@gmail.com", "--n", "5")
|
||||||
|
if r.code != 0 || len(d.posts()) != 5 {
|
||||||
|
t.Errorf("exit %d, %d requests\n%s", r.code, len(d.posts()), r.all())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSend_GuardAtThresholdSendsNothing(t *testing.T) {
|
||||||
|
d := startDaemon(t, nil)
|
||||||
|
d.set(t, "A", hosted, "o", 11)
|
||||||
|
r := send(t, d.url, "--route", "out", "--auth-user", hosted, "--recipient", "x@gmail.com", "--n", "5")
|
||||||
|
if r.code != 1 || len(d.posts()) != 0 {
|
||||||
|
t.Fatalf("exit %d, %d requests\n%s", r.code, len(d.posts()), r.all())
|
||||||
|
}
|
||||||
|
if !strings.Contains(r.all(), "--allow-notify") || !strings.Contains(r.all(), hosted) {
|
||||||
|
t.Errorf("refusal does not explain itself:\n%s", r.all())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSend_AllowNotifyPassesTheGuard(t *testing.T) {
|
||||||
|
d := startDaemon(t, nil)
|
||||||
|
d.set(t, "A", hosted, "o", 11)
|
||||||
|
r := send(t, d.url, "--route", "out", "--auth-user", hosted, "--recipient", "x@gmail.com", "--n", "5", "--allow-notify")
|
||||||
|
if r.code != 0 || len(d.posts()) != 5 {
|
||||||
|
t.Errorf("exit %d, %d requests\n%s", r.code, len(d.posts()), r.all())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A counter already past both thresholds cannot notify again.
|
||||||
|
func TestSend_GuardIgnoresCountersAlreadyPast(t *testing.T) {
|
||||||
|
d := startDaemon(t, nil)
|
||||||
|
for _, lv := range [][2]string{{"A", hosted}, {"D", "yagolivas.com"}, {"O", "1049"}} {
|
||||||
|
d.set(t, lv[0], lv[1], "o", 25)
|
||||||
|
}
|
||||||
|
r := send(t, d.url, "--route", "out", "--auth-user", hosted, "--recipient", "x@gmail.com", "--n", "2")
|
||||||
|
if r.code != 0 || len(d.posts()) != 2 {
|
||||||
|
t.Errorf("exit %d, %d requests\n%s", r.code, len(d.posts()), r.all())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeConfig(t *testing.T, body string) string {
|
||||||
|
t.Helper()
|
||||||
|
path := filepath.Join(t.TempDir(), "config.toml")
|
||||||
|
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return path
|
||||||
|
}
|
||||||
|
|
||||||
|
// With warnings off only the limit itself counts.
|
||||||
|
func TestSend_GuardUsesWarnPercentFromConfig(t *testing.T) {
|
||||||
|
d := startDaemon(t, nil)
|
||||||
|
cfg := writeConfig(t, "[notify]\nwarn_percent = 0\n")
|
||||||
|
d.set(t, "A", hosted, "o", 11)
|
||||||
|
r := send(t, d.url, "--config", cfg, "--route", "out", "--auth-user", hosted, "--recipient", "x@gmail.com", "--n", "5")
|
||||||
|
if r.code != 0 {
|
||||||
|
t.Fatalf("below the limit with warnings off: exit %d\n%s", r.code, r.all())
|
||||||
|
}
|
||||||
|
r = send(t, d.url, "--config", cfg, "--route", "out", "--auth-user", hosted, "--recipient", "x@gmail.com", "--n", "4")
|
||||||
|
if r.code != 1 {
|
||||||
|
t.Errorf("reaching the limit: exit %d\n%s", r.code, r.all())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSend_GuardNamesNotifyHosts(t *testing.T) {
|
||||||
|
d := startDaemon(t, nil)
|
||||||
|
cfg := writeConfig(t, "[notify]\norg_url = \"https://user:pw@admin.example.net/api/limits?x=1\"\n")
|
||||||
|
d.set(t, "A", hosted, "o", 19)
|
||||||
|
r := send(t, d.url, "--config", cfg, "--route", "out", "--auth-user", hosted, "--recipient", "x@gmail.com")
|
||||||
|
if r.code != 1 || !strings.Contains(r.all(), "admin.example.net") {
|
||||||
|
t.Errorf("exit %d\n%s", r.code, r.all())
|
||||||
|
}
|
||||||
|
if strings.Contains(r.all(), "user:pw") {
|
||||||
|
t.Errorf("URL credentials printed:\n%s", r.all())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// fakeDaemon answers POSTs with postStatus and /counters with a fixed body.
|
||||||
|
func fakeDaemon(t *testing.T, postStatus, countersStatus int, posts *int) string {
|
||||||
|
t.Helper()
|
||||||
|
var mu sync.Mutex
|
||||||
|
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method == http.MethodPost {
|
||||||
|
mu.Lock()
|
||||||
|
*posts++
|
||||||
|
mu.Unlock()
|
||||||
|
w.WriteHeader(postStatus)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.WriteHeader(countersStatus)
|
||||||
|
json.NewEncoder(w).Encode(api.CountersResponse{Query: hosted, Mode: "address", Managed: true,
|
||||||
|
Levels: []api.CountersLevel{{Level: "A", ID: hosted, In: 1}}})
|
||||||
|
}))
|
||||||
|
t.Cleanup(ts.Close)
|
||||||
|
return ts.URL
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSend_UnreadableCountersRefuses(t *testing.T) {
|
||||||
|
var posts int
|
||||||
|
url := fakeDaemon(t, 202, 500, &posts)
|
||||||
|
r := send(t, url, "--route", "in", "--recipient", hosted)
|
||||||
|
if r.code != 1 || posts != 0 {
|
||||||
|
t.Errorf("exit %d, %d requests\n%s", r.code, posts, r.all())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// All 202 but no way to confirm counting is not a pass.
|
||||||
|
func TestSend_UnreadableCountersWithAllowNotifyStillFails(t *testing.T) {
|
||||||
|
var posts int
|
||||||
|
url := fakeDaemon(t, 202, 500, &posts)
|
||||||
|
r := send(t, url, "--route", "in", "--recipient", hosted, "--allow-notify")
|
||||||
|
if r.code != 1 || posts != 1 {
|
||||||
|
t.Errorf("exit %d, %d requests\n%s", r.code, posts, r.all())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSend_WrongTokenShowsInTally(t *testing.T) {
|
||||||
|
d := startDaemon(t, nil)
|
||||||
|
var out, errb bytes.Buffer
|
||||||
|
code := runSend([]string{"--url", d.url, "--wait", "100ms", "--route", "in", "--recipient", hosted, "--allow-notify"}, &out, &errb,
|
||||||
|
func(k string) string {
|
||||||
|
if k == config.EnvAuthToken {
|
||||||
|
return "wrong-token-value"
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
})
|
||||||
|
if code != 1 || !strings.Contains(out.String(), "401") {
|
||||||
|
t.Errorf("exit %d\n%s%s", code, out.String(), errb.String())
|
||||||
|
}
|
||||||
|
if strings.Contains(out.String()+errb.String(), "wrong-token-value") {
|
||||||
|
t.Error("token printed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSend_ServerErrorShowsInTally(t *testing.T) {
|
||||||
|
var posts int
|
||||||
|
url := fakeDaemon(t, 503, 200, &posts)
|
||||||
|
r := send(t, url, "--route", "in", "--recipient", hosted, "--n", "2")
|
||||||
|
if r.code != 1 || posts != 2 || !strings.Contains(r.stdout, "503") {
|
||||||
|
t.Errorf("exit %d, %d requests\n%s", r.code, posts, r.all())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSend_CountersThatNeverMoveFail(t *testing.T) {
|
||||||
|
var posts int
|
||||||
|
url := fakeDaemon(t, 202, 200, &posts)
|
||||||
|
var out, errb bytes.Buffer
|
||||||
|
code := runSend([]string{"--url", url, "--wait", "100ms", "--route", "in", "--recipient", hosted}, &out, &errb,
|
||||||
|
func(k string) string {
|
||||||
|
if k == config.EnvAuthToken {
|
||||||
|
return testToken
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
})
|
||||||
|
if code != 1 || !strings.Contains(out.String()+errb.String(), "did not") {
|
||||||
|
t.Errorf("exit %d\n%s%s", code, out.String(), errb.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSend_NotHostedExpectsNoChange(t *testing.T) {
|
||||||
|
d := startDaemon(t, nil)
|
||||||
|
r := send(t, d.url, "--route", "in", "--recipient", "x@countersend.invalid")
|
||||||
|
if r.code != 0 || !strings.Contains(r.stdout, "not hosted") {
|
||||||
|
t.Errorf("exit %d\n%s", r.code, r.all())
|
||||||
|
}
|
||||||
|
if keys := d.redis.Keys(); len(keys) != 0 {
|
||||||
|
t.Errorf("keys written: %v", keys)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSend_ExemptExpectsNoChange(t *testing.T) {
|
||||||
|
d := startDaemon(t, nil)
|
||||||
|
r := send(t, d.url, "--route", "in", "--recipient", "support@migadu.com")
|
||||||
|
if r.code != 0 || !strings.Contains(r.stdout, "exempt") {
|
||||||
|
t.Errorf("exit %d\n%s", r.code, r.all())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// An exempt envelope sender cancels the whole request, so the hosted recipient
|
||||||
|
// is not expected to move either.
|
||||||
|
func TestSend_ExemptMailFromCancelsTheRequest(t *testing.T) {
|
||||||
|
d := startDaemon(t, nil)
|
||||||
|
r := send(t, d.url, "--route", "in", "--recipient", hosted, "--mail-from", "support@migadu.com")
|
||||||
|
if r.code != 0 || !strings.Contains(r.stdout, "exempt") {
|
||||||
|
t.Errorf("exit %d\n%s", r.code, r.all())
|
||||||
|
}
|
||||||
|
if got := d.get("A", hosted, "i"); got != "" {
|
||||||
|
t.Errorf("A/i = %q, want untouched", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSend_JunkIsReportedNotJudged(t *testing.T) {
|
||||||
|
d := startDaemon(t, nil)
|
||||||
|
r := send(t, d.url, "--route", "in", "--recipient", hosted, "--junk")
|
||||||
|
if r.code != 0 {
|
||||||
|
t.Errorf("exit %d\n%s", r.code, r.all())
|
||||||
|
}
|
||||||
|
var body api.InRequest
|
||||||
|
json.Unmarshal(d.posts()[0].Body, &body)
|
||||||
|
if !body.Junk {
|
||||||
|
t.Errorf("body = %+v", body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The counters of a token login live under the base address and the suffix,
|
||||||
|
// which may be a credential, is never printed.
|
||||||
|
func TestSend_TokenLogin(t *testing.T) {
|
||||||
|
d := startDaemon(t, nil)
|
||||||
|
r := send(t, d.url, "--route", "out", "--auth-user", hosted+"@SUFFIXSECRET", "--recipient", "x@gmail.com", "--n", "2")
|
||||||
|
if r.code != 0 {
|
||||||
|
t.Fatalf("exit %d\n%s", r.code, r.all())
|
||||||
|
}
|
||||||
|
if got := d.get("A", hosted, "o"); got != "2" {
|
||||||
|
t.Errorf("A/o = %q, want 2", got)
|
||||||
|
}
|
||||||
|
if strings.Contains(r.all(), "SUFFIXSECRET") {
|
||||||
|
t.Errorf("suffix printed:\n%s", r.all())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSend_TokenNeverPrinted(t *testing.T) {
|
||||||
|
d := startDaemon(t, nil)
|
||||||
|
r := send(t, d.url, "--route", "in", "--recipient", hosted)
|
||||||
|
if strings.Contains(r.all(), testToken) {
|
||||||
|
t.Errorf("token printed:\n%s", r.all())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSend_BadURLIsAUsageError(t *testing.T) {
|
||||||
|
if r := send(t, "not a url", "--route", "in", "--recipient", hosted); r.code != 2 {
|
||||||
|
t.Errorf("exit %d\n%s", r.code, r.all())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSend_UnreachableDaemonFails(t *testing.T) {
|
||||||
|
r := send(t, "http://127.0.0.1:1", "--route", "in", "--recipient", hosted, "--allow-notify")
|
||||||
|
if r.code != 1 || !strings.Contains(r.stdout, "connection errors") {
|
||||||
|
t.Errorf("exit %d\n%s", r.code, fmt.Sprint(r.all()))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,234 @@
|
|||||||
|
# Testing migadu_counters with countersend
|
||||||
|
|
||||||
|
`countersend` stands in for the two services next to the daemon, so you can test the daemon on its own server:
|
||||||
|
|
||||||
|
```
|
||||||
|
countersend send ──POST /in, /out──▶ migadu_counters ──GET notify URLs──▶ countersend receive ──▶ one file per notification
|
||||||
|
(plays mailqueuer) (daemon under test) (plays the web app)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Read this first
|
||||||
|
|
||||||
|
- **While the notify URLs point at `receive`, every notification goes to a file, including real customers' notifications.**
|
||||||
|
Nobody is emailed, and the daemon records those notifications as sent, so they are not sent again that day. This is harmless while no real
|
||||||
|
traffic reaches the daemon. Once mailqueuer is live, test on a separate instance instead.
|
||||||
|
- **Test requests are real counts.** They go to the Redis the daemon is configured for and stay on today's counters
|
||||||
|
(TTL 31 days), on the mailbox row and also on its domain and organisation rows. The API has no decrement.
|
||||||
|
- **Use a test mailbox on a domain with no customer mail**, so that the domain and organisation rows belong to you too.
|
||||||
|
- **Step 12 is not optional:** put the real notify URLs back when you finish.
|
||||||
|
|
||||||
|
If `send` would make a counter reach a warning threshold or a limit, it refuses and sends nothing unless you add `--allow-notify`.
|
||||||
|
It also prints where those notifications would go. **Check that line says `receive`'s address before adding the flag.** With the real URLs, the web app
|
||||||
|
emails the customer and posts to Telegram.
|
||||||
|
|
||||||
|
The commands below use `/tmp/countersend`, the default config path, and `test@yourdomain`. Replace them with your own.
|
||||||
|
Run them as a user that can read the daemon's config, because `send` takes the address and token from it.
|
||||||
|
|
||||||
|
## 1. Build and copy
|
||||||
|
|
||||||
|
On your machine:
|
||||||
|
|
||||||
|
```
|
||||||
|
make freebsd
|
||||||
|
scp bin/countersend-freebsd-amd64 server:/tmp/countersend
|
||||||
|
```
|
||||||
|
|
||||||
|
## 2. Start the receiver and point the daemon at it
|
||||||
|
|
||||||
|
In a second terminal on the server (it runs until Ctrl-C, which prints the totals):
|
||||||
|
|
||||||
|
```
|
||||||
|
/tmp/countersend receive --listen 127.0.0.1:8099 --dir /var/tmp/countersend/notifications
|
||||||
|
```
|
||||||
|
|
||||||
|
`--dir` is where the files go, and it is created if missing. If the daemon is on another host, use a `--listen` address it can reach.
|
||||||
|
|
||||||
|
Keep a copy of the daemon's config. Then replace the URLs in its `[notify]` section with these, leaving `user`, `password` and `timeout_seconds` as they are:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[notify]
|
||||||
|
org_url = "http://127.0.0.1:8099/api/limits?level=$LEVEL&id=$ID&flow=$FLOW&period=$PERIOD&by=$ADDRESS&count=$COUNT&limit=$LIMIT"
|
||||||
|
address_url = "http://127.0.0.1:8099/api/limits?level=$LEVEL&id=$ID&flow=$FLOW&period=$PERIOD&by=$ADDRESS&count=$COUNT&limit=$LIMIT"
|
||||||
|
domain_url = "http://127.0.0.1:8099/api/limits?level=$LEVEL&id=$ID&flow=$FLOW&period=$PERIOD&by=$ADDRESS&count=$COUNT&limit=$LIMIT"
|
||||||
|
warn_percent = 80
|
||||||
|
warn_org_url = "http://127.0.0.1:8099/api/limits/warning?level=$LEVEL&id=$ID&flow=$FLOW&period=$PERIOD&by=$ADDRESS&count=$COUNT&limit=$LIMIT&percent=$PERCENT"
|
||||||
|
warn_address_url = "http://127.0.0.1:8099/api/limits/warning?level=$LEVEL&id=$ID&flow=$FLOW&period=$PERIOD&by=$ADDRESS&count=$COUNT&limit=$LIMIT&percent=$PERCENT"
|
||||||
|
warn_domain_url = "http://127.0.0.1:8099/api/limits/warning?level=$LEVEL&id=$ID&flow=$FLOW&period=$PERIOD&by=$ADDRESS&count=$COUNT&limit=$LIMIT&percent=$PERCENT"
|
||||||
|
```
|
||||||
|
|
||||||
|
Restart the daemon. SIGHUP (`reload`) only reloads the CDB and reopens the logs, so it does not pick up new URLs.
|
||||||
|
|
||||||
|
```
|
||||||
|
service migadu_counters restart
|
||||||
|
```
|
||||||
|
|
||||||
|
## 3. Read the test mailbox's limits
|
||||||
|
|
||||||
|
```
|
||||||
|
counterctl --address test@yourdomain
|
||||||
|
```
|
||||||
|
|
||||||
|
```
|
||||||
|
LEVEL ID IN LIMIT OUT LIMIT
|
||||||
|
A test@yourdomain 0 200 0 20
|
||||||
|
D yourdomain 0 200 0 20
|
||||||
|
O 1049 0 200 0 20
|
||||||
|
```
|
||||||
|
|
||||||
|
The examples below assume this mailbox: outgoing limit 20, nothing sent today. The warning threshold is 80% of the limit, rounded up, so 16 here.
|
||||||
|
Limits of 1 and 2 have no warning. Adjust `--n` for your own limits.
|
||||||
|
|
||||||
|
## 4. Counting works
|
||||||
|
|
||||||
|
```
|
||||||
|
/tmp/countersend send --route in --recipient test@yourdomain --n 10
|
||||||
|
/tmp/countersend send --route out --auth-user test@yourdomain --recipient someone@gmail.com --n 2
|
||||||
|
```
|
||||||
|
|
||||||
|
Each run ends in `OK`, exit code 0, and shows what moved:
|
||||||
|
|
||||||
|
```
|
||||||
|
POST http://localhost:5555/in n=10 concurrency=1 trace ids: countersend-3d66700b-*
|
||||||
|
status: 202=10
|
||||||
|
timing: 1.426ms total, 7011 req/s, p50 80µs, p99 435µs
|
||||||
|
recipient test@yourdomain, incoming
|
||||||
|
LEVEL ID BEFORE AFTER CHANGE LIMIT
|
||||||
|
A test@yourdomain 0 10 +10 200
|
||||||
|
D yourdomain 0 10 +10 200
|
||||||
|
O 1049 0 10 +10 200
|
||||||
|
OK
|
||||||
|
```
|
||||||
|
|
||||||
|
`--url http://HOST:5555` sends to another daemon. To check independently, `counterctl --address test@yourdomain` shows the same numbers, and this shows the whole run in the log:
|
||||||
|
|
||||||
|
```
|
||||||
|
grep countersend-3d66700b /var/log/migadu_counters/counting.log
|
||||||
|
```
|
||||||
|
|
||||||
|
`send` exits 1 and prints `FAIL` if any request is not answered `202` or if the mailbox counter does not rise in time.
|
||||||
|
`--wait 15s` allows longer for a slow replica.
|
||||||
|
|
||||||
|
## 5. What must not count
|
||||||
|
|
||||||
|
| Command | Expected |
|
||||||
|
|---|---|
|
||||||
|
| `/tmp/countersend send --route in --recipient someone@countersend.invalid` | `domain not hosted: nothing should move`, `OK` |
|
||||||
|
| `/tmp/countersend send --route in --recipient support@migadu.com` | `exempt address in this request: nothing should move`, `OK` |
|
||||||
|
| `/tmp/countersend send --route in --recipient test@yourdomain --junk` | Changes stay `+0` when `count_junk = false`. `send` does not judge this one. |
|
||||||
|
| `/tmp/countersend send --route in --recipient not-an-address` | `status: 400=1`, `FAIL`, exit 1. That is the daemon correctly refusing it. |
|
||||||
|
|
||||||
|
## 6. The 80% warning and the breach are each sent once
|
||||||
|
|
||||||
|
Files appear within a moment of the run. Mailbox outgoing is at 2 after step 4.
|
||||||
|
|
||||||
|
| Command | Counter | New files |
|
||||||
|
|---|---|---|
|
||||||
|
| `send --route out --auth-user test@yourdomain --recipient someone@gmail.com --n 13` | 15 | None |
|
||||||
|
| Same with `--n 1` | | None: refused, nothing sent, exit 1. This is the guard working. |
|
||||||
|
| Same with `--n 1 --allow-notify` | 16 | One `warning` per level |
|
||||||
|
| Same with `--n 3` | 19 | None |
|
||||||
|
| Same with `--n 1 --allow-notify` | 20 | One `limit` per level |
|
||||||
|
| Same with `--n 5` | 25 | None: past the limit nothing is sent again |
|
||||||
|
|
||||||
|
```
|
||||||
|
ls /var/tmp/countersend/notifications
|
||||||
|
```
|
||||||
|
|
||||||
|
```
|
||||||
|
20261110T074614.022873Z-000001-warning-A-o-test@yourdomain.json
|
||||||
|
20261110T074614.022878Z-000003-warning-O-o-1049.json
|
||||||
|
20261110T074614.022920Z-000002-warning-D-o-yourdomain.json
|
||||||
|
20261110T074614.573333Z-000004-limit-A-o-test@yourdomain.json
|
||||||
|
20261110T074614.573359Z-000005-limit-D-o-yourdomain.json
|
||||||
|
20261110T074614.573470Z-000006-limit-O-o-1049.json
|
||||||
|
```
|
||||||
|
|
||||||
|
The name is `<UTC time>-<sequence>-<limit|warning>-<level>-<flow>-<id>.json`, and each notification gets its own file, so **two files with the same kind, level, flow and id in one day
|
||||||
|
are a repeat**. Open one to check the values. `count` must be 16 on a warning and 20 on a limit here:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"received_at": "2026-11-10T07:46:14.022873Z",
|
||||||
|
"kind": "warning",
|
||||||
|
"level": "A",
|
||||||
|
"id": "test@yourdomain",
|
||||||
|
"flow": "o",
|
||||||
|
"period": "d",
|
||||||
|
"by": "test@yourdomain",
|
||||||
|
"count": "16",
|
||||||
|
"limit": "20",
|
||||||
|
"percent": "80",
|
||||||
|
"path": "/api/limits/warning",
|
||||||
|
"raw_query": "level=A&id=test%40yourdomain&flow=o&...",
|
||||||
|
"remote_addr": "127.0.0.1:55395",
|
||||||
|
"auth_user": "weblogin"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`auth_user` is the login the daemon sent. The password is never stored. Your levels differ if the domain or organisation has other limits or other mail today.
|
||||||
|
|
||||||
|
## 7. Concurrent requests still notify once
|
||||||
|
|
||||||
|
Use the incoming side, with enough requests to pass the limit (the current count of 10 and limit of 200 need at least 190):
|
||||||
|
|
||||||
|
```
|
||||||
|
/tmp/countersend send --route in --recipient test@yourdomain --n 220 --concurrency 16 --allow-notify
|
||||||
|
ls /var/tmp/countersend/notifications | grep -- '-i-'
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: the counters rise by exactly 220, and there is one `warning` and one `limit` file per level.
|
||||||
|
|
||||||
|
## 8. No repeat after a restart
|
||||||
|
|
||||||
|
```
|
||||||
|
service migadu_counters restart
|
||||||
|
/tmp/countersend send --route out --auth-user test@yourdomain --recipient someone@gmail.com --n 3
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: the counter continues from where it was and there are no new files.
|
||||||
|
|
||||||
|
## 9. When the web app is unreachable
|
||||||
|
|
||||||
|
Stop `receive` with Ctrl-C, then use a second test mailbox and take it across a limit:
|
||||||
|
|
||||||
|
```
|
||||||
|
/tmp/countersend send --route out --auth-user test2@yourdomain --recipient someone@gmail.com --n 20 --allow-notify
|
||||||
|
```
|
||||||
|
|
||||||
|
The daemon tries 5 times over about 15 s and then gives up:
|
||||||
|
|
||||||
|
```
|
||||||
|
grep 'failed limit' /var/log/migadu_counters/counting.log
|
||||||
|
fetch -qo - http://127.0.0.1:9095/metrics | grep 'notifications_total.*failed'
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: a `failed limit exceeded notification ... after 5 attempts` line, and the metric at 1 or more. That notification is not sent later, since delivery is at most once by design.
|
||||||
|
If `admin_addr` is not on `127.0.0.1:9095`, use yours. Start `receive` again afterwards.
|
||||||
|
|
||||||
|
## 10. Load
|
||||||
|
|
||||||
|
```
|
||||||
|
/tmp/countersend send --route in --recipient load@countersend.invalid --n 5000 --concurrency 32
|
||||||
|
fetch -qo - http://127.0.0.1:9095/metrics | grep -E '^migadu_counters_(queue_depth|dropped_total)'
|
||||||
|
```
|
||||||
|
|
||||||
|
A `.invalid` recipient tests the HTTP side and the queue without writing to Redis. To load Redis as well, use the test mailbox as `--recipient`, which adds that many real counts and may need `--allow-notify`.
|
||||||
|
|
||||||
|
Expected: all `202`, `queue_depth` back to 0, and `dropped_total` absent or unchanged. A `503` in the tally means the queue was full.
|
||||||
|
|
||||||
|
## 11. Repeating a test on the same day
|
||||||
|
|
||||||
|
A counter already past a limit will not cross it again, so either use a new test mailbox or clear this one. On the Redis **master**, with the day in UTC (`date -u +%F`):
|
||||||
|
|
||||||
|
```
|
||||||
|
redis-cli -h MASTER -a PASSWORD DEL cnt/A/test@yourdomain/d/2026-11-10/o ntf/A/test@yourdomain/d/2026-11-10/o/warn ntf/A/test@yourdomain/d/2026-11-10/o/limit
|
||||||
|
```
|
||||||
|
|
||||||
|
Use `/i` in place of `/o` for incoming. Only delete mailbox (`A`) keys unless the domain and organisation are yours alone, because the `D` and `O` keys hold every mailbox's count.
|
||||||
|
|
||||||
|
## 12. When you finish
|
||||||
|
|
||||||
|
1. Put the original `[notify]` section back and run `service migadu_counters restart`. Until the web app has `GET /api/limits/warning` deployed, leave `warn_*_url` empty.
|
||||||
|
2. Read the config once more: no notify URL may still contain `127.0.0.1:8099`.
|
||||||
|
3. Stop `receive`, and delete `/var/tmp/countersend/notifications` when you are done reading it.
|
||||||
|
4. What stays behind: the test counts (31 days) and the `ntf/` markers (48 hours). Today's real limits for the test domain are reached sooner because of them.
|
||||||
Reference in New Issue
Block a user