Files
FlowReader/internal/handler/auth.go
T
Antigravity AgentandClaude Opus 5.5 03e57e4308 fix(backend): harden security and speed up feeds and article API
Security:
- WebSocket events are routed to their owner only (no cross-user leak);
  hub close is idempotent (fixes double-close panic), adds ping/pong and
  write deadlines.
- Session tokens stored as SHA-256 (migration 008 keeps sessions valid);
  single-query auth middleware puts the user in the request context.
- Client IP only trusts X-Forwarded-For from TRUSTED_PROXIES; rate limiter
  map is bounded; per-user limit on AI summaries.
- Argon2id at OWASP minimum with a concurrency cap; constant-time login
  for unknown emails; atomic first-admin bootstrap; REGISTRATION_ENABLED.
- CSP/HSTS/COOP headers, same-origin guard on mutations, body size limits,
  wider SSRF denylist, bounded feed/page/AI response reads, generic errors.
- Upgrade chi, pgx, x/net, x/text, x/crypto (known CVEs); commit go.sum.

Performance:
- List endpoints return a plain-text excerpt and reading time instead of
  full HTML; content is sanitized once at ingest (legacy rows backfilled).
- Keyset pagination on (sort_at, id) with matching partial indexes;
  redundant indexes dropped (migration 007).
- Fetcher: bounded worker pool, conditional GET (ETag/Last-Modified),
  exponential backoff, dedupe before insert, column-safe truncation,
  retention-aware ingest, per-user refresh coalescing.
- Read/favorite/read-all are single ownership-scoped statements.
- gzip compression, immutable caching for hashed assets, path-safe SPA
  handler, server timeouts; expired sessions purged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 07:34:08 +02:00

155 lines
4.4 KiB
Go

package handler
import (
"encoding/json"
"errors"
"net/http"
"os"
"strings"
"github.com/michael/flowreader/internal/service"
)
// secureCookie reports whether the session cookie should carry the Secure flag.
// It honours TLS termination at a reverse proxy (X-Forwarded-Proto) and an
// explicit COOKIE_SECURE override, so HTTPS deployments behind a proxy still
// get Secure cookies even though r.TLS is nil.
func secureCookie(r *http.Request) bool {
switch strings.ToLower(os.Getenv("COOKIE_SECURE")) {
case "true", "1", "yes":
return true
case "false", "0", "no":
return false
}
if r.TLS != nil {
return true
}
return strings.EqualFold(r.Header.Get("X-Forwarded-Proto"), "https")
}
// AuthHandler handles authentication-related HTTP requests.
type AuthHandler struct {
authService *service.AuthService
}
// NewAuthHandler creates a new authentication handler.
func NewAuthHandler(authService *service.AuthService) *AuthHandler {
return &AuthHandler{authService: authService}
}
// Register handles POST /api/v1/auth/register
func (h *AuthHandler) Register(w http.ResponseWriter, r *http.Request) {
var req service.RegisterRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
respondError(w, http.StatusBadRequest, "Invalid request body")
return
}
resp, err := h.authService.Register(req)
if err != nil {
switch {
case errors.Is(err, service.ErrInvalidEmail):
respondError(w, http.StatusBadRequest, "Invalid email format")
case errors.Is(err, service.ErrPasswordTooShort):
respondError(w, http.StatusBadRequest, "Password must be at least 8 characters")
case errors.Is(err, service.ErrPasswordTooLong):
respondError(w, http.StatusBadRequest, "Password is too long")
case errors.Is(err, service.ErrEmailAlreadyExists):
respondError(w, http.StatusConflict, "Email already registered")
case errors.Is(err, service.ErrRegistrationClosed):
respondError(w, http.StatusForbidden, "Registration is disabled on this instance")
default:
respondError(w, http.StatusInternalServerError, "Registration failed")
}
return
}
respondJSON(w, http.StatusCreated, resp)
}
// Login handles POST /api/v1/auth/login
func (h *AuthHandler) Login(w http.ResponseWriter, r *http.Request) {
var req service.LoginRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
respondError(w, http.StatusBadRequest, "Invalid request body")
return
}
// Add request metadata
req.UserAgent = r.UserAgent()
req.IPAddress = getClientIP(r)
resp, err := h.authService.Login(req)
if err != nil {
if errors.Is(err, service.ErrInvalidCredentials) {
respondError(w, http.StatusUnauthorized, "Invalid email or password")
} else {
respondError(w, http.StatusInternalServerError, "Login failed")
}
return
}
// Set session cookie
http.SetCookie(w, &http.Cookie{
Name: "session_id",
Value: resp.Token,
Path: "/",
Expires: resp.ExpiresAt,
HttpOnly: true,
Secure: secureCookie(r),
SameSite: http.SameSiteStrictMode,
})
respondJSON(w, http.StatusOK, resp)
}
// Logout handles POST /api/v1/auth/logout
func (h *AuthHandler) Logout(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("session_id")
if err != nil {
respondJSON(w, http.StatusOK, map[string]string{"message": "Already logged out"})
return
}
_ = h.authService.Logout(cookie.Value)
// Clear the cookie
http.SetCookie(w, &http.Cookie{
Name: "session_id",
Value: "",
Path: "/",
MaxAge: -1,
HttpOnly: true,
Secure: secureCookie(r),
SameSite: http.SameSiteStrictMode,
})
respondJSON(w, http.StatusOK, map[string]string{"message": "Logged out successfully"})
}
// Me handles GET /api/v1/users/me (behind RequireAuth).
func (h *AuthHandler) Me(w http.ResponseWriter, r *http.Request) {
user := currentUser(r)
respondJSON(w, http.StatusOK, service.UserInfo{
ID: user.ID,
Email: user.Email,
IsAdmin: user.IsAdmin,
})
}
// respondJSON writes a JSON response.
func respondJSON(w http.ResponseWriter, status int, data interface{}) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
enc := json.NewEncoder(w)
// Safe: served as application/json with nosniff; avoids inflating HTML
// content with \u003c escapes.
enc.SetEscapeHTML(false)
enc.Encode(data)
}
// respondError writes an error response.
func respondError(w http.ResponseWriter, status int, message string) {
respondJSON(w, status, map[string]string{"error": message})
}