Files
selfpost/internal/web/handlers/handlers_account.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

293 lines
9.8 KiB
Go

package handlers
import (
"context"
"errors"
"net/http"
"strings"
"time"
"github.com/mixeme/selfpost/internal/dnscheck"
"github.com/mixeme/selfpost/internal/store"
"github.com/mixeme/selfpost/internal/web/validate"
"github.com/mixeme/selfpost/internal/web/view"
"golang.org/x/crypto/bcrypt"
)
// Account is the signed-in user's own half of what used to be one Settings
// page: who they are to the panel (username, e-mail), their password, and their
// default DMARC report address. Every role has it. Each part is its own form
// and its own POST, so changing one never asks for the others.
//
// The e-mail is the user's — what the panel writes to. The DMARC default is a
// separate choice that may use it: a domain whose report address is "this
// user's default" resolves to whatever is chosen here (store.DMARCDefault).
// accountForm is what the page shows back: the stored values, or the ones just
// submitted when a form is re-rendered with an error.
type accountForm struct {
Err string
Username string
Email string
DMARCMode string
DMARCAddress string
}
func (h *Handlers) accountUser(w http.ResponseWriter, r *http.Request) (store.User, bool) {
p, ok := h.principal(r)
if !ok {
http.NotFound(w, r)
return store.User{}, false
}
u, err := h.store.GetUser(p.ID)
if err != nil {
logf("panel: account: get user %d: %v", p.ID, err)
http.Error(w, "internal error", http.StatusInternalServerError)
return store.User{}, false
}
return u, true
}
func formOf(u store.User) accountForm {
return accountForm{Username: u.Username, Email: u.Email, DMARCMode: u.DMARCDefaultMode, DMARCAddress: u.DMARCDefaultAddress}
}
// HandleAccount shows the Account page.
func (h *Handlers) HandleAccount(w http.ResponseWriter, r *http.Request) {
u, ok := h.accountUser(w, r)
if !ok {
return
}
h.renderAccount(w, r, http.StatusOK, u, formOf(u))
}
func (h *Handlers) renderAccount(w http.ResponseWriter, r *http.Request, status int, u store.User, f accountForm) {
hosted := h.dmarc != nil && h.cfg.DMARCEnabled
page := view.NewAccount(h.shellMeta(r), string(u.Role), hosted, u.Email)
page.Username, page.Email = f.Username, f.Email
page.DMARCSelected, page.DMARCAddress = f.DMARCMode, f.DMARCAddress
page.WithResult(accountFlash(r), f.Err)
page.WithDomainUse(h.domainsFollowing(r, u))
// The stored default, not the one being typed: the authorization record
// belongs to the address domains are actually told to publish.
def := u.DMARCDefault()
if addr := def.Resolve(""); addr != "" && def.Mode != store.DMARCDefaultHosted {
if hub := dnscheck.EmailDomain(addr); hub != "" {
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
ra := h.dns.ReportAuth(ctx, hub)
cancel()
page.WithAuthorization(dnscheck.ReportAuthRecordName(hub), dnscheck.ReportAuthExample(),
string(ra.Status), ra.Detail, ra.Records)
}
}
h.view.Render(w, status, "account", page)
}
// domainsFollowing counts the outbound domains the user reaches and how many of
// them take their report address from this user's default.
func (h *Handlers) domainsFollowing(r *http.Request, u store.User) (following, total int) {
p, ok := h.principal(r)
if !ok {
return 0, 0
}
domains, err := h.assignedDomains(p)
if err != nil {
logf("panel: account: list domains: %v", err)
return 0, 0
}
for _, d := range domains {
if d.DMARCRuaUserID.Valid && d.DMARCRuaUserID.Int64 == u.ID {
following++
}
}
return following, len(domains)
}
func accountFlash(r *http.Request) string {
switch r.URL.Query().Get("done") {
case "profile":
return "Profile saved."
case "password":
return "Password changed. Any other signed-in sessions were signed out."
case "dmarc":
return "Default report address saved."
}
return ""
}
// HandleAccountProfile saves the username and the account e-mail.
func (h *Handlers) HandleAccountProfile(w http.ResponseWriter, r *http.Request) {
u, ok := h.accountUser(w, r)
if !ok {
return
}
f := formOf(u)
fail := func(status int, msg string) {
f.Err = msg
h.renderAccount(w, r, status, u, f)
}
if err := r.ParseForm(); err != nil {
fail(http.StatusBadRequest, "Invalid form submission.")
return
}
f.Username = strings.TrimSpace(r.PostFormValue("username"))
f.Email = strings.TrimSpace(r.PostFormValue("email"))
if f.Username == "" {
f.Username = u.Username
}
if f.Username != u.Username {
if err := validate.Username(f.Username); err != nil {
fail(http.StatusBadRequest, err.Error())
return
}
}
if err := validate.Email(f.Email); err != nil {
fail(http.StatusBadRequest, err.Error())
return
}
if err := h.store.UpdateUser(u.ID, f.Username, u.PasswordHash, f.Email); err != nil {
if errors.Is(err, store.ErrUserExists) {
fail(http.StatusConflict, "That username is already in use.")
return
}
logf("panel: account: update user %d: %v", u.ID, err)
fail(http.StatusInternalServerError, "Could not save the profile. Please check the logs and try again.")
return
}
// 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)
logf("panel: user %d profile updated (username: %t, e-mail: %t)", u.ID, f.Username != u.Username, f.Email != u.Email)
http.Redirect(w, r, "/account?done=profile", http.StatusSeeOther)
}
// HandleAccountPassword changes the password. It asks for the current one and
// is rate-limited like a sign-in: the form is a place to guess a password from
// an unattended session.
func (h *Handlers) HandleAccountPassword(w http.ResponseWriter, r *http.Request) {
u, ok := h.accountUser(w, r)
if !ok {
return
}
f := formOf(u)
fail := func(status int, msg string) {
f.Err = msg
h.renderAccount(w, r, status, u, f)
}
if !h.auth.AllowLoginAttempt(r) {
fail(http.StatusTooManyRequests, "Too many attempts. Please wait and try again.")
return
}
if err := r.ParseForm(); err != nil {
fail(http.StatusBadRequest, "Invalid form submission.")
return
}
current := r.PostFormValue("current_password")
password := r.PostFormValue("new_password")
confirm := r.PostFormValue("new_password_confirm")
if err := bcrypt.CompareHashAndPassword([]byte(u.PasswordHash), []byte(current)); err != nil {
fail(http.StatusUnauthorized, "Current password is incorrect.")
return
}
if password != confirm {
fail(http.StatusBadRequest, "New passwords do not match.")
return
}
if err := validate.AdminPassword(password); err != nil {
fail(http.StatusBadRequest, err.Error())
return
}
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcryptCost)
if err != nil {
logf("panel: account: hashing password failed: %v", err)
fail(http.StatusInternalServerError, "Internal error. Please try again.")
return
}
if err := h.store.UpdateUser(u.ID, u.Username, string(hash), u.Email); err != nil {
logf("panel: account: update password of user %d: %v", u.ID, err)
fail(http.StatusInternalServerError, "Could not save the password. Please check the logs and try again.")
return
}
if token, ok := h.auth.SessionToken(r); ok {
h.auth.DestroyOtherSessions(u.ID, token)
}
logf("panel: user %d changed their password", u.ID)
http.Redirect(w, r, "/account?done=password", http.StatusSeeOther)
}
// HandleAccountDMARC saves the user's default report address: SelfPost hosted,
// the account e-mail, another address, or none.
func (h *Handlers) HandleAccountDMARC(w http.ResponseWriter, r *http.Request) {
u, ok := h.accountUser(w, r)
if !ok {
return
}
f := formOf(u)
fail := func(status int, msg string) {
f.Err = msg
h.renderAccount(w, r, status, u, f)
}
if err := r.ParseForm(); err != nil {
fail(http.StatusBadRequest, "Invalid form submission.")
return
}
f.DMARCMode = strings.TrimSpace(r.PostFormValue("dmarc_default"))
f.DMARCAddress = strings.TrimSpace(r.PostFormValue("dmarc_default_address"))
switch f.DMARCMode {
case store.DMARCDefaultNone:
case store.DMARCDefaultHosted:
if h.dmarc == nil || !h.dmarc.Enabled() {
fail(http.StatusBadRequest, "SelfPost-hosted reports are not enabled on this server.")
return
}
case store.DMARCDefaultAccount:
if u.Email == "" {
fail(http.StatusBadRequest, "Your account has no e-mail yet. Save one under Profile first, or choose another address.")
return
}
case store.DMARCDefaultCustom:
if f.DMARCAddress == "" {
fail(http.StatusBadRequest, "Enter the report address or choose another option.")
return
}
if err := validate.Email(f.DMARCAddress); err != nil {
fail(http.StatusBadRequest, err.Error())
return
}
default:
fail(http.StatusBadRequest, "Choose where your DMARC reports go.")
return
}
if err := h.store.SetDMARCDefault(u.ID, f.DMARCMode, f.DMARCAddress); err != nil {
logf("panel: account: set dmarc default of user %d: %v", u.ID, err)
fail(http.StatusInternalServerError, "Could not save the report address. Please check the logs and try again.")
return
}
h.resyncDMARC("default report address")
logf("panel: user %d set their default report address to %q", u.ID, f.DMARCMode)
http.Redirect(w, r, "/account?done=dmarc", http.StatusSeeOther)
}
// resyncAfterEmailChange is what changing a user's account e-mail does for
// DMARC: the address is the report address of every domain that follows a user
// whose default is "my account e-mail", so the ingest allow-list is rebuilt. It
// is the one path both the Account page and the user form take.
func (h *Handlers) resyncAfterEmailChange(u store.User, newEmail string) {
if newEmail != u.Email && u.DMARCDefaultMode == store.DMARCDefaultAccount {
h.resyncDMARC("account e-mail")
}
}
// resyncDMARC rebuilds the ingest allow-list after something that changes
// where a domain's reports go. A failure is logged, not shown: the setting is
// saved, and the next resync picks it up.
func (h *Handlers) resyncDMARC(why string) {
if h.dmarc == nil || !h.dmarc.Enabled() {
return
}
if err := h.dmarc.Resync(); err != nil {
logf("panel: dmarc resync after %s change: %v", why, err)
}
}