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:
@@ -35,16 +35,22 @@ func localCfg() *config.Config {
|
||||
return &config.Config{Registration: config.RegistrationOpen, LocalAuth: true}
|
||||
}
|
||||
|
||||
// doJSON issues a JSON request, optionally carrying a session cookie.
|
||||
func doJSON(t *testing.T, r *gin.Engine, method, path string, body any, cookie *http.Cookie) *httptest.ResponseRecorder {
|
||||
// encodeBody JSON-encodes v into a reader for a request body.
|
||||
func encodeBody(t *testing.T, v any) *bytes.Buffer {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
if body != nil {
|
||||
if err := json.NewEncoder(&buf).Encode(body); err != nil {
|
||||
if v != nil {
|
||||
if err := json.NewEncoder(&buf).Encode(v); err != nil {
|
||||
t.Fatalf("encode body: %v", err)
|
||||
}
|
||||
}
|
||||
req := httptest.NewRequest(method, path, &buf)
|
||||
return &buf
|
||||
}
|
||||
|
||||
// doJSON issues a JSON request, optionally carrying a session cookie.
|
||||
func doJSON(t *testing.T, r *gin.Engine, method, path string, body any, cookie *http.Cookie) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(method, path, encodeBody(t, body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if cookie != nil {
|
||||
req.AddCookie(cookie)
|
||||
@@ -153,6 +159,71 @@ func TestProvidersEndpoint(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthenticatedRequestRefreshesCookie(t *testing.T) {
|
||||
// requireAuth must re-set the session cookie so the browser's Max-Age slides
|
||||
// with the server session rather than expiring 30 days after login.
|
||||
r := authEngine(t, localCfg())
|
||||
w := doJSON(t, r, http.MethodPost, "/api/v1/auth/register",
|
||||
map[string]string{"email": "[email protected]", "displayName": "Alice", "password": "password123"}, nil)
|
||||
cookie := sessionCookieFrom(t, w)
|
||||
|
||||
w = doJSON(t, r, http.MethodGet, "/api/v1/auth/me", nil, cookie)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("me status = %d", w.Code)
|
||||
}
|
||||
// A fresh session cookie should be present on the /me response.
|
||||
refreshed := sessionCookieFrom(t, w)
|
||||
if refreshed.Value != cookie.Value {
|
||||
t.Errorf("refreshed cookie value changed: got %q want same token", refreshed.Value)
|
||||
}
|
||||
if refreshed.MaxAge <= 0 {
|
||||
t.Errorf("refreshed cookie Max-Age = %d, want > 0", refreshed.MaxAge)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCSRFGuardRejectsCrossOrigin(t *testing.T) {
|
||||
cfg := localCfg()
|
||||
cfg.BaseURL = "https://pansy.example.com"
|
||||
r := authEngine(t, cfg)
|
||||
|
||||
body := map[string]string{"email": "[email protected]", "displayName": "Alice", "password": "password123"}
|
||||
|
||||
// Cross-origin POST is rejected before touching the service.
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/register", encodeBody(t, body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Origin", "https://evil.example.com")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Fatalf("cross-origin register status = %d, want 403", w.Code)
|
||||
}
|
||||
|
||||
// Same-origin POST is allowed.
|
||||
req = httptest.NewRequest(http.MethodPost, "/api/v1/auth/register", encodeBody(t, body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Origin", "https://pansy.example.com")
|
||||
w = httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("same-origin register status = %d, want 200 (body %s)", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestCSRFGuardNoopWithoutBaseURL(t *testing.T) {
|
||||
// In local dev (no PANSY_BASE_URL) the guard must not interfere, even with a
|
||||
// foreign Origin (the Vite dev proxy forwards the browser's origin).
|
||||
r := authEngine(t, localCfg())
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/register",
|
||||
encodeBody(t, map[string]string{"email": "[email protected]", "displayName": "Alice", "password": "password123"}))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Origin", "http://localhost:5173")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("dev cross-origin register status = %d, want 200", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecureCookieWithHTTPSBaseURL(t *testing.T) {
|
||||
cfg := localCfg()
|
||||
cfg.BaseURL = "https://pansy.example.com"
|
||||
|
||||
Reference in New Issue
Block a user