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())) } }