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