feat: implement B.1 — persist login sessions in SQLite with sliding idle timeout

Sessions move from an in-memory map (absolute 12h TTL) to a `sessions`
table (migration 0002), storing only the SHA-256 of the token. Expiry is
now a sliding idle window (PANEL_SESSION_IDLE_DAYS, default 7, no
absolute cap), extended at most once an hour and never by the
monitoring screens' background polling (GET + HX-Request), so a
forgotten open tab doesn't keep a session alive indefinitely. A login
now survives a container restart or redeploy.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-02 23:21:49 +03:00
parent 750a65d5ee
commit 82ec287ba1
14 changed files with 331 additions and 51 deletions
+51 -3
View File
@@ -1,9 +1,25 @@
package web
import "testing"
import (
"path/filepath"
"testing"
"time"
"codeberg.org/mix/selfpost/internal/store"
)
func newTestSessionStore(t *testing.T) *sessionStore {
t.Helper()
st, err := store.Open(filepath.Join(t.TempDir(), "test.db"))
if err != nil {
t.Fatalf("open store: %v", err)
}
t.Cleanup(func() { st.Close() })
return newSessionStore(st, 7*24*time.Hour)
}
func TestSessionRename(t *testing.T) {
s := newSessionStore()
s := newTestSessionStore(t)
token := s.Create("admin")
s.Rename(token, "operator")
@@ -21,7 +37,7 @@ func TestSessionRename(t *testing.T) {
// under the old password stops working) while keeping the one performing the
// change signed in.
func TestSessionDestroyOthers(t *testing.T) {
s := newSessionStore()
s := newTestSessionStore(t)
keep := s.Create("admin")
other := s.Create("admin")
@@ -34,3 +50,35 @@ func TestSessionDestroyOthers(t *testing.T) {
t.Fatal("other session survived")
}
}
// A session past its sliding idle expiry must not be honoured.
func TestSessionLookupRejectsExpired(t *testing.T) {
s := newTestSessionStore(t)
s.idle = -time.Minute // already expired the instant it's created
token := s.Create("admin")
if _, ok := s.Lookup(token); ok {
t.Fatal("expired session was accepted")
}
}
// Touch must not rewrite the expiry (or report a renewal) inside the
// once-an-hour throttle window, so an active tab's polling doesn't turn into
// a database write per request.
func TestSessionTouchThrottled(t *testing.T) {
s := newTestSessionStore(t)
token := s.Create("admin")
if s.Touch(token) {
t.Fatal("touch renewed a session created moments ago")
}
// Back-date the session's last renewal by rewriting its expiry, as if it
// had been created (or last renewed) 2 hours ago rather than moments ago.
if err := s.store.RenewSession(hashToken(token), time.Now().Add(-2*time.Hour).Add(s.idle)); err != nil {
t.Fatalf("renew session: %v", err)
}
if !s.Touch(token) {
t.Fatal("touch did not renew a session past the throttle window")
}
}