release: 1.3.0: 1.3.0-1.3.1: security pass, queue persist, full backup layout
[1.3.0] Security and quality after 1.2.5: domain-admin send-log authorization, fail-closed sign-in and application delete, level-2 rate-limit race fix, restore Resync, expanded tests, operator docs, release CI, and OFL for IBM Plex. Upgrading from 1.2.x is a tag bump; no migration. Added: - licence: the SIL Open Font License 1.1 text now travels with the IBM Plex - docs: agreed roadmap item **queue-retries** — show this Postfix's retry Security: - The independent security review of the send-log authorization and Fixed: - test (e2e): send-log status scrapers follow the badge markup in - security (panel): the Deliveries list is scoped to a domain administrator's - mail (level-2 rate limit): the ceiling is no longer overshot by messages that - panel (sign-in): a session that cannot be written to the database no longer - panel (applications): deleting an application removes its SASL credentials … (2 more in CHANGELOG) Changed: - docs: operator and as-built docs aligned with the code after a full - docs: [guide.md](docs/guide.md) reorganised into **Installation**, **Instance - docs: the 2026-08-13 full-tree review plan is complete — every phase (P0–P7) - licence: [NOTICE](NOTICE) tells modifiers to update `SourceURL` in - ci: the release image is published only for a **published** GitHub Release … (9 more in CHANGELOG) [1.3.1] Retry policy in the panel, persistent Postfix queue, and self-contained full backups. Mail queue and delivery history show this Postfix's first retry, backoff cap, and queue lifetime. Deferred mail survives container recreate. Full backups now archive `data/`, compose, `.env`, and `certs/`; the archive layout breaks 1.3.0 flat backups (unpack those with `tar xzf backup.tar.gz -C ./data` as before). Upgrading from 1.3.0 is a tag bump; no schema migration. Added: - Mail queue and a delivery's history show this Postfix's retry policy - docs: **Plan checklists** in [development.md](docs/development.md) — format, - docs: **Implementation checklists** with model routing in - docs: roadmap candidates **send-log-retention** (panel Settings for delivery - Postfix queue under `/data/postfix/queue` — deferred and active mail survive … (1 more in CHANGELOG) Changed: - **Breaking:** full-backup archive layout — paths are prefixed with `data/`; - docs: operator guide, architecture, security, and backup UI updated for - docs: HTML mockups for a full panel UI refresh Changed: - docs: panel UI mockups after review — Status restored to live readings - docs: panel UI design system and mockups rebuilt as separate pages - docs: panel UI mockups — add-domain sits in the list card (Domains and Fixed: - ci (GHCR): per-arch package tags (`X.Y.Z-amd64`, `X.Y.Z-arm64`) are dropped Squashed CHANGELOG sections: [1.3.0], [1.3.1]. Full detail: CHANGELOG.md (1.3.0, 1.3.1).
This commit is contained in:
@@ -51,6 +51,8 @@ func New(st *store.Store, cfg Config, v *view.Engine, setupTokenPath string) *Mo
|
||||
loginLimiter: newRateLimiter(10, 15*time.Minute),
|
||||
trustedProxies: cfg.TrustedProxyCIDRs,
|
||||
}
|
||||
m.setupLimiter.startSweeper()
|
||||
m.loginLimiter.startSweeper()
|
||||
m.setup = newSetupManager(st, cfg.Hostname, setupTokenPath)
|
||||
return m
|
||||
}
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"github.com/mixeme/selfpost/internal/store"
|
||||
"github.com/mixeme/selfpost/internal/web/view"
|
||||
)
|
||||
@@ -22,6 +26,15 @@ func newTestSessionStore(t *testing.T) *sessionStore {
|
||||
return newSessionStore(st, 7*24*time.Hour)
|
||||
}
|
||||
|
||||
func mustCreate(t *testing.T, s *sessionStore, username string) string {
|
||||
t.Helper()
|
||||
token, err := s.Create(username)
|
||||
if err != nil {
|
||||
t.Fatalf("create session: %v", err)
|
||||
}
|
||||
return token
|
||||
}
|
||||
|
||||
func mustView(t *testing.T) *view.Engine {
|
||||
t.Helper()
|
||||
v, err := view.New("test")
|
||||
@@ -86,7 +99,7 @@ func TestSessionTokenIgnoresTheOtherName(t *testing.T) {
|
||||
|
||||
func TestRequireAuthRejectsDuplicateCookies(t *testing.T) {
|
||||
m := testModule(t, false)
|
||||
token := m.sessions.Create("admin")
|
||||
token := mustCreate(t, m.sessions, "admin")
|
||||
|
||||
reached := false
|
||||
h := m.RequireAuth(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { reached = true }))
|
||||
@@ -107,7 +120,7 @@ func TestRequireAuthRejectsDuplicateCookies(t *testing.T) {
|
||||
|
||||
func TestLogoutClearsBothCookieNames(t *testing.T) {
|
||||
m := testModule(t, true)
|
||||
token := m.sessions.Create("admin")
|
||||
token := mustCreate(t, m.sessions, "admin")
|
||||
|
||||
r := httptest.NewRequest(http.MethodPost, "http://panel.example.com/logout", nil)
|
||||
r.Host = "panel.example.com"
|
||||
@@ -132,9 +145,63 @@ func TestLogoutClearsBothCookieNames(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A session that could not be stored must not turn into a cookie: the browser
|
||||
// would look signed in, and every request it made would be bounced to /login
|
||||
// with no explanation. Only the sessions table is broken here, so the request
|
||||
// gets past the user lookup and password check and fails exactly where the
|
||||
// session is written.
|
||||
func TestLoginSetsNoCookieWhenTheSessionCannotBeStored(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "test.db")
|
||||
st, err := store.Open(path)
|
||||
if err != nil {
|
||||
t.Fatalf("open store: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { st.Close() })
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte("correct-horse-battery"), bcrypt.MinCost)
|
||||
if err != nil {
|
||||
t.Fatalf("hash password: %v", err)
|
||||
}
|
||||
if err := st.CreateGlobalUser("admin", string(hash)); err != nil {
|
||||
t.Fatalf("create user: %v", err)
|
||||
}
|
||||
dropSessionsTable(t, path)
|
||||
|
||||
m := New(st, Config{}, mustView(t), "")
|
||||
form := url.Values{"username": {"admin"}, "password": {"correct-horse-battery"}}
|
||||
r := httptest.NewRequest(http.MethodPost, "http://panel.example.com/login",
|
||||
strings.NewReader(form.Encode()))
|
||||
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
rec := httptest.NewRecorder()
|
||||
m.HandleLogin(rec, r)
|
||||
|
||||
if got := rec.Header().Values("Set-Cookie"); len(got) != 0 {
|
||||
t.Errorf("a session cookie was issued for a session that was never stored: %v", got)
|
||||
}
|
||||
if rec.Code != http.StatusInternalServerError {
|
||||
t.Errorf("status = %d, want 500 (the login failed)", rec.Code)
|
||||
}
|
||||
if loc := rec.Header().Get("Location"); loc != "" {
|
||||
t.Errorf("the browser was sent to %q as if it were signed in", loc)
|
||||
}
|
||||
}
|
||||
|
||||
// dropSessionsTable breaks session persistence while leaving the rest of the
|
||||
// schema usable. The SQLite driver is registered by internal/store.
|
||||
func dropSessionsTable(t *testing.T, path string) {
|
||||
t.Helper()
|
||||
db, err := sql.Open("sqlite", "file:"+path+"?_pragma=busy_timeout(5000)")
|
||||
if err != nil {
|
||||
t.Fatalf("open database directly: %v", err)
|
||||
}
|
||||
defer db.Close()
|
||||
if _, err := db.Exec("DROP TABLE sessions"); err != nil {
|
||||
t.Fatalf("drop sessions table: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionRename(t *testing.T) {
|
||||
s := newTestSessionStore(t)
|
||||
token := s.Create("admin")
|
||||
token := mustCreate(t, s, "admin")
|
||||
|
||||
s.Rename(token, "operator")
|
||||
|
||||
@@ -149,8 +216,8 @@ func TestSessionRename(t *testing.T) {
|
||||
|
||||
func TestSessionDestroyOthers(t *testing.T) {
|
||||
s := newTestSessionStore(t)
|
||||
keep := s.Create("admin")
|
||||
other := s.Create("admin")
|
||||
keep := mustCreate(t, s, "admin")
|
||||
other := mustCreate(t, s, "admin")
|
||||
|
||||
s.DestroyOthers(keep)
|
||||
|
||||
@@ -165,7 +232,7 @@ func TestSessionDestroyOthers(t *testing.T) {
|
||||
func TestSessionLookupRejectsExpired(t *testing.T) {
|
||||
s := newTestSessionStore(t)
|
||||
s.idle = -time.Minute
|
||||
token := s.Create("admin")
|
||||
token := mustCreate(t, s, "admin")
|
||||
|
||||
if _, ok := s.Lookup(token); ok {
|
||||
t.Fatal("expired session was accepted")
|
||||
@@ -174,7 +241,7 @@ func TestSessionLookupRejectsExpired(t *testing.T) {
|
||||
|
||||
func TestSessionTouchThrottled(t *testing.T) {
|
||||
s := newTestSessionStore(t)
|
||||
token := s.Create("admin")
|
||||
token := mustCreate(t, s, "admin")
|
||||
|
||||
if s.Touch(token) {
|
||||
t.Fatal("touch renewed a session created moments ago")
|
||||
|
||||
@@ -120,7 +120,12 @@ func (m *Module) submitLogin(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
token := m.sessions.Create(user.Username)
|
||||
token, err := m.sessions.Create(user.Username)
|
||||
if err != nil {
|
||||
logf("panel: login: create session failed: %v", err)
|
||||
m.renderLogin(w, http.StatusInternalServerError, "Internal error. Please try again.")
|
||||
return
|
||||
}
|
||||
m.setSessionCookie(w, token)
|
||||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,284 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
const testPassword = "correct-horse-battery"
|
||||
|
||||
// moduleWithAdmin returns a panel that has already been through setup, with one
|
||||
// global administrator whose password is testPassword.
|
||||
func moduleWithAdmin(t *testing.T) *Module {
|
||||
t.Helper()
|
||||
m := testModule(t, false)
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(testPassword), bcrypt.MinCost)
|
||||
if err != nil {
|
||||
t.Fatalf("hash password: %v", err)
|
||||
}
|
||||
if err := m.store.CreateGlobalUser("admin", string(hash)); err != nil {
|
||||
t.Fatalf("create user: %v", err)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// postLogin submits the sign-in form from remoteAddr (the limiter's key) and
|
||||
// returns what the handler wrote.
|
||||
func postLogin(m *Module, remoteAddr, username, password string) *httptest.ResponseRecorder {
|
||||
form := url.Values{"username": {username}, "password": {password}}
|
||||
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.RemoteAddr = remoteAddr
|
||||
rec := httptest.NewRecorder()
|
||||
m.HandleLogin(rec, r)
|
||||
return rec
|
||||
}
|
||||
|
||||
// sessionCookieValue returns the session token the response issued, or "" if it
|
||||
// issued none.
|
||||
func sessionCookieValue(t *testing.T, m *Module, rec *httptest.ResponseRecorder) string {
|
||||
t.Helper()
|
||||
for _, c := range rec.Result().Cookies() {
|
||||
if c.Name == m.sessionCookie() {
|
||||
return c.Value
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func TestLoginSignsInWithTheRightPassword(t *testing.T) {
|
||||
m := moduleWithAdmin(t)
|
||||
|
||||
rec := postLogin(m, "203.0.113.7:5000", "admin", testPassword)
|
||||
|
||||
if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/" {
|
||||
t.Fatalf("status = %d, Location = %q; want a redirect to /", rec.Code, rec.Header().Get("Location"))
|
||||
}
|
||||
token := sessionCookieValue(t, m, rec)
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
// A refused sign-in must not say which half was wrong: the panel is public, and
|
||||
// distinguishable answers would turn the form into a list of usernames.
|
||||
func TestLoginRefusesBadCredentialsWithoutSayingWhy(t *testing.T) {
|
||||
m := moduleWithAdmin(t)
|
||||
|
||||
bodies := make(map[string]string, 2)
|
||||
for name, creds := range map[string][2]string{
|
||||
"wrong password": {"admin", "not-the-password"},
|
||||
"unknown user": {"nobody", testPassword},
|
||||
} {
|
||||
rec := postLogin(m, "203.0.113.7:5000", creds[0], creds[1])
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Errorf("%s: status = %d, want 401", name, rec.Code)
|
||||
}
|
||||
if got := sessionCookieValue(t, m, rec); got != "" {
|
||||
t.Errorf("%s: a session cookie was issued: %q", name, got)
|
||||
}
|
||||
bodies[name] = rec.Body.String()
|
||||
}
|
||||
if bodies["wrong password"] != bodies["unknown user"] {
|
||||
t.Error("the two refusals differ, so the form tells an attacker which usernames exist")
|
||||
}
|
||||
}
|
||||
|
||||
// The lockout is what makes online guessing pointless, so it has to hold even
|
||||
// for the request that finally carries the right password — and it has to be
|
||||
// scoped to the address that spent the attempts.
|
||||
func TestLoginLocksOutAfterTooManyAttempts(t *testing.T) {
|
||||
m := moduleWithAdmin(t)
|
||||
const attacker = "203.0.113.7:5000"
|
||||
|
||||
for i := 0; i < 10; i++ {
|
||||
if rec := postLogin(m, attacker, "admin", "guess"); rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("attempt %d: status = %d, want 401 (still under the limit)", i+1, rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
rec := postLogin(m, attacker, "admin", testPassword)
|
||||
if rec.Code != http.StatusTooManyRequests {
|
||||
t.Errorf("status = %d, want 429; the lockout was bypassed by guessing right", rec.Code)
|
||||
}
|
||||
if got := sessionCookieValue(t, m, rec); got != "" {
|
||||
t.Errorf("a locked-out request was signed in: %q", got)
|
||||
}
|
||||
|
||||
if rec := postLogin(m, "198.51.100.9:5000", "admin", testPassword); rec.Code != http.StatusSeeOther {
|
||||
t.Errorf("another address got %d; one guesser locked out the whole internet", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// Before the first administrator exists there is nothing to sign in as, so the
|
||||
// form is replaced by a pointer to the setup link rather than a password box
|
||||
// that can never succeed.
|
||||
func TestLoginPointsAtSetupBeforeTheFirstAdministrator(t *testing.T) {
|
||||
m := testModule(t, false)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
m.HandleLogin(rec, httptest.NewRequest(http.MethodGet, "http://panel.example.com/login", nil))
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200", rec.Code)
|
||||
}
|
||||
body := rec.Body.String()
|
||||
if !strings.Contains(body, "No administrator has been created yet") {
|
||||
t.Errorf("the login page does not point at the setup link:\n%s", body)
|
||||
}
|
||||
if strings.Contains(body, `name="password"`) {
|
||||
t.Errorf("the login page offers a password field with no account to use it:\n%s", body)
|
||||
}
|
||||
}
|
||||
|
||||
// getSetup performs the GET the operator's browser makes when it follows the
|
||||
// one-time link.
|
||||
func getSetup(m *Module, token string) *httptest.ResponseRecorder {
|
||||
rec := httptest.NewRecorder()
|
||||
m.HandleSetup(rec, httptest.NewRequest(http.MethodGet, "http://panel.example.com/setup/"+token, nil))
|
||||
return rec
|
||||
}
|
||||
|
||||
func postSetup(m *Module, token string, form url.Values) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest(http.MethodPost, "http://panel.example.com/setup/"+token,
|
||||
strings.NewReader(form.Encode()))
|
||||
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
rec := httptest.NewRecorder()
|
||||
m.HandleSetup(rec, r)
|
||||
return rec
|
||||
}
|
||||
|
||||
func setupForm(username, password, confirm string) url.Values {
|
||||
return url.Values{
|
||||
"username": {username},
|
||||
"password": {password},
|
||||
"password_confirm": {confirm},
|
||||
}
|
||||
}
|
||||
|
||||
// The setup link creates the first global administrator and then stops
|
||||
// existing: the persistent fact is the user row, so the link is dead after a
|
||||
// restart too, not only for the process that served it.
|
||||
func TestSetupCreatesTheFirstAdministratorAndThenCloses(t *testing.T) {
|
||||
m := testModule(t, false)
|
||||
token, ok := m.setup.activeToken()
|
||||
if !ok {
|
||||
t.Fatal("no setup token on a panel with no users")
|
||||
}
|
||||
|
||||
if rec := getSetup(m, token); rec.Code != http.StatusOK {
|
||||
t.Fatalf("GET the setup link = %d, want the form", rec.Code)
|
||||
}
|
||||
|
||||
rec := postSetup(m, token, setupForm("operator", "a-long-enough-password", "a-long-enough-password"))
|
||||
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"))
|
||||
}
|
||||
|
||||
u, err := m.store.GetUserByUsername("operator")
|
||||
if err != nil {
|
||||
t.Fatalf("the administrator was not created: %v", err)
|
||||
}
|
||||
if u.Role != RoleGlobal {
|
||||
t.Errorf("the first administrator has role %q, want global", u.Role)
|
||||
}
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(u.PasswordHash), []byte("a-long-enough-password")); err != nil {
|
||||
t.Errorf("the stored hash does not match the password that was set: %v", err)
|
||||
}
|
||||
|
||||
if rec := getSetup(m, token); rec.Code != http.StatusNotFound {
|
||||
t.Errorf("the setup link still answers %d after setup completed, want 404", rec.Code)
|
||||
}
|
||||
if rec := postSetup(m, token, setupForm("second", "a-long-enough-password", "a-long-enough-password")); rec.Code != http.StatusNotFound {
|
||||
t.Errorf("a second administrator could be created through the setup link (%d)", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// A token that is wrong, or one that has aged out and been replaced, is not a
|
||||
// hint that setup exists: both answer 404, the same as any unknown path.
|
||||
func TestSetupRejectsAWrongOrExpiredToken(t *testing.T) {
|
||||
m := testModule(t, false)
|
||||
token, ok := m.setup.activeToken()
|
||||
if !ok {
|
||||
t.Fatal("no setup token on a panel with no users")
|
||||
}
|
||||
|
||||
if rec := getSetup(m, token+"x"); rec.Code != http.StatusNotFound {
|
||||
t.Errorf("a wrong token answered %d, want 404", rec.Code)
|
||||
}
|
||||
|
||||
expireSetupToken(m)
|
||||
|
||||
if rec := getSetup(m, token); rec.Code != http.StatusNotFound {
|
||||
t.Errorf("the expired token still opens setup (%d)", rec.Code)
|
||||
}
|
||||
fresh, _ := m.setup.activeToken()
|
||||
if fresh == token {
|
||||
t.Fatal("the expired token was not replaced")
|
||||
}
|
||||
if rec := getSetup(m, fresh); rec.Code != http.StatusOK {
|
||||
t.Errorf("the reissued token does not open setup (%d)", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// The first account is the one that can never be locked out of the panel from
|
||||
// outside, so the rules that apply to every other user apply here too — before
|
||||
// anything is written.
|
||||
func TestSetupRejectsCredentialsItWouldNotAcceptLater(t *testing.T) {
|
||||
for name, form := range map[string]url.Values{
|
||||
"username too short": setupForm("op", "a-long-enough-password", "a-long-enough-password"),
|
||||
"username not ASCII": setupForm("оператор", "a-long-enough-password", "a-long-enough-password"),
|
||||
"passwords differ": setupForm("operator", "a-long-enough-password", "a-long-enough-passwerd"),
|
||||
"password too short": setupForm("operator", "short", "short"),
|
||||
"no password at all": setupForm("operator", "", ""),
|
||||
"no username at all": setupForm("", "a-long-enough-password", "a-long-enough-password"),
|
||||
} {
|
||||
m := testModule(t, false)
|
||||
token, _ := m.setup.activeToken()
|
||||
|
||||
rec := postSetup(m, token, form)
|
||||
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Errorf("%s: status = %d, want 400", name, rec.Code)
|
||||
}
|
||||
if exists, err := m.store.UserExists(); err != nil || exists {
|
||||
t.Errorf("%s: an administrator was created anyway (err=%v)", name, err)
|
||||
}
|
||||
if rec := getSetup(m, token); rec.Code != http.StatusOK {
|
||||
t.Errorf("%s: the setup link was burned by a rejected form (%d)", name, rec.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Setup is unauthenticated by definition, so the only thing between the token
|
||||
// and an offline guesser is the limiter in front of it.
|
||||
func TestSetupIsRateLimited(t *testing.T) {
|
||||
m := testModule(t, false)
|
||||
|
||||
for i := 0; i < 10; i++ {
|
||||
if rec := getSetup(m, "wrong-token"); rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("attempt %d: status = %d, want 404 (still under the limit)", i+1, rec.Code)
|
||||
}
|
||||
}
|
||||
if rec := getSetup(m, "wrong-token"); rec.Code != http.StatusTooManyRequests {
|
||||
t.Errorf("status = %d, want 429 after the eleventh attempt", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// expireSetupToken ages the current token out, the state the panel reaches when
|
||||
// nobody follows the link within setupTokenTTL.
|
||||
func expireSetupToken(m *Module) {
|
||||
m.setup.mu.Lock()
|
||||
defer m.setup.mu.Unlock()
|
||||
m.setup.expiresAt = m.setup.expiresAt.Add(-2 * setupTokenTTL)
|
||||
}
|
||||
@@ -44,15 +44,3 @@ 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)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -10,8 +10,8 @@ import (
|
||||
type ctxKey int
|
||||
|
||||
const (
|
||||
usernameKey ctxKey = 0
|
||||
principalKey ctxKey = 1
|
||||
usernameKey ctxKey = 0
|
||||
principalKey ctxKey = 1
|
||||
)
|
||||
|
||||
// Role is a panel user's access level.
|
||||
|
||||
@@ -5,11 +5,14 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
const defaultMaxBuckets = 4096
|
||||
|
||||
// rateLimiter is a simple fixed-window per-key counter used to throttle the
|
||||
// setup and login routes (security.md). Keys are client IPs.
|
||||
type rateLimiter struct {
|
||||
max int
|
||||
window time.Duration
|
||||
max int
|
||||
window time.Duration
|
||||
maxBuckets int
|
||||
|
||||
mu sync.Mutex
|
||||
buckets map[string]*rlBucket
|
||||
@@ -22,12 +25,25 @@ type rlBucket struct {
|
||||
|
||||
func newRateLimiter(max int, window time.Duration) *rateLimiter {
|
||||
return &rateLimiter{
|
||||
max: max,
|
||||
window: window,
|
||||
buckets: make(map[string]*rlBucket),
|
||||
max: max,
|
||||
window: window,
|
||||
maxBuckets: defaultMaxBuckets,
|
||||
buckets: make(map[string]*rlBucket),
|
||||
}
|
||||
}
|
||||
|
||||
func (r *rateLimiter) startSweeper() {
|
||||
go func() {
|
||||
ticker := time.NewTicker(r.window)
|
||||
defer ticker.Stop()
|
||||
for range ticker.C {
|
||||
r.mu.Lock()
|
||||
r.sweep(time.Now())
|
||||
r.mu.Unlock()
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (r *rateLimiter) Allow(key string) bool {
|
||||
now := time.Now()
|
||||
r.mu.Lock()
|
||||
@@ -35,6 +51,7 @@ func (r *rateLimiter) Allow(key string) bool {
|
||||
|
||||
b := r.buckets[key]
|
||||
if b == nil || now.After(b.windowEnds) {
|
||||
r.makeRoom(now)
|
||||
r.buckets[key] = &rlBucket{count: 1, windowEnds: now.Add(r.window)}
|
||||
r.sweep(now)
|
||||
return true
|
||||
@@ -46,6 +63,32 @@ func (r *rateLimiter) Allow(key string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (r *rateLimiter) makeRoom(now time.Time) {
|
||||
if r.maxBuckets <= 0 || len(r.buckets) < r.maxBuckets {
|
||||
return
|
||||
}
|
||||
r.sweep(now)
|
||||
for len(r.buckets) >= r.maxBuckets {
|
||||
r.evictOldest()
|
||||
}
|
||||
}
|
||||
|
||||
func (r *rateLimiter) evictOldest() {
|
||||
var oldestKey string
|
||||
var oldestEnds time.Time
|
||||
first := true
|
||||
for k, b := range r.buckets {
|
||||
if first || b.windowEnds.Before(oldestEnds) {
|
||||
oldestKey = k
|
||||
oldestEnds = b.windowEnds
|
||||
first = false
|
||||
}
|
||||
}
|
||||
if oldestKey != "" {
|
||||
delete(r.buckets, oldestKey)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *rateLimiter) sweep(now time.Time) {
|
||||
for k, b := range r.buckets {
|
||||
if now.After(b.windowEnds) {
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The limiter is what stands between the public login form and an unlimited
|
||||
// guessing rate (security.md), so the ceiling has to be exact: the configured
|
||||
// number of attempts go through and the next one does not, however often it is
|
||||
// repeated.
|
||||
func TestRateLimiterStopsAtTheCeiling(t *testing.T) {
|
||||
r := newRateLimiter(3, time.Minute)
|
||||
|
||||
for i := 1; i <= 3; i++ {
|
||||
if !r.Allow("203.0.113.7") {
|
||||
t.Fatalf("attempt %d of 3 was refused before the ceiling", i)
|
||||
}
|
||||
}
|
||||
for i := 4; i <= 6; i++ {
|
||||
if r.Allow("203.0.113.7") {
|
||||
t.Fatalf("attempt %d passed after the ceiling of 3", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Buckets are per key, so one locked-out address must not lock out the rest of
|
||||
// the internet — a shared counter would turn a single guesser into a denial of
|
||||
// service against every operator.
|
||||
func TestRateLimiterKeepsKeysApart(t *testing.T) {
|
||||
r := newRateLimiter(1, time.Minute)
|
||||
|
||||
if !r.Allow("203.0.113.7") || r.Allow("203.0.113.7") {
|
||||
t.Fatal("the first key did not use up its single attempt")
|
||||
}
|
||||
if !r.Allow("198.51.100.9") {
|
||||
t.Fatal("a second address was refused because another one was locked out")
|
||||
}
|
||||
}
|
||||
|
||||
// The window is fixed, not sliding: once it has elapsed the count starts again
|
||||
// from zero rather than being carried over. Time is moved by ageing the bucket
|
||||
// instead of sleeping, so the test states the boundary rather than approaching
|
||||
// it.
|
||||
func TestRateLimiterReopensAfterTheWindow(t *testing.T) {
|
||||
r := newRateLimiter(2, time.Minute)
|
||||
r.Allow("203.0.113.7")
|
||||
r.Allow("203.0.113.7")
|
||||
if r.Allow("203.0.113.7") {
|
||||
t.Fatal("the ceiling was not reached")
|
||||
}
|
||||
|
||||
expire(r, "203.0.113.7")
|
||||
|
||||
if !r.Allow("203.0.113.7") {
|
||||
t.Fatal("the key is still locked out after its window ended")
|
||||
}
|
||||
if !r.Allow("203.0.113.7") {
|
||||
t.Fatal("the new window did not start from an empty count")
|
||||
}
|
||||
if r.Allow("203.0.113.7") {
|
||||
t.Fatal("the new window allowed more than the ceiling")
|
||||
}
|
||||
}
|
||||
|
||||
// Every address that ever tried to sign in gets a bucket, and the only thing
|
||||
// that removes the finished ones is the sweep on a new window. It runs on the
|
||||
// key that triggered it as well as on the others, so a long-running panel does
|
||||
// not accumulate a bucket per source address for ever.
|
||||
func TestRateLimiterSweepsFinishedBuckets(t *testing.T) {
|
||||
r := newRateLimiter(2, time.Minute)
|
||||
for _, key := range []string{"203.0.113.7", "198.51.100.9"} {
|
||||
r.Allow(key)
|
||||
expire(r, key)
|
||||
}
|
||||
r.Allow("192.0.2.5") // still inside its window
|
||||
|
||||
r.Allow("203.0.113.7") // new window for this key: sweeps the rest
|
||||
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if _, ok := r.buckets["198.51.100.9"]; ok {
|
||||
t.Error("a bucket whose window ended is still held")
|
||||
}
|
||||
for _, key := range []string{"203.0.113.7", "192.0.2.5"} {
|
||||
if _, ok := r.buckets[key]; !ok {
|
||||
t.Errorf("the sweep dropped %s, whose window is still open", key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// expire moves a key's window into the past, the same state it would reach by
|
||||
// waiting for the window to elapse.
|
||||
func expire(r *rateLimiter, key string) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if b := r.buckets[key]; b != nil {
|
||||
b.windowEnds = time.Now().Add(-time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
// A long-running panel can see many unique client addresses. Finished buckets
|
||||
// are swept on every new window, and a hard cap evicts the oldest when the map
|
||||
// would otherwise grow without bound.
|
||||
func TestRateLimiterCapsBucketCount(t *testing.T) {
|
||||
r := newRateLimiter(1, time.Minute)
|
||||
r.maxBuckets = 3
|
||||
|
||||
for i, key := range []string{"203.0.113.7", "198.51.100.9", "192.0.2.5"} {
|
||||
if !r.Allow(key) {
|
||||
t.Fatalf("attempt %d for %s was refused under the cap", i+1, key)
|
||||
}
|
||||
expire(r, key)
|
||||
}
|
||||
|
||||
if !r.Allow("203.0.113.8") {
|
||||
t.Fatal("a fourth address was refused even though room was made")
|
||||
}
|
||||
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if len(r.buckets) > 3 {
|
||||
t.Fatalf("bucket count = %d, want at most 3", len(r.buckets))
|
||||
}
|
||||
}
|
||||
@@ -41,17 +41,22 @@ func hashToken(token string) string {
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// Create issues a new session for username and returns its token.
|
||||
func (s *sessionStore) Create(username string) string {
|
||||
// Create issues a new session for username 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) {
|
||||
token := randomToken(32)
|
||||
now := time.Now()
|
||||
if err := s.store.CreateSession(hashToken(token), username, now.Add(s.idle)); err != nil {
|
||||
logf("panel: session: create failed: %v", err)
|
||||
return "", err
|
||||
}
|
||||
// Pruning is housekeeping: the new session is already valid, so a failure
|
||||
// here is logged and does not fail the login.
|
||||
if _, err := s.store.DeleteExpiredSessions(now); err != nil {
|
||||
logf("panel: session: prune expired failed: %v", err)
|
||||
}
|
||||
return token
|
||||
return token, nil
|
||||
}
|
||||
|
||||
// Lookup returns the session username for a token if it exists and is
|
||||
|
||||
@@ -16,8 +16,9 @@ const setupTokenTTL = 10 * time.Minute
|
||||
|
||||
// setupManager owns the one-time administrator setup token. The token itself is
|
||||
// ephemeral (regenerated on restart or expiry) and lives only in memory; the
|
||||
// persistent "setup complete" fact is the presence of the admin row in the
|
||||
// store, so once that exists the token is gone for good (security.md).
|
||||
// persistent "setup complete" fact is the presence of any row in the store's
|
||||
// users table (`store.UserExists`), so once the first global administrator is
|
||||
// created the token is gone for good (security.md).
|
||||
type setupManager struct {
|
||||
store *store.Store
|
||||
hostname string
|
||||
|
||||
Reference in New Issue
Block a user