release: 1.9.2: Review pass: port-25 milters, DMARC validation, rate-limit fix

Review pass over `1.4.0`…`1.9.1`: port 25 no longer shares the submission milter chain, DMARC reports are validated before they are stored, and the auto rate limit is correct for a non-default level-1 window. Schema migration `0010` (index only). Upgrading is a tag bump.
Added:
  - SQLite migration `0010_send_log_app_login_index.sql` —
  - DMARC aggregate reports are accepted as **zip** as well as gzip or plain XML
  - e2e: `checkPort25ConfigCombinations` regenerates the Postfix configuration
Changed:
  - README hero line and a **Positioning** block in `docs/product.md` record the
Fixed:
  - The setup account's password is hashed at bcrypt cost `12` like every other
  - Login/setup rate limiter: protecting blocked buckets from eviction is now
  - `postqueue -p` output is bounded to 4 MiB (the timeout alone left the size of
  - [schema-migrations.md](docs/schema-migrations.md): the schema section was
  - postqueue reader is now time-bounded: `postqueue -p` runs under a 5-second
  … (11 more in CHANGELOG)
Changed:
  - [roadmap.md](docs/roadmap.md) now carries everything the 2026-08-19 code
  - Extracted `internal/configsafe` — the empty-value and forbidden-character
  - Build, deploy and migration comments no longer cite the archived
  - Dropped the `parseDomainRateLimitForm` / `parseAppRateLimitForm` pass-through
  - Extracted shared helpers: `internal/atomicfile` (atomic temp-write+rename) and
  … (7 more in CHANGELOG)
Removed:
  - Unused legacy asset `docs/assets/icon.png` (superseded by the four brand SVGs
  - Plan documents for already-shipped features: `domain-stats-auto-ratelimit`,

Full detail: CHANGELOG.md (1.9.2).
This commit is contained in:
mix
2026-09-22 15:24:53 +03:00
parent 967d3d95de
commit 7ef7f75246
179 changed files with 11558 additions and 1738 deletions
+45
View File
@@ -0,0 +1,45 @@
package atomicfile
import (
"fmt"
"os"
"path/filepath"
)
// Write writes data to path via a temp file in the same directory followed by
// a rename, so readers only ever see the complete old or new file.
func Write(path string, data []byte, perm os.FileMode) error {
dir := filepath.Dir(path)
tmp, err := os.CreateTemp(dir, ".tmp-*")
if err != nil {
return fmt.Errorf("create temp in %s: %w", dir, err)
}
tmpName := tmp.Name()
cleanup := true
defer func() {
if cleanup {
_ = os.Remove(tmpName)
}
}()
if _, err := tmp.Write(data); err != nil {
tmp.Close()
return fmt.Errorf("write temp %s: %w", tmpName, err)
}
if err := tmp.Chmod(perm); err != nil {
tmp.Close()
return fmt.Errorf("chmod temp %s: %w", tmpName, err)
}
if err := tmp.Sync(); err != nil {
tmp.Close()
return fmt.Errorf("sync temp %s: %w", tmpName, err)
}
if err := tmp.Close(); err != nil {
return fmt.Errorf("close temp %s: %w", tmpName, err)
}
if err := os.Rename(tmpName, path); err != nil {
return fmt.Errorf("rename %s -> %s: %w", tmpName, path, err)
}
cleanup = false
return nil
}
+28
View File
@@ -0,0 +1,28 @@
// Package configsafe holds the defence-in-depth check that every generated
// configuration file shares: a value about to be written into a table line must
// be non-empty and must not carry a character that could end the field, end the
// line, or otherwise change what the file means (security.md).
//
// The forbidden set stays with the caller rather than living here, because what
// breaks a line differs per format — a comma separates values in a Postfix map,
// a colon separates fields in an OpenDKIM table — and the set belongs next to
// the writer it protects, where a reviewer of that writer can see it.
package configsafe
import (
"fmt"
"strings"
)
// Token reports whether value is safe to interpolate into a config line. what
// names the field for the error message ("domain", "login", …) and forbidden
// lists the characters the format cannot carry.
func Token(what, value, forbidden string) error {
if value == "" {
return fmt.Errorf("empty %s", what)
}
if strings.ContainsAny(value, forbidden) {
return fmt.Errorf("unsafe character in %s %q", what, value)
}
return nil
}
+25
View File
@@ -0,0 +1,25 @@
package configsafe
import "testing"
// The check is the last line of defence before a value reaches a config file,
// so it must reject both halves of the problem: an empty value that would write
// a malformed line, and any character from the caller's forbidden set.
func TestToken(t *testing.T) {
if err := Token("domain", "example.com", " \t\r\n,\\"); err != nil {
t.Fatalf("clean value rejected: %v", err)
}
if err := Token("domain", "", " "); err == nil {
t.Fatal("empty value accepted")
}
for _, bad := range []string{"a b", "a\tb", "a\rb", "a\nb", "a,b", "a\\b"} {
if err := Token("domain", bad, " \t\r\n,\\"); err == nil {
t.Errorf("Token(%q) = nil, want error", bad)
}
}
// A character outside the caller's set is that format's business, not this
// function's: a colon is fatal in an OpenDKIM table and fine in a texthash.
if err := Token("domain", "a:b", " \t\r\n,\\"); err != nil {
t.Errorf("character outside the forbidden set rejected: %v", err)
}
}
+18
View File
@@ -29,3 +29,21 @@ func IsHostedOnHostname(addr, hostname string) bool {
at := strings.LastIndex(addr, "@")
return addr[at+1:] == hostname
}
// TaggedDomain returns the domain a hosted report address is tagged for
// (dmarc-reports+<domain>@<hostname> → <domain>), or "" when addr carries no
// such tag. Used to check a report's claimed domain against the address it
// actually arrived at.
func TaggedDomain(addr string) string {
addr = strings.ToLower(strings.TrimSpace(addr))
at := strings.LastIndex(addr, "@")
if at <= 0 {
return ""
}
local := addr[:at]
plus := strings.Index(local, "+")
if plus < 0 || local[:plus] != DefaultLocalPart {
return ""
}
return local[plus+1:]
}
+34 -1
View File
@@ -18,6 +18,15 @@ import (
// IngestMessage parses a raw RFC 5322 message from r and stores any DMARC
// aggregate attachment it finds.
//
// The report XML is unauthenticated input: anyone who can reach an allow-listed
// rua= address can post one, and the address form is predictable. So the domain
// the report claims is checked twice before anything is stored — it must be a
// domain this relay actually sends for, and, when the report arrived at a
// per-domain hosted address (dmarc-reports+<domain>@<hostname>), it must be the
// domain that address is tagged for. Without this a stranger could file reports
// under someone else's domain, skew the panel's alignment figures, and push
// genuine reports out through the retention cap.
func IngestMessage(st *store.Store, r io.Reader, recipient string, receivedAt time.Time) error {
raw, err := io.ReadAll(io.LimitReader(r, 12<<20))
if err != nil {
@@ -31,6 +40,10 @@ func IngestMessage(st *store.Store, r io.Reader, recipient string, receivedAt ti
if err != nil {
return err
}
recipient = strings.ToLower(strings.TrimSpace(recipient))
if err := checkReportDomain(st, parsed.Domain, recipient); err != nil {
return err
}
rep := store.DMARCReport{
Domain: parsed.Domain,
Reporter: parsed.Reporter,
@@ -46,7 +59,7 @@ func IngestMessage(st *store.Store, r io.Reader, recipient string, receivedAt ti
PolicyASPF: parsed.PolicyASPF,
PassCount: parsed.PassCount,
FailCount: parsed.FailCount,
Recipient: strings.ToLower(strings.TrimSpace(recipient)),
Recipient: recipient,
}
for _, rec := range parsed.Records {
rep.Records = append(rep.Records, store.DMARCReportRecord{
@@ -64,6 +77,26 @@ func IngestMessage(st *store.Store, r io.Reader, recipient string, receivedAt ti
return st.PruneDMARCReports()
}
// checkReportDomain refuses a report whose policy domain is not one of this
// relay's sending domains, or that contradicts the +tag of the address it was
// delivered to.
func checkReportDomain(st *store.Store, domain, recipient string) error {
if domain == "" {
return fmt.Errorf("dmarc report: no policy domain")
}
if tagged := TaggedDomain(recipient); tagged != "" && tagged != domain {
return fmt.Errorf("dmarc report: domain %q does not match the address it was sent to (%s)", domain, recipient)
}
ok, err := st.DomainExists(domain)
if err != nil {
return err
}
if !ok {
return fmt.Errorf("dmarc report: %q is not a domain configured on this relay", domain)
}
return nil
}
func extractAggregatePayload(raw []byte) ([]byte, error) {
msg, err := mail.ReadMessage(bytes.NewReader(raw))
if err != nil {
+51 -11
View File
@@ -1,6 +1,7 @@
package dmarc
import (
"archive/zip"
"bytes"
"compress/gzip"
"encoding/xml"
@@ -73,9 +74,9 @@ type feedbackXML struct {
} `xml:"record"`
}
// ParseAggregate decodes gzip-compressed or raw DMARC aggregate XML.
// ParseAggregate decodes gzip- or zip-compressed, or raw, DMARC aggregate XML.
func ParseAggregate(raw []byte) (ParsedReport, error) {
data, err := maybeGunzip(raw)
data, err := decompress(raw)
if err != nil {
return ParsedReport{}, err
}
@@ -128,20 +129,59 @@ func dmarcRecordPasses(r ParsedRecord) bool {
return strings.EqualFold(r.SPFResult, "pass") || strings.EqualFold(r.DKIMResult, "pass")
}
func maybeGunzip(raw []byte) ([]byte, error) {
if len(raw) >= 2 && raw[0] == 0x1f && raw[1] == 0x8b {
zr, err := gzip.NewReader(bytes.NewReader(raw))
if err != nil {
return nil, fmt.Errorf("dmarc gzip: %w", err)
// maxAggregateXML bounds the decompressed payload, so a small archive cannot
// expand into an unbounded allocation.
const maxAggregateXML = 8 << 20
// decompress unwraps the container the reporter used. Both are seen in the
// wild: most senders gzip the XML, some (notably several Microsoft and Yahoo
// endpoints) ship it as a single-entry zip.
func decompress(raw []byte) ([]byte, error) {
switch {
case len(raw) >= 2 && raw[0] == 0x1f && raw[1] == 0x8b:
return gunzip(raw)
case len(raw) >= 4 && raw[0] == 'P' && raw[1] == 'K' && raw[2] == 0x03 && raw[3] == 0x04:
return unzip(raw)
}
return raw, nil
}
func gunzip(raw []byte) ([]byte, error) {
zr, err := gzip.NewReader(bytes.NewReader(raw))
if err != nil {
return nil, fmt.Errorf("dmarc gzip: %w", err)
}
defer zr.Close()
data, err := io.ReadAll(io.LimitReader(zr, maxAggregateXML))
if err != nil {
return nil, fmt.Errorf("dmarc gzip read: %w", err)
}
return data, nil
}
// unzip returns the first .xml entry of a zip archive. Directories and any
// other members are skipped rather than trusted.
func unzip(raw []byte) ([]byte, error) {
zr, err := zip.NewReader(bytes.NewReader(raw), int64(len(raw)))
if err != nil {
return nil, fmt.Errorf("dmarc zip: %w", err)
}
for _, f := range zr.File {
if f.FileInfo().IsDir() || !strings.HasSuffix(strings.ToLower(f.Name), ".xml") {
continue
}
defer zr.Close()
data, err := io.ReadAll(io.LimitReader(zr, 8<<20))
rc, err := f.Open()
if err != nil {
return nil, fmt.Errorf("dmarc gzip read: %w", err)
return nil, fmt.Errorf("dmarc zip open %s: %w", f.Name, err)
}
data, err := io.ReadAll(io.LimitReader(rc, maxAggregateXML))
rc.Close()
if err != nil {
return nil, fmt.Errorf("dmarc zip read %s: %w", f.Name, err)
}
return data, nil
}
return raw, nil
return nil, fmt.Errorf("dmarc zip: no xml entry")
}
// TightenPolicyHint summarises whether raising p= looks reasonable.
+100
View File
@@ -1,6 +1,7 @@
package dmarc
import (
"archive/zip"
"bytes"
"compress/gzip"
"testing"
@@ -76,6 +77,9 @@ func TestIngestMessageStoresReport(t *testing.T) {
t.Fatal(err)
}
defer st.Close()
if _, err := st.AddDomain("example.com", "selfpost"); err != nil {
t.Fatal(err)
}
var gz bytes.Buffer
zw := gzip.NewWriter(&gz)
@@ -114,3 +118,99 @@ func TestHostedReportAddress(t *testing.T) {
t.Fatalf("got %q want %q", got, want)
}
}
func TestIngestMessageRejectsUnknownDomain(t *testing.T) {
st, err := store.Open(t.TempDir() + "/test.db")
if err != nil {
t.Fatal(err)
}
defer st.Close()
if err := IngestMessage(st, bytes.NewBufferString(gzipMessage(t, sampleXML)), "dmarc-reports@mail.example.com", time.Now().UTC()); err == nil {
t.Fatal("report for an unconfigured domain was accepted")
}
list, err := st.ListDMARCReports(nil, 10)
if err != nil {
t.Fatal(err)
}
if len(list) != 0 {
t.Fatalf("stored %d report(s) for an unconfigured domain", len(list))
}
}
// A report claiming example.com must not be accepted at the address tagged for
// another domain, even when both domains are configured here.
func TestIngestMessageRejectsTagMismatch(t *testing.T) {
st, err := store.Open(t.TempDir() + "/test.db")
if err != nil {
t.Fatal(err)
}
defer st.Close()
if _, err := st.AddDomain("example.com", "selfpost"); err != nil {
t.Fatal(err)
}
if _, err := st.AddDomain("other.example", "selfpost"); err != nil {
t.Fatal(err)
}
err = IngestMessage(st, bytes.NewBufferString(gzipMessage(t, sampleXML)),
"dmarc-reports+other.example@mail.example.com", time.Now().UTC())
if err == nil {
t.Fatal("report was accepted at an address tagged for another domain")
}
}
func TestTaggedDomain(t *testing.T) {
cases := map[string]string{
"dmarc-reports+example.com@mail.example.com": "example.com",
"dmarc-reports@mail.example.com": "",
"postmaster+example.com@mail.example.com": "",
"not-an-address": "",
}
for addr, want := range cases {
if got := TaggedDomain(addr); got != want {
t.Errorf("TaggedDomain(%q) = %q, want %q", addr, got, want)
}
}
}
func TestParseAggregateFromZip(t *testing.T) {
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
w, err := zw.Create("report.xml")
if err != nil {
t.Fatal(err)
}
if _, err := w.Write([]byte(sampleXML)); err != nil {
t.Fatal(err)
}
if err := zw.Close(); err != nil {
t.Fatal(err)
}
got, err := ParseAggregate(buf.Bytes())
if err != nil {
t.Fatalf("ParseAggregate(zip): %v", err)
}
if got.Domain != "example.com" || got.PassCount != 10 {
t.Fatalf("zip report = %+v", got)
}
}
// gzipMessage wraps xml in the single-part gzip message the ingest pipe sees.
func gzipMessage(t *testing.T, xml string) string {
t.Helper()
var gz bytes.Buffer
zw := gzip.NewWriter(&gz)
if _, err := zw.Write([]byte(xml)); err != nil {
t.Fatal(err)
}
if err := zw.Close(); err != nil {
t.Fatal(err)
}
return "From: noreply@google.com\r\n" +
"To: dmarc-reports@mail.example.com\r\n" +
"Subject: Report\r\n" +
"Content-Type: application/gzip; name=\"report.xml.gz\"\r\n" +
"\r\n" + gz.String()
}
+3 -34
View File
@@ -13,7 +13,8 @@ import (
"encoding/pem"
"fmt"
"os"
"path/filepath"
"github.com/mixeme/selfpost/internal/atomicfile"
)
// dkimKeyBits is the RSA key size for DKIM signing keys. 2048 is the DKIM
@@ -91,37 +92,5 @@ func dkimRecord(selector, domainName string, pub *rsa.PublicKey) (DKIMRecord, er
// It is the single safe-write primitive for DKIM keys and OpenDKIM tables
// (security.md).
func writeFileAtomic(path string, data []byte, perm os.FileMode) error {
dir := filepath.Dir(path)
tmp, err := os.CreateTemp(dir, ".tmp-*")
if err != nil {
return fmt.Errorf("create temp in %s: %w", dir, err)
}
tmpName := tmp.Name()
cleanup := true
defer func() {
if cleanup {
_ = os.Remove(tmpName)
}
}()
if _, err := tmp.Write(data); err != nil {
tmp.Close()
return fmt.Errorf("write temp %s: %w", tmpName, err)
}
if err := tmp.Chmod(perm); err != nil {
tmp.Close()
return fmt.Errorf("chmod temp %s: %w", tmpName, err)
}
if err := tmp.Sync(); err != nil {
tmp.Close()
return fmt.Errorf("sync temp %s: %w", tmpName, err)
}
if err := tmp.Close(); err != nil {
return fmt.Errorf("close temp %s: %w", tmpName, err)
}
if err := os.Rename(tmpName, path); err != nil {
return fmt.Errorf("rename %s -> %s: %w", tmpName, path, err)
}
cleanup = false
return nil
return atomicfile.Write(path, data, perm)
}
+17 -16
View File
@@ -5,10 +5,13 @@ import (
"encoding/pem"
"fmt"
"os"
"os/exec"
"path"
"path/filepath"
"sort"
"strings"
"github.com/mixeme/selfpost/internal/configsafe"
"github.com/mixeme/selfpost/internal/supervisor"
)
// OpenDKIM manages the on-disk OpenDKIM state the panel is responsible for
@@ -191,7 +194,7 @@ func renderTables(keysDir string, domains []SigningDomain) (keyTable, signingTab
}
keyName := d.Name // one key per domain; the domain name is a fine handle
// Absolute key path so OpenDKIM resolves it independently of its CWD.
keyFile := filepath.Join(keysDir, d.Name, d.Selector+".private")
keyFile := path.Join(keysDir, d.Name, d.Selector+".private")
// KeyTable: <key-name> <domain>:<selector>:<key-path>
fmt.Fprintf(&kt, "%s %s:%s:%s\n", keyName, d.Name, d.Selector, keyFile)
// SigningTable (refile): <address-pattern> <key-name>
@@ -200,18 +203,23 @@ func renderTables(keysDir string, domains []SigningDomain) (keyTable, signingTab
return []byte(kt.String()), []byte(st.String()), nil
}
// opendkimForbidden is what may never appear in a KeyTable or SigningTable
// value: whitespace and the newline that would end the line, and the colon and
// path separators that carry meaning inside a table entry.
const opendkimForbidden = " \t\r\n:/\\"
// assertConfigSafe rejects any domain/selector value that could break out of a
// single table line. Domains are already whitelisted to [a-z0-9.-] and selectors
// to a similar set before they reach here (security.md); this is defence in depth
// against a validation gap ever letting whitespace, a newline or a field
// separator through into a config file (security.md).
func assertConfigSafe(domainName, selector string) error {
for _, v := range []string{domainName, selector} {
if v == "" {
return fmt.Errorf("opendkim: empty domain or selector")
}
if strings.ContainsAny(v, " \t\r\n:/\\") {
return fmt.Errorf("opendkim: unsafe character in %q", v)
for _, f := range []struct{ what, value string }{
{"domain", domainName},
{"selector", selector},
} {
if err := configsafe.Token(f.what, f.value, opendkimForbidden); err != nil {
return fmt.Errorf("opendkim: %w", err)
}
}
return nil
@@ -226,12 +234,5 @@ func assertConfigSafe(domainName, selector string) error {
// Arguments are fixed literals — no user input is interpolated into the command,
// and it never goes through a shell (security.md).
func reloadViaSupervisor() error {
cmd := exec.Command("supervisorctl",
"-c", "/etc/supervisor/supervisord.conf",
"signal", "USR1", "opendkim")
out, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("reload opendkim via supervisor: %w: %s", err, strings.TrimSpace(string(out)))
}
return nil
return supervisor.Signal("USR1", "opendkim")
}
+25 -17
View File
@@ -19,14 +19,14 @@ const FormatDomainExport = "selfpost-domain-export"
// transfer without regeneration). The file is therefore as sensitive as a full
// backup and must be handled as a secret.
type DomainExport struct {
Format string `json:"format"`
Version string `json:"version"`
Domain string `json:"domain"`
DKIMSelector string `json:"dkim_selector"`
DKIMPrivateKey string `json:"dkim_private_key"` // PKCS#1 PEM
DMARCRua *string `json:"dmarc_rua,omitempty"` // nil = inherit profile; set = override ("" = none)
Format string `json:"format"`
Version string `json:"version"`
Domain string `json:"domain"`
DKIMSelector string `json:"dkim_selector"`
DKIMPrivateKey string `json:"dkim_private_key"` // PKCS#1 PEM
DMARCRua *string `json:"dmarc_rua,omitempty"` // nil = inherit profile; set = override ("" = none)
RateLimit *RateLimitExport `json:"rate_limit,omitempty"`
Applications []AppExport `json:"applications"`
Applications []AppExport `json:"applications"`
}
// RateLimitExport is the transferable level-2 limit for a domain or application.
@@ -40,13 +40,13 @@ type RateLimitExport struct {
// AppExport is one application within a DomainExport.
type AppExport struct {
Login string `json:"login"`
AddressMode string `json:"address_mode"`
Addresses []string `json:"addresses,omitempty"` // list mode only
Password string `json:"password"`
AuthIPRestrict bool `json:"auth_ip_restrict,omitempty"`
AuthAllowedIPs []string `json:"auth_allowed_ips,omitempty"`
RateLimit *RateLimitExport `json:"rate_limit,omitempty"`
Login string `json:"login"`
AddressMode string `json:"address_mode"`
Addresses []string `json:"addresses,omitempty"` // list mode only
Password string `json:"password"`
AuthIPRestrict bool `json:"auth_ip_restrict,omitempty"`
AuthAllowedIPs []string `json:"auth_allowed_ips,omitempty"`
RateLimit *RateLimitExport `json:"rate_limit,omitempty"`
}
// Export builds the transferable representation of a domain: its DKIM key, its
@@ -78,7 +78,11 @@ func (s *Service) Export(id int64) (DomainExport, error) {
s := d.DMARCRua.String
exp.DMARCRua = &s
}
if rl, ok, err := s.store.GetRateLimit(store.RateLimitScopeDomain, id); err == nil && ok {
rl, ok, err := s.store.GetRateLimit(store.RateLimitScopeDomain, id)
if err != nil {
return DomainExport{}, fmt.Errorf("export rate limit for %s: %w", d.Name, err)
}
if ok {
exp.RateLimit = exportRateLimit(rl)
}
for _, a := range apps {
@@ -94,8 +98,12 @@ func (s *Service) Export(id int64) (DomainExport, error) {
AuthIPRestrict: a.AuthIPRestrict,
AuthAllowedIPs: a.AuthAllowedIPs,
}
if rl, ok, err := s.store.GetRateLimit(store.RateLimitScopeApp, a.ID); err == nil && ok {
appExp.RateLimit = exportRateLimit(rl)
appRL, ok, err := s.store.GetRateLimit(store.RateLimitScopeApp, a.ID)
if err != nil {
return DomainExport{}, fmt.Errorf("export rate limit for %s: %w", a.Login, err)
}
if ok {
appExp.RateLimit = exportRateLimit(appRL)
}
exp.Applications = append(exp.Applications, appExp)
}
+18
View File
@@ -33,3 +33,21 @@ func TestRenderDMARCMapsEmpty(t *testing.T) {
t.Fatalf("expected empty maps")
}
}
func TestRenderDMARCMapsRejectsInjectionTokens(t *testing.T) {
_, _, _, err := renderDMARCMaps(DMARCMapsConfig{
Recipients: []string{"dmarc@example.com\nattacker@example.com"},
Domains: []string{"example.com"},
})
if err == nil {
t.Fatal("expected recipient token validation error")
}
_, _, _, err = renderDMARCMaps(DMARCMapsConfig{
Recipients: []string{"dmarc@example.com"},
Domains: []string{"example.com attacker"},
})
if err == nil {
t.Fatal("expected domain token validation error")
}
}
+12 -11
View File
@@ -2,11 +2,12 @@ package postfix
import (
"fmt"
"net"
"path/filepath"
"sort"
"strconv"
"strings"
"github.com/mixeme/selfpost/internal/configsafe"
)
// InboundRoute is one inbound domain's Postfix map material: the relay
@@ -83,12 +84,10 @@ func renderInboundMaps(routes []InboundRoute) (relay, transport, recipients, tls
return []byte(relayB.String()), []byte(transportB.String()), []byte(recipB.String()), []byte(tlsB.String()), nil
}
// inboundNexthop is the Postfix next-hop [host]:port form that disables MX
// lookup for the explicit upstream.
// inboundNexthop is the Postfix next-hop [host]:port form. The brackets are
// what disable the MX lookup, so the operator's explicit upstream is used as
// given; they also delimit a bare IPv6 address.
func inboundNexthop(host string, port int) string {
if ip := net.ParseIP(host); ip != nil && ip.To4() == nil {
return "[" + host + "]:" + strconv.Itoa(port)
}
return "[" + host + "]:" + strconv.Itoa(port)
}
@@ -118,13 +117,15 @@ func assertInboundRouteSafe(r InboundRoute) error {
return nil
}
// texthashForbidden is what may never appear in a texthash line: whitespace and
// the newline that would end it, the comma that separates values, and the
// backslash.
const texthashForbidden = " \t\r\n,\\"
// assertMapToken rejects values that could break out of a texthash line.
func assertMapToken(v, what string) error {
if v == "" {
return fmt.Errorf("postfix: empty %s", what)
}
if strings.ContainsAny(v, " \t\r\n,\\") {
return fmt.Errorf("postfix: unsafe character in %s %q", what, v)
if err := configsafe.Token(what, v, texthashForbidden); err != nil {
return fmt.Errorf("postfix: %w", err)
}
return nil
}
+17 -21
View File
@@ -7,10 +7,12 @@ package postfix
import (
"fmt"
"os/exec"
"path/filepath"
"sort"
"strings"
"github.com/mixeme/selfpost/internal/configsafe"
"github.com/mixeme/selfpost/internal/supervisor"
)
// Postfix manages the on-disk Postfix state the panel is responsible for. After
@@ -122,6 +124,15 @@ func appendUnique(list []string, v string) []string {
return append(list, v)
}
// What may never reach a sender-map line: whitespace and the newline that would
// end it, the comma that separates values, the colon a lookup key cannot carry,
// and the backslash. A login additionally may not carry "@" — that would make it
// look like an address.
const (
senderMapAddressForbidden = " \t\r\n,:\\"
senderMapLoginForbidden = " \t\r\n,:@\\"
)
// assertMapSafe rejects any address/login value that could break out of a single
// map line or inject a directive. Addresses are validated to a strict whitelist
// (letters, digits, '@', '.', '-', '_', '+') and logins to an even stricter one
@@ -129,14 +140,11 @@ func appendUnique(list []string, v string) []string {
// letting whitespace, a newline or a comma (the value separator) through into
// the file (security.md).
func assertMapSafe(address, login string) error {
if address == "" || login == "" {
return fmt.Errorf("postfix: empty address or login")
if err := configsafe.Token("address", address, senderMapAddressForbidden); err != nil {
return fmt.Errorf("postfix: %w", err)
}
if strings.ContainsAny(address, " \t\r\n,:\\") {
return fmt.Errorf("postfix: unsafe character in address %q", address)
}
if strings.ContainsAny(login, " \t\r\n,:@\\") {
return fmt.Errorf("postfix: unsafe character in login %q", login)
if err := configsafe.Token("login", login, senderMapLoginForbidden); err != nil {
return fmt.Errorf("postfix: %w", err)
}
return nil
}
@@ -154,17 +162,5 @@ func assertMapSafe(address, login string) error {
// Arguments are fixed literals — no user input is interpolated into the command,
// and it never goes through a shell (security.md).
func reloadViaSupervisor() error {
cmd := exec.Command("supervisorctl",
"-c", "/etc/supervisor/supervisord.conf",
"start", "postfix-reload")
out, err := cmd.CombinedOutput()
if err != nil {
// A reload already in flight is not a failure: that pending run reloads
// Postfix after our file is in place (the file is written before this).
if strings.Contains(string(out), "already started") {
return nil
}
return fmt.Errorf("reload postfix via supervisor: %w: %s", err, strings.TrimSpace(string(out)))
}
return nil
return supervisor.Start("postfix-reload")
}
+51 -5
View File
@@ -1,12 +1,46 @@
package postfix
import (
"bytes"
"context"
"fmt"
"os/exec"
"regexp"
"strings"
"time"
)
const postqueueTimeout = 5 * time.Second
// maxQueueOutput bounds how much of `postqueue -p` the panel keeps. A deferred
// queue with a very large backlog prints one paragraph per message, and the
// whole listing is held in memory and then rendered into a page — so the read
// is capped and the remainder reported as truncated rather than being allowed
// to size the panel's memory by the size of the queue.
const maxQueueOutput = 4 << 20
// limitWriter keeps the first remaining bytes written to it and drops the rest,
// recording that it did. Writes always report full consumption so postqueue is
// never killed by a short write; the extra output is simply discarded.
type limitWriter struct {
buf bytes.Buffer
remaining int
truncated bool
}
func (l *limitWriter) Write(p []byte) (int, error) {
keep := len(p)
if keep > l.remaining {
keep = l.remaining
l.truncated = true
}
if keep > 0 {
l.buf.Write(p[:keep])
l.remaining -= keep
}
return len(p), nil
}
// Queue returns Postfix's own human-readable mail-queue listing
// (architecture.md § Panel HTTP surface): active, deferred and held messages,
// exactly as an administrator would see via the CLI. The command takes a
@@ -14,12 +48,24 @@ import (
// (security.md). The panel is responsible for escaping the output before
// display (security.md); this function returns it as-is.
func Queue() (string, error) {
cmd := exec.Command("postqueue", "-p")
out, err := cmd.CombinedOutput()
if err != nil {
return "", fmt.Errorf("postqueue -p: %w: %s", err, strings.TrimSpace(string(out)))
ctx, cancel := context.WithTimeout(context.Background(), postqueueTimeout)
defer cancel()
cmd := exec.CommandContext(ctx, "postqueue", "-p")
out := &limitWriter{remaining: maxQueueOutput}
cmd.Stdout = out
cmd.Stderr = out
err := cmd.Run()
if ctx.Err() == context.DeadlineExceeded {
return "", fmt.Errorf("postqueue -p timed out after %s", postqueueTimeout)
}
return string(out), nil
if err != nil {
return "", fmt.Errorf("postqueue -p: %w: %s", err, strings.TrimSpace(out.buf.String()))
}
text := out.buf.String()
if out.truncated {
text += fmt.Sprintf("\n[listing truncated at %d bytes]\n", maxQueueOutput)
}
return text, nil
}
// QueueIDs returns the set of queue ids Postfix is still holding — everything
+31
View File
@@ -41,3 +41,34 @@ func TestParseQueueIDsOnAnEmptyQueue(t *testing.T) {
t.Errorf("got %v, want no ids", ids)
}
}
// The queue listing is held in memory and rendered into a page, so a very large
// queue must not size the panel's allocation: the writer keeps the cap and
// reports the rest as dropped, while still accepting every write so postqueue
// itself is never cut short.
func TestLimitWriterCapsOutput(t *testing.T) {
w := &limitWriter{remaining: 8}
n, err := w.Write([]byte("12345"))
if n != 5 || err != nil {
t.Fatalf("first write = %d, %v", n, err)
}
if w.truncated {
t.Fatal("truncated before the cap was reached")
}
n, err = w.Write([]byte("67890"))
if n != 5 || err != nil {
t.Fatalf("second write = %d, %v", n, err)
}
if !w.truncated {
t.Fatal("write past the cap was not recorded as truncated")
}
if got := w.buf.String(); got != "12345678" {
t.Fatalf("kept %q, want the first 8 bytes", got)
}
if n, err := w.Write([]byte("more")); n != 4 || err != nil {
t.Fatalf("write after the cap = %d, %v (must still accept)", n, err)
}
if got := w.buf.String(); got != "12345678" {
t.Fatalf("buffer grew past the cap: %q", got)
}
}
+4 -37
View File
@@ -1,47 +1,14 @@
package postfix
import (
"fmt"
"os"
"path/filepath"
"github.com/mixeme/selfpost/internal/atomicfile"
)
// writeFileAtomic writes data to path via a temp file in the same directory
// followed by a rename, so a concurrent Postfix reload only ever sees the
// complete old or new map, never a partial write (security.md). It mirrors the
// same primitive used for the OpenDKIM tables.
// complete old or new map, never a partial write (security.md).
func writeFileAtomic(path string, data []byte, perm os.FileMode) error {
dir := filepath.Dir(path)
tmp, err := os.CreateTemp(dir, ".tmp-*")
if err != nil {
return fmt.Errorf("create temp in %s: %w", dir, err)
}
tmpName := tmp.Name()
cleanup := true
defer func() {
if cleanup {
_ = os.Remove(tmpName)
}
}()
if _, err := tmp.Write(data); err != nil {
tmp.Close()
return fmt.Errorf("write temp %s: %w", tmpName, err)
}
if err := tmp.Chmod(perm); err != nil {
tmp.Close()
return fmt.Errorf("chmod temp %s: %w", tmpName, err)
}
if err := tmp.Sync(); err != nil {
tmp.Close()
return fmt.Errorf("sync temp %s: %w", tmpName, err)
}
if err := tmp.Close(); err != nil {
return fmt.Errorf("close temp %s: %w", tmpName, err)
}
if err := os.Rename(tmpName, path); err != nil {
return fmt.Errorf("rename %s -> %s: %w", tmpName, path, err)
}
cleanup = false
return nil
return atomicfile.Write(path, data, perm)
}
+8 -8
View File
@@ -29,14 +29,14 @@ const (
// hashed — so it can be shown exactly once at creation/regeneration
// (security.md). Addresses is populated only in 'list' mode.
type Application struct {
ID int64
DomainID int64
Login string
AddressMode string
CreatedAt time.Time
Addresses []string
AuthIPRestrict bool // when true, only AuthAllowedIPs may submit as this login
AuthAllowedIPs []string // client IPs permitted when AuthIPRestrict is set
ID int64
DomainID int64
Login string
AddressMode string
CreatedAt time.Time
Addresses []string
AuthIPRestrict bool // when true, only AuthAllowedIPs may submit as this login
AuthAllowedIPs []string // client IPs permitted when AuthIPRestrict is set
}
// AllowsAuthFromIP reports whether a client at ip may submit mail authenticated
+15
View File
@@ -4,6 +4,7 @@ import (
"database/sql"
"errors"
"fmt"
"strings"
"time"
"modernc.org/sqlite"
@@ -182,3 +183,17 @@ func (s *Store) UpdateDomainDMARCRua(id int64, rua sql.NullString) error {
}
return nil
}
// DomainExists reports whether a sending domain with this name is configured.
// Used by the DMARC ingest path to refuse reports for domains this relay does
// not send for (security.md: report XML is attacker-supplied input).
func (s *Store) DomainExists(name string) (bool, error) {
var n int
err := s.db.QueryRow(
"SELECT COUNT(*) FROM domains WHERE name = ? COLLATE NOCASE", strings.TrimSpace(name),
).Scan(&n)
if err != nil {
return false, fmt.Errorf("domain exists %q: %w", name, err)
}
return n > 0, nil
}
+14 -14
View File
@@ -1,9 +1,9 @@
-- Initial SelfPost schema (spec 9). One SQLite file under /data holds the whole
-- panel state so a single directory backup/restore is sufficient (spec 7.5.A).
-- Initial SelfPost schema. One SQLite file under /data holds the whole panel
-- state so a single directory backup/restore is sufficient.
-- Single administrator account (spec 7.6.1). Exactly one row is allowed; the
-- presence of that row is what marks primary setup as complete, which is why
-- the /setup route disappears once it exists.
-- Single administrator account. Exactly one row is allowed; the presence of
-- that row is what marks primary setup as complete, which is why the /setup
-- route disappears once it exists.
CREATE TABLE admin (
id INTEGER PRIMARY KEY CHECK (id = 1),
username TEXT NOT NULL,
@@ -17,8 +17,8 @@ CREATE TABLE settings (
value TEXT NOT NULL
);
-- Sending domains managed through the panel (spec 4.1). DKIM keys themselves
-- live on disk under /data; this row records the selector and metadata.
-- Sending domains managed through the panel. DKIM keys themselves live on disk
-- under /data; this row records the selector and metadata.
CREATE TABLE domains (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE,
@@ -26,8 +26,8 @@ CREATE TABLE domains (
created_at TEXT NOT NULL
);
-- Applications bound to a domain (spec 4.1). address_mode is either the domain
-- wildcard or an explicit address list; the SASL login is globally unique.
-- Applications bound to a domain. address_mode is either the domain wildcard or
-- an explicit address list; the SASL login is globally unique.
CREATE TABLE applications (
id INTEGER PRIMARY KEY AUTOINCREMENT,
domain_id INTEGER NOT NULL REFERENCES domains(id) ON DELETE CASCADE,
@@ -37,7 +37,7 @@ CREATE TABLE applications (
);
-- Explicit sender addresses for applications in 'list' mode. Each address must
-- belong to the application's domain (validated in the panel, spec 7.6.2).
-- belong to the application's domain (validated in the panel).
CREATE TABLE application_addresses (
id INTEGER PRIMARY KEY AUTOINCREMENT,
application_id INTEGER NOT NULL REFERENCES applications(id) ON DELETE CASCADE,
@@ -45,8 +45,8 @@ CREATE TABLE application_addresses (
UNIQUE (application_id, address)
);
-- Structured send log (spec 7.3). One row per (queue-id, recipient); the
-- log-tailer advances status from queued to a final state.
-- Structured send log. One row per (queue-id, recipient); the log-tailer
-- advances status from queued to a final state.
CREATE TABLE send_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
queue_id TEXT,
@@ -63,8 +63,8 @@ CREATE INDEX idx_send_log_queue_id ON send_log (queue_id);
CREATE INDEX idx_send_log_domain ON send_log (domain);
CREATE INDEX idx_send_log_created_at ON send_log (created_at);
-- Differentiated rate limits per domain/application (spec 7.4). Both the IP
-- binding and the message limit are optional.
-- Differentiated rate limits per domain/application. Both the IP binding and
-- the message limit are optional.
CREATE TABLE rate_limits (
id INTEGER PRIMARY KEY AUTOINCREMENT,
scope TEXT NOT NULL CHECK (scope IN ('domain', 'application')),
+5 -5
View File
@@ -1,8 +1,8 @@
-- Panel login sessions (spec 7.6.6, plan B.1). Persisted so a login survives a
-- container restart or redeploy; only the SHA-256 of the session token is
-- stored, never the token itself, so a stolen database file cannot be used to
-- sign in. expires_at implements the sliding idle timeout: it is pushed
-- forward on activity rather than being fixed at creation time.
-- Panel login sessions. Persisted so a login survives a container restart or
-- redeploy; only the SHA-256 of the session token is stored, never the token
-- itself, so a stolen database file cannot be used to sign in. expires_at
-- implements the sliding idle timeout: it is pushed forward on activity rather
-- than being fixed at creation time.
CREATE TABLE sessions (
token_hash TEXT PRIMARY KEY,
username TEXT NOT NULL,
@@ -0,0 +1,9 @@
-- Send-log lookups by application login run on two hot paths: the journal
-- milter counts messages for a level-2 rate limit on every MAIL FROM, and the
-- domain page computes 30-day statistics per application on every render.
-- 0001 indexed queue_id, domain and created_at, but not app_login, so both
-- fell back to scanning the created_at range. The composite matches the shape
-- of those queries (equality on app_login, range on created_at).
CREATE INDEX IF NOT EXISTS idx_send_log_app_login_created_at
ON send_log (app_login, created_at);
+16 -4
View File
@@ -116,7 +116,7 @@ func (s *Store) recalcAutoRateLimit(rl RateLimit, retentionDays, l1Max, l1Window
return fmt.Errorf("unknown scope %q", rl.Scope)
}
maxMsgs := computeAutoMaxMessages(stats, mult, l1Max)
maxMsgs := computeAutoMaxMessages(stats, mult, l1Max, l1Window)
rl.MaxMessages = maxMsgs
rl.WindowSeconds = l1Window
@@ -128,14 +128,26 @@ func (s *Store) recalcAutoRateLimit(rl RateLimit, retentionDays, l1Max, l1Window
return s.SetRateLimit(rl)
}
func computeAutoMaxMessages(stats SendStats, multiplier float64, l1Max int) int {
// computeAutoMaxMessages turns an average send rate into a ceiling for one
// level-1 window. AvgPerHour is per hour, the ceiling counts messages per
// windowSeconds, so the rate is scaled to the window before the multiplier is
// applied — otherwise a window other than the default 3600s would silently
// shift the effective allowance by windowSeconds/3600. The result is never
// below 1 for a domain that has sent anything, and never above level 1.
func computeAutoMaxMessages(stats SendStats, multiplier float64, l1Max, windowSeconds int) int {
if stats.Total == 0 {
return 0
}
max := int(math.Ceil(stats.AvgPerHour * multiplier))
if windowSeconds <= 0 {
windowSeconds = 3600
}
perWindow := stats.AvgPerHour * float64(windowSeconds) / 3600
max := int(math.Ceil(perWindow * multiplier))
if max < 1 {
max = 1
}
if max > l1Max {
max = l1Max
}
return max
}
+39 -2
View File
@@ -154,8 +154,8 @@ func TestRateLimitActive(t *testing.T) {
inactive := []RateLimit{
{},
{Scope: RateLimitScopeDomain, AllowedIPs: []string{"203.0.113.1"}}, // no ceiling
{Scope: RateLimitScopeDomain, MaxMessages: 5}, // no window
{Scope: RateLimitScopeApp, MaxMessages: 5}, // no window
{Scope: RateLimitScopeDomain, MaxMessages: 5}, // no window
{Scope: RateLimitScopeApp, MaxMessages: 5}, // no window
}
for i, rl := range inactive {
if rl.Active() {
@@ -261,3 +261,40 @@ func TestAutoRateLimitZeroTrafficInactive(t *testing.T) {
t.Fatalf("zero traffic auto should be inactive: %+v", rl)
}
}
// The auto ceiling counts messages per level-1 window, so the per-hour average
// must be scaled to that window: half an hour of traffic, not a full hour's.
func TestComputeAutoMaxMessagesScalesToWindow(t *testing.T) {
stats := SendStats{Total: 100, AvgPerHour: 10}
cases := []struct {
name string
windowSeconds int
want int
}{
{"one hour", 3600, 20},
{"half an hour", 1800, 10},
{"two hours", 7200, 40},
{"unset falls back to an hour", 0, 20},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got := computeAutoMaxMessages(stats, 2.0, 1000, tc.windowSeconds)
if got != tc.want {
t.Fatalf("max = %d, want %d", got, tc.want)
}
})
}
}
func TestComputeAutoMaxMessagesBounds(t *testing.T) {
if got := computeAutoMaxMessages(SendStats{}, 2.0, 1000, 3600); got != 0 {
t.Fatalf("no traffic: max = %d, want 0 (inactive)", got)
}
// A trickle still has to leave room for one message.
if got := computeAutoMaxMessages(SendStats{Total: 1, AvgPerHour: 0.001}, 1.0, 1000, 3600); got != 1 {
t.Fatalf("trickle: max = %d, want 1", got)
}
if got := computeAutoMaxMessages(SendStats{Total: 100, AvgPerHour: 500}, 2.0, 100, 3600); got != 100 {
t.Fatalf("capped: max = %d, want the level-1 ceiling 100", got)
}
}
+1 -1
View File
@@ -15,7 +15,7 @@ type SendStats struct {
Total int64
PeakPerHour int64
AvgPerHour float64
WindowDays int // actual days queried (min(30, retention))
WindowDays int // actual days queried (min(30, retention))
WindowHours float64 // hours used for the average-rate denominator
}
+36
View File
@@ -0,0 +1,36 @@
// Package supervisor provides helpers for controlling processes through
// supervisord's control socket (architecture.md, security.md).
package supervisor
import (
"fmt"
"os/exec"
"strings"
)
const confPath = "/etc/supervisor/supervisord.conf"
// Start issues a `supervisorctl start` for the named program. A program that
// is already running is not an error (the pending run covers the caller's
// intent).
func Start(program string) error {
cmd := exec.Command("supervisorctl", "-c", confPath, "start", program)
out, err := cmd.CombinedOutput()
if err != nil {
if strings.Contains(string(out), "already started") {
return nil
}
return fmt.Errorf("supervisor start %s: %w: %s", program, err, strings.TrimSpace(string(out)))
}
return nil
}
// Signal sends a signal to a supervised program via `supervisorctl signal`.
func Signal(sig, program string) error {
cmd := exec.Command("supervisorctl", "-c", confPath, "signal", sig, program)
out, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("supervisor signal %s %s: %w: %s", sig, program, err, strings.TrimSpace(string(out)))
}
return nil
}
+8 -1
View File
@@ -15,6 +15,13 @@ const (
sessionCookiePrefixed = "__Host-" + sessionCookieBase
)
// BcryptCost is the work factor for every panel password hash — the setup
// account created here and the ones the settings and user pages write
// (security.md). bcrypt records the cost inside the hash, so raising it only
// affects passwords set from now on; existing hashes keep verifying at the
// cost they were written with.
const BcryptCost = 12
func (m *Module) sessionCookie() string {
if m.cfg.CookieSecure {
return sessionCookiePrefixed
@@ -219,7 +226,7 @@ func (m *Module) submitSetup(w http.ResponseWriter, r *http.Request, token strin
return
}
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
hash, err := bcrypt.GenerateFromPassword([]byte(password), BcryptCost)
if err != nil {
logf("panel: setup: hashing password failed: %v", err)
m.renderSetupForm(w, http.StatusInternalServerError, token, "Internal error. Please try again.")
+48 -11
View File
@@ -7,6 +7,16 @@ import (
const defaultMaxBuckets = 4096
// blockedBucketCeiling is how far past maxBuckets the map may grow while every
// bucket in it is blocked. Blocked buckets are normally protected from
// eviction (see evictNearest), but protecting them unconditionally would let
// an attacker with many source addresses grow the map without bound — each
// address only has to fail max times. Past the ceiling blocked buckets are
// evicted too, nearest expiry first: bounded memory wins over holding every
// block, and the addresses that lose their bucket have to spend max attempts
// again to get back to blocked.
const blockedBucketCeiling = 4
// rateLimiter is a simple fixed-window per-key counter used to throttle the
// setup and login routes (security.md). Keys are client IPs.
type rateLimiter struct {
@@ -14,8 +24,9 @@ type rateLimiter struct {
window time.Duration
maxBuckets int
mu sync.Mutex
buckets map[string]*rlBucket
mu sync.Mutex
buckets map[string]*rlBucket
lastOverflow time.Time
}
type rlBucket struct {
@@ -68,25 +79,51 @@ func (r *rateLimiter) makeRoom(now time.Time) {
return
}
r.sweep(now)
hardCap := r.maxBuckets * blockedBucketCeiling
for len(r.buckets) >= r.maxBuckets {
r.evictOldest()
if r.evictNearest(false) {
continue
}
// Nothing evictable is left: every remaining bucket is blocked. Hold
// them until the map reaches the hard ceiling, then start evicting
// blocked buckets as well so memory stays bounded.
if len(r.buckets) < hardCap {
break
}
if !r.evictNearest(true) {
break
}
if now.Sub(r.lastOverflow) >= r.window {
r.lastOverflow = now
logf("panel: login rate limiter holds %d blocked buckets (cap %d) — evicting blocked entries; "+
"this means many distinct client addresses are failing authentication", len(r.buckets), r.maxBuckets)
}
}
}
func (r *rateLimiter) evictOldest() {
var oldestKey string
var oldestEnds time.Time
// evictNearest removes the bucket whose window ends soonest and reports whether
// it removed one. Blocked buckets (count >= max) are skipped unless evictBlocked
// is set, so an attacker cannot flush active rate-limit state by filling the map
// with new keys.
func (r *rateLimiter) evictNearest(evictBlocked bool) bool {
var bestKey string
var bestEnds time.Time
first := true
for k, b := range r.buckets {
if first || b.windowEnds.Before(oldestEnds) {
oldestKey = k
oldestEnds = b.windowEnds
if !evictBlocked && b.count >= r.max {
continue
}
if first || b.windowEnds.Before(bestEnds) {
bestKey = k
bestEnds = b.windowEnds
first = false
}
}
if oldestKey != "" {
delete(r.buckets, oldestKey)
if bestKey == "" {
return false
}
delete(r.buckets, bestKey)
return true
}
func (r *rateLimiter) sweep(now time.Time) {
+51
View File
@@ -1,6 +1,7 @@
package auth
import (
"fmt"
"testing"
"time"
)
@@ -123,3 +124,53 @@ func TestRateLimiterCapsBucketCount(t *testing.T) {
t.Fatalf("bucket count = %d, want at most 3", len(r.buckets))
}
}
// A flood of new addresses must not be able to reset the limiter for an address
// that is already blocked: below the hard ceiling, blocked buckets survive
// eviction even though the map is over its soft cap.
func TestRateLimiterKeepsBlockedBucketsUnderPressure(t *testing.T) {
r := newRateLimiter(2, time.Minute)
r.maxBuckets = 3
blocked := []string{"203.0.113.7", "198.51.100.9", "192.0.2.5"}
for _, key := range blocked {
for i := 0; i < 2; i++ {
if !r.Allow(key) {
t.Fatalf("%s refused before reaching the limit", key)
}
}
if r.Allow(key) {
t.Fatalf("%s was not blocked after 2 attempts", key)
}
}
// Fresh addresses arrive and find nothing evictable.
for i := 0; i < 10; i++ {
r.Allow(fmt.Sprintf("198.51.100.%d", 100+i))
}
for _, key := range blocked {
if r.Allow(key) {
t.Fatalf("%s lost its block after new addresses arrived", key)
}
}
}
// Protecting blocked buckets is bounded: past maxBuckets * blockedBucketCeiling
// they are evicted too, so an attacker cannot grow the map without limit by
// burning through source addresses.
func TestRateLimiterBoundsBlockedBuckets(t *testing.T) {
r := newRateLimiter(1, time.Minute)
r.maxBuckets = 2
hardCap := r.maxBuckets * blockedBucketCeiling
for i := 0; i < 100; i++ {
r.Allow(fmt.Sprintf("192.0.2.%d", i))
}
r.mu.Lock()
defer r.mu.Unlock()
if len(r.buckets) > hardCap {
t.Fatalf("bucket count = %d, want at most the hard cap %d", len(r.buckets), hardCap)
}
}
@@ -14,9 +14,9 @@ import (
type dmarcListRow struct {
store.DMARCReportSummary
DomainID int64
ReceivedLabel string
PeriodLabel string
DomainID int64
ReceivedLabel string
PeriodLabel string
}
func (h *Handlers) requireDMARC(w http.ResponseWriter, r *http.Request) (auth.Principal, bool) {
+6 -6
View File
@@ -108,12 +108,12 @@ func (h *Handlers) HandleDelivery(w http.ResponseWriter, r *http.Request) {
row.Subject = mailhdr.DecodeSubject(row.Subject)
logRows, logNote := h.deliveryLog(row)
h.view.Render(w, http.StatusOK, "delivery", map[string]any{
"Title": "SelfPost — delivery",
"User": auth.CurrentUser(r),
"Active": "deliveries",
"IsGlobal": p.IsGlobal(),
"SendLogRetentionDays": h.sendLogRetentionDays(),
"Row": row,
"Title": "SelfPost — delivery",
"User": auth.CurrentUser(r),
"Active": "deliveries",
"IsGlobal": p.IsGlobal(),
"SendLogRetentionDays": h.sendLogRetentionDays(),
"Row": row,
// The status in the panel's own badge vocabulary, so the headline reads
// the same way as every other health signal in the panel.
"Level": deliveryLevel(row.Status),
+15 -70
View File
@@ -61,7 +61,7 @@ func parseRateLimitMode(raw string) (string, error) {
return raw, nil
}
func parseDomainRateLimitForm(r *http.Request, l1Max int) (rateLimitInput, error) {
func parseRateLimitForm(r *http.Request, l1Max int) (rateLimitInput, error) {
if err := r.ParseForm(); err != nil {
return rateLimitInput{}, fmt.Errorf("invalid form submission")
}
@@ -98,44 +98,6 @@ func parseDomainRateLimitForm(r *http.Request, l1Max int) (rateLimitInput, error
return rateLimitInput{mode: store.RateLimitModeManual, maxMessages: maxMessages, windowSeconds: windowSeconds}, nil
}
func parseAppRateLimitForm(r *http.Request, l1Max int) (rateLimitInput, error) {
if err := r.ParseForm(); err != nil {
return rateLimitInput{}, fmt.Errorf("invalid form submission")
}
if r.PostFormValue("clear") != "" {
return rateLimitInput{clear: true}, nil
}
mode, err := parseRateLimitMode(r.PostFormValue("mode"))
if err != nil {
return rateLimitInput{}, err
}
if mode == store.RateLimitModeAuto {
mult, err := parseAutoMultiplier(r.PostFormValue("auto_multiplier"))
if err != nil {
return rateLimitInput{}, err
}
return rateLimitInput{mode: mode, autoMultiplier: mult}, nil
}
rawMax := strings.TrimSpace(r.PostFormValue("max_messages"))
if rawMax == "" {
return rateLimitInput{clear: true}, nil
}
maxMessages, err := parsePositiveInt(rawMax, 0)
if err != nil || maxMessages <= 0 {
return rateLimitInput{}, fmt.Errorf("enter a message limit greater than zero")
}
if maxMessages > l1Max {
return rateLimitInput{}, fmt.Errorf("message limit cannot exceed the level-1 backstop (%d)", l1Max)
}
windowSeconds, err := parsePositiveInt(r.PostFormValue("window_seconds"), defaultRateLimitWindowSeconds)
if err != nil || windowSeconds <= 0 {
return rateLimitInput{}, fmt.Errorf("enter a time window greater than zero seconds")
}
return rateLimitInput{mode: store.RateLimitModeManual, maxMessages: maxMessages, windowSeconds: windowSeconds}, nil
}
func parseAppAuthIPsForm(r *http.Request) (bool, []string, error) {
if err := r.ParseForm(); err != nil {
return false, nil, fmt.Errorf("invalid form submission")
@@ -187,7 +149,7 @@ func (h *Handlers) HandleDomainRateLimit(w http.ResponseWriter, r *http.Request)
if !ok {
return
}
in, err := parseDomainRateLimitForm(r, h.l1Messages())
in, err := parseRateLimitForm(r, h.l1Messages())
if err != nil {
h.renderDomainDetail(w, r, http.StatusBadRequest, d, detailView{
FormMode: store.AddressModeWildcard,
@@ -195,7 +157,7 @@ func (h *Handlers) HandleDomainRateLimit(w http.ResponseWriter, r *http.Request)
})
return
}
if err := h.applyDomainRateLimit(in, d.ID); err != nil {
if err := h.applyRateLimit(in, store.RateLimitScopeDomain, d.ID, h.domains); err != nil {
logf("panel: domain %d: save rate limit: %v", d.ID, err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
@@ -213,7 +175,7 @@ func (h *Handlers) HandleAppRateLimit(w http.ResponseWriter, r *http.Request) {
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
in, err := parseAppRateLimitForm(r, h.l1Messages())
in, err := parseRateLimitForm(r, h.l1Messages())
if err != nil {
h.renderDomainDetail(w, r, http.StatusBadRequest, d, detailView{
FormMode: store.AddressModeWildcard,
@@ -221,7 +183,7 @@ func (h *Handlers) HandleAppRateLimit(w http.ResponseWriter, r *http.Request) {
})
return
}
if err := h.applyAppRateLimit(in, a.ID); err != nil {
if err := h.applyRateLimit(in, store.RateLimitScopeApp, a.ID, h.apps); err != nil {
logf("panel: application %d: save rate limit: %v", a.ID, err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
@@ -291,35 +253,18 @@ func (h *Handlers) recalcRateLimit(scope string, refID int64) error {
return h.store.RecalcAutoRateLimit(scope, refID, h.sendLogRetentionDays(), h.l1Messages(), h.l1Window())
}
func (h *Handlers) applyDomainRateLimit(in rateLimitInput, domainID int64) error {
if in.clear {
return h.domains.ClearRateLimit(domainID)
}
rl := store.RateLimit{
Scope: store.RateLimitScopeDomain,
RefID: domainID,
Mode: in.mode,
MaxMessages: in.maxMessages,
WindowSeconds: in.windowSeconds,
AutoMultiplier: in.autoMultiplier,
}
if in.mode == store.RateLimitModeAuto {
rl.WindowSeconds = h.l1Window()
if err := h.domains.SaveRateLimit(domainID, rl); err != nil {
return err
}
return h.recalcRateLimit(store.RateLimitScopeDomain, domainID)
}
return h.domains.SaveRateLimit(domainID, rl)
type rateLimitSaver interface {
ClearRateLimit(id int64) error
SaveRateLimit(id int64, rl store.RateLimit) error
}
func (h *Handlers) applyAppRateLimit(in rateLimitInput, appID int64) error {
func (h *Handlers) applyRateLimit(in rateLimitInput, scope string, refID int64, saver rateLimitSaver) error {
if in.clear {
return h.apps.ClearRateLimit(appID)
return saver.ClearRateLimit(refID)
}
rl := store.RateLimit{
Scope: store.RateLimitScopeApp,
RefID: appID,
Scope: scope,
RefID: refID,
Mode: in.mode,
MaxMessages: in.maxMessages,
WindowSeconds: in.windowSeconds,
@@ -327,10 +272,10 @@ func (h *Handlers) applyAppRateLimit(in rateLimitInput, appID int64) error {
}
if in.mode == store.RateLimitModeAuto {
rl.WindowSeconds = h.l1Window()
if err := h.apps.SaveRateLimit(appID, rl); err != nil {
if err := saver.SaveRateLimit(refID, rl); err != nil {
return err
}
return h.recalcRateLimit(store.RateLimitScopeApp, appID)
return h.recalcRateLimit(scope, refID)
}
return h.apps.SaveRateLimit(appID, rl)
return saver.SaveRateLimit(refID, rl)
}
@@ -8,7 +8,9 @@ import (
"testing"
)
func TestParseDomainRateLimitForm(t *testing.T) {
// Domain and application limits are parsed by the same function; the form
// fields and the level-1 backstop are identical for both scopes.
func TestParseRateLimitForm(t *testing.T) {
t.Parallel()
form := func(vals url.Values) *http.Request {
r := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(vals.Encode()))
@@ -16,7 +18,7 @@ func TestParseDomainRateLimitForm(t *testing.T) {
return r
}
in, err := parseDomainRateLimitForm(form(url.Values{
in, err := parseRateLimitForm(form(url.Values{
"mode": {"manual"},
"max_messages": {"50"},
"window_seconds": {"3600"},
@@ -25,44 +27,12 @@ func TestParseDomainRateLimitForm(t *testing.T) {
t.Fatalf("valid domain = %+v err=%v", in, err)
}
in, err = parseDomainRateLimitForm(form(url.Values{"max_messages": {""}}), 100)
in, err = parseRateLimitForm(form(url.Values{"max_messages": {""}}), 100)
if err != nil || !in.clear {
t.Fatalf("empty max should clear: %+v err=%v", in, err)
}
_, err = parseDomainRateLimitForm(form(url.Values{
"mode": {"manual"},
"max_messages": {"150"},
"window_seconds": {"3600"},
}), 100)
if err == nil || !strings.Contains(err.Error(), "level-1") {
t.Fatalf("over L1 want error, got %v", err)
}
}
func TestParseAppRateLimitForm(t *testing.T) {
t.Parallel()
form := func(vals url.Values) *http.Request {
r := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(vals.Encode()))
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
return r
}
in, err := parseAppRateLimitForm(form(url.Values{
"mode": {"manual"},
"max_messages": {"80"},
"window_seconds": {"3600"},
}), 100)
if err != nil || in.maxMessages != 80 {
t.Fatalf("valid app limit = %+v err=%v", in, err)
}
in, err = parseAppRateLimitForm(form(url.Values{"max_messages": {""}}), 100)
if err != nil || !in.clear {
t.Fatalf("empty max should clear: %+v err=%v", in, err)
}
_, err = parseAppRateLimitForm(form(url.Values{
_, err = parseRateLimitForm(form(url.Values{
"mode": {"manual"},
"max_messages": {"150"},
"window_seconds": {"3600"},
@@ -82,7 +52,7 @@ func TestParseAppAuthIPsForm(t *testing.T) {
restrict, ips, err := parseAppAuthIPsForm(form(url.Values{
"auth_ip_restrict": {"1"},
"auth_allowed_ips": {"203.0.113.10"},
"auth_allowed_ips": {"203.0.113.10"},
}))
if err != nil || !restrict || len(ips) != 1 {
t.Fatalf("enabled with IP = restrict=%v ips=%v err=%v", restrict, ips, err)
@@ -99,23 +69,23 @@ func TestParseAppAuthIPsForm(t *testing.T) {
}
}
func TestParseDomainRateLimitFormAuto(t *testing.T) {
func TestParseRateLimitFormAuto(t *testing.T) {
t.Parallel()
form := func(vals url.Values) *http.Request {
r := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(vals.Encode()))
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
return r
}
in, err := parseDomainRateLimitForm(form(url.Values{
"mode": {"auto"},
"auto_multiplier": {"2.5"},
in, err := parseRateLimitForm(form(url.Values{
"mode": {"auto"},
"auto_multiplier": {"2.5"},
}), 100)
if err != nil || in.mode != "auto" || in.autoMultiplier != 2.5 {
t.Fatalf("auto domain = %+v err=%v", in, err)
}
_, err = parseDomainRateLimitForm(form(url.Values{
"mode": {"auto"},
"auto_multiplier": {"10"},
_, err = parseRateLimitForm(form(url.Values{
"mode": {"auto"},
"auto_multiplier": {"10"},
}), 100)
if err == nil {
t.Fatal("multiplier out of range should fail")
+30 -39
View File
@@ -71,26 +71,29 @@ func (h *Handlers) renderSettings(w http.ResponseWriter, r *http.Request, status
}
func settingsFlash(r *http.Request) string {
switch r.URL.Query().Get("updated") {
case "username":
return "Username changed."
case "password":
return "Password changed. Any other signed-in sessions were signed out."
case "both":
return "Username and password changed. Any other signed-in sessions were signed out."
case "email":
return "DMARC report address updated."
case "retention":
return "Send log retention updated."
case "username-email":
return "Username and DMARC report address updated."
case "password-email":
return "Password and DMARC report address updated. Any other signed-in sessions were signed out."
case "all":
return "Settings updated. Any other signed-in sessions were signed out."
default:
q := r.URL.Query()
var parts []string
if q.Has("u") {
parts = append(parts, "username")
}
if q.Has("p") {
parts = append(parts, "password")
}
if q.Has("e") {
parts = append(parts, "DMARC report address")
}
if q.Has("r") {
parts = append(parts, "send log retention")
}
if len(parts) == 0 {
return ""
}
msg := strings.Join(parts, ", ") + " updated."
msg = strings.ToUpper(msg[:1]) + msg[1:]
if q.Has("p") {
msg += " Any other signed-in sessions were signed out."
}
return msg
}
func (h *Handlers) submitSettings(w http.ResponseWriter, r *http.Request) {
@@ -188,7 +191,7 @@ func (h *Handlers) submitSettings(w http.ResponseWriter, r *http.Request) {
hash := user.PasswordHash
if repassword {
newHash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
newHash, err := bcrypt.GenerateFromPassword([]byte(password), bcryptCost)
if err != nil {
logf("panel: settings: hashing password failed: %v", err)
h.renderSettings(w, r, http.StatusInternalServerError,
@@ -240,36 +243,24 @@ func (h *Handlers) submitSettings(w http.ResponseWriter, r *http.Request) {
}
logf("panel: user %d settings updated (username: %t, password: %t, dmarc email: %t, retention: %t)", user.ID, renaming, repassword, emailChanging, retentionChanging)
http.Redirect(w, r, "/settings?updated="+updatedFlag(renaming, repassword, emailChanging, retentionChanging), http.StatusSeeOther)
http.Redirect(w, r, "/settings?"+updatedQuery(renaming, repassword, emailChanging, retentionChanging), http.StatusSeeOther)
}
func updatedFlag(renamed, repassword, emailChanged, retentionChanged bool) string {
changed := 0
func updatedQuery(renamed, repassword, emailChanged, retentionChanged bool) string {
var params []string
if renamed {
changed++
params = append(params, "u=1")
}
if repassword {
changed++
params = append(params, "p=1")
}
if emailChanged {
changed++
params = append(params, "e=1")
}
if retentionChanged {
changed++
}
if changed > 1 {
return "all"
}
switch {
case renamed:
return "username"
case repassword:
return "password"
case emailChanged:
return "email"
default:
return "retention"
params = append(params, "r=1")
}
return strings.Join(params, "&")
}
// sendLogRetentionDays returns the effective delivery-journal retention window.
+7 -11
View File
@@ -171,7 +171,7 @@ func (h *Handlers) submitUserCreate(w http.ResponseWriter, r *http.Request) {
return
}
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcryptCost)
if err != nil {
logf("panel: create user hash: %v", err)
h.renderUserForm(w, r, http.StatusInternalServerError, 0, userFormView{FormErr: "Internal error. Please try again."})
@@ -225,15 +225,11 @@ func (h *Handlers) submitUserUpdate(w http.ResponseWriter, r *http.Request, u st
if u.Role == store.RoleGlobal && role == store.RoleDomainAdmin {
n, err := h.store.CountGlobalUsers()
if err != nil || n <= 1 {
h.renderUserForm(w, r, http.StatusBadRequest, u.ID, userFormView{FormErr: "Cannot demote the last global administrator.", FormUsername: username, FormRole: string(u.Role), FormDomains: selected})
return
}
}
if u.ID == p.ID && u.Role == store.RoleGlobal && role == store.RoleDomainAdmin {
n, err := h.store.CountGlobalUsers()
if err != nil || n <= 1 {
h.renderUserForm(w, r, http.StatusBadRequest, u.ID, userFormView{FormErr: "You cannot demote yourself without another global administrator.", FormUsername: username, FormRole: string(u.Role), FormDomains: selected})
msg := "Cannot demote the last global administrator."
if u.ID == p.ID {
msg = "You cannot demote yourself without another global administrator."
}
h.renderUserForm(w, r, http.StatusBadRequest, u.ID, userFormView{FormErr: msg, FormUsername: username, FormRole: string(u.Role), FormDomains: selected})
return
}
}
@@ -244,7 +240,7 @@ func (h *Handlers) submitUserUpdate(w http.ResponseWriter, r *http.Request, u st
h.renderUserForm(w, r, http.StatusBadRequest, u.ID, userFormView{FormErr: err.Error(), FormUsername: username, FormRole: string(role), FormDomains: selected})
return
}
newHash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
newHash, err := bcrypt.GenerateFromPassword([]byte(password), bcryptCost)
if err != nil {
logf("panel: update user hash: %v", err)
h.renderUserForm(w, r, http.StatusInternalServerError, u.ID, userFormView{FormErr: "Internal error. Please try again.", FormUsername: username, FormRole: string(role), FormDomains: selected})
+7
View File
@@ -0,0 +1,7 @@
package handlers
import "github.com/mixeme/selfpost/internal/web/auth"
// bcryptCost is the panel-wide password work factor; see auth.BcryptCost for
// why it lives in one place.
const bcryptCost = auth.BcryptCost
-103
View File
@@ -3,8 +3,6 @@ package validate
import (
"fmt"
"net"
"strconv"
"strings"
"unicode"
)
@@ -148,104 +146,3 @@ func Email(addr string) error {
}
return nil
}
const maxHostLen = 253
// NormalizeHost trims, lower-cases, and strips wrapping IPv6 brackets so the
// stored value is a bare hostname or IP, safe to wrap again when writing maps.
func NormalizeHost(host string) string {
host = strings.ToLower(strings.TrimSpace(host))
if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
host = host[1 : len(host)-1]
}
return host
}
// Host enforces a whitelist for an upstream hostname or IP (security.md): a
// dotted domain, a single DNS label (LAN names), or an IPv4/IPv6 address.
func Host(host string) error {
if host == "" {
return fmt.Errorf("host is required")
}
if len(host) > maxHostLen {
return fmt.Errorf("host must be at most %d characters", maxHostLen)
}
if ip := net.ParseIP(host); ip != nil {
return nil
}
labels := strings.Split(host, ".")
for _, label := range labels {
if err := domainLabel(label); err != nil {
return fmt.Errorf("host is invalid: %w", err)
}
}
return nil
}
// Port checks a TCP port number parsed from form input.
func Port(raw string) (int, error) {
raw = strings.TrimSpace(raw)
if raw == "" {
return 0, fmt.Errorf("port is required")
}
n, err := strconv.Atoi(raw)
if err != nil || n < 1 || n > 65535 {
return 0, fmt.Errorf("port must be between 1 and 65535")
}
return n, nil
}
// TLSMode checks a Postfix smtp_tls_policy_maps level.
func TLSMode(mode string) error {
switch mode {
case "may", "encrypt", "none":
return nil
default:
return fmt.Errorf("invalid TLS mode")
}
}
// RecipientMode checks an inbound-domain recipient policy.
func RecipientMode(mode string) error {
switch mode {
case "list", "any":
return nil
default:
return fmt.Errorf("invalid recipient mode")
}
}
// MailboxInDomain checks that addr is a conservative mailbox on domain
// (security.md). domain must already be normalised.
func MailboxInDomain(addr, domain string) error {
at := strings.LastIndexByte(addr, '@')
if at <= 0 || at >= len(addr)-1 {
return fmt.Errorf("%q is not a valid email address", addr)
}
local, host := addr[:at], addr[at+1:]
if host != domain {
return fmt.Errorf("%q does not belong to domain %s", addr, domain)
}
if err := mailboxLocalPart(local); err != nil {
return fmt.Errorf("%q: %w", addr, err)
}
return nil
}
func mailboxLocalPart(local string) error {
if local == "" {
return fmt.Errorf("missing the part before '@'")
}
if local[0] == '.' || local[len(local)-1] == '.' {
return fmt.Errorf("local part must not start or end with '.'")
}
for i := 0; i < len(local); i++ {
c := local[i]
lower := c >= 'a' && c <= 'z'
digit := c >= '0' && c <= '9'
if !lower && !digit && c != '.' && c != '-' && c != '_' && c != '+' {
return fmt.Errorf("local part may contain only lower-case letters, digits, '.', '-', '_' and '+'")
}
}
return nil
}
@@ -15,4 +15,19 @@ func TestValidateEmail(t *testing.T) {
if err := Email("x@gmail.com"); err == nil {
t.Error("gmail accepted")
}
if err := Email("reports+rua@mail.example.com"); err != nil {
t.Errorf("plus-address valid: %v", err)
}
if err := Email("bad space@mail.example.com"); err == nil {
t.Error("address with space accepted")
}
if err := Email("привет@mail.example.com"); err == nil {
t.Error("non-ascii local-part accepted")
}
if err := Email("x@-example.com"); err == nil {
t.Error("invalid domain accepted")
}
if err := Email("x@protonmail.com"); err == nil {
t.Error("blocked freemail domain accepted")
}
}
-66
View File
@@ -65,69 +65,3 @@ func TestValidateDomainLongLabelRejected(t *testing.T) {
t.Error("expected error for over-long label")
}
}
func TestHostValid(t *testing.T) {
valid := []string{
"10.0.0.8",
"192.0.2.20",
"2001:db8::1",
"mail.internal.example",
"mx1",
"mail-1.lan",
}
for _, h := range valid {
if err := Host(h); err != nil {
t.Errorf("Host(%q) unexpected error: %v", h, err)
}
}
}
func TestHostInvalid(t *testing.T) {
invalid := []string{
"",
"exa mple",
"host/name",
"host;rm",
"-bad",
"bad-",
"host\nname",
}
for _, h := range invalid {
if err := Host(h); err == nil {
t.Errorf("Host(%q) = nil, want error", h)
}
}
}
func TestNormalizeHostStripsIPv6Brackets(t *testing.T) {
if got := NormalizeHost(" [2001:DB8::1] "); got != "2001:db8::1" {
t.Errorf("NormalizeHost IPv6 = %q", got)
}
if got := NormalizeHost("Mail.Example.COM"); got != "mail.example.com" {
t.Errorf("NormalizeHost hostname = %q", got)
}
}
func TestPort(t *testing.T) {
n, err := Port("25")
if err != nil || n != 25 {
t.Fatalf("Port(25) = %d, %v", n, err)
}
for _, raw := range []string{"", "0", "65536", "abc", "-1"} {
if _, err := Port(raw); err == nil {
t.Errorf("Port(%q) = nil, want error", raw)
}
}
}
func TestMailboxInDomain(t *testing.T) {
if err := MailboxInDomain("staff@lists.example.com", "lists.example.com"); err != nil {
t.Fatal(err)
}
if err := MailboxInDomain("staff@other.com", "lists.example.com"); err == nil {
t.Fatal("expected domain mismatch error")
}
if err := MailboxInDomain("bad addr@lists.example.com", "lists.example.com"); err == nil {
t.Fatal("expected local-part error")
}
}
+36
View File
@@ -824,3 +824,39 @@ html:has(#help-export:checked) .help-pane-export { display: block; }
@media (max-width: 66rem) {
.help-drawer { width: 100vw; }
}
/* DMARC pages: paired cards side by side, same layout as .split but for two
summary cards at the top of a page. */
.pair {
display: grid; grid-template-columns: repeat(auto-fit, minmax(18rem, 1fr));
gap: 1.2rem; margin-top: 1.2rem;
}
.pair > .card { margin-left: 0; margin-right: 0; min-width: 0; }
.pair > .card + .card { margin-top: 0; }
/* Attention card: elevated border when a DMARC report has failures. */
.card.attn { border-color: var(--st-warn-fg); }
/* Responsive visibility: hide elements on narrow/wide screens. */
.desk-only { display: revert; }
.phone-only, .phone-list { display: none; }
@media (max-width: 48rem) {
.desk-only { display: none !important; }
.phone-only, .phone-list { display: revert !important; }
}
.phone-list { list-style: none; margin: 0; padding: 0; }
.phone-list li { border-bottom: 1px solid var(--border); }
.phone-list li:last-child { border-bottom: none; }
.phone-list a {
display: grid; grid-template-columns: auto 1fr; gap: 0.15rem 0.6rem;
padding: 0.7rem 0; text-decoration: none; color: inherit;
}
.phone-list .when { grid-column: 1; font-family: var(--font-mono); font-size: 0.75rem; color: var(--muted); }
.phone-list .meta { grid-column: 2; font-size: 0.85rem; }
.phone-list .subj { grid-column: 1 / -1; font-size: 0.85rem; color: var(--muted); }
/* Checkbox-label row inside a form (IP restriction toggle). */
.check-row {
display: flex; align-items: center; gap: 0.5rem;
margin: 0.5rem 0; cursor: pointer;
}
@@ -330,8 +330,11 @@
<div class="check-col">
<p class="check-col-title">Client IP allow-list
{{if .AuthIPRestrict}}<span class="st st-ok">active</span>{{else}}<span class="st st-unknown">off</span>{{end}}</p>
<p class="muted">When enabled, only these addresses may authenticate
and submit mail as this application. When off, any client IP is allowed.</p>
<p class="muted">When enabled, only these addresses may submit mail as
this application; a login from anywhere else is refused with a 4xx at
<code>MAIL FROM</code>. When off, any client IP is allowed. Like the
level-2 rate limit this runs in the journal-milter and is fail-open —
it is a sending control, not an authentication boundary.</p>
<form method="post" action="/applications/{{.ID}}/authips">
<label class="check-row">
<input type="checkbox" name="auth_ip_restrict" value="1"
+1 -1
View File
@@ -32,7 +32,7 @@ on the card itself.</p>
</ul>
<p class="muted">Topics marked as labels open the same text in the help
drawer. For installation, backup, and environment variables see the
<a href="https://github.com/mixeme/selfpost/blob/main/docs/guide.md">operator
<a href="{{.SourceURL}}/blob/main/docs/guide.md">operator
guide</a> in the repository.</p>
</div>
+8 -5
View File
@@ -21,14 +21,14 @@
{{end}}
{{define "help_drawer"}}
<label class="help-scrim" for="help-off"></label>
<label class="help-scrim" for="help-off" role="button" aria-label="Close help"></label>
<aside class="help-drawer">
<label class="help-close" for="help-off">Close</label>
<label class="help-close" for="help-off" role="button" aria-label="Close help">Close</label>
<article class="help-pane help-pane-index">
<h2>Help</h2>
<p>Short notes for the card you opened — not a second copy of the
<a href="https://github.com/mixeme/selfpost/blob/main/docs/guide.md">operator guide</a>.</p>
<a href="{{.SourceURL}}/blob/main/docs/guide.md">operator guide</a>.</p>
{{if .IsGlobal}}
<p class="muted">Status</p>
<ul class="toc"><li><label for="help-status">Status checks</label></li></ul>
@@ -131,8 +131,11 @@
shown once.</p>
<p>Address mode is which From addresses this application may use: any
address of the domain, or a fixed list. Client IP allow-list, when enabled,
restricts which addresses may authenticate as this application; when off,
any client IP is allowed. The level-2 rate limit <em>overrides</em> the
restricts which client addresses may <em>submit</em> as this application;
when off, any client IP is allowed. It is checked in the journal-milter at
<code>MAIL FROM</code>, alongside the level-2 limit and fail-open like it,
so it narrows sending rather than blocking the SASL login itself. The
level-2 rate limit <em>overrides</em> the
domain limit for that application — you can set a ceiling above or below
the domain (still ≤ level&nbsp;1). Independent of the client IP allow-list.</p>
{{template "help_more" true}}
+16 -16
View File
@@ -9,9 +9,9 @@ import (
"net/http"
"github.com/mixeme/selfpost/internal/app"
"github.com/mixeme/selfpost/internal/dmarc"
"github.com/mixeme/selfpost/internal/dnscheck"
"github.com/mixeme/selfpost/internal/domain"
"github.com/mixeme/selfpost/internal/dmarc"
"github.com/mixeme/selfpost/internal/health"
"github.com/mixeme/selfpost/internal/inbound"
"github.com/mixeme/selfpost/internal/legal"
@@ -118,21 +118,21 @@ func New(st *store.Store, domains *domain.Service, apps *app.Service, inboundSvc
TrustedProxyCIDRs: cfg.TrustedProxyCIDRs,
}, v, setupTokenPath)
h := handlers.New(st, domains, apps, inboundSvc, dmarcSvc, handlers.Config{
Hostname: cfg.Hostname,
SubmissionEnabled: cfg.SubmissionEnabled,
MailLogPath: cfg.MailLogPath,
DataDir: cfg.DataDir,
DBPath: cfg.DBPath,
DeployRoot: cfg.DeployRoot,
Version: cfg.Version,
TLSCertFile: cfg.TLSCertFile,
OpenDKIMSocket: cfg.OpenDKIMSocket,
JournalSocket: cfg.JournalSocket,
RateLimitMessagesPerIP: cfg.RateLimitMessagesPerIP,
RateLimitWindowSeconds: cfg.RateLimitWindowSeconds,
RetryPolicy: cfg.RetryPolicy,
InboundEnabled: cfg.InboundEnabled,
DMARCEnabled: cfg.DMARCEnabled,
Hostname: cfg.Hostname,
SubmissionEnabled: cfg.SubmissionEnabled,
MailLogPath: cfg.MailLogPath,
DataDir: cfg.DataDir,
DBPath: cfg.DBPath,
DeployRoot: cfg.DeployRoot,
Version: cfg.Version,
TLSCertFile: cfg.TLSCertFile,
OpenDKIMSocket: cfg.OpenDKIMSocket,
JournalSocket: cfg.JournalSocket,
RateLimitMessagesPerIP: cfg.RateLimitMessagesPerIP,
RateLimitWindowSeconds: cfg.RateLimitWindowSeconds,
RetryPolicy: cfg.RetryPolicy,
InboundEnabled: cfg.InboundEnabled,
DMARCEnabled: cfg.DMARCEnabled,
SendLogRetentionEnvDefault: cfg.SendLogRetentionEnvDefault,
}, v, dnscheck.New(cfg.DNSResolvers), &health.MachineSampler{}, a)
return &Server{cfg: cfg, auth: a, handlers: h}, nil