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:
@@ -75,14 +75,14 @@ func (m *Module) SessionToken(r *http.Request) (string, bool) {
|
||||
return m.sessionToken(r)
|
||||
}
|
||||
|
||||
// RenameSession updates the username carried by a session.
|
||||
func (m *Module) RenameSession(token, username string) {
|
||||
m.sessions.Rename(token, username)
|
||||
// DestroyOtherSessions invalidates every session of the user except keep.
|
||||
func (m *Module) DestroyOtherSessions(userID int64, keep string) {
|
||||
m.sessions.DestroyOthers(userID, keep)
|
||||
}
|
||||
|
||||
// DestroyOtherSessions invalidates every session except keep.
|
||||
func (m *Module) DestroyOtherSessions(keep string) {
|
||||
m.sessions.DestroyOthers(keep)
|
||||
// DestroyUserSessions invalidates every session of the user.
|
||||
func (m *Module) DestroyUserSessions(userID int64) {
|
||||
m.sessions.DestroyAll(userID)
|
||||
}
|
||||
|
||||
func logf(format string, args ...any) {
|
||||
|
||||
+122
-17
@@ -2,6 +2,7 @@ package auth
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
@@ -26,9 +27,20 @@ func newTestSessionStore(t *testing.T) *sessionStore {
|
||||
return newSessionStore(st, 7*24*time.Hour)
|
||||
}
|
||||
|
||||
// mustCreate signs the named user in, creating the user first if there is none
|
||||
// by that name.
|
||||
func mustCreate(t *testing.T, s *sessionStore, username string) string {
|
||||
t.Helper()
|
||||
token, err := s.Create(username)
|
||||
u, err := s.store.GetUserByUsername(username)
|
||||
if errors.Is(err, store.ErrUserNotFound) {
|
||||
var id int64
|
||||
id, err = s.store.CreateUser(username, "hash", store.RoleGlobal, store.Reach{})
|
||||
u.ID = id
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("user %q: %v", username, err)
|
||||
}
|
||||
token, err := s.Create(u.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("create session: %v", err)
|
||||
}
|
||||
@@ -199,27 +211,17 @@ func dropSessionsTable(t *testing.T, path string) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionRename(t *testing.T) {
|
||||
s := newTestSessionStore(t)
|
||||
token := mustCreate(t, s, "admin")
|
||||
|
||||
s.Rename(token, "operator")
|
||||
|
||||
name, ok := s.Lookup(token)
|
||||
if !ok {
|
||||
t.Fatal("session lost after rename")
|
||||
}
|
||||
if name != "operator" {
|
||||
t.Fatalf("session username = %q, want %q", name, "operator")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionDestroyOthers(t *testing.T) {
|
||||
s := newTestSessionStore(t)
|
||||
keep := mustCreate(t, s, "admin")
|
||||
other := mustCreate(t, s, "admin")
|
||||
elsewhere := mustCreate(t, s, "operator")
|
||||
admin, err := s.store.GetUserByUsername("admin")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
s.DestroyOthers(keep)
|
||||
s.DestroyOthers(admin.ID, keep)
|
||||
|
||||
if _, ok := s.Lookup(keep); !ok {
|
||||
t.Fatal("current session was destroyed")
|
||||
@@ -227,6 +229,9 @@ func TestSessionDestroyOthers(t *testing.T) {
|
||||
if _, ok := s.Lookup(other); ok {
|
||||
t.Fatal("other session survived")
|
||||
}
|
||||
if _, ok := s.Lookup(elsewhere); !ok {
|
||||
t.Fatal("another user's session was destroyed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionLookupRejectsExpired(t *testing.T) {
|
||||
@@ -254,3 +259,103 @@ func TestSessionTouchThrottled(t *testing.T) {
|
||||
t.Fatal("touch did not renew a session past the throttle window")
|
||||
}
|
||||
}
|
||||
|
||||
// requireAuthAs runs one request carrying token through RequireAuth and
|
||||
// returns the response and the principal the handler saw (nil when it never
|
||||
// ran). It is a POST, an activity request of the kind that renews a session.
|
||||
func requireAuthAs(t *testing.T, m *Module, token string) (*httptest.ResponseRecorder, *Principal) {
|
||||
t.Helper()
|
||||
var seen *Principal
|
||||
h := m.RequireAuth(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
|
||||
if p, ok := CurrentPrincipal(r.Context()); ok {
|
||||
seen = &p
|
||||
}
|
||||
}))
|
||||
r := httptest.NewRequest(http.MethodPost, "http://panel.example.com/domains", nil)
|
||||
r.AddCookie(&http.Cookie{Name: m.sessionCookie(), Value: token})
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, r)
|
||||
return rec, seen
|
||||
}
|
||||
|
||||
func mustUser(t *testing.T, m *Module, username string) int64 {
|
||||
t.Helper()
|
||||
id, err := m.store.CreateUser(username, "hash", store.RoleGlobal, store.Reach{})
|
||||
if err != nil {
|
||||
t.Fatalf("create user %q: %v", username, err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// A session is the person's, not the name's: when the user is deleted the
|
||||
// cookie is dead, and a new user created under the same name does not inherit
|
||||
// it (with that account's role).
|
||||
func TestRequireAuthDoesNotRebindASessionToANewUserWithTheSameName(t *testing.T) {
|
||||
m := testModule(t, false)
|
||||
mustUser(t, m, "admin")
|
||||
id := mustUser(t, m, "alice")
|
||||
token := mustCreate(t, m.sessions, "alice")
|
||||
|
||||
if err := m.store.DeleteUser(id); err != nil {
|
||||
t.Fatalf("delete user: %v", err)
|
||||
}
|
||||
mustUser(t, m, "alice")
|
||||
|
||||
rec, seen := requireAuthAs(t, m, token)
|
||||
if seen != nil {
|
||||
t.Fatalf("the old cookie signed in as %q after the user was deleted and the name reused", seen.Username)
|
||||
}
|
||||
if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/login" {
|
||||
t.Fatalf("status = %d, Location = %q; want a redirect to /login", rec.Code, rec.Header().Get("Location"))
|
||||
}
|
||||
}
|
||||
|
||||
// Renaming a user (the Account page, or an administrator on the user form)
|
||||
// leaves every session of theirs signed in, under the new name.
|
||||
func TestRenamingAUserKeepsTheirOtherSessions(t *testing.T) {
|
||||
m := testModule(t, false)
|
||||
id := mustUser(t, m, "alice")
|
||||
current := mustCreate(t, m.sessions, "alice")
|
||||
other := mustCreate(t, m.sessions, "alice")
|
||||
|
||||
if err := m.store.UpdateUser(id, "alicia", "hash", ""); err != nil {
|
||||
t.Fatalf("rename: %v", err)
|
||||
}
|
||||
|
||||
for name, token := range map[string]string{"current": current, "other": other} {
|
||||
_, seen := requireAuthAs(t, m, token)
|
||||
if seen == nil {
|
||||
t.Errorf("the %s session was lost by the rename", name)
|
||||
continue
|
||||
}
|
||||
if seen.Username != "alicia" || seen.ID != id {
|
||||
t.Errorf("the %s session is %q (id %d) after the rename, want alicia (id %d)", name, seen.Username, seen.ID, id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A session whose user is gone is not renewed by being used: the renewal would
|
||||
// keep a dead cookie alive for as long as someone presses it.
|
||||
func TestRequireAuthDoesNotRenewASessionWhoseUserIsGone(t *testing.T) {
|
||||
m := testModule(t, false)
|
||||
mustUser(t, m, "admin")
|
||||
id := mustUser(t, m, "alice")
|
||||
token := mustCreate(t, m.sessions, "alice")
|
||||
// Past the renewal throttle, so a Touch would write.
|
||||
stale := time.Now().Add(-2 * time.Hour).Add(m.sessions.idle)
|
||||
if err := m.store.RenewSession(hashToken(token), stale); err != nil {
|
||||
t.Fatalf("age session: %v", err)
|
||||
}
|
||||
if err := m.store.DeleteUser(id); err != nil {
|
||||
t.Fatalf("delete user: %v", err)
|
||||
}
|
||||
|
||||
rec, _ := requireAuthAs(t, m, token)
|
||||
|
||||
if got := rec.Header().Values("Set-Cookie"); len(got) != 0 {
|
||||
t.Errorf("a session of a missing user was renewed: %v", got)
|
||||
}
|
||||
if row, found, _ := m.store.LookupSession(hashToken(token)); found && !row.ExpiresAt.Equal(stale.UTC().Truncate(time.Second)) {
|
||||
t.Errorf("expiry of a missing user's session moved to %v", row.ExpiresAt)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,7 +120,7 @@ func (m *Module) submitLogin(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
token, err := m.sessions.Create(user.Username)
|
||||
token, err := m.sessions.Create(user.ID)
|
||||
if err != nil {
|
||||
logf("panel: login: create session failed: %v", err)
|
||||
m.renderLogin(w, http.StatusInternalServerError, "Internal error. Please try again.")
|
||||
|
||||
@@ -64,9 +64,9 @@ func TestLoginSignsInWithTheRightPassword(t *testing.T) {
|
||||
if token == "" {
|
||||
t.Fatal("no session cookie was issued")
|
||||
}
|
||||
name, ok := m.sessions.Lookup(token)
|
||||
if !ok || name != "admin" {
|
||||
t.Fatalf("the cookie's session resolves to %q, %t; want admin", name, ok)
|
||||
id, ok := m.sessions.Lookup(token)
|
||||
if u, err := m.store.GetUser(id); !ok || err != nil || u.Username != "admin" {
|
||||
t.Fatalf("the cookie's session resolves to user %d (%q), %t, %v; want admin", id, u.Username, ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,19 +14,20 @@ func (m *Module) RequireAuth(next http.Handler) http.Handler {
|
||||
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
username, ok := m.sessions.Lookup(token)
|
||||
userID, ok := m.sessions.Lookup(token)
|
||||
if !ok {
|
||||
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
if isSessionActivity(r) && m.sessions.Touch(token) {
|
||||
m.setSessionCookie(w, token)
|
||||
}
|
||||
u, err := m.store.GetUserByUsername(username)
|
||||
u, err := m.store.GetUser(userID)
|
||||
if err != nil {
|
||||
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
// Only a session whose user exists is kept alive by being used.
|
||||
if isSessionActivity(r) && m.sessions.Touch(token) {
|
||||
m.setSessionCookie(w, token)
|
||||
}
|
||||
p := principalFromUser(u)
|
||||
ctx := withPrincipal(r.Context(), p)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
|
||||
@@ -41,14 +41,14 @@ func hashToken(token string) string {
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// Create issues a new session for username and returns its token. It fails
|
||||
// Create issues a new session for the user and returns its token. It fails
|
||||
// closed: if the row cannot be written the caller gets an error and must not
|
||||
// hand out a cookie, because a token that is not in the database looks like a
|
||||
// signed-in browser while every request it makes bounces back to /login.
|
||||
func (s *sessionStore) Create(username string) (string, error) {
|
||||
func (s *sessionStore) Create(userID int64) (string, error) {
|
||||
token := randomToken(32)
|
||||
now := time.Now()
|
||||
if err := s.store.CreateSession(hashToken(token), username, now.Add(s.idle)); err != nil {
|
||||
if err := s.store.CreateSession(hashToken(token), userID, now.Add(s.idle)); err != nil {
|
||||
return "", err
|
||||
}
|
||||
// Pruning is housekeeping: the new session is already valid, so a failure
|
||||
@@ -59,28 +59,28 @@ func (s *sessionStore) Create(username string) (string, error) {
|
||||
return token, nil
|
||||
}
|
||||
|
||||
// Lookup returns the session username for a token if it exists and is
|
||||
// unexpired.
|
||||
func (s *sessionStore) Lookup(token string) (string, bool) {
|
||||
// Lookup returns the id of the user a token's session belongs to, if the
|
||||
// session exists and is unexpired.
|
||||
func (s *sessionStore) Lookup(token string) (int64, bool) {
|
||||
if token == "" {
|
||||
return "", false
|
||||
return 0, false
|
||||
}
|
||||
hash := hashToken(token)
|
||||
row, found, err := s.store.LookupSession(hash)
|
||||
if err != nil {
|
||||
logf("panel: session: lookup failed: %v", err)
|
||||
return "", false
|
||||
return 0, false
|
||||
}
|
||||
if !found {
|
||||
return "", false
|
||||
return 0, false
|
||||
}
|
||||
if time.Now().After(row.ExpiresAt) {
|
||||
if err := s.store.DeleteSession(hash); err != nil {
|
||||
logf("panel: session: delete expired failed: %v", err)
|
||||
}
|
||||
return "", false
|
||||
return 0, false
|
||||
}
|
||||
return row.Username, true
|
||||
return row.UserID, true
|
||||
}
|
||||
|
||||
// Touch extends a session's sliding expiry if it has been at least
|
||||
@@ -107,17 +107,17 @@ func (s *sessionStore) Touch(token string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// Rename updates the username carried by a session, keeping its expiry.
|
||||
func (s *sessionStore) Rename(token, username string) {
|
||||
if err := s.store.RenameSession(hashToken(token), username); err != nil {
|
||||
logf("panel: session: rename failed: %v", err)
|
||||
// DestroyOthers invalidates every session of the user except keep.
|
||||
func (s *sessionStore) DestroyOthers(userID int64, keep string) {
|
||||
if err := s.store.DeleteOtherSessions(userID, hashToken(keep)); err != nil {
|
||||
logf("panel: session: destroy others failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// DestroyOthers invalidates every session except keep.
|
||||
func (s *sessionStore) DestroyOthers(keep string) {
|
||||
if err := s.store.DeleteOtherSessions(hashToken(keep)); err != nil {
|
||||
logf("panel: session: destroy others failed: %v", err)
|
||||
// DestroyAll invalidates every session of the user.
|
||||
func (s *sessionStore) DestroyAll(userID int64) {
|
||||
if err := s.store.DeleteUserSessions(userID); err != nil {
|
||||
logf("panel: session: destroy all failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user