Address Gadfly review on #4: TOCTOU, sliding cookie, CSRF, argon2
Build image / build-and-push (push) Successful in 5s
Build image / build-and-push (push) Successful in 5s
Fixes from the PR #23 adversarial review (graded 35 real / 1 false positive): Security / correctness - Race-free registration: is_admin and the registration gate are now computed atomically inside a single INSERT...SELECT, so concurrent first registrations can't both become admin or bypass closed registration (fixed the whole TOCTOU cluster). - Sliding session now reaches the browser: ResolveSession returns the current expiry and requireAuth re-sets the cookie, so active users aren't logged out 30 days after login regardless of activity. - Login CSRF: csrfGuard rejects state-changing requests whose Origin doesn't match PANSY_BASE_URL (no-op when unset, so the dev proxy is unaffected). SameSite=Lax alone didn't cover this. - argon2id tuned to RFC 9106's second recommended profile (t=3). - Timing equalizer can't fail open: the dummy hash is derived deterministically (fixed salt, no RNG) so it's always present. - Password length (<=1024) enforced in the service for both register and login, not just HTTP binding tags; login rejects over-long input before spending argon2 work. Error handling / robustness - Login logs a malformed stored hash instead of silently treating it as a wrong password. - Best-effort session writes (Touch/Delete during renewal, expiry, and corrupt-expiry cleanup) now log on failure. - index sessions.expires_at via new migration 0002 (0001 is immutable). Maintainability - Extract startSessionAndRespond and abortUnauthenticated; make writeServiceError a free function; consistent error handling in decodeHash; doc/comment fixes. Tests: over-long password, CSRF guard (cross-origin/same-origin/dev no-op), and cookie refresh on authenticated requests; migration-version assertions bumped to 2. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01JdQpdYYsTgtkJBxbcpAszi
This commit is contained in:
+58
-34
@@ -3,12 +3,17 @@ package service
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.stevedudenhoeffer.com/steve/pansy/internal/domain"
|
||||
)
|
||||
|
||||
// maxPasswordLen caps accepted password length. It bounds argon2 input and
|
||||
// request work, and sits far above any real password.
|
||||
const maxPasswordLen = 1024
|
||||
|
||||
// RegisterInput is the payload for local self-service signup.
|
||||
type RegisterInput struct {
|
||||
Email string
|
||||
@@ -46,27 +51,22 @@ func (s *Service) Register(ctx context.Context, in RegisterInput) (*domain.User,
|
||||
|
||||
email := normalizeEmail(in.Email)
|
||||
displayName := strings.TrimSpace(in.DisplayName)
|
||||
if email == "" || displayName == "" || in.Password == "" {
|
||||
if email == "" || displayName == "" || in.Password == "" || len(in.Password) > maxPasswordLen {
|
||||
return nil, domain.ErrInvalidInput
|
||||
}
|
||||
|
||||
count, err := s.store.CountUsers(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Closed registration still allows the very first account so a locked-down
|
||||
// instance can be bootstrapped without editing config.
|
||||
if count > 0 && !s.cfg.RegistrationOpen() {
|
||||
return nil, domain.ErrRegistrationClosed
|
||||
}
|
||||
|
||||
// Friendly duplicate check. The UNIQUE index is the real guard against a
|
||||
// race; that path surfaces as a generic insert error (500), acceptable at
|
||||
// household scale.
|
||||
if _, err := s.store.GetUserByEmail(ctx, email); err == nil {
|
||||
return nil, domain.ErrEmailTaken
|
||||
} else if !errors.Is(err, domain.ErrNotFound) {
|
||||
return nil, err
|
||||
// Cheap best-effort gate so a closed instance doesn't burn argon2 work on
|
||||
// signups it will reject anyway. The authoritative, race-free gate — plus
|
||||
// atomic first-user-is-admin assignment and duplicate-email detection — lives
|
||||
// in store.CreateUser's single INSERT.
|
||||
if !s.cfg.RegistrationOpen() {
|
||||
n, err := s.store.CountUsers(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if n > 0 {
|
||||
return nil, domain.ErrRegistrationClosed
|
||||
}
|
||||
}
|
||||
|
||||
hash, err := hashPassword(in.Password)
|
||||
@@ -78,8 +78,7 @@ func (s *Service) Register(ctx context.Context, in RegisterInput) (*domain.User,
|
||||
Email: email,
|
||||
DisplayName: displayName,
|
||||
PasswordHash: &hash,
|
||||
IsAdmin: count == 0,
|
||||
})
|
||||
}, s.cfg.RegistrationOpen())
|
||||
}
|
||||
|
||||
// Login verifies an email/password pair and returns the user. Unknown-email and
|
||||
@@ -89,6 +88,10 @@ func (s *Service) Login(ctx context.Context, email, password string) (*domain.Us
|
||||
if !s.cfg.LocalAuth {
|
||||
return nil, domain.ErrLocalAuthDisabled
|
||||
}
|
||||
if len(password) > maxPasswordLen {
|
||||
// No stored password is this long; reject without spending argon2 work.
|
||||
return nil, domain.ErrInvalidCredentials
|
||||
}
|
||||
|
||||
u, err := s.store.GetUserByEmail(ctx, normalizeEmail(email))
|
||||
switch {
|
||||
@@ -105,7 +108,13 @@ func (s *Service) Login(ctx context.Context, email, password string) (*domain.Us
|
||||
}
|
||||
|
||||
ok, err := verifyPassword(*u.PasswordHash, password)
|
||||
if err != nil || !ok {
|
||||
if err != nil {
|
||||
// A stored hash we can't parse is a data problem, not a wrong password;
|
||||
// surface it so a corrupt row doesn't silently lock a user out unnoticed.
|
||||
slog.Error("service: malformed stored password hash", "user_id", u.ID, "error", err)
|
||||
return nil, domain.ErrInvalidCredentials
|
||||
}
|
||||
if !ok {
|
||||
return nil, domain.ErrInvalidCredentials
|
||||
}
|
||||
return u, nil
|
||||
@@ -129,38 +138,53 @@ func (s *Service) CreateSession(ctx context.Context, userID int64) (token string
|
||||
return raw, exp, nil
|
||||
}
|
||||
|
||||
// ResolveSession validates a raw bearer token and returns its user. An expired
|
||||
// session is deleted and treated as absent (domain.ErrNotFound). A still-valid
|
||||
// session has its expiry slid forward, but only when that moves it by more than
|
||||
// an hour, so a busy client doesn't write on every request.
|
||||
func (s *Service) ResolveSession(ctx context.Context, rawToken string) (*domain.User, error) {
|
||||
// ResolveSession validates a raw bearer token and returns its user and the
|
||||
// session's current expiry (so the caller can slide the client cookie in
|
||||
// lockstep with the server). An expired session is deleted and treated as absent
|
||||
// (domain.ErrNotFound). A still-valid session has its expiry slid forward, but
|
||||
// only when that moves it by more than an hour, so a busy client doesn't write
|
||||
// on every request.
|
||||
func (s *Service) ResolveSession(ctx context.Context, rawToken string) (*domain.User, time.Time, error) {
|
||||
if rawToken == "" {
|
||||
return nil, domain.ErrNotFound
|
||||
return nil, time.Time{}, domain.ErrNotFound
|
||||
}
|
||||
hash := hashToken(rawToken)
|
||||
sess, err := s.store.GetSession(ctx, hash)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, time.Time{}, err
|
||||
}
|
||||
|
||||
exp, err := parseTime(sess.ExpiresAt)
|
||||
if err != nil {
|
||||
// A corrupt expiry means we can't trust the session; drop it.
|
||||
_ = s.store.DeleteSession(ctx, hash)
|
||||
return nil, domain.ErrNotFound
|
||||
if delErr := s.store.DeleteSession(ctx, hash); delErr != nil {
|
||||
slog.Warn("service: deleting session with corrupt expiry", "error", delErr)
|
||||
}
|
||||
return nil, time.Time{}, domain.ErrNotFound
|
||||
}
|
||||
|
||||
now := s.now()
|
||||
if !now.Before(exp) {
|
||||
_ = s.store.DeleteSession(ctx, hash)
|
||||
return nil, domain.ErrNotFound
|
||||
if delErr := s.store.DeleteSession(ctx, hash); delErr != nil {
|
||||
slog.Warn("service: deleting expired session", "error", delErr)
|
||||
}
|
||||
return nil, time.Time{}, domain.ErrNotFound
|
||||
}
|
||||
|
||||
if newExp := now.Add(sessionTTL); newExp.Sub(exp) > time.Hour {
|
||||
_ = s.store.TouchSession(ctx, hash, formatTime(newExp))
|
||||
if err := s.store.TouchSession(ctx, hash, formatTime(newExp)); err != nil {
|
||||
// Non-fatal: the session is still valid at its current expiry.
|
||||
slog.Warn("service: sliding session expiry", "error", err)
|
||||
} else {
|
||||
exp = newExp
|
||||
}
|
||||
}
|
||||
|
||||
return s.store.GetUserByID(ctx, sess.UserID)
|
||||
user, err := s.store.GetUserByID(ctx, sess.UserID)
|
||||
if err != nil {
|
||||
return nil, time.Time{}, err
|
||||
}
|
||||
return user, exp, nil
|
||||
}
|
||||
|
||||
// Logout deletes the session behind a raw bearer token. It is idempotent.
|
||||
|
||||
Reference in New Issue
Block a user