audit 4: sign-in timing and sessions, server timeouts, polling that recovers
test / test (push) Canceled after 0s
test / test (push) Canceled after 0s
Steps 1-3 of stage 4, tested together (their docs share files).
Step 1 (M8, L15, L16): an unknown name pays a bcrypt comparison at the
panel's work factor too (noSuchUserHash, made once) -
TestLoginTakesAsLongForAnUnknownName holds the medians within a factor of
two; the Account form's current-password check has its own limiter, per
user (AllowPasswordChange); a sign-in destroys every session the request
presents before it issues its own.
Step 2 (L14): newHTTPServer - ReadTimeout 30 s, WriteTimeout 60 s,
IdleTimeout 2 min beside ReadHeaderTimeout; the full backup moves its write
deadline to two hours through http.ResponseController (e2e: the log shows
no failure to move it).
Step 3 (M11), read in htmx 2.0.4's source (dev/upstream/htmx-2.0.4, the npm
build byte-equal to the shipped htmx.min.js): the poll passes source: box,
and the next refresh is scheduled from htmx:afterRequest, which htmx fires
on load, error, abort and timeout, and after a swap on the nearest parent
left (the box found by detail.target's id); failures in a row double the
wait to 60 s. RequireAuth answers htmx with 401 + HX-Redirect: /login,
which htmx follows before it looks at the status. testdata/poll_test.js
runs panel.js in node against a stand-in DOM and clock (TestPanelJS; skipped
without node, which the test server lacks - run here, and it fails on the
old panel.js).
Also measured: the stage-3 e2e regression for H1 fails as it should on HEAD
with the old entrypoint ("check data/postfix/e2e_extra_map: permission
denied", the panel restarting).
Tested on the test server: go vet + go test of 25 packages, make e2e (all
pass, 639 s) on this tree.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+21
-13
@@ -6,6 +6,7 @@ import (
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -29,8 +30,9 @@ type Module struct {
|
||||
sessions *sessionStore
|
||||
setup *setupManager
|
||||
|
||||
loginLimiter *rateLimiter
|
||||
setupLimiter *rateLimiter
|
||||
loginLimiter *rateLimiter
|
||||
setupLimiter *rateLimiter
|
||||
passwordLimiter *rateLimiter
|
||||
|
||||
trustedProxies []*net.IPNet
|
||||
}
|
||||
@@ -43,16 +45,22 @@ func New(st *store.Store, cfg Config, v *view.Engine, setupTokenPath string) *Mo
|
||||
idleDays = 7
|
||||
}
|
||||
m := &Module{
|
||||
store: st,
|
||||
cfg: cfg,
|
||||
view: v,
|
||||
sessions: newSessionStore(st, time.Duration(idleDays)*24*time.Hour),
|
||||
setupLimiter: newRateLimiter(10, time.Minute),
|
||||
loginLimiter: newRateLimiter(10, 15*time.Minute),
|
||||
trustedProxies: cfg.TrustedProxyCIDRs,
|
||||
store: st,
|
||||
cfg: cfg,
|
||||
view: v,
|
||||
sessions: newSessionStore(st, time.Duration(idleDays)*24*time.Hour),
|
||||
setupLimiter: newRateLimiter(10, time.Minute),
|
||||
loginLimiter: newRateLimiter(10, 15*time.Minute),
|
||||
// The Account form's current-password check has a bucket of its
|
||||
// own, per user: ten wrong guesses there used to lock the address
|
||||
// out of signing in (audit 2026-10-12, L15), and the one guessing
|
||||
// is whoever holds that user's session, wherever from.
|
||||
passwordLimiter: newRateLimiter(10, 15*time.Minute),
|
||||
trustedProxies: cfg.TrustedProxyCIDRs,
|
||||
}
|
||||
m.setupLimiter.startSweeper()
|
||||
m.loginLimiter.startSweeper()
|
||||
m.passwordLimiter.startSweeper()
|
||||
m.setup = newSetupManager(st, cfg.Hostname, setupTokenPath)
|
||||
return m
|
||||
}
|
||||
@@ -63,10 +71,10 @@ func (m *Module) Bootstrap() error {
|
||||
return m.setup.bootstrap()
|
||||
}
|
||||
|
||||
// AllowLoginAttempt reports whether a login or account-password change attempt
|
||||
// from r is within the rate limit (security.md).
|
||||
func (m *Module) AllowLoginAttempt(r *http.Request) bool {
|
||||
return m.loginLimiter.Allow(clientIP(r, m.trustedProxies))
|
||||
// AllowPasswordChange reports whether another current-password check on the
|
||||
// Account form is within the user's rate limit (security.md).
|
||||
func (m *Module) AllowPasswordChange(userID int64) bool {
|
||||
return m.passwordLimiter.Allow("user:" + strconv.FormatInt(userID, 10))
|
||||
}
|
||||
|
||||
// SessionToken returns the session token the request carries, if exactly one
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/mixeme/selfpost/internal/store"
|
||||
"github.com/mixeme/selfpost/internal/web/validate"
|
||||
@@ -117,6 +118,10 @@ func (m *Module) submitLogin(w http.ResponseWriter, r *http.Request) {
|
||||
if !errors.Is(err, store.ErrUserNotFound) {
|
||||
logf("panel: login: get user failed: %v", err)
|
||||
}
|
||||
// A comparison anyway, so an unknown name is refused in the time
|
||||
// a wrong password is: the answer's delay told which names exist
|
||||
// (audit 2026-10-12, M8).
|
||||
_ = bcrypt.CompareHashAndPassword(noSuchUserHash(), []byte(password))
|
||||
m.renderLogin(w, http.StatusUnauthorized, "Invalid username or password.")
|
||||
return
|
||||
}
|
||||
@@ -126,6 +131,15 @@ func (m *Module) submitLogin(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
// The session the browser presents, if any, ends here: a sign-in issues
|
||||
// a new token and leaves no other behind it - one planted before the
|
||||
// sign-in is worth nothing after (audit 2026-10-12, L16).
|
||||
name := m.sessionCookie()
|
||||
for _, c := range r.Cookies() {
|
||||
if c.Name == name {
|
||||
m.sessions.Destroy(c.Value)
|
||||
}
|
||||
}
|
||||
token, err := m.sessions.Create(user.ID)
|
||||
if err != nil {
|
||||
logf("panel: login: create session failed: %v", err)
|
||||
@@ -136,6 +150,16 @@ func (m *Module) submitLogin(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
// noSuchUserHash is a hash of the panel's work factor, compared against when
|
||||
// a sign-in names no user.
|
||||
var noSuchUserHash = sync.OnceValue(func() []byte {
|
||||
h, err := bcrypt.GenerateFromPassword([]byte("selfpost: no such user"), BcryptCost)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return h
|
||||
})
|
||||
|
||||
// setSessionCookie sets the session cookie. SameSite=Lax withholds it from a
|
||||
// cross-site request unless that is a top-level navigation with a safe method
|
||||
// (rfc6265bis § 5.8.3, § 5.6.7.1), so a cross-site POST arrives without it.
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
@@ -282,3 +285,94 @@ func expireSetupToken(m *Module) {
|
||||
defer m.setup.mu.Unlock()
|
||||
m.setup.expiresAt = m.setup.expiresAt.Add(-2 * setupTokenTTL)
|
||||
}
|
||||
|
||||
// An unknown name is refused in the time a wrong password is: both pay one
|
||||
// bcrypt comparison at the panel's work factor (audit 2026-10-12, M8). The
|
||||
// medians of a few attempts each must be within a factor of two; before the
|
||||
// fix the unknown name answered some hundred times faster.
|
||||
func TestLoginTakesAsLongForAnUnknownName(t *testing.T) {
|
||||
m := testModule(t, false)
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(testPassword), BcryptCost)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := m.store.CreateGlobalUser("admin", string(hash)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
noSuchUserHash() // made once, not inside a measurement
|
||||
|
||||
median := func(username string) time.Duration {
|
||||
var d []time.Duration
|
||||
for i := 0; i < 5; i++ {
|
||||
start := time.Now()
|
||||
// A fresh address each time: the limiter is not what is timed.
|
||||
rec := postLogin(m, fmt.Sprintf("203.0.113.%d:5000", len(d)+10*len(username)), username, "not-the-password")
|
||||
d = append(d, time.Since(start))
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("%s: status %d, want 401", username, rec.Code)
|
||||
}
|
||||
}
|
||||
slices.Sort(d)
|
||||
return d[len(d)/2]
|
||||
}
|
||||
known, unknown := median("admin"), median("nobody")
|
||||
if unknown*2 < known || known*2 < unknown {
|
||||
t.Errorf("a wrong password takes %v, an unknown name %v: the time tells which names exist", known, unknown)
|
||||
}
|
||||
}
|
||||
|
||||
// A sign-in ends the session the browser presented: a token planted before
|
||||
// it is worth nothing after (audit 2026-10-12, L16).
|
||||
func TestLoginEndsThePresentedSession(t *testing.T) {
|
||||
m := moduleWithAdmin(t)
|
||||
u, err := m.store.GetUserByUsername("admin")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
planted, err := m.sessions.Create(u.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
form := url.Values{"username": {"admin"}, "password": {testPassword}}
|
||||
r := httptest.NewRequest(http.MethodPost, "http://panel.example.com/login", strings.NewReader(form.Encode()))
|
||||
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
r.AddCookie(&http.Cookie{Name: m.sessionCookie(), Value: planted})
|
||||
rec := httptest.NewRecorder()
|
||||
m.HandleLogin(rec, r)
|
||||
if rec.Code != http.StatusSeeOther {
|
||||
t.Fatalf("sign-in = %d", rec.Code)
|
||||
}
|
||||
if _, ok := m.sessions.Lookup(planted); ok {
|
||||
t.Error("the session presented at sign-in still works after it")
|
||||
}
|
||||
if fresh := sessionCookieValue(t, m, rec); fresh == "" || fresh == planted {
|
||||
t.Errorf("the sign-in issued %q", fresh)
|
||||
} else if _, ok := m.sessions.Lookup(fresh); !ok {
|
||||
t.Error("the new session does not work")
|
||||
}
|
||||
}
|
||||
|
||||
// htmx asking without a session is told to load the sign-in page, not given
|
||||
// it to swap into the box that asked (audit 2026-10-12, M11); a browser is
|
||||
// redirected as before.
|
||||
func TestRequireAuthTellsHtmxToSignIn(t *testing.T) {
|
||||
m := moduleWithAdmin(t)
|
||||
h := m.RequireAuth(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
t.Error("a request without a session reached the page")
|
||||
}))
|
||||
|
||||
r := httptest.NewRequest(http.MethodGet, "http://panel.example.com/overview/stats", nil)
|
||||
r.Header.Set("HX-Request", "true")
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, r)
|
||||
if rec.Code != http.StatusUnauthorized || rec.Header().Get("HX-Redirect") != "/login" || rec.Header().Get("Location") != "" {
|
||||
t.Errorf("htmx without a session: %d, HX-Redirect %q, Location %q; want 401 with HX-Redirect /login",
|
||||
rec.Code, rec.Header().Get("HX-Redirect"), rec.Header().Get("Location"))
|
||||
}
|
||||
|
||||
rec = httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "http://panel.example.com/overview", nil))
|
||||
if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/login" {
|
||||
t.Errorf("a browser without a session: %d, Location %q", rec.Code, rec.Header().Get("Location"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,17 +11,17 @@ func (m *Module) RequireAuth(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
token, ok := m.sessionToken(r)
|
||||
if !ok {
|
||||
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||
toLogin(w, r)
|
||||
return
|
||||
}
|
||||
userID, ok := m.sessions.Lookup(token)
|
||||
if !ok {
|
||||
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||
toLogin(w, r)
|
||||
return
|
||||
}
|
||||
u, err := m.store.GetUser(userID)
|
||||
if err != nil {
|
||||
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||
toLogin(w, r)
|
||||
return
|
||||
}
|
||||
// Only a session whose user exists is kept alive by being used.
|
||||
@@ -34,6 +34,21 @@ func (m *Module) RequireAuth(next http.Handler) http.Handler {
|
||||
})
|
||||
}
|
||||
|
||||
// toLogin sends a request without a session to the sign-in page. A browser
|
||||
// gets a redirect; htmx gets HX-Redirect, which it follows with the whole
|
||||
// page, before it looks at the status (htmx 2.0.4, src/htmx.js
|
||||
// handleAjaxResponse(): location.href = the header's value). A 303 to htmx
|
||||
// was followed inside the request, and the sign-in page swapped into the box
|
||||
// that asked (audit 2026-10-12, M11).
|
||||
func toLogin(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("HX-Request") != "" {
|
||||
w.Header().Set("HX-Redirect", "/login")
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
// isSessionActivity: a GET from htmx is a background poll - every panel hx-get
|
||||
// is a load or a poll - and does not renew the session. htmx 2.0.4, src/htmx.js
|
||||
// getHeaders(): every request it issues carries HX-Request: true (and
|
||||
|
||||
Reference in New Issue
Block a user