Files
selfpost/internal/web/handlers/handlers_settings_test.go
T
mixandClaude Opus 5.5 b2fbe91de9 panel-redesign: security review of 2.0 - sessions belong to a user by id
Stage 3, step 2. Reviewed by Fable (read-only), fixed by Sonnet with a
failing test before each fix, checked by Opus. No Critical or High
finding: route authorization, tenant isolation by id, the /server/
subtree guard, output encoding and the origin check were found sound.

Fixed
  - M1: a session was keyed by user name and had no link to the user. A
    deleted or renamed user's cookie stayed alive (renewed on every hit,
    before the user was looked up) and became a session of whoever was
    later created under that name, with that account's role. The
    baseline now has sessions.user_id REFERENCES users(id) ON DELETE
    CASCADE; the principal is resolved by id and a session is renewed
    only after its user was found. RenameSession is gone.
  - M2: any user's password change deleted every other user's sessions.
    It ends that user's other sessions only.
  - L1: a password set on the user form ends that user's sessions (an
    administrator editing their own account keeps the current one).
  - L2: store, saslpasswd2 and Postfix reload errors were shown verbatim
    on the application form, the inbound upstream / recipients forms and
    the limit recalculation - pages a domain administrator reaches.
    Validation errors (app.ValidationError, inbound.ValidationError,
    store.ErrNotAutoRateLimit) keep their text; anything else is logged
    and shown as "Could not save ... Check the logs and try again."
  - L3: store.ListDMARCReports treated an empty domain list as "all". It
    takes a scope now (AllDomains or a list; an empty list is no rows),
    and the DMARC hub is open to the domain role as the plan says: the
    reports of the assigned domains, without the instance-wide ingest
    box. The menu entry was already shown to them and led to a 404.
  - I1: /static/ answered with a listing of the embedded assets. A path
    that is not a known asset is a 404.

Consequences
  - The global DMARC hub lists reports of domains that were deleted
    since, too.
  - dev/migrate1x (not in the tree) no longer carries sessions over:
    everyone signs in again after the transfer.
  - docs/schema-migrations.md: the sessions row.

Recorded, not changed - for the owner:
  - L4: the report-address select names the followed user and their
    address to every administrator of the domain, by default the global
    administrator's login name. The plan asks for it.
  - L5: a delegated inbound upstream may be any host and port, loopback
    and private ranges included - within the trusted-operator model; to
    be listed among the accepted risks in security.md.
  - L6: Account's profile is saved without the password; becomes a
    requirement once password-reset mails to users.email.
  - Still echoing an error's text: backup and domain import (global
    only), the domain form's validation messages.

Not checked by the review: anything needing the container (e2e, real
Postfix / DNS), CSP behaviour in a live browser.

  go test -count=1 ./internal/web/... ./internal/store/... ./internal/app/...
    ./internal/inbound/... ./internal/dmarc/... ./cmd/panel
      ok  (all eleven packages; dev/migrate1x also ok)

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

126 lines
4.2 KiB
Go

package handlers
import (
"net/http"
"net/url"
"path/filepath"
"strings"
"testing"
"github.com/mixeme/selfpost/internal/dnscheck"
"github.com/mixeme/selfpost/internal/store"
"github.com/mixeme/selfpost/internal/web/auth"
"golang.org/x/crypto/bcrypt"
)
func TestSettingsPageShowsSendLogRetention(t *testing.T) {
h, _ := settingsServer(t)
if err := h.store.SetSendLogRetentionDays(45); err != nil {
t.Fatalf("SetSendLogRetentionDays: %v", err)
}
out := getBody(t, h.HandleServerSettings, "/server/settings")
for _, want := range []string{
`name="send_log_retention_days"`,
`value="45"`,
"Keep outbound log rows, days",
"Save settings",
`action="/server/settings"`,
`id="rate-limits"`,
} {
if !strings.Contains(out, want) {
t.Errorf("settings page missing %q:\n%s", want, out)
}
}
// What belongs to a user is not on the instance's page.
for _, gone := range []string{`name="current_password"`, `name="username"`, `name="dmarc_default"`} {
if strings.Contains(out, gone) {
t.Errorf("the instance settings page still carries the user's %s", gone)
}
}
}
// The instance settings ask for no password: they are the server's, and the
// page is behind the global role.
func TestSubmitSettingsSavesSendLogRetention(t *testing.T) {
h, _ := settingsServer(t)
rec := postFormAs(h.HandleServerSettings, globalPrincipal, "/server/settings", nil, url.Values{"send_log_retention_days": {"120"}})
if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/server/settings?saved=1" {
t.Fatalf("POST /server/settings = %d to %q, want 303:\n%s", rec.Code, rec.Header().Get("Location"), rec.Body.String())
}
got, err := h.store.GetSendLogRetentionDays(90)
if err != nil {
t.Fatalf("GetSendLogRetentionDays: %v", err)
}
if got != 120 {
t.Fatalf("retention = %d, want 120", got)
}
}
func TestSubmitSettingsRejectsOutOfRangeRetention(t *testing.T) {
h, _ := settingsServer(t)
for _, bad := range []string{"3", "nine", ""} {
rec := postFormAs(h.HandleServerSettings, globalPrincipal, "/server/settings", nil, url.Values{"send_log_retention_days": {bad}})
if rec.Code != http.StatusBadRequest {
t.Fatalf("POST /server/settings (%q) = %d, want 400:\n%s", bad, rec.Code, rec.Body.String())
}
}
rec := postFormAs(h.HandleServerSettings, globalPrincipal, "/server/settings", nil, url.Values{"send_log_retention_days": {"3"}})
if !strings.Contains(rec.Body.String(), "between 7 and 365") {
t.Errorf("expected range error in body:\n%s", rec.Body.String())
}
if got, _ := h.store.GetSendLogRetentionDays(90); got != 90 {
t.Errorf("a refused value changed the retention to %d", got)
}
}
func TestServerSettingsIsGlobalOnly(t *testing.T) {
h, _ := settingsServer(t)
d, err := h.store.AddDomain("example.com", "mail")
if err != nil {
t.Fatal(err)
}
p := domainAdmin(t, h.store, "ops", d.ID)
if rec := postFormAs(h.HandleServerSettings, p, "/server/settings", nil, url.Values{"send_log_retention_days": {"120"}}); rec.Code != http.StatusNotFound {
t.Errorf("POST /server/settings as a domain administrator = %d, want 404", rec.Code)
}
if got, _ := h.store.GetSendLogRetentionDays(90); got != 90 {
t.Errorf("a domain administrator changed the retention to %d", got)
}
}
func settingsServer(t *testing.T) (*Handlers, string) {
t.Helper()
return settingsServerAt(t, filepath.Join(t.TempDir(), "test.db"))
}
// settingsServerAt is settingsServer over a database at a path the test knows,
// for the tests that break the database from outside.
func settingsServerAt(t *testing.T, dbPath string) (*Handlers, string) {
t.Helper()
st, err := store.Open(dbPath)
if err != nil {
t.Fatalf("open store: %v", err)
}
t.Cleanup(func() { _ = st.Close() })
const password = "correct-password-here!"
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.MinCost)
if err != nil {
t.Fatalf("hash password: %v", err)
}
if _, err := st.CreateUser("admin", string(hash), store.RoleGlobal, store.Reach{}); err != nil {
t.Fatalf("create user: %v", err)
}
v := mustView(t)
a := auth.New(st, auth.Config{}, v, filepath.Join(t.TempDir(), "setup-token"))
return &Handlers{
store: st,
view: v,
auth: a,
dns: dnscheck.New(nil),
cfg: Config{SendLogRetentionEnvDefault: 90},
}, password
}