feat(panel): add domain-admin role with per-domain authorization
test / test (push) Has been cancelled

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-08-10 23:43:59 +03:00
parent c9076655b9
commit 15baa1e5d0
28 changed files with 1425 additions and 333 deletions
+9 -10
View File
@@ -61,7 +61,7 @@ func (m *Module) clearSessionCookies(w http.ResponseWriter) {
// HandleLogin serves the login form (GET) and authenticates (POST).
func (m *Module) HandleLogin(w http.ResponseWriter, r *http.Request) {
exists, err := m.store.AdminExists()
exists, err := m.store.UserExists()
if err != nil {
http.Error(w, "internal error", http.StatusInternalServerError)
return
@@ -106,22 +106,21 @@ func (m *Module) submitLogin(w http.ResponseWriter, r *http.Request) {
username := strings.TrimSpace(r.PostFormValue("username"))
password := r.PostFormValue("password")
admin, err := m.store.GetAdmin()
user, err := m.store.GetUserByUsername(username)
if err != nil {
if !errors.Is(err, store.ErrNoAdmin) {
logf("panel: login: get admin failed: %v", err)
if !errors.Is(err, store.ErrUserNotFound) {
logf("panel: login: get user failed: %v", err)
}
m.renderLogin(w, http.StatusUnauthorized, "Invalid username or password.")
return
}
pwErr := bcrypt.CompareHashAndPassword([]byte(admin.PasswordHash), []byte(password))
if username != admin.Username || pwErr != nil {
if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(password)); err != nil {
m.renderLogin(w, http.StatusUnauthorized, "Invalid username or password.")
return
}
token := m.sessions.Create(admin.Username)
token := m.sessions.Create(user.Username)
m.setSessionCookie(w, token)
http.Redirect(w, r, "/", http.StatusSeeOther)
}
@@ -222,13 +221,13 @@ func (m *Module) submitSetup(w http.ResponseWriter, r *http.Request, token strin
return
}
if err := m.store.CreateAdmin(username, string(hash)); err != nil {
if exists, _ := m.store.AdminExists(); exists {
if err := m.store.CreateGlobalUser(username, string(hash)); err != nil {
if exists, _ := m.store.UserExists(); exists {
m.setup.complete()
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
logf("panel: setup: create admin failed: %v", err)
logf("panel: setup: create user failed: %v", err)
m.renderSetupForm(w, http.StatusInternalServerError, token, "Internal error. Please try again.")
return
}
+20 -7
View File
@@ -1,17 +1,12 @@
package auth
import (
"context"
"net/http"
)
type ctxKey int
const usernameKey ctxKey = 0
// RequireAuth wraps a handler so only requests with a valid session cookie
// reach it; everyone else is redirected to the login page. The authenticated
// username is stashed in the request context for downstream handlers.
// principal is stashed in the request context for downstream handlers.
func (m *Module) RequireAuth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token, ok := m.sessionToken(r)
@@ -27,7 +22,13 @@ func (m *Module) RequireAuth(next http.Handler) http.Handler {
if isSessionActivity(r) && m.sessions.Touch(token) {
m.setSessionCookie(w, token)
}
ctx := context.WithValue(r.Context(), usernameKey, username)
u, err := m.store.GetUserByUsername(username)
if err != nil {
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
p := principalFromUser(u)
ctx := withPrincipal(r.Context(), p)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
@@ -43,3 +44,15 @@ func CurrentUser(r *http.Request) string {
}
return ""
}
// RequireGlobal wraps a handler that only global administrators may reach.
func RequireGlobal(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
p, ok := CurrentPrincipal(r.Context())
if !ok || !p.IsGlobal() {
http.NotFound(w, r)
return
}
next.ServeHTTP(w, r)
})
}
+86
View File
@@ -0,0 +1,86 @@
package auth
import (
"context"
"net/http"
"github.com/mixeme/selfpost/internal/store"
)
type ctxKey int
const (
usernameKey ctxKey = 0
principalKey ctxKey = 1
)
// Role is a panel user's access level.
type Role = store.Role
const (
RoleGlobal = store.RoleGlobal
RoleDomainAdmin = store.RoleDomainAdmin
)
// Principal is the authenticated panel user attached to a request.
type Principal struct {
ID int64
Username string
Role Role
Domains []int64 // assigned domain IDs; empty for global (all domains)
}
// IsGlobal reports whether the principal has full panel access.
func (p Principal) IsGlobal() bool {
return p.Role == RoleGlobal
}
// CanAccessDomain reports whether the principal may access a domain id.
func (p Principal) CanAccessDomain(domainID int64) bool {
if p.IsGlobal() {
return true
}
for _, id := range p.Domains {
if id == domainID {
return true
}
}
return false
}
// CanAccessApp reports whether the principal may access an application.
func (p Principal) CanAccessApp(app store.Application) bool {
return p.CanAccessDomain(app.DomainID)
}
func principalFromUser(u store.User) Principal {
return Principal{
ID: u.ID,
Username: u.Username,
Role: u.Role,
Domains: u.DomainIDs,
}
}
func withPrincipal(ctx context.Context, p Principal) context.Context {
ctx = context.WithValue(ctx, usernameKey, p.Username)
return context.WithValue(ctx, principalKey, p)
}
// CurrentPrincipal returns the authenticated principal from the request context.
func CurrentPrincipal(ctx context.Context) (Principal, bool) {
if v, ok := ctx.Value(principalKey).(Principal); ok {
return v, true
}
return Principal{}, false
}
// PrincipalFromRequest returns the authenticated principal from an HTTP request.
func PrincipalFromRequest(r *http.Request) (Principal, bool) {
return CurrentPrincipal(r.Context())
}
// RequestWithPrincipal attaches a principal for middleware-equivalent tests.
func RequestWithPrincipal(r *http.Request, p Principal) *http.Request {
return r.WithContext(withPrincipal(r.Context(), p))
}
+3 -3
View File
@@ -33,7 +33,7 @@ func newSetupManager(st *store.Store, hostname, tokenPath string) *setupManager
}
func (m *setupManager) bootstrap() error {
done, err := m.store.AdminExists()
done, err := m.store.UserExists()
if err != nil {
return err
}
@@ -48,9 +48,9 @@ func (m *setupManager) bootstrap() error {
}
func (m *setupManager) activeToken() (string, bool) {
done, err := m.store.AdminExists()
done, err := m.store.UserExists()
if err != nil {
logf("panel: setup: admin check failed: %v", err)
logf("panel: setup: user check failed: %v", err)
return "", false
}
if done {
+65
View File
@@ -0,0 +1,65 @@
package handlers
import (
"net/http"
"github.com/mixeme/selfpost/internal/store"
"github.com/mixeme/selfpost/internal/web/auth"
)
func (h *Handlers) principal(r *http.Request) (auth.Principal, bool) {
return auth.PrincipalFromRequest(r)
}
func (h *Handlers) requireGlobal(w http.ResponseWriter, r *http.Request) (auth.Principal, bool) {
p, ok := h.principal(r)
if !ok || !p.IsGlobal() {
http.NotFound(w, r)
return auth.Principal{}, false
}
return p, true
}
func (h *Handlers) pageBase(r *http.Request) map[string]any {
p, _ := h.principal(r)
return map[string]any{
"User": auth.CurrentUser(r),
"IsGlobal": p.IsGlobal(),
}
}
func (h *Handlers) assignedDomains(p auth.Principal) ([]store.Domain, error) {
if p.IsGlobal() {
return h.store.ListDomains()
}
all, err := h.store.ListDomains()
if err != nil {
return nil, err
}
var out []store.Domain
for _, d := range all {
if p.CanAccessDomain(d.ID) {
out = append(out, d)
}
}
return out, nil
}
func domainNameSet(domains []store.Domain) map[string]bool {
m := make(map[string]bool, len(domains))
for _, d := range domains {
m[d.Name] = true
}
return m
}
func domainIDSet(p auth.Principal) map[int64]bool {
if p.IsGlobal() {
return nil
}
m := make(map[int64]bool, len(p.Domains))
for _, id := range p.Domains {
m[id] = true
}
return m
}
+75 -65
View File
@@ -14,21 +14,22 @@ import (
"golang.org/x/crypto/bcrypt"
)
// HandleAccount serves the administrator's own account settings: the username
// and password chosen during setup are the only panel credentials
// (security.md), and until now they could be changed only by recreating the
// state. Changing them here never touches application SASL logins, which are a
// separate identity system (architecture.md § Mail path).
// HandleAccount serves the signed-in user's account settings.
func (h *Handlers) HandleAccount(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
admin, err := h.store.GetAdmin()
if err != nil {
logf("panel: account: get admin failed: %v", err)
p, ok := h.principal(r)
if !ok {
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
h.renderAccount(w, r, http.StatusOK, "", admin.Username, admin.DMARCReportEmail)
u, err := h.store.GetUser(p.ID)
if err != nil {
logf("panel: account: get user failed: %v", err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
h.renderAccount(w, r, http.StatusOK, "", u.Username, u.DMARCReportEmail, p.IsGlobal())
case http.MethodPost:
h.submitAccount(w, r)
default:
@@ -37,33 +38,30 @@ func (h *Handlers) HandleAccount(w http.ResponseWriter, r *http.Request) {
}
}
// renderAccount draws the settings form. formUsername and formDMARCEmail
// repopulate fields after a rejected submission; password fields are never
// repopulated.
func (h *Handlers) renderAccount(w http.ResponseWriter, r *http.Request, status int, formErr, formUsername, formDMARCEmail string) {
func (h *Handlers) renderAccount(w http.ResponseWriter, r *http.Request, status int, formErr, formUsername, formDMARCEmail string, showDMARC bool) {
var reportAuth dnscheck.Result
if hub := dnscheck.EmailDomain(formDMARCEmail); hub != "" {
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
reportAuth = h.dns.ReportAuth(ctx, hub)
cancel()
if showDMARC && formDMARCEmail != "" {
if hub := dnscheck.EmailDomain(formDMARCEmail); hub != "" {
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
reportAuth = h.dns.ReportAuth(ctx, hub)
cancel()
}
}
h.view.Render(w, status, "account", map[string]any{
"Title": "SelfPost — settings",
"User": auth.CurrentUser(r),
"Active": "account",
"FormUsername": formUsername,
"FormDMARCEmail": formDMARCEmail,
"ReportAuthName": dnscheck.ReportAuthRecordName(dnscheck.EmailDomain(formDMARCEmail)),
"ReportAuthExample": dnscheck.ReportAuthExample(),
"ReportAuthDNS": reportAuth,
"ReportAuthHub": dnscheck.EmailDomain(formDMARCEmail),
"Error": formErr,
"Flash": accountFlash(r),
})
data := h.pageBase(r)
data["Title"] = "SelfPost — settings"
data["Active"] = "account"
data["FormUsername"] = formUsername
data["FormDMARCEmail"] = formDMARCEmail
data["ShowDMARC"] = showDMARC
data["ReportAuthName"] = dnscheck.ReportAuthRecordName(dnscheck.EmailDomain(formDMARCEmail))
data["ReportAuthExample"] = dnscheck.ReportAuthExample()
data["ReportAuthDNS"] = reportAuth
data["ReportAuthHub"] = dnscheck.EmailDomain(formDMARCEmail)
data["Error"] = formErr
data["Flash"] = accountFlash(r)
h.view.Render(w, status, "account", data)
}
// accountFlash maps a fixed redirect flag to a fixed message, so status text
// after a redirect is never attacker-influenced.
func accountFlash(r *http.Request) string {
switch r.URL.Query().Get("updated") {
case "username":
@@ -85,19 +83,28 @@ func accountFlash(r *http.Request) string {
}
}
// submitAccount applies a username and/or password change. The current password
// is always required, so a stolen session alone cannot lock the administrator
// out of their own panel, and the attempt is throttled on the same limiter as
// the login form so this route cannot be used to brute-force the password past
// that limit (security.md).
func (h *Handlers) submitAccount(w http.ResponseWriter, r *http.Request) {
if !h.auth.AllowLoginAttempt(r) {
p, _ := h.principal(r)
h.renderAccount(w, r, http.StatusTooManyRequests,
"Too many attempts. Please wait and try again.", auth.CurrentUser(r), "")
"Too many attempts. Please wait and try again.", auth.CurrentUser(r), "", p.IsGlobal())
return
}
if err := r.ParseForm(); err != nil {
h.renderAccount(w, r, http.StatusBadRequest, "Invalid form submission.", auth.CurrentUser(r), "")
p, _ := h.principal(r)
h.renderAccount(w, r, http.StatusBadRequest, "Invalid form submission.", auth.CurrentUser(r), "", p.IsGlobal())
return
}
p, ok := h.principal(r)
if !ok {
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
user, err := h.store.GetUser(p.ID)
if err != nil {
logf("panel: account: get user failed: %v", err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
@@ -106,73 +113,76 @@ func (h *Handlers) submitAccount(w http.ResponseWriter, r *http.Request) {
password := r.PostFormValue("new_password")
confirm := r.PostFormValue("new_password_confirm")
dmarcEmail := strings.TrimSpace(r.PostFormValue("dmarc_report_email"))
admin, err := h.store.GetAdmin()
if err != nil {
logf("panel: account: get admin failed: %v", err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
if !p.IsGlobal() {
dmarcEmail = user.DMARCReportEmail
}
if username == "" {
username = admin.Username
username = user.Username
}
if err := bcrypt.CompareHashAndPassword([]byte(admin.PasswordHash), []byte(current)); err != nil {
h.renderAccount(w, r, http.StatusUnauthorized, "Current password is incorrect.", username, dmarcEmail)
if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(current)); err != nil {
h.renderAccount(w, r, http.StatusUnauthorized, "Current password is incorrect.", username, dmarcEmail, p.IsGlobal())
return
}
renaming := username != admin.Username
renaming := username != user.Username
if renaming {
if err := validate.Username(username); err != nil {
h.renderAccount(w, r, http.StatusBadRequest, err.Error(), username, dmarcEmail)
h.renderAccount(w, r, http.StatusBadRequest, err.Error(), username, dmarcEmail, p.IsGlobal())
return
}
}
if err := validate.Email(dmarcEmail); err != nil {
h.renderAccount(w, r, http.StatusBadRequest, err.Error(), username, dmarcEmail)
return
if p.IsGlobal() {
if err := validate.Email(dmarcEmail); err != nil {
h.renderAccount(w, r, http.StatusBadRequest, err.Error(), username, dmarcEmail, true)
return
}
}
emailChanging := dmarcEmail != admin.DMARCReportEmail
emailChanging := p.IsGlobal() && dmarcEmail != user.DMARCReportEmail
repassword := password != "" || confirm != ""
if repassword {
if password != confirm {
h.renderAccount(w, r, http.StatusBadRequest, "New passwords do not match.", username, dmarcEmail)
h.renderAccount(w, r, http.StatusBadRequest, "New passwords do not match.", username, dmarcEmail, p.IsGlobal())
return
}
if err := validate.AdminPassword(password); err != nil {
h.renderAccount(w, r, http.StatusBadRequest, err.Error(), username, dmarcEmail)
h.renderAccount(w, r, http.StatusBadRequest, err.Error(), username, dmarcEmail, p.IsGlobal())
return
}
}
if !renaming && !repassword && !emailChanging {
h.renderAccount(w, r, http.StatusBadRequest,
"Nothing to change: enter a new username, password, or DMARC report address.", username, dmarcEmail)
"Nothing to change: enter a new username, password, or DMARC report address.", username, dmarcEmail, p.IsGlobal())
return
}
hash := admin.PasswordHash
hash := user.PasswordHash
if repassword {
newHash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
logf("panel: account: hashing password failed: %v", err)
h.renderAccount(w, r, http.StatusInternalServerError,
"Internal error. Please try again.", username, dmarcEmail)
"Internal error. Please try again.", username, dmarcEmail, p.IsGlobal())
return
}
hash = string(newHash)
}
if err := h.store.UpdateAdmin(username, hash, dmarcEmail); err != nil {
logf("panel: account: update admin failed: %v", err)
if err := h.store.UpdateUser(user.ID, username, hash, dmarcEmail); err != nil {
logf("panel: account: update user failed: %v", err)
msg := "Could not save the changes. Please check the logs and try again."
if errors.Is(err, store.ErrNoAdmin) {
msg = "There is no administrator account to update."
if errors.Is(err, store.ErrUserNotFound) {
msg = "There is no user account to update."
}
h.renderAccount(w, r, http.StatusInternalServerError, msg, username, dmarcEmail)
if errors.Is(err, store.ErrUserExists) {
msg = "That username is already in use."
h.renderAccount(w, r, http.StatusConflict, msg, username, dmarcEmail, p.IsGlobal())
return
}
h.renderAccount(w, r, http.StatusInternalServerError, msg, username, dmarcEmail, p.IsGlobal())
return
}
@@ -185,7 +195,7 @@ func (h *Handlers) submitAccount(w http.ResponseWriter, r *http.Request) {
}
}
logf("panel: administrator account updated (username: %t, password: %t, dmarc email: %t)", renaming, repassword, emailChanging)
logf("panel: user %d account updated (username: %t, password: %t, dmarc email: %t)", user.ID, renaming, repassword, emailChanging)
http.Redirect(w, r, "/account?updated="+updatedFlag(renaming, repassword, emailChanging), http.StatusSeeOther)
}
+47 -53
View File
@@ -10,7 +10,6 @@ import (
"github.com/mixeme/selfpost/internal/dnscheck"
"github.com/mixeme/selfpost/internal/domain"
"github.com/mixeme/selfpost/internal/store"
"github.com/mixeme/selfpost/internal/web/auth"
"github.com/mixeme/selfpost/internal/web/validate"
)
@@ -104,13 +103,12 @@ func (h *Handlers) renderDomainDetail(w http.ResponseWriter, r *http.Request, st
// What DNS actually publishes for the domain today, checked against the key
// this server signs with. Cached by the checker, so re-rendering the page
// after a form post costs nothing.
admin, err := h.store.GetAdmin()
profileEmail, err := h.store.GlobalDMARCReportEmail()
if err != nil {
logf("panel: domain %d: get admin: %v", d.ID, err)
logf("panel: domain %d: global dmarc email: %v", d.ID, err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
profileEmail := admin.DMARCReportEmail
reportEmail := dnscheck.ResolveDMARCRua(d.DMARCRua, profileEmail)
dns, srv := h.domainDNS(d, record, profileEmail, false)
reportAuthName, reportAuthValue, needsReportAuth := dnscheck.ExternalReportAuth(d.Name, reportEmail)
@@ -134,52 +132,43 @@ func (h *Handlers) renderDomainDetail(w http.ResponseWriter, r *http.Request, st
dmarcSource = "settings"
}
h.view.Render(w, status, "domain_detail", map[string]any{
"Title": "SelfPost — " + d.Name,
"User": auth.CurrentUser(r),
"Active": "domains",
"Domain": d,
"Record": record,
"DNS": dns,
// SPF and DMARC are the operator's to write — SelfPost cannot generate
// them the way it generates the DKIM record — so the page shows what
// this server expects rather than leaving it to the documentation. The
// same builders phrase the suggestions in the check messages, so the
// page and the checks below it never recommend different records.
"SPFExample": dnscheck.SPFExample(h.cfg.Hostname, srv.IPs),
"DMARCName": dnscheck.DMARCRecordName(d.Name),
"DMARCExample": dnscheck.DMARCExample(reportEmail),
"DMARCSource": dmarcSource,
"ProfileDMARCEmail": profileEmail,
"ResolvedDMARCEmail": reportEmail,
"DMARCRuaMode": dmarcMode,
"DMARCRuaCustom": dmarcCustom,
"ReportAuthName": reportAuthName,
"ReportAuthValue": reportAuthValue,
"NeedsReportAuth": needsReportAuth,
"SameDomainRUA": reportEmail != "" && strings.EqualFold(dnscheck.EmailDomain(reportEmail), d.Name),
// Client connection settings (the same for every domain on this
// instance): the hostname clients connect to, and whether the optional
// submission listener is enabled in this deployment.
"Hostname": h.cfg.Hostname,
"SubmissionEnabled": h.cfg.SubmissionEnabled,
"Apps": appViews,
"Error": view.FormErr,
"FormLogin": view.FormLogin,
"FormMode": view.FormMode,
"FormAddrs": view.FormAddrs,
"NewCred": view.NewCred,
"Flash": detailFlash(r),
"Wildcard": store.AddressModeWildcard,
"List": store.AddressModeList,
"RateLimitErr": view.RateLimitErr,
"ExportErr": view.ExportErr,
"MinPwLen": validate.MinSecretFilePasswordLen,
"DomainHasRL": domainRLok && domainRL.Active(),
"DomainRLIPs": strings.Join(domainRL.AllowedIPs, "\n"),
"DomainRLMax": intOrBlank(domainRL.MaxMessages),
"DomainRLWin": windowOrDefault(domainRL.WindowSeconds),
})
data := h.pageBase(r)
data["Title"] = "SelfPost — " + d.Name
data["Active"] = "domains"
data["Domain"] = d
data["Record"] = record
data["DNS"] = dns
data["SPFExample"] = dnscheck.SPFExample(h.cfg.Hostname, srv.IPs)
data["DMARCName"] = dnscheck.DMARCRecordName(d.Name)
data["DMARCExample"] = dnscheck.DMARCExample(reportEmail)
data["DMARCSource"] = dmarcSource
data["ProfileDMARCEmail"] = profileEmail
data["ResolvedDMARCEmail"] = reportEmail
data["DMARCRuaMode"] = dmarcMode
data["DMARCRuaCustom"] = dmarcCustom
data["ReportAuthName"] = reportAuthName
data["ReportAuthValue"] = reportAuthValue
data["NeedsReportAuth"] = needsReportAuth
data["SameDomainRUA"] = reportEmail != "" && strings.EqualFold(dnscheck.EmailDomain(reportEmail), d.Name)
data["Hostname"] = h.cfg.Hostname
data["SubmissionEnabled"] = h.cfg.SubmissionEnabled
data["Apps"] = appViews
data["Error"] = view.FormErr
data["FormLogin"] = view.FormLogin
data["FormMode"] = view.FormMode
data["FormAddrs"] = view.FormAddrs
data["NewCred"] = view.NewCred
data["Flash"] = detailFlash(r)
data["Wildcard"] = store.AddressModeWildcard
data["List"] = store.AddressModeList
data["RateLimitErr"] = view.RateLimitErr
data["ExportErr"] = view.ExportErr
data["MinPwLen"] = validate.MinSecretFilePasswordLen
data["DomainHasRL"] = domainRLok && domainRL.Active()
data["DomainRLIPs"] = strings.Join(domainRL.AllowedIPs, "\n")
data["DomainRLMax"] = intOrBlank(domainRL.MaxMessages)
data["DomainRLWin"] = windowOrDefault(domainRL.WindowSeconds)
h.view.Render(w, status, "domain_detail", data)
}
// domainDNS resolves what the world sees for a domain: its DKIM, SPF and DMARC
@@ -213,13 +202,13 @@ func (h *Handlers) HandleDomainDNSRecheck(w http.ResponseWriter, r *http.Request
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
admin, err := h.store.GetAdmin()
profileEmail, err := h.store.GlobalDMARCReportEmail()
if err != nil {
logf("panel: domain %d: get admin: %v", d.ID, err)
logf("panel: domain %d: global dmarc email: %v", d.ID, err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
h.domainDNS(d, record, admin.DMARCReportEmail, true)
h.domainDNS(d, record, profileEmail, true)
http.Redirect(w, r, fmt.Sprintf("/domains/%d?rechecked=1", d.ID), http.StatusSeeOther)
}
@@ -387,6 +376,11 @@ func (h *Handlers) lookupApplication(w http.ResponseWriter, r *http.Request) (st
http.Error(w, "internal error", http.StatusInternalServerError)
return store.Application{}, false
}
p, ok := h.principal(r)
if !ok || !p.CanAccessApp(a) {
http.NotFound(w, r)
return store.Application{}, false
}
return a, true
}
+16 -9
View File
@@ -13,7 +13,6 @@ import (
"github.com/mixeme/selfpost/internal/domain"
"github.com/mixeme/selfpost/internal/secretfile"
"github.com/mixeme/selfpost/internal/store"
"github.com/mixeme/selfpost/internal/web/auth"
"github.com/mixeme/selfpost/internal/web/validate"
)
@@ -28,6 +27,9 @@ const maxImportBytes = 1 << 20 // 1 MiB
// and the domain import are separate actions with different risk, so each gets
// its own card here rather than sharing a block on the domain list.
func (h *Handlers) HandleBackupPage(w http.ResponseWriter, r *http.Request) {
if _, ok := h.requireGlobal(w, r); !ok {
return
}
h.renderBackupPage(w, r, http.StatusOK, "")
}
@@ -42,14 +44,13 @@ func (h *Handlers) renderBackupPage(w http.ResponseWriter, r *http.Request, stat
// password), importErr to the import card, so neither message appears under the
// wrong form.
func (h *Handlers) renderBackupPageWith(w http.ResponseWriter, r *http.Request, status int, importErr, backupErr string) {
h.view.Render(w, status, "backup", map[string]any{
"Title": "SelfPost — backup",
"User": auth.CurrentUser(r),
"Active": "backup",
"ImportErr": importErr,
"BackupErr": backupErr,
"MinPwLen": validate.MinSecretFilePasswordLen,
})
data := h.pageBase(r)
data["Title"] = "SelfPost — backup"
data["Active"] = "backup"
data["ImportErr"] = importErr
data["BackupErr"] = backupErr
data["MinPwLen"] = validate.MinSecretFilePasswordLen
h.view.Render(w, status, "backup", data)
}
// HandleBackup streams a full-server backup as a download (architecture.md §
@@ -61,6 +62,9 @@ func (h *Handlers) renderBackupPageWith(w http.ResponseWriter, r *http.Request,
// way out, so the file that lands on their disk — wherever it is copied
// afterwards — is useless without the password.
func (h *Handlers) HandleBackup(w http.ResponseWriter, r *http.Request) {
if _, ok := h.requireGlobal(w, r); !ok {
return
}
password, pwErr := secretFilePassword(r)
if pwErr != "" {
h.renderBackupPageWith(w, r, http.StatusBadRequest, "", pwErr)
@@ -184,6 +188,9 @@ func (h *Handlers) HandleExportDomain(w http.ResponseWriter, r *http.Request) {
// re-renders the backup page, where the import form lives, with a friendly
// message.
func (h *Handlers) HandleImportDomain(w http.ResponseWriter, r *http.Request) {
if _, ok := h.requireGlobal(w, r); !ok {
return
}
r.Body = http.MaxBytesReader(w, r.Body, maxImportBytes)
if err := r.ParseMultipartForm(maxImportBytes); err != nil {
h.renderBackupPage(w, r, http.StatusBadRequest, "Could not read the uploaded file (too large or not a valid upload).")
+34 -12
View File
@@ -29,27 +29,31 @@ func (h *Handlers) HandleDashboard(w http.ResponseWriter, r *http.Request) {
}
func (h *Handlers) renderDashboard(w http.ResponseWriter, r *http.Request, status int, formErr, formName string) {
domains, err := h.domains.List()
p, ok := h.principal(r)
if !ok {
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
domains, err := h.assignedDomains(p)
if err != nil {
logf("panel: dashboard: list domains: %v", err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
h.view.Render(w, status, "dashboard", map[string]any{
"Title": "SelfPost",
"User": auth.CurrentUser(r),
"Active": "domains",
"Domains": h.domainRows(domains),
"Error": formErr,
"FormName": formName,
"Flash": dashboardFlash(r),
})
data := h.pageBase(r)
data["Title"] = "SelfPost"
data["Active"] = "domains"
data["Domains"] = h.domainRows(domains)
data["Error"] = formErr
data["FormName"] = formName
data["Flash"] = dashboardFlash(r)
h.view.Render(w, status, "dashboard", data)
}
func (h *Handlers) domainRows(domains []store.Domain) []domainRow {
profileEmail := ""
if admin, err := h.store.GetAdmin(); err == nil {
profileEmail = admin.DMARCReportEmail
if email, err := h.store.GlobalDMARCReportEmail(); err == nil {
profileEmail = email
}
rows := make([]domainRow, len(domains))
var wg sync.WaitGroup
@@ -82,6 +86,9 @@ func dashboardFlash(r *http.Request) string {
// OpenDKIM reload), and redirects to the domain's page so the DNS record to
// publish is shown (product.md).
func (h *Handlers) HandleAddDomain(w http.ResponseWriter, r *http.Request) {
if _, ok := h.requireGlobal(w, r); !ok {
return
}
if err := r.ParseForm(); err != nil {
h.renderDashboard(w, r, http.StatusBadRequest, "Invalid form submission.", "")
return
@@ -109,6 +116,9 @@ func (h *Handlers) HandleAddDomain(w http.ResponseWriter, r *http.Request) {
// HandleDeleteConfirm shows the cascade warning before a domain is removed.
func (h *Handlers) HandleDeleteConfirm(w http.ResponseWriter, r *http.Request) {
if _, ok := h.requireGlobal(w, r); !ok {
return
}
d, ok := h.lookupDomain(w, r)
if !ok {
return
@@ -118,11 +128,15 @@ func (h *Handlers) HandleDeleteConfirm(w http.ResponseWriter, r *http.Request) {
"User": auth.CurrentUser(r),
"Active": "domains",
"Domain": d,
"IsGlobal": true,
})
}
// HandleDeleteDomain performs the deletion and returns to the domain list.
func (h *Handlers) HandleDeleteDomain(w http.ResponseWriter, r *http.Request) {
if _, ok := h.requireGlobal(w, r); !ok {
return
}
id, ok := parseDomainID(w, r)
if !ok {
return
@@ -145,6 +159,9 @@ func (h *Handlers) HandleDeleteDomain(w http.ResponseWriter, r *http.Request) {
// HandleReload re-applies both the OpenDKIM configuration and the Postfix
// sender map on demand (architecture.md § Panel HTTP surface).
func (h *Handlers) HandleReload(w http.ResponseWriter, r *http.Request) {
if _, ok := h.requireGlobal(w, r); !ok {
return
}
if err := h.domains.Resync(); err != nil {
logf("panel: manual reload (opendkim): %v", err)
http.Error(w, "reload failed", http.StatusInternalServerError)
@@ -173,6 +190,11 @@ func (h *Handlers) lookupDomain(w http.ResponseWriter, r *http.Request) (store.D
http.Error(w, "internal error", http.StatusInternalServerError)
return store.Domain{}, false
}
p, ok := h.principal(r)
if !ok || !p.CanAccessDomain(d.ID) {
http.NotFound(w, r)
return store.Domain{}, false
}
return d, true
}
+87 -23
View File
@@ -5,6 +5,7 @@ import (
"io/fs"
"net/http"
"net/url"
"sort"
"strconv"
"time"
@@ -38,7 +39,9 @@ func (h *Handlers) HandleDeliveries(w http.ResponseWriter, r *http.Request) {
return
}
data["Title"] = "SelfPost — deliveries"
data["User"] = auth.CurrentUser(r)
for k, v := range h.pageBase(r) {
data[k] = v
}
data["Active"] = "deliveries"
h.view.Render(w, http.StatusOK, "deliveries", data)
}
@@ -85,12 +88,29 @@ func (h *Handlers) HandleDelivery(w http.ResponseWriter, r *http.Request) {
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
p, ok := h.principal(r)
if !ok {
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
if !p.IsGlobal() {
allowed, err := h.assignedDomains(p)
if err != nil {
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
if !domainNameSet(allowed)[row.Domain] {
http.NotFound(w, r)
return
}
}
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(),
"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.
@@ -269,11 +289,31 @@ func deliveriesBackURL(r *http.Request) string {
// string, queries the store, and assembles everything the template needs
// (filter dropdown options plus the current selection, rows, and pagination).
func (h *Handlers) sendLogData(r *http.Request) (map[string]any, error) {
p, ok := h.principal(r)
if !ok {
return nil, errors.New("no principal")
}
q := r.URL.Query()
filter := store.SendLogFilter{
Domain: q.Get("domain"),
AppLogin: q.Get("app"),
}
assigned, err := h.assignedDomains(p)
if err != nil {
return nil, err
}
allowedNames := domainNameSet(assigned)
if !p.IsGlobal() {
if filter.Domain != "" && !allowedNames[filter.Domain] {
filter.Domain = ""
}
if filter.Domain == "" && len(assigned) == 1 {
filter.Domain = assigned[0].Name
}
}
page := parsePage(q.Get("p"))
total, err := h.store.CountSendLog(filter)
@@ -284,23 +324,33 @@ func (h *Handlers) sendLogData(r *http.Request) (map[string]any, error) {
if err != nil {
return nil, err
}
// Decode on the way out as well as on the way in: rows the journal-milter
// wrote before it decoded subjects itself still hold the raw header, and
// they are the ones an operator is most likely to be looking at.
for i := range rows {
rows[i].Subject = mailhdr.DecodeSubject(rows[i].Subject)
}
domains, err := h.store.ListDomains()
if err != nil {
return nil, err
domainNames := make([]string, 0, len(assigned))
for _, d := range assigned {
domainNames = append(domainNames, d.Name)
}
domainNames := make([]string, len(domains))
for i, d := range domains {
domainNames[i] = d.Name
loginSet := make(map[string]bool)
for _, d := range assigned {
apps, err := h.store.ListApplicationsByDomain(d.ID)
if err != nil {
return nil, err
}
for _, a := range apps {
loginSet[a.Login] = true
}
}
logins, err := h.store.ListApplicationLogins()
if err != nil {
return nil, err
logins := make([]string, 0, len(loginSet))
for login := range loginSet {
logins = append(logins, login)
}
sort.Strings(logins)
if !p.IsGlobal() && filter.AppLogin != "" && !loginSet[filter.AppLogin] {
filter.AppLogin = ""
}
lastPage := 1
@@ -335,18 +385,25 @@ func parsePage(v string) int {
// HandleMailQueue renders the Mail queue page (architecture.md § Panel HTTP
// surface).
func (h *Handlers) HandleMailQueue(w http.ResponseWriter, r *http.Request) {
if _, ok := h.requireGlobal(w, r); !ok {
return
}
out, errText := readQueue()
h.view.Render(w, http.StatusOK, "mail_queue", map[string]any{
"Title": "SelfPost — mail queue",
"User": auth.CurrentUser(r),
"Active": "mail_queue",
"Output": out,
"Error": errText,
"Title": "SelfPost — mail queue",
"User": auth.CurrentUser(r),
"Active": "mail_queue",
"IsGlobal": true,
"Output": out,
"Error": errText,
})
}
// HandleMailQueueBody serves the HTMX polling fragment for the queue view.
func (h *Handlers) HandleMailQueueBody(w http.ResponseWriter, r *http.Request) {
if _, ok := h.requireGlobal(w, r); !ok {
return
}
out, errText := readQueue()
h.view.RenderFragment(w, http.StatusOK, "mail_queue_body", map[string]any{
"Output": out,
@@ -369,18 +426,25 @@ func readQueue() (string, string) {
// HandleSystemLog renders the System log page over mail.log (architecture.md §
// Panel HTTP surface).
func (h *Handlers) HandleSystemLog(w http.ResponseWriter, r *http.Request) {
if _, ok := h.requireGlobal(w, r); !ok {
return
}
lines, errText := h.readLogTail()
h.view.Render(w, http.StatusOK, "system_log", map[string]any{
"Title": "SelfPost — system log",
"User": auth.CurrentUser(r),
"Active": "system_log",
"Lines": lines,
"Error": errText,
"Title": "SelfPost — system log",
"User": auth.CurrentUser(r),
"Active": "system_log",
"IsGlobal": true,
"Lines": lines,
"Error": errText,
})
}
// HandleSystemLogBody serves the HTMX polling fragment for the log-tail view.
func (h *Handlers) HandleSystemLogBody(w http.ResponseWriter, r *http.Request) {
if _, ok := h.requireGlobal(w, r); !ok {
return
}
lines, errText := h.readLogTail()
h.view.RenderFragment(w, http.StatusOK, "system_log_body", map[string]any{
"Lines": lines,
@@ -10,6 +10,7 @@ import (
"testing"
"github.com/mixeme/selfpost/internal/store"
"github.com/mixeme/selfpost/internal/web/auth"
)
// After log rotation renames mail.log away, Postfix takes about a second to
@@ -252,6 +253,11 @@ func getBody(t *testing.T, h http.HandlerFunc, target string) string {
t.Helper()
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, target, nil)
req = auth.RequestWithPrincipal(req, auth.Principal{
ID: 1,
Username: "admin",
Role: auth.RoleGlobal,
})
if rest, ok := strings.CutPrefix(req.URL.Path, "/deliveries/"); ok && rest != "rows" {
req.SetPathValue("id", rest)
}
+11 -1
View File
@@ -9,23 +9,33 @@ import (
)
func (h *Handlers) HandleStatus(w http.ResponseWriter, r *http.Request) {
if _, ok := h.requireGlobal(w, r); !ok {
return
}
data := h.statusBody()
srv := h.dns.Server(h.cfg.Hostname, false)
data["Title"] = "SelfPost — status"
data["User"] = auth.CurrentUser(r)
data["Active"] = "status"
data["IsGlobal"] = true
data["Flash"] = statusFlash(r)
data["Hostname"] = h.cfg.Hostname
data["PTR"] = srv.PTR
h.view.Render(w, http.StatusOK, "status", data)
}
func (h *Handlers) HandleStatusFragment(w http.ResponseWriter, _ *http.Request) {
func (h *Handlers) HandleStatusFragment(w http.ResponseWriter, r *http.Request) {
if _, ok := h.requireGlobal(w, r); !ok {
return
}
h.view.RenderFragment(w, http.StatusOK, "status_body", h.statusBody())
}
func (h *Handlers) HandleStatusRecheck(w http.ResponseWriter, r *http.Request) {
if _, ok := h.requireGlobal(w, r); !ok {
return
}
h.dns.Server(h.cfg.Hostname, true)
http.Redirect(w, r, "/status?rechecked=1", http.StatusSeeOther)
}
+328
View File
@@ -0,0 +1,328 @@
package handlers
import (
"errors"
"net/http"
"strconv"
"strings"
"github.com/mixeme/selfpost/internal/store"
"github.com/mixeme/selfpost/internal/web/validate"
"golang.org/x/crypto/bcrypt"
)
type userFormView struct {
FormErr string
FormUsername string
FormRole string
FormDomains map[int64]bool
FormPassword string
}
// HandleUsers lists panel users (global only).
func (h *Handlers) HandleUsers(w http.ResponseWriter, r *http.Request) {
if _, ok := h.requireGlobal(w, r); !ok {
return
}
rows, err := h.store.ListUserRows()
if err != nil {
logf("panel: list users: %v", err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
data := h.pageBase(r)
data["Title"] = "SelfPost — users"
data["Active"] = "users"
data["Users"] = rows
data["Flash"] = usersFlash(r)
h.view.Render(w, http.StatusOK, "users", data)
}
func usersFlash(r *http.Request) string {
switch r.URL.Query().Get("done") {
case "created":
return "User created."
case "updated":
return "User updated."
case "deleted":
return "User deleted."
default:
return ""
}
}
// HandleUserNew creates a panel user (global only).
func (h *Handlers) HandleUserNew(w http.ResponseWriter, r *http.Request) {
if _, ok := h.requireGlobal(w, r); !ok {
return
}
switch r.Method {
case http.MethodGet:
h.renderUserForm(w, r, http.StatusOK, 0, userFormView{FormRole: string(store.RoleDomainAdmin)})
case http.MethodPost:
h.submitUserCreate(w, r)
default:
w.Header().Set("Allow", "GET, POST")
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
}
}
// HandleUserEdit edits or deletes a panel user (global only).
func (h *Handlers) HandleUserEdit(w http.ResponseWriter, r *http.Request) {
if _, ok := h.requireGlobal(w, r); !ok {
return
}
uid, ok := parseUserID(w, r)
if !ok {
return
}
u, err := h.store.GetUser(uid)
if err != nil {
if errors.Is(err, store.ErrUserNotFound) {
http.NotFound(w, r)
return
}
logf("panel: get user %d: %v", uid, err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
switch r.Method {
case http.MethodGet:
selected := make(map[int64]bool, len(u.DomainIDs))
for _, id := range u.DomainIDs {
selected[id] = true
}
h.renderUserForm(w, r, http.StatusOK, u.ID, userFormView{
FormUsername: u.Username,
FormRole: string(u.Role),
FormDomains: selected,
})
case http.MethodPost:
if err := r.ParseForm(); err != nil {
h.renderUserForm(w, r, http.StatusBadRequest, u.ID, userFormView{FormErr: "Invalid form submission.", FormUsername: u.Username, FormRole: string(u.Role)})
return
}
if r.PostFormValue("action") == "delete" {
h.submitUserDelete(w, r, u)
return
}
h.submitUserUpdate(w, r, u)
default:
w.Header().Set("Allow", "GET, POST")
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
}
}
func (h *Handlers) renderUserForm(w http.ResponseWriter, r *http.Request, status int, userID int64, view userFormView) {
domains, err := h.store.ListDomains()
if err != nil {
logf("panel: user form: list domains: %v", err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
data := h.pageBase(r)
data["Title"] = "SelfPost — user"
data["Active"] = "users"
data["UserID"] = userID
data["Domains"] = domains
data["Error"] = view.FormErr
data["FormUsername"] = view.FormUsername
data["FormRole"] = view.FormRole
data["FormDomains"] = view.FormDomains
data["FormPassword"] = view.FormPassword
data["IsEdit"] = userID != 0
h.view.Render(w, status, "user_form", data)
}
func (h *Handlers) submitUserCreate(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
h.renderUserForm(w, r, http.StatusBadRequest, 0, userFormView{FormErr: "Invalid form submission."})
return
}
username := strings.TrimSpace(r.PostFormValue("username"))
password := r.PostFormValue("password")
role := store.Role(r.PostFormValue("role"))
domainIDs := parseDomainIDs(r)
if err := validate.Username(username); err != nil {
h.renderUserForm(w, r, http.StatusBadRequest, 0, userFormView{FormErr: err.Error(), FormUsername: username, FormRole: string(role), FormDomains: domainIDSetFromForm(r)})
return
}
if err := validate.AdminPassword(password); err != nil {
h.renderUserForm(w, r, http.StatusBadRequest, 0, userFormView{FormErr: err.Error(), FormUsername: username, FormRole: string(role), FormDomains: domainIDSetFromForm(r)})
return
}
if role != store.RoleGlobal && role != store.RoleDomainAdmin {
h.renderUserForm(w, r, http.StatusBadRequest, 0, userFormView{FormErr: "Choose a valid role.", FormUsername: username, FormRole: string(role), FormDomains: domainIDSetFromForm(r)})
return
}
if role == store.RoleDomainAdmin && len(domainIDs) == 0 {
h.renderUserForm(w, r, http.StatusBadRequest, 0, userFormView{FormErr: "Select at least one domain for a domain administrator.", FormUsername: username, FormRole: string(role), FormDomains: domainIDSetFromForm(r)})
return
}
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
logf("panel: create user hash: %v", err)
h.renderUserForm(w, r, http.StatusInternalServerError, 0, userFormView{FormErr: "Internal error. Please try again."})
return
}
if _, err := h.store.CreateUser(username, string(hash), role, domainIDs); err != nil {
if errors.Is(err, store.ErrUserExists) {
h.renderUserForm(w, r, http.StatusConflict, 0, userFormView{FormErr: "That username is already in use.", FormUsername: username, FormRole: string(role), FormDomains: domainIDSetFromForm(r)})
return
}
logf("panel: create user: %v", err)
h.renderUserForm(w, r, http.StatusInternalServerError, 0, userFormView{FormErr: "Could not create user. Please check the logs."})
return
}
http.Redirect(w, r, "/users?done=created", http.StatusSeeOther)
}
func (h *Handlers) submitUserUpdate(w http.ResponseWriter, r *http.Request, u store.User) {
if err := r.ParseForm(); err != nil {
h.renderUserForm(w, r, http.StatusBadRequest, u.ID, userFormView{FormErr: "Invalid form submission.", FormUsername: u.Username, FormRole: string(u.Role)})
return
}
p, ok := h.principal(r)
if !ok {
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
username := strings.TrimSpace(r.PostFormValue("username"))
password := r.PostFormValue("password")
role := store.Role(r.PostFormValue("role"))
domainIDs := parseDomainIDs(r)
selected := domainIDSetFromForm(r)
if username == "" {
username = u.Username
}
if err := validate.Username(username); err != nil {
h.renderUserForm(w, r, http.StatusBadRequest, u.ID, userFormView{FormErr: err.Error(), FormUsername: username, FormRole: string(role), FormDomains: selected})
return
}
if role != store.RoleGlobal && role != store.RoleDomainAdmin {
h.renderUserForm(w, r, http.StatusBadRequest, u.ID, userFormView{FormErr: "Choose a valid role.", FormUsername: username, FormRole: string(role), FormDomains: selected})
return
}
if role == store.RoleDomainAdmin && len(domainIDs) == 0 {
h.renderUserForm(w, r, http.StatusBadRequest, u.ID, userFormView{FormErr: "Select at least one domain for a domain administrator.", FormUsername: username, FormRole: string(role), FormDomains: selected})
return
}
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})
return
}
}
hash := u.PasswordHash
if password != "" {
if err := validate.AdminPassword(password); err != nil {
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)
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})
return
}
hash = string(newHash)
}
if err := h.store.UpdateUser(u.ID, username, hash, u.DMARCReportEmail); err != nil {
if errors.Is(err, store.ErrUserExists) {
h.renderUserForm(w, r, http.StatusConflict, u.ID, userFormView{FormErr: "That username is already in use.", FormUsername: username, FormRole: string(role), FormDomains: selected})
return
}
logf("panel: update user: %v", err)
h.renderUserForm(w, r, http.StatusInternalServerError, u.ID, userFormView{FormErr: "Could not save user. Please check the logs.", FormUsername: username, FormRole: string(role), FormDomains: selected})
return
}
if role != u.Role {
if err := h.store.SetUserRole(u.ID, role); err != nil {
logf("panel: set user role: %v", err)
h.renderUserForm(w, r, http.StatusInternalServerError, u.ID, userFormView{FormErr: "Could not update role.", FormUsername: username, FormRole: string(role), FormDomains: selected})
return
}
if role == store.RoleGlobal {
if err := h.store.ClearUserDomains(u.ID); err != nil {
logf("panel: clear user domains: %v", err)
}
}
}
if role == store.RoleDomainAdmin {
if err := h.store.SetUserDomains(u.ID, domainIDs); err != nil {
logf("panel: set user domains: %v", err)
h.renderUserForm(w, r, http.StatusInternalServerError, u.ID, userFormView{FormErr: "Could not save domain assignments.", FormUsername: username, FormRole: string(role), FormDomains: selected})
return
}
}
http.Redirect(w, r, "/users?done=updated", http.StatusSeeOther)
}
func (h *Handlers) submitUserDelete(w http.ResponseWriter, r *http.Request, u store.User) {
p, ok := h.principal(r)
if !ok {
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
if u.ID == p.ID {
h.renderUserForm(w, r, http.StatusBadRequest, u.ID, userFormView{FormErr: "You cannot delete your own account while signed in.", FormUsername: u.Username, FormRole: string(u.Role)})
return
}
if err := h.store.DeleteUser(u.ID); err != nil {
if errors.Is(err, store.ErrLastGlobal) {
h.renderUserForm(w, r, http.StatusBadRequest, u.ID, userFormView{FormErr: "Cannot delete the last global administrator.", FormUsername: u.Username, FormRole: string(u.Role)})
return
}
logf("panel: delete user %d: %v", u.ID, err)
h.renderUserForm(w, r, http.StatusInternalServerError, u.ID, userFormView{FormErr: "Could not delete user.", FormUsername: u.Username, FormRole: string(u.Role)})
return
}
http.Redirect(w, r, "/users?done=deleted", http.StatusSeeOther)
}
func parseUserID(w http.ResponseWriter, r *http.Request) (int64, bool) {
id, err := strconv.ParseInt(r.PathValue("uid"), 10, 64)
if err != nil || id <= 0 {
http.NotFound(w, r)
return 0, false
}
return id, true
}
func parseDomainIDs(r *http.Request) []int64 {
var ids []int64
for _, v := range r.PostForm["domain_ids"] {
id, err := strconv.ParseInt(v, 10, 64)
if err == nil && id > 0 {
ids = append(ids, id)
}
}
return ids
}
func domainIDSetFromForm(r *http.Request) map[int64]bool {
m := make(map[int64]bool)
for _, id := range parseDomainIDs(r) {
m[id] = true
}
return m
}
+3 -1
View File
@@ -23,6 +23,7 @@
<label for="new_password_confirm">Confirm new password</label>
<input id="new_password_confirm" name="new_password_confirm" type="password" autocomplete="new-password">
{{if .ShowDMARC}}
<h3>DMARC aggregate reports</h3>
<p class="muted">Optional default <code>rua=</code> address for every sending
domain (can be overridden per domain). Use a mailbox on a domain that
@@ -58,11 +59,12 @@
{{end}}</span>{{end}}
{{end}}
{{end}}
{{end}}
<button type="submit">Save changes</button>
</form>
<p class="muted">Leave both new-password fields empty to change the username
or DMARC address only. Changing the password signs out every other session;
{{if .ShowDMARC}}or DMARC address {{end}}only. Changing the password signs out every other session;
this one stays signed in.</p>
</div>
{{end}}
+3 -1
View File
@@ -3,6 +3,7 @@
{{if .Flash}}<div class="flash">{{.Flash}}</div>{{end}}
{{if .IsGlobal}}
<div class="card">
<h2>Add a sending domain</h2>
<form method="post" action="/domains">
@@ -16,6 +17,7 @@
<p class="muted">A DKIM key is generated for the domain; you then publish the
shown DNS record. Adding a domain does not create an application.</p>
</div>
{{end}}
<div class="card">
<h2>Domains</h2>
@@ -31,7 +33,7 @@
<td><a class="st st-{{.DNS}}" href="/domains/{{.ID}}#dns-status">{{.DNS}}</a></td>
<td class="muted">{{.DKIMSelector}}</td>
<td>{{.AppCount}}</td>
<td class="actions"><a class="danger" href="/domains/{{.ID}}/delete">Delete</a></td>
{{if $.IsGlobal}}<td class="actions"><a class="danger" href="/domains/{{.ID}}/delete">Delete</a></td>{{else}}<td></td>{{end}}
</tr>
{{end}}
</tbody>
+6 -1
View File
@@ -64,14 +64,19 @@
the column: the mark, the panel's pages, the current page's own sections,
and the session last. The mark goes to /status, the page the panel opens
on — named outright rather than as "/", which is only a redirect to it. */}}
<a class="brand" href="/status"><img src="/static/logo-compact.svg" width="220" height="100" alt="SelfPost"></a>
<a class="brand" href="{{if .IsGlobal}}/status{{else}}/domains{{end}}"><img src="/static/logo-compact.svg" width="220" height="100" alt="SelfPost"></a>
<div class="links">
{{if .IsGlobal}}
{{if eq .Active "status"}}<span aria-current="page">{{template "icon-status"}}Status</span>{{else}}<a href="/status">{{template "icon-status"}}Status</a>{{end}}
{{end}}
{{if eq .Active "domains"}}<span aria-current="page">{{template "icon-domains"}}Domains</span>{{else}}<a href="/domains">{{template "icon-domains"}}Domains</a>{{end}}
{{if eq .Active "deliveries"}}<span aria-current="page">{{template "icon-deliveries"}}Deliveries</span>{{else}}<a href="/deliveries">{{template "icon-deliveries"}}Deliveries</a>{{end}}
{{if .IsGlobal}}
{{if eq .Active "mail_queue"}}<span aria-current="page">{{template "icon-mail-queue"}}Mail queue</span>{{else}}<a href="/mail-queue">{{template "icon-mail-queue"}}Mail queue</a>{{end}}
{{if eq .Active "system_log"}}<span aria-current="page">{{template "icon-system-log"}}System log</span>{{else}}<a href="/system-log">{{template "icon-system-log"}}System log</a>{{end}}
{{if eq .Active "backup"}}<span aria-current="page">{{template "icon-backup"}}Backup</span>{{else}}<a href="/backup">{{template "icon-backup"}}Backup</a>{{end}}
{{if eq .Active "users"}}<span aria-current="page">{{template "icon-account"}}Users</span>{{else}}<a href="/users">{{template "icon-account"}}Users</a>{{end}}
{{end}}
</div>
{{template "sections" .}}
<div class="session">
@@ -0,0 +1,38 @@
{{define "content"}}
<h1>{{if .IsEdit}}Edit user{{else}}Create user{{end}}</h1>
<div class="card narrow">
{{if .Error}}<p class="error">{{.Error}}</p>{{end}}
<form method="post" action="{{if .IsEdit}}/users/{{.UserID}}{{else}}/users/new{{end}}">
<label for="username">Username</label>
<input id="username" name="username" autocomplete="username"
autocapitalize="none" spellcheck="false" value="{{.FormUsername}}" required>
<label for="password">Password{{if .IsEdit}} (leave empty to keep){{end}}</label>
<input id="password" name="password" type="password" autocomplete="new-password" {{if not .IsEdit}}required{{end}}>
<label for="role">Role</label>
<select id="role" name="role">
<option value="domain_admin" {{if eq .FormRole "domain_admin"}}selected{{end}}>Domain administrator</option>
<option value="global" {{if eq .FormRole "global"}}selected{{end}}>Global administrator</option>
</select>
<fieldset id="domain-pick">
<legend>Assigned domains</legend>
<p class="muted">Required for domain administrators.</p>
{{range .Domains}}
<label class="checkbox">
<input type="checkbox" name="domain_ids" value="{{.ID}}" {{if index $.FormDomains .ID}}checked{{end}}>
{{.Name}}
</label>
{{end}}
</fieldset>
<button type="submit">{{if .IsEdit}}Save{{else}}Create{{end}}</button>
{{if .IsEdit}}
<button type="submit" name="action" value="delete" class="danger">Delete user</button>
{{end}}
</form>
<p class="muted"><a href="/users">Back to users</a></p>
</div>
{{end}}
+28
View File
@@ -0,0 +1,28 @@
{{define "content"}}
<h1>Panel users</h1>
{{if .Flash}}<div class="flash">{{.Flash}}</div>{{end}}
<div class="card">
<p><a href="/users/new">Create user</a></p>
{{if .Users}}
<table>
<thead>
<tr><th>Username</th><th>Role</th><th>Domains</th><th></th></tr>
</thead>
<tbody>
{{range .Users}}
<tr>
<td>{{.User.Username}}</td>
<td>{{if eq .User.Role "global"}}Global{{else}}Domain admin{{end}}</td>
<td class="muted">{{if eq .User.Role "global"}}All{{else}}{{range $i, $n := .DomainNames}}{{if $i}}, {{end}}{{$n}}{{end}}{{end}}</td>
<td class="actions"><a href="/users/{{.User.ID}}">Edit</a></td>
</tr>
{{end}}
</tbody>
</table>
{{else}}
<p class="muted">No panel users besides the global administrator yet.</p>
{{end}}
</div>
{{end}}
+6 -4
View File
@@ -207,8 +207,9 @@ func TestNavMarksActivePage(t *testing.T) {
}
var buf bytes.Buffer
err = engine.Page("dashboard").ExecuteTemplate(&buf, "nav", map[string]any{
"User": "admin",
"Active": "mail_queue",
"User": "admin",
"Active": "mail_queue",
"IsGlobal": true,
})
if err != nil {
t.Fatalf("execute nav: %v", err)
@@ -234,8 +235,9 @@ func TestNavLeadsWithStatusAndPointsDomainsAtItsOwnPath(t *testing.T) {
}
var buf bytes.Buffer
if err := engine.Page("status").ExecuteTemplate(&buf, "nav", map[string]any{
"User": "admin",
"Active": "status",
"User": "admin",
"Active": "status",
"IsGlobal": true,
}); err != nil {
t.Fatalf("execute nav: %v", err)
}
+2
View File
@@ -35,6 +35,8 @@ var pageFiles = map[string][]string{
"login": {"templates/login.html"},
"dashboard": {"templates/dashboard.html"},
"account": {"templates/account.html"},
"users": {"templates/users.html"},
"user_form": {"templates/user_form.html"},
"backup": {"templates/backup.html", "templates/encrypt_fields.html"},
"domain_detail": {"templates/domain_detail.html", "templates/encrypt_fields.html"},
"domain_delete": {"templates/domain_delete.html"},
+13 -2
View File
@@ -129,7 +129,7 @@ func (s *Server) Handler() http.Handler {
mux.HandleFunc("/logout", s.auth.HandleLogout)
authed := http.NewServeMux()
authed.HandleFunc("GET /{$}", redirectToStatus)
authed.HandleFunc("GET /{$}", redirectHome)
authed.HandleFunc("GET /status", h.HandleStatus)
authed.HandleFunc("GET /status/fragment", h.HandleStatusFragment)
authed.HandleFunc("POST /status/recheck", h.HandleStatusRecheck)
@@ -153,6 +153,12 @@ func (s *Server) Handler() http.Handler {
authed.HandleFunc("/account", h.HandleAccount)
authed.HandleFunc("GET /users", h.HandleUsers)
authed.HandleFunc("GET /users/new", h.HandleUserNew)
authed.HandleFunc("POST /users/new", h.HandleUserNew)
authed.HandleFunc("GET /users/{uid}", h.HandleUserEdit)
authed.HandleFunc("POST /users/{uid}", h.HandleUserEdit)
authed.HandleFunc("GET /backup", h.HandleBackupPage)
authed.HandleFunc("POST /backup", h.HandleBackup)
@@ -168,7 +174,12 @@ func (s *Server) Handler() http.Handler {
return s.secure(mux)
}
func redirectToStatus(w http.ResponseWriter, r *http.Request) {
func redirectHome(w http.ResponseWriter, r *http.Request) {
p, ok := auth.PrincipalFromRequest(r)
if ok && !p.IsGlobal() {
http.Redirect(w, r, "/domains", http.StatusSeeOther)
return
}
http.Redirect(w, r, "/status", http.StatusSeeOther)
}