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
@@ -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()))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user