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
+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