Sessions: Token nur als Hash speichern

Reset-Links lagen schon als SHA-256 in der DB, Sessions dagegen im
Klartext: Wer die Datenbank oder ein Backup lesen kann, hätte damit bis zu
ein Jahr gültige Anmeldungen in der Hand. Jetzt speichert startSession den
Hash (account.HashToken, dieselbe Funktion wie beim Reset) und session()
hasht den Cookie-Wert vor dem Nachschlagen. Bestehende Sessions werden
damit ungültig; alle müssen sich einmal neu anmelden (siehe deploy.md).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
2026-11-22 13:03:36 +01:00
co-authored by Claude Fable 5.1
parent e38f108f0b
commit 6df584645b
9 changed files with 802 additions and 21 deletions
+25 -8
View File
@@ -111,12 +111,35 @@ func TestRegisterLoginSession(t *testing.T) {
if got := getStatus(t, c, srv.URL+"/api/auth/sessioninfo"); got != http.StatusOK {
t.Fatalf("sessioninfo nach Login: erwartet 200, bekam %d", got)
}
// In der DB steht nur der Hash des Cookie-Werts.
cookie := sessionCookieValue(t, c, srv.URL)
var plain, hashed int
if err := srv.db.QueryRow(`SELECT COUNT(*) FILTER (WHERE value = $1), COUNT(*) FILTER (WHERE value = $2) FROM session`,
cookie, account.HashToken(cookie)).Scan(&plain, &hashed); err != nil {
t.Fatal(err)
}
if plain != 0 || hashed != 1 {
t.Fatalf("session in der DB: %d im Klartext, %d gehasht", plain, hashed)
}
// Anonymer Client hat keine Session.
if got := getStatus(t, newClient(t), srv.URL+"/api/auth/sessioninfo"); got != http.StatusUnauthorized {
t.Fatalf("sessioninfo anonym: erwartet 401, bekam %d", got)
}
}
// sessionCookieValue liest den Session-Cookie aus dem Jar des Clients.
func sessionCookieValue(t *testing.T, c *http.Client, srvURL string) string {
t.Helper()
u, _ := url.Parse(srvURL)
for _, ck := range c.Jar.Cookies(u) {
if ck.Name == sessionCookie {
return ck.Value
}
}
t.Fatal("kein Session-Cookie")
return ""
}
// getStatus macht einen GET und liefert nur den Statuscode.
func getStatus(t *testing.T, c *http.Client, urlStr string) int {
t.Helper()
@@ -819,19 +842,13 @@ func TestPasswordResetReplacesSession(t *testing.T) {
srv := newTestServer(t)
registerAndLogin(t, srv, "alice")
bob := registerAndLogin(t, srv, "bob")
var bobSession string
u, _ := url.Parse(srv.URL)
for _, ck := range bob.Jar.Cookies(u) {
if ck.Name == sessionCookie {
bobSession = ck.Value
}
}
bobSession := sessionCookieValue(t, bob, srv.URL)
form := resetForm(srv.resetToken(t, "alice"), "drittesgeheim")
if got := postStatus(t, bob, srv.URL+"/api/auth/reset", form); got != http.StatusOK {
t.Fatalf("reset mit fremder Session: erwartet 200, bekam %d", got)
}
var n int
if err := srv.db.QueryRow(`SELECT COUNT(*) FROM session WHERE value = $1`, bobSession).Scan(&n); err != nil {
if err := srv.db.QueryRow(`SELECT COUNT(*) FROM session WHERE value = $1`, account.HashToken(bobSession)).Scan(&n); err != nil {
t.Fatal(err)
}
if n != 0 {