Files
selfpost/internal/store/notify_test.go
T
mixandClaude Opus 5.5 f09b60aaa2
test / test (push) Canceled after 0s
panel-notifications: findings of the technical and security reviews
Neither review (read-only agents, Opus and Fable, over 972a9f8..400aa76) has
a Critical finding. Both found the same serious one, and more:

- The notification about refused mail was built on what a rejected row says
  of itself. Its domain is the one in MAIL FROM, which the client typed and
  Postfix has not yet held against the login when the milter refuses: an
  application over its limit could have had the panel write a message per
  made-up domain, to another tenant's users among others. And the same
  status is written when an application is refused for its client address,
  which is no limit. Refusals are now counted by the domain the login is
  registered under, only for logins that exist and only while a limit is set
  on the login or its domain; one subject per sending domain. They are read
  through a partial index of their own (migration 0005): the query walked
  the whole send log every minute.
- Account and user e-mails were checked with the DMARC report validator,
  which refuses Gmail and the like - the owner's own kind of address. A new
  validate.AccountEmail accepts them and refuses a local part beginning "-".
- "Said" now means sent: what arises while nobody can be told, or while
  Postfix does not take the message, is told at a later check. Its ending
  with nobody left to tell is simply over.
- Two DNS checks must be 45 minutes apart as well as two: the last check
  before a restart and the first after it were minutes apart.
- The notifier's own mail waiting in the queue, and its bounce coming back
  to postmaster@ this server, are not the queue's subject. A listing cut at
  its size limit or with a line too long to read is no listing; postqueue -j
  gets 30 seconds.
- The tables must name the selector the panel shows, not only have the line.
- An a/mx lookup that did not answer inside the SPF check made the record
  "not authorising"; it is "cannot tell" now, for the pages too.
- A ceiling of 60 messages an hour; a pass stops between domains when the
  process is asked to stop; sendmail gets a WaitDelay; days are rounded as a
  person counts; a failed read of the switch shows it on, not off.

Recorded as accepted in security.md, with a roadmap candidate
(from-header-binding): an application can have a message signed as the
server's own name - or, as always, as another registered domain - by writing
it into the From: header, which nothing holds against the login.

Left as found: a recipient whose copy failed while another's went out is not
tried again; a certificate that lives under 14 days is reported at each
renewal.

On the test server, for this tree: go vet clean, go test ./... 23 packages
ok, make e2e ok (326 s).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 17:00:01 +03:00

223 lines
8.0 KiB
Go

package store
import (
"strings"
"testing"
"time"
)
// The instance switch is on until someone turns it off: a database that never
// saw the setting sends notifications.
func TestNotificationsEnabledByDefault(t *testing.T) {
s := openTestStore(t)
if on, err := s.NotificationsEnabled(); err != nil || !on {
t.Fatalf("a fresh database: enabled = %v, %v; want on", on, err)
}
if err := s.SetNotificationsEnabled(false); err != nil {
t.Fatal(err)
}
if on, err := s.NotificationsEnabled(); err != nil || on {
t.Errorf("after turning off: enabled = %v, %v", on, err)
}
if err := s.SetNotificationsEnabled(true); err != nil {
t.Fatal(err)
}
if on, err := s.NotificationsEnabled(); err != nil || !on {
t.Errorf("after turning on again: enabled = %v, %v", on, err)
}
}
// Who is written to: every global user about everything, a domain user about
// the domains on their list or all of them - and nobody without an e-mail or
// with their own switch off.
func TestNotifyRecipients(t *testing.T) {
s := openTestStore(t)
mine, err := s.AddDomain("mine.example.com", "sp")
if err != nil {
t.Fatal(err)
}
other, err := s.AddDomain("other.example.com", "sp")
if err != nil {
t.Fatal(err)
}
user := func(name string, role Role, reach Reach, email string, notify bool) {
t.Helper()
id, err := s.CreateUser(name, "hash", role, reach)
if err != nil {
t.Fatalf("create %s: %v", name, err)
}
if err := s.UpdateUser(id, name, "hash", email); err != nil {
t.Fatalf("update %s: %v", name, err)
}
if u, err := s.GetUser(id); err != nil || !u.Notify {
t.Fatalf("%s: a new user's switch is %v, %v; want on", name, u.Notify, err)
}
if !notify {
if err := s.SetUserNotify(id, false); err != nil {
t.Fatalf("switch off %s: %v", name, err)
}
}
}
user("root", RoleGlobal, Reach{}, "root@example.org", true)
user("root2", RoleGlobal, Reach{}, "root@example.org", true) // the same mailbox
user("quiet", RoleGlobal, Reach{}, "quiet@example.org", false)
user("nomail", RoleGlobal, Reach{}, "", true)
user("mine", RoleDomain, Reach{DomainIDs: []int64{mine.ID}}, "mine@example.org", true)
user("theirs", RoleDomain, Reach{DomainIDs: []int64{other.ID}}, "theirs@example.org", true)
user("every", RoleDomain, Reach{AllDomains: true}, "every@example.org", true)
user("mineoff", RoleDomain, Reach{DomainIDs: []int64{mine.ID}}, "mineoff@example.org", false)
for _, c := range []struct{ domain, want string }{
{"", "root@example.org"},
{"mine.example.com", "every@example.org mine@example.org root@example.org"},
{"other.example.com", "every@example.org root@example.org theirs@example.org"},
{"gone.example.com", "every@example.org root@example.org"},
} {
got, err := s.NotifyRecipients(c.domain)
if err != nil {
t.Fatalf("recipients for %q: %v", c.domain, err)
}
if strings.Join(got, " ") != c.want {
t.Errorf("recipients for %q = %q, want %q", c.domain, strings.Join(got, " "), c.want)
}
}
if err := s.SetUserNotify(99999, true); err != ErrUserNotFound {
t.Errorf("switch of a user that does not exist: %v", err)
}
}
// What has been said is remembered by key, replaced whole, and forgotten.
func TestNotifyStateRoundTrip(t *testing.T) {
s := openTestStore(t)
if _, ok, err := s.GetNotifyState("dns:example.com"); err != nil || ok {
t.Fatalf("no state yet: ok = %v, %v", ok, err)
}
since := time.Date(2026, 10, 12, 9, 0, 0, 0, time.UTC)
st := NotifyState{Key: "dns:example.com", Phase: "pending", Count: 1, Since: since}
if err := s.SetNotifyState(st); err != nil {
t.Fatal(err)
}
got, ok, err := s.GetNotifyState("dns:example.com")
if err != nil || !ok || got.Phase != "pending" || got.Count != 1 || !got.Since.Equal(since) || !got.SentAt.IsZero() {
t.Fatalf("state = %+v, %v, %v", got, ok, err)
}
st.Phase, st.Count, st.Mark, st.SentAt = "open", 0, "x", since.Add(time.Hour)
if err := s.SetNotifyState(st); err != nil {
t.Fatal(err)
}
got, _, _ = s.GetNotifyState("dns:example.com")
if got.Phase != "open" || got.Mark != "x" || !got.SentAt.Equal(since.Add(time.Hour)) {
t.Errorf("replaced state = %+v", got)
}
for _, key := range []string{"dns:other.example.com", "queue", "limit:example.com:app"} {
if err := s.SetNotifyState(NotifyState{Key: key, Phase: "open", Since: since}); err != nil {
t.Fatal(err)
}
}
keys, err := s.ListNotifyStateKeys("dns:")
if err != nil || strings.Join(keys, " ") != "dns:example.com dns:other.example.com" {
t.Errorf("dns keys = %v, %v", keys, err)
}
if err := s.DeleteNotifyState("dns:example.com"); err != nil {
t.Fatal(err)
}
if _, ok, _ := s.GetNotifyState("dns:example.com"); ok {
t.Error("state still there after delete")
}
}
// Refused mail is counted per sending domain from a point in time - and only
// what was refused under a limit. The row's own domain is what the client
// typed in MAIL FROM; the login's registered domain is what counts. A login
// that is nobody's is not counted, nor is one refused with no limit set (its
// client address was not on its list).
func TestLimitRefusalsSince(t *testing.T) {
s := openTestStore(t)
d, err := s.AddDomain("example.com", "sp")
if err != nil {
t.Fatal(err)
}
other, err := s.AddDomain("other.example", "sp")
if err != nil {
t.Fatal(err)
}
app := func(domainID int64, login string) int64 {
t.Helper()
a, err := s.AddApplication(domainID, login, AddressModeWildcard, nil)
if err != nil {
t.Fatalf("add %s: %v", login, err)
}
return a.ID
}
limit := func(scope string, id int64) {
t.Helper()
if err := s.SetRateLimit(RateLimit{Scope: scope, RefID: id, MaxMessages: 1, WindowSeconds: 3600}); err != nil {
t.Fatalf("set limit: %v", err)
}
}
limit(RateLimitScopeApp, app(d.ID, "app1"))
limit(RateLimitScopeApp, app(d.ID, "app2"))
app(d.ID, "nolimit") // refused for its client address
app(other.ID, "byitsdomain") // limited through its domain
limit(RateLimitScopeDomain, other.ID)
for _, e := range []SendLogEntry{
{Domain: "example.com", AppLogin: "app1", From: "a@example.com"},
{Domain: "victim.example", AppLogin: "app1", From: "a@victim.example"}, // a domain the client made up
{Domain: "other.example", AppLogin: "app2", From: "b@other.example"}, // another tenant's name
{Domain: "example.com", AppLogin: "nolimit", From: "c@example.com"},
{Domain: "example.com", AppLogin: "ghost", From: "d@example.com"},
{Domain: "other.example", AppLogin: "byitsdomain", From: "e@other.example"},
} {
if err := s.InsertRejected(e); err != nil {
t.Fatal(err)
}
}
if err := s.InsertQueued(SendLogEntry{QueueID: "ABC123", Domain: "example.com", AppLogin: "app1", To: "x@example.net"}); err != nil {
t.Fatal(err)
}
if err := s.InsertRejected(SendLogEntry{Domain: "example.com", AppLogin: "app2", From: "old@example.com"}); err != nil {
t.Fatal(err)
}
if _, err := s.db.Exec(`UPDATE send_log SET created_at = '2026-01-01T00:00:00Z' WHERE from_addr = 'old@example.com'`); err != nil {
t.Fatal(err)
}
got, err := s.LimitRefusalsSince(time.Now().UTC().Add(-time.Hour))
if err != nil {
t.Fatal(err)
}
if len(got) != 2 {
t.Fatalf("refusals = %+v, want two domains", got)
}
if g := got[0]; g.Domain != "example.com" || strings.Join(g.Apps, " ") != "app1 app2" || g.Count != 3 || g.First.IsZero() {
t.Errorf("example.com = %+v; want app1 (2, one under a made-up domain) and app2 (1, under another tenant's name)", g)
}
if g := got[1]; g.Domain != "other.example" || strings.Join(g.Apps, " ") != "byitsdomain" || g.Count != 1 {
t.Errorf("other.example = %+v", g)
}
// The question is answered from the index of the refused rows alone.
var plan []string
rows, err := s.db.Query(`EXPLAIN QUERY PLAN SELECT COUNT(*) FROM send_log l WHERE l.status = 'rejected' AND l.created_at >= '2026-10-01T00:00:00Z'`)
if err != nil {
t.Fatal(err)
}
for rows.Next() {
var id, parent, notused int
var detail string
if err := rows.Scan(&id, &parent, &notused, &detail); err != nil {
t.Fatal(err)
}
plan = append(plan, detail)
}
rows.Close()
if !strings.Contains(strings.Join(plan, "; "), "idx_send_log_rejected") {
t.Errorf("refused rows are not found through their index: %v", plan)
}
}