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>
This commit is contained in:
mix
2026-10-10 03:04:02 +03:00
co-authored by Claude Opus 5.5
parent 32c6ae98a1
commit b2fbe91de9
36 changed files with 1035 additions and 196 deletions
+1 -6
View File
@@ -155,11 +155,6 @@ func (h *Handlers) HandleAccountProfile(w http.ResponseWriter, r *http.Request)
fail(http.StatusInternalServerError, "Could not save the profile. Please check the logs and try again.")
return
}
if f.Username != u.Username {
if token, ok := h.auth.SessionToken(r); ok {
h.auth.RenameSession(token, f.Username)
}
}
// The e-mail is the report address of every domain that follows this
// user's "my account e-mail" default.
h.resyncAfterEmailChange(u, f.Email)
@@ -215,7 +210,7 @@ func (h *Handlers) HandleAccountPassword(w http.ResponseWriter, r *http.Request)
return
}
if token, ok := h.auth.SessionToken(r); ok {
h.auth.DestroyOtherSessions(token)
h.auth.DestroyOtherSessions(u.ID, token)
}
logf("panel: user %d changed their password", u.ID)
http.Redirect(w, r, "/account?done=password", http.StatusSeeOther)
+9 -6
View File
@@ -737,18 +737,21 @@ func splitAddresses(s string) []string {
})
}
// applicationErrorMessage turns a service error into a user-facing message,
// passing through the validation errors (which are safe, fixed strings) and
// masking anything unexpected.
// applicationErrorMessage turns a service error into what the form says. A
// validation error is the administrator's to read — it says what to fix — and
// is shown as it is. Anything else is the server's own business (a path, a
// command's output, SQL): it goes to the log and the page gets a fixed line.
func applicationErrorMessage(err error) string {
var validation *app.ValidationError
switch {
case errors.Is(err, store.ErrLoginExists):
return "That login is already in use. Choose another."
case errors.Is(err, store.ErrDomainNotFound), errors.Is(err, store.ErrApplicationNotFound):
return "The item no longer exists."
default:
// Validation errors from the app service are safe to surface verbatim;
// they describe what the admin must fix (login/address rules).
case errors.As(err, &validation):
return err.Error()
default:
logf("panel: application: %v", err)
return "Could not save the application. Check the logs and try again."
}
}
+8 -1
View File
@@ -3,6 +3,7 @@ package handlers
import (
"net/http"
"net/url"
"path/filepath"
"strings"
"testing"
@@ -32,7 +33,13 @@ type appStand struct {
func newAppStand(t *testing.T) appStand {
t.Helper()
h, _ := settingsServer(t)
return newAppStandAt(t, filepath.Join(t.TempDir(), "test.db"))
}
// newAppStandAt is newAppStand over a database at a path the test knows.
func newAppStandAt(t *testing.T, dbPath string) appStand {
t.Helper()
h, _ := settingsServerAt(t, dbPath)
s := appStand{h: h, sasl: map[string]string{}}
sasl := app.NewSASLDB("/data/sasl/sasldb2", "mail.example.org").WithRunner(func(args []string, stdin []byte) error {
login := args[len(args)-1]
@@ -155,8 +155,9 @@ func TestDMARCPagesAreAbsentWithIngestOff(t *testing.T) {
}
// A domain administrator reaches the reports of the domains assigned to them
// and nothing else: not the hub, not another tenant's domain page, not another
// tenant's report. A report that does not exist is the same 404 as one that is
// and nothing else: the hub lists only theirs and does not carry the ingest
// statistics of the whole instance, and another tenant's domain page and report
// are not there. A report that does not exist is the same 404 as one that is
// not theirs.
func TestDMARCPagesStayWithinTheViewersDomains(t *testing.T) {
s := newDMARCStand(t)
@@ -174,22 +175,31 @@ func TestDMARCPagesStayWithinTheViewersDomains(t *testing.T) {
}
ops := domainAdmin(t, s.h.store, "ops", s.d.ID)
// Their own domain and report are theirs; the way back to the hub is not
// offered, since the hub is not theirs.
// The hub is open to them: their own domain's reports, no one else's, and
// not the statistics of the instance's ingest box.
hub := send(s.h.HandleDMARCList, &ops, "GET", "/outbound/dmarc", nil, nil)
if hub.Code != http.StatusOK {
t.Fatalf("hub for its administrator = %d, want 200: %s", hub.Code, hub.Body.String())
}
has(t, "hub for its administrator", hub.Body.String(), `<h1 class="title is-3">DMARC reports</h1>`, `<h2>Recent reports</h2>`,
`<a href="/outbound/dmarc/domains/1">example.org</a>`, `Outlook.com`, `href="/outbound/dmarc/reports/`+idStr(s.reportID)+`"`)
lacks(t, "hub for its administrator", hub.Body.String(), "other.example.net", "google.com",
`/outbound/dmarc/reports/`+idStr(otherReport)+`"`, `<h2>Ingest</h2>`, `dmarc-reports@mail.example.org`,
`parse failure`, `Last report`, `Retention`)
// Their own domain and report are theirs, and so is the way back to the hub.
own := send(s.h.HandleDMARCDomain, &ops, "GET", "/outbound/dmarc/domains/1", map[string]string{"id": "1"}, nil)
if own.Code != http.StatusOK {
t.Fatalf("own domain = %d", own.Code)
}
has(t, "domain for its administrator", own.Body.String(), `<h1 class="title is-3">example.org</h1>`)
lacks(t, "domain for its administrator", own.Body.String(), `<a href="/outbound/dmarc">`)
has(t, "domain for its administrator", own.Body.String(), `<h1 class="title is-3">example.org</h1>`, `<a href="/outbound/dmarc">DMARC reports</a>`)
rep := send(s.h.HandleDMARCReport, &ops, "GET", "/outbound/dmarc/reports/"+idStr(s.reportID), map[string]string{"id": idStr(s.reportID)}, nil)
if rep.Code != http.StatusOK {
t.Fatalf("own report = %d", rep.Code)
}
lacks(t, "report for its administrator", rep.Body.String(), `<a href="/outbound/dmarc">`)
has(t, "report for its administrator", rep.Body.String(), `<a href="/outbound/dmarc">DMARC reports</a>`)
for name, code := range map[string]int{
"hub": send(s.h.HandleDMARCList, &ops, "GET", "/outbound/dmarc", nil, nil).Code,
"another tenant's domain": send(s.h.HandleDMARCDomain, &ops, "GET", "/outbound/dmarc/domains/"+idStr(other.ID),
map[string]string{"id": idStr(other.ID)}, nil).Code,
"another tenant's report": send(s.h.HandleDMARCReport, &ops, "GET", "/outbound/dmarc/reports/"+idStr(otherReport),
@@ -202,3 +212,32 @@ func TestDMARCPagesStayWithinTheViewersDomains(t *testing.T) {
}
}
}
// A domain administrator with no outbound domain is not shown every tenant's
// reports because their own list is empty: the hub has no rows, and no error.
func TestDMARCHubForAnAdministratorWithoutOutboundDomains(t *testing.T) {
s := newDMARCStand(t)
nobody := domainAdmin(t, s.h.store, "nobody")
rec := send(s.h.HandleDMARCList, &nobody, "GET", "/outbound/dmarc", nil, nil)
if rec.Code != http.StatusOK {
t.Fatalf("hub = %d, want 200: %s", rec.Code, rec.Body.String())
}
has(t, "hub", rec.Body.String(), `No reports yet.`)
lacks(t, "hub", rec.Body.String(), "example.org", "Outlook.com", `<table`, `<h2>Ingest</h2>`)
}
// The global role sees the ingest box and every report, including those of a
// domain that has since been removed.
func TestDMARCHubForTheGlobalRoleSeesEverything(t *testing.T) {
s := newDMARCStand(t)
if _, err := s.h.store.InsertDMARCReport(store.DMARCReport{
Domain: "gone.example.net", Reporter: "yahoo.com", ReportID: "gone", ReceivedAt: time.Now(),
PeriodBegin: time.Now().Add(-24 * time.Hour), PeriodEnd: time.Now(), PassCount: 3,
}); err != nil {
t.Fatal(err)
}
body := getBody(t, s.h.HandleDMARCList, "/outbound/dmarc")
has(t, "hub", body, `<h2>Ingest</h2>`, `<h2>Recent reports</h2>`, `example.org`, `Outlook.com`, `gone.example.net`, `yahoo.com`)
}
+21 -16
View File
@@ -38,13 +38,13 @@ func (h *Handlers) canViewDMARCDomain(p auth.Principal, d store.Domain) bool {
return p.CanAccessDomain(d.ID)
}
// HandleDMARCList is the global DMARC reports index.
// HandleDMARCList is the DMARC reports hub. The global role sees every report
// and the ingest statistics of the instance; a domain administrator sees the
// reports of the sending domains assigned to them, and no ingest statistics
// (the box describes the whole instance: its mailbox, its failures).
func (h *Handlers) HandleDMARCList(w http.ResponseWriter, r *http.Request) {
p, ok := h.requireDMARC(w, r)
if !ok || !p.IsGlobal() {
if ok && !p.IsGlobal() {
http.NotFound(w, r)
}
if !ok {
return
}
assigned, err := h.assignedDomains(p)
@@ -53,24 +53,18 @@ func (h *Handlers) HandleDMARCList(w http.ResponseWriter, r *http.Request) {
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
names := make([]string, 0, len(assigned))
scope := store.DMARCReportScope{AllDomains: p.IsGlobal()}
domainIDs := make(map[string]int64, len(assigned))
for _, d := range assigned {
names = append(names, d.Name)
scope.Domains = append(scope.Domains, d.Name)
domainIDs[d.Name] = d.ID
}
reports, err := h.store.ListDMARCReports(names, 100)
reports, err := h.store.ListDMARCReports(scope, 100)
if err != nil {
logf("panel: dmarc list: %v", err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
stats, err := h.store.DMARCIngestStats()
if err != nil {
logf("panel: dmarc ingest stats: %v", err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
rows := make([]view.DMARCReportRow, len(reports))
for i, rep := range reports {
rows[i] = dmarcRow(rep)
@@ -78,6 +72,17 @@ func (h *Handlers) HandleDMARCList(w http.ResponseWriter, r *http.Request) {
rows[i].DomainHref = view.DMARCDomainHref(id)
}
}
if !p.IsGlobal() {
page := view.NewDMARCHub(h.shellMeta(r), view.IngestInput{}).WithoutIngest().WithReports(rows)
h.view.Render(w, http.StatusOK, "dmarc", page)
return
}
stats, err := h.store.DMARCIngestStats()
if err != nil {
logf("panel: dmarc ingest stats: %v", err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
in := view.IngestInput{
OK: stats.IngestOK, KeptThisWeek: stats.KeptThisWeek, ParseFailures: stats.ParseFailures,
Hosted: h.dmarc.DefaultHostedSuggestion(), Host: h.cfg.Hostname,
@@ -135,7 +140,7 @@ func (h *Handlers) HandleDMARCDomain(w http.ResponseWriter, r *http.Request) {
Source: s.SourceIP, ThisRelay: relay[s.SourceIP], Pass: s.PassCount, Fail: s.FailCount, Disposition: s.Disposition,
}
}
page := view.NewDMARCDomain(h.shellMeta(r), d.ID, d.Name, p.IsGlobal(), pass, fail, windowDays,
page := view.NewDMARCDomain(h.shellMeta(r), d.ID, d.Name, true, pass, fail, windowDays,
dmarc.TightenPolicyHint(pass, fail, hints)).
WithSources(sourceRows).WithReports(reportRows)
h.view.Render(w, http.StatusOK, "dmarc-domain", page)
@@ -198,7 +203,7 @@ func (h *Handlers) HandleDMARCReport(w http.ResponseWriter, r *http.Request) {
Received: rep.ReceivedAt.UTC().Format("2006-01-02 15:04") + " UTC",
PolicyP: rep.PolicyP, PolicySP: rep.PolicySP, PolicyPct: rep.PolicyPct,
PolicyADKIM: rep.PolicyADKIM, PolicyASPF: rep.PolicyASPF, Recipient: rep.Recipient,
Hub: p.IsGlobal(),
Hub: true,
}).WithRecords(records)
h.view.Render(w, http.StatusOK, "dmarc-report", page)
}
@@ -0,0 +1,208 @@
package handlers
import (
"database/sql"
"errors"
"net/http"
"net/url"
"path/filepath"
"strings"
"testing"
"github.com/mixeme/selfpost/internal/app"
"github.com/mixeme/selfpost/internal/inbound"
"github.com/mixeme/selfpost/internal/postfix"
"github.com/mixeme/selfpost/internal/store"
)
// A page that a domain administrator sees says what is wrong with what they
// typed. It never says what went wrong inside the server: paths, SQL, the
// output of a command. Those go to the log, and the page gets a fixed line.
// leak is a stand-in for internal detail that must never reach a page.
const leak = "secret-internal-detail"
const savedElsewhere = "Check the logs and try again."
type failingSenderMaps struct{}
func (failingSenderMaps) RebuildSenderLoginMaps([]postfix.Binding) error {
return errors.New("write /srv/" + leak + "/sender_login_maps: permission denied")
}
type failingInboundMaps struct{}
func (failingInboundMaps) RebuildInboundMaps([]postfix.InboundRoute) error {
return errors.New("postmap /srv/" + leak + "/transport_maps: exit status 1")
}
// breakDatabase makes the statements fail inside SQLite with an error that
// carries the leak, as a real storage failure would carry its own detail.
func breakDatabase(t *testing.T, dbPath string, triggers ...string) {
t.Helper()
db, err := sql.Open("sqlite", "file:"+dbPath+"?_pragma=busy_timeout(5000)")
if err != nil {
t.Fatalf("open database directly: %v", err)
}
defer db.Close()
for _, stmt := range triggers {
if _, err := db.Exec(stmt); err != nil {
t.Fatalf("%s: %v", stmt, err)
}
}
}
// refusal checks a refused request: the status it has today, none of the
// internal detail, and the fixed line in its place.
func refusal(t *testing.T, what, body string, wantCode, code int) {
t.Helper()
shown := noticeOf(body)
if code != wantCode {
t.Errorf("%s = %d, want %d; page says %q", what, code, wantCode, shown)
}
if strings.Contains(body, leak) {
t.Errorf("%s shows internal detail; page says %q", what, shown)
}
if !strings.Contains(body, savedElsewhere) {
t.Errorf("%s does not give the fixed line %q; page says %q", what, savedElsewhere, shown)
}
}
// noticeOf is the text of the page's refusal notice, for failure messages.
func noticeOf(body string) string {
for _, line := range strings.Split(body, "\n") {
if strings.Contains(line, "ti-alert-circle") {
return strings.TrimSpace(line)
}
}
return "(no notice)"
}
func TestApplicationFormDoesNotEchoInternalErrors(t *testing.T) {
path := filepath.Join(t.TempDir(), "test.db")
s := newAppStandAt(t, path)
working := s.h.apps
a, _, err := working.CreateWithSettings(s.d.ID, "prod-server", app.Settings{Mode: store.AddressModeWildcard}, nil)
if err != nil {
t.Fatal(err)
}
paths := map[string]string{"id": idStr(s.d.ID), "aid": idStr(a.ID)}
// The reload of the Postfix maps fails.
sasl := app.NewSASLDB("/data/sasl/sasldb2", "mail.example.org").WithRunner(func([]string, []byte) error { return nil })
s.h.apps = app.NewService(s.h.store, sasl, failingSenderMaps{})
rec := postFormAs(s.h.HandleApplicationCreate, globalPrincipal, "/outbound/domains/1/applications/new", s.paths,
url.Values{"login": {"new-server"}, "mode": {"wildcard"}})
refusal(t, "create when the reload fails", rec.Body.String(), http.StatusBadRequest, rec.Code)
rec = postFormAs(s.h.HandleApplicationSave, globalPrincipal, "/outbound/domains/1/applications/1", paths,
url.Values{"mode": {"wildcard"}})
refusal(t, "save when the reload fails", rec.Body.String(), http.StatusBadRequest, rec.Code)
// The database fails.
s.h.apps = working
breakDatabase(t, path, `CREATE TRIGGER boom BEFORE UPDATE ON applications BEGIN SELECT RAISE(ABORT, '`+leak+`'); END`)
rec = postFormAs(s.h.HandleApplicationSave, globalPrincipal, "/outbound/domains/1/applications/1", paths,
url.Values{"mode": {"wildcard"}})
refusal(t, "save when the database fails", rec.Body.String(), http.StatusBadRequest, rec.Code)
}
// What the administrator typed wrong is still said in full.
func TestApplicationFormStillShowsValidationMessages(t *testing.T) {
s := newAppStand(t)
a, _, err := s.h.apps.CreateWithSettings(s.d.ID, "prod-server", app.Settings{Mode: store.AddressModeWildcard}, nil)
if err != nil {
t.Fatal(err)
}
paths := map[string]string{"id": idStr(s.d.ID), "aid": idStr(a.ID)}
for name, tc := range map[string]struct {
url.Values
want string
}{
"a bad login": {url.Values{"login": {"has space"}, "mode": {"wildcard"}}, "login may contain only letters, digits"},
"another domain's one": {url.Values{"login": {"other-app"}, "mode": {"list"}, "addresses": {"a@evil.example"}}, "does not belong to domain example.org"},
"a taken login": {url.Values{"login": {"prod-server"}, "mode": {"wildcard"}}, "That login is already in use"},
} {
rec := postFormAs(s.h.HandleApplicationCreate, globalPrincipal, "/outbound/domains/1/applications/new", s.paths, tc.Values)
if !strings.Contains(rec.Body.String(), tc.want) {
t.Errorf("create with %s does not say %q:\n%s", name, tc.want, rec.Body.String())
}
}
rec := postFormAs(s.h.HandleApplicationSave, globalPrincipal, "/outbound/domains/1/applications/1", paths,
url.Values{"mode": {"list"}, "addresses": {"a@evil.example"}})
if !strings.Contains(rec.Body.String(), "does not belong to domain example.org") {
t.Errorf("save with another domain's address does not say so:\n%s", rec.Body.String())
}
}
func TestInboundFormsDoNotEchoInternalErrors(t *testing.T) {
h, st := inboundHandlers(t)
d, err := st.AddInboundDomain("lists.example.com")
if err != nil {
t.Fatal(err)
}
h.inbound = inbound.NewService(st, failingInboundMaps{})
id := itoa(d.ID)
rec := inboundCall(h, http.MethodPost, "/inbound/domains/"+id+"/upstream",
url.Values{"host": {"10.0.0.8"}, "port": {"25"}, "tls_mode": {"encrypt"}}, globalPrincipal)
refusal(t, "upstream when the reload fails", rec.Body.String(), http.StatusBadRequest, rec.Code)
rec = inboundCall(h, http.MethodPost, "/inbound/domains/"+id+"/recipients",
url.Values{"recipient_mode": {"any"}}, globalPrincipal)
refusal(t, "recipients when the reload fails", rec.Body.String(), http.StatusBadRequest, rec.Code)
}
func TestInboundFormsStillShowValidationMessages(t *testing.T) {
h, st := inboundHandlers(t)
d, err := st.AddInboundDomain("lists.example.com")
if err != nil {
t.Fatal(err)
}
id := itoa(d.ID)
for name, tc := range map[string]struct {
target string
form url.Values
want string
}{
"a bad host": {"/upstream", url.Values{"host": {"bad host!"}, "port": {"25"}, "tls_mode": {"may"}}, "host is invalid"},
"a bad port": {"/upstream", url.Values{"host": {"10.0.0.8"}, "port": {"99999"}, "tls_mode": {"may"}}, "port must be between 1 and 65535"},
"a bad TLS mode": {"/upstream", url.Values{"host": {"10.0.0.8"}, "port": {"25"}, "tls_mode": {"sometimes"}}, "invalid TLS mode"},
"another domain": {"/recipients", url.Values{"recipient_mode": {"list"}, "addresses": {"abuse@other.com"}}, "does not belong to domain lists.example.com"},
"an empty list": {"/recipients", url.Values{"recipient_mode": {"list"}}, "requires at least one address"},
"an unknown mode": {"/recipients", url.Values{"recipient_mode": {"some"}}, "invalid recipient mode"},
} {
rec := inboundCall(h, http.MethodPost, "/inbound/domains/"+id+tc.target, tc.form, globalPrincipal)
if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), tc.want) {
t.Errorf("%s = %d, does not say %q:\n%s", name, rec.Code, tc.want, rec.Body.String())
}
}
}
func TestRecalculationDoesNotEchoInternalErrors(t *testing.T) {
path := filepath.Join(t.TempDir(), "test.db")
s := newAppStandAt(t, path)
a, _, err := s.h.apps.CreateWithSettings(s.d.ID, "prod-server", app.Settings{Mode: store.AddressModeWildcard}, nil)
if err != nil {
t.Fatal(err)
}
for scope, ref := range map[string]int64{store.RateLimitScopeDomain: s.d.ID, store.RateLimitScopeApp: a.ID} {
rl := store.RateLimit{Scope: scope, RefID: ref, Mode: store.RateLimitModeAuto, AutoMultiplier: store.DefaultAutoMultiplier, WindowSeconds: 3600}
if err := s.h.store.SetRateLimit(rl); err != nil {
t.Fatal(err)
}
}
breakDatabase(t, path,
`CREATE TRIGGER boom_insert BEFORE INSERT ON rate_limits BEGIN SELECT RAISE(ABORT, '`+leak+`'); END`,
`CREATE TRIGGER boom_update BEFORE UPDATE ON rate_limits BEGIN SELECT RAISE(ABORT, '`+leak+`'); END`)
rec := postFormAs(s.h.HandleDomainRateLimitRecalc, globalPrincipal, "/outbound/domains/1/settings/ratelimit/recalc", s.paths, url.Values{})
refusal(t, "domain recalculation when the database fails", rec.Body.String(), http.StatusBadRequest, rec.Code)
paths := map[string]string{"id": idStr(s.d.ID), "aid": idStr(a.ID)}
rec = postFormAs(s.h.HandleAppRateLimitRecalc, globalPrincipal, "/outbound/domains/1/applications/1/ratelimit/recalc", paths, url.Values{})
refusal(t, "application recalculation when the database fails", rec.Body.String(), http.StatusBadRequest, rec.Code)
}
+20 -2
View File
@@ -9,6 +9,7 @@ import (
"github.com/mixeme/selfpost/internal/dnscheck"
"github.com/mixeme/selfpost/internal/health"
"github.com/mixeme/selfpost/internal/inbound"
"github.com/mixeme/selfpost/internal/store"
"github.com/mixeme/selfpost/internal/web/auth"
"github.com/mixeme/selfpost/internal/web/validate"
@@ -225,6 +226,19 @@ func (h *Handlers) inboundFilter() (on bool, milter, action string) {
return true, h.cfg.InboundAntispamMilter, h.cfg.InboundAntispamAction
}
// inboundErrorMessage is what a form of the inbound domain page says about a
// failed save. A validation error says what to fix and is shown as it is;
// anything else (the reload of the Postfix maps, the database) goes to the log
// and the page gets a fixed line.
func inboundErrorMessage(err error, form, what string) string {
var validation *inbound.ValidationError
if errors.As(err, &validation) {
return err.Error()
}
logf("panel: inbound: save %s: %v", form, err)
return "Could not save " + what + ". Check the logs and try again."
}
func firstNonEmpty(ss ...string) string {
for _, s := range ss {
if s != "" {
@@ -271,7 +285,9 @@ func (h *Handlers) HandleInboundTransport(w http.ResponseWriter, r *http.Request
port := r.PostFormValue("port")
tlsMode := r.PostFormValue("tls_mode")
if err := h.inbound.SetTransport(d.ID, host, port, tlsMode); err != nil {
h.renderInboundDetail(w, r, http.StatusBadRequest, d, inboundDetailView{TransportErr: err.Error()})
h.renderInboundDetail(w, r, http.StatusBadRequest, d, inboundDetailView{
TransportErr: inboundErrorMessage(err, "upstream", "the upstream"),
})
return
}
http.Redirect(w, r, fmt.Sprintf("/inbound/domains/%d?saved=1", d.ID), http.StatusSeeOther)
@@ -289,7 +305,9 @@ func (h *Handlers) HandleInboundRecipients(w http.ResponseWriter, r *http.Reques
mode := r.PostFormValue("recipient_mode")
addrs := splitAddresses(r.PostFormValue("addresses"))
if err := h.inbound.SetRecipients(d.ID, mode, addrs); err != nil {
h.renderInboundDetail(w, r, http.StatusBadRequest, d, inboundDetailView{RecipientErr: err.Error()})
h.renderInboundDetail(w, r, http.StatusBadRequest, d, inboundDetailView{
RecipientErr: inboundErrorMessage(err, "recipients", "the recipients"),
})
return
}
http.Redirect(w, r, fmt.Sprintf("/inbound/domains/%d?recipients=1", d.ID), http.StatusSeeOther)
+15 -3
View File
@@ -1,6 +1,7 @@
package handlers
import (
"errors"
"fmt"
"net"
"net/http"
@@ -168,8 +169,7 @@ func (h *Handlers) HandleDomainRateLimitRecalc(w http.ResponseWriter, r *http.Re
return
}
if err := h.recalcRateLimit(store.RateLimitScopeDomain, d.ID); err != nil {
logf("panel: domain %d: recalc rate limit: %v", d.ID, err)
h.renderDomainSettings(w, r, http.StatusBadRequest, d, settingsView{Err: err.Error()})
h.renderDomainSettings(w, r, http.StatusBadRequest, d, settingsView{Err: recalcErrorMessage(err, "domain", d.ID)})
return
}
http.Redirect(w, r, fmt.Sprintf("/outbound/domains/%d?recalculated=1", d.ID), http.StatusSeeOther)
@@ -181,12 +181,24 @@ func (h *Handlers) HandleAppRateLimitRecalc(w http.ResponseWriter, r *http.Reque
return
}
if err := h.recalcRateLimit(store.RateLimitScopeApp, a.ID); err != nil {
h.renderApplicationForm(w, r, http.StatusBadRequest, d, &a, nil, fmt.Sprintf("%s: %s", a.Login, err.Error()))
h.renderApplicationForm(w, r, http.StatusBadRequest, d, &a, nil,
fmt.Sprintf("%s: %s", a.Login, recalcErrorMessage(err, "application", a.ID)))
return
}
http.Redirect(w, r, fmt.Sprintf("/outbound/domains/%d?recalculated=1", a.DomainID), http.StatusSeeOther)
}
// recalcErrorMessage is what the page says about a recalculation that did not
// happen. A limit that is not automatic has nothing to recalculate, and the
// administrator is told so; any other failure goes to the log.
func recalcErrorMessage(err error, what string, id int64) string {
if errors.Is(err, store.ErrNotAutoRateLimit) {
return err.Error()
}
logf("panel: %s %d: recalc rate limit: %v", what, id, err)
return "Could not recalculate the limit. Check the logs and try again."
}
func (h *Handlers) recalcRateLimit(scope string, refID int64) error {
return h.store.RecalcAutoRateLimit(scope, refID, h.sendLogRetentionDays(), h.l1Messages(), h.l1Window())
}
@@ -0,0 +1,161 @@
package handlers
import (
"crypto/sha256"
"encoding/hex"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
"github.com/mixeme/selfpost/internal/store"
"github.com/mixeme/selfpost/internal/web/auth"
"golang.org/x/crypto/bcrypt"
)
// sessionCookieName is the panel's cookie without TLS (auth.Config{} here).
const sessionCookieName = "selfpost_session"
// signedIn stores a session for the user the way a login does and returns the
// token the browser would hold.
func signedIn(t *testing.T, h *Handlers, username, token string) string {
t.Helper()
u, err := h.store.GetUserByUsername(username)
if err != nil {
t.Fatalf("get %s: %v", username, err)
}
sum := sha256.Sum256([]byte(token))
if err := h.store.CreateSession(hex.EncodeToString(sum[:]), u.ID, time.Now().Add(time.Hour)); err != nil {
t.Fatalf("create session of %s: %v", username, err)
}
return token
}
func hasSession(t *testing.T, h *Handlers, token string) bool {
t.Helper()
sum := sha256.Sum256([]byte(token))
_, found, err := h.store.LookupSession(hex.EncodeToString(sum[:]))
if err != nil {
t.Fatalf("lookup session: %v", err)
}
return found
}
// postWithSession is postFormAs for a request that also carries the session
// cookie of the browser it comes from.
func postWithSession(h http.HandlerFunc, p auth.Principal, token, target string, pathValues map[string]string, values url.Values) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodPost, target, strings.NewReader(values.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.AddCookie(&http.Cookie{Name: sessionCookieName, Value: token})
for k, v := range pathValues {
req.SetPathValue(k, v)
}
rec := httptest.NewRecorder()
h(rec, auth.RequestWithPrincipal(req, p))
return rec
}
// addUser creates a global user with a known password and returns its principal.
func addUser(t *testing.T, h *Handlers, username, password string) auth.Principal {
t.Helper()
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.MinCost)
if err != nil {
t.Fatal(err)
}
id, err := h.store.CreateUser(username, string(hash), store.RoleGlobal, store.Reach{})
if err != nil {
t.Fatalf("create %s: %v", username, err)
}
return auth.Principal{ID: id, Username: username, Role: auth.RoleGlobal}
}
// Changing your own password signs out your other sessions, and only yours:
// the Account page is open to every role, so it cannot reach into anybody
// else's login.
func TestAccountPasswordSignsOutOnlyTheUsersOtherSessions(t *testing.T) {
h, _ := settingsServer(t)
bob := addUser(t, h, "bob", "bobs-long-password-1")
aliceCurrent := signedIn(t, h, "admin", "admin-current")
bobCurrent := signedIn(t, h, "bob", "bob-current")
bobOther := signedIn(t, h, "bob", "bob-other")
const next = "bobs-new-long-password-2"
rec := postWithSession(h.HandleAccountPassword, bob, bobCurrent, "/account/password", nil,
url.Values{"current_password": {"bobs-long-password-1"}, "new_password": {next}, "new_password_confirm": {next}})
if rec.Code != http.StatusSeeOther {
t.Fatalf("POST /account/password = %d:\n%s", rec.Code, rec.Body.String())
}
if hasSession(t, h, bobOther) {
t.Error("the user's other session survived their password change")
}
if !hasSession(t, h, bobCurrent) {
t.Error("the session that changed the password was signed out")
}
if !hasSession(t, h, aliceCurrent) {
t.Error("another user's session was signed out by someone else's password change")
}
}
// An administrator who sets another user's password on the user form takes
// away every login that user had under the old one.
func TestUserFormPasswordSignsOutThatUsersSessions(t *testing.T) {
h, _ := settingsServer(t)
admin := globalPrincipal
bob := addUser(t, h, "bob", "bobs-long-password-1")
adminCurrent := signedIn(t, h, "admin", "admin-current")
bob1 := signedIn(t, h, "bob", "bob-1")
bob2 := signedIn(t, h, "bob", "bob-2")
rec := postWithSession(h.HandleUserEdit, admin, adminCurrent, "/server/users/"+idStr(bob.ID), map[string]string{"uid": idStr(bob.ID)},
url.Values{"username": {"bob"}, "role": {"global"}, "password": {"a-brand-new-long-password"}})
if rec.Code != http.StatusSeeOther {
t.Fatalf("POST user form = %d:\n%s", rec.Code, rec.Body.String())
}
if hasSession(t, h, bob1) || hasSession(t, h, bob2) {
t.Error("the user's sessions survived an administrator setting their password")
}
if !hasSession(t, h, adminCurrent) {
t.Error("the administrator's own session was signed out by editing someone else")
}
}
// Saving the form without a new password does not sign anyone out.
func TestUserFormWithoutAPasswordKeepsTheSessions(t *testing.T) {
h, _ := settingsServer(t)
bob := addUser(t, h, "bob", "bobs-long-password-1")
bob1 := signedIn(t, h, "bob", "bob-1")
rec := postWithSession(h.HandleUserEdit, globalPrincipal, "no-session", "/server/users/"+idStr(bob.ID), map[string]string{"uid": idStr(bob.ID)},
url.Values{"username": {"bob"}, "role": {"global"}, "email": {"bob@example.org"}})
if rec.Code != http.StatusSeeOther {
t.Fatalf("POST user form = %d:\n%s", rec.Code, rec.Body.String())
}
if !hasSession(t, h, bob1) {
t.Error("an edit without a new password signed the user out")
}
}
// An administrator who sets their own password through the user form is signed
// out everywhere except in the browser they are using.
func TestUserFormOwnPasswordKeepsTheCurrentSession(t *testing.T) {
h, _ := settingsServer(t)
current := signedIn(t, h, "admin", "admin-current")
other := signedIn(t, h, "admin", "admin-other")
rec := postWithSession(h.HandleUserEdit, globalPrincipal, current, "/server/users/1", map[string]string{"uid": "1"},
url.Values{"username": {"admin"}, "role": {"global"}, "password": {"a-brand-new-long-password"}})
if rec.Code != http.StatusSeeOther {
t.Fatalf("POST user form = %d:\n%s", rec.Code, rec.Body.String())
}
if !hasSession(t, h, current) {
t.Error("the administrator's current session was signed out")
}
if hasSession(t, h, other) {
t.Error("the administrator's other session survived their own password change")
}
}
@@ -91,7 +91,14 @@ func TestServerSettingsIsGlobalOnly(t *testing.T) {
func settingsServer(t *testing.T) (*Handlers, string) {
t.Helper()
st, err := store.Open(filepath.Join(t.TempDir(), "test.db"))
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)
}
+17
View File
@@ -7,6 +7,7 @@ import (
"strings"
"github.com/mixeme/selfpost/internal/store"
"github.com/mixeme/selfpost/internal/web/auth"
"github.com/mixeme/selfpost/internal/web/validate"
"github.com/mixeme/selfpost/internal/web/view"
"golang.org/x/crypto/bcrypt"
@@ -310,6 +311,9 @@ func (h *Handlers) submitUserUpdate(w http.ResponseWriter, r *http.Request, u st
return
}
h.resyncAfterEmailChange(u, email)
if password != "" {
h.endSessionsAfterPasswordSet(r, p, u)
}
if role != u.Role {
if err := h.store.SetUserRole(u.ID, role); err != nil {
@@ -335,6 +339,19 @@ func (h *Handlers) submitUserUpdate(w http.ResponseWriter, r *http.Request, u st
http.Redirect(w, r, "/server/users?done=updated", http.StatusSeeOther)
}
// endSessionsAfterPasswordSet signs out the logins a user had under the old
// password when an administrator sets a new one on the user form. An
// administrator who sets their own password keeps the browser they are using.
func (h *Handlers) endSessionsAfterPasswordSet(r *http.Request, by auth.Principal, u store.User) {
if u.ID == by.ID {
if token, ok := h.auth.SessionToken(r); ok {
h.auth.DestroyOtherSessions(u.ID, token)
return
}
}
h.auth.DestroyUserSessions(u.ID)
}
// HandleUserDeleteConfirm shows the cascade warning before a panel user is
// removed — the same pattern as HandleDeleteConfirm for domains, so a single
// mis-click on Delete cannot remove a user (P3, code-review.md).