fix backend audit findings (auth, upload, sync, data, ocr, contract)
CI / lint-backend (push) Failing after 1m39s
CI / lint-mobile (push) Canceled after 11m8s
CI / test-backend (push) Canceled after 0s
CI / test-mobile (push) Canceled after 0s
CI / build-backend (push) Canceled after 0s
CI / docker (push) Canceled after 0s

This commit is contained in:
m
2026-09-21 19:59:52 +02:00
parent df7dc76405
commit a6b7f2002b
60 changed files with 3414 additions and 412 deletions
+79 -8
View File
@@ -4,12 +4,12 @@ import (
"errors"
"net/http"
"strings"
"sync"
"time"
"github.com/gin-gonic/gin"
"github.com/kazier/backend/pkg/api"
"github.com/kazier/backend/pkg/auth"
"github.com/kazier/backend/pkg/passwd"
"github.com/kazier/backend/repository"
"github.com/kazier/backend/service"
@@ -33,9 +33,55 @@ type LoginResponse struct {
User LoginUserDTO `json:"user"`
}
// Anti-bruteforce du login (FEEDBACK #12) : limiteur basique en mémoire,
// N tentatives / minute / IP sur POST /auth/login, placé AVANT la vérification
// argon2 (coûteuse) pour protéger le CPU. Au-delà → 429 RATE_LIMITED.
// TODO(suivi) : rate-limit distribué (ex. Redis) + métriques pour les déploiements
// multi-réplicas, et budget global coordonné avec le rate-limit POST /devices
// (LOT 6) contre le remplissage de table.
var (
loginRateLimitPerMinute = 60
loginRateWindow = time.Minute
loginAttemptsMu sync.Mutex
loginAttempts = map[string][]time.Time{}
)
// OnLoginRateLimited est un hook d'observabilité appelé quand le limiteur
// rejette une tentative (nil par défaut = no-op). Les tests peuvent l'utiliser
// pour asserter le déclenchement sans dépendre du timing.
var OnLoginRateLimited func(ip string)
// ResetLoginRateLimit vide le compteur (tests uniquement).
func ResetLoginRateLimit() {
loginAttemptsMu.Lock()
defer loginAttemptsMu.Unlock()
loginAttempts = map[string][]time.Time{}
}
// loginRateLimited enregistre une tentative et retourne true si le quota
// IP est dépassé (fenêtre glissante).
func loginRateLimited(ip string, now time.Time) bool {
loginAttemptsMu.Lock()
defer loginAttemptsMu.Unlock()
cutoff := now.Add(-loginRateWindow)
kept := make([]time.Time, 0, len(loginAttempts[ip])+1)
for _, t := range loginAttempts[ip] {
if t.After(cutoff) {
kept = append(kept, t)
}
}
if len(kept) >= loginRateLimitPerMinute {
loginAttempts[ip] = kept
return true
}
loginAttempts[ip] = append(kept, now)
return false
}
// AuthLogin est la SEULE porte d'émission de token (V1). L'erreur est
// volontairement indistinguable entre « username inconnu » et « mauvais mot de
// passe » — même code, même message, délai égalisé via passwd.VerifyTimedEqual.
// volontairement indistinguable entre « username inconnu », « mauvais mot de
// passe » et « device non enregistré » — même code 401, même message, délai
// égalisé via passwd.VerifyTimedEqual (anti-oracle, FEEDBACK #12).
func AuthLogin(c *gin.Context) {
if Store == nil || Store.Repository == nil || Auth == nil {
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
@@ -51,12 +97,24 @@ func AuthLogin(c *gin.Context) {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "username, password and device_id are required")
return
}
if !deviceIDPattern.MatchString(req.DeviceID) {
api.Error(c, http.StatusBadRequest, "INVALID_DEVICE_ID", "device_id must be 32 lowercase hex chars")
return
}
if loginRateLimited(c.ClientIP(), time.Now()) {
if OnLoginRateLimited != nil {
OnLoginRateLimited(c.ClientIP())
}
api.Error(c, http.StatusTooManyRequests, "RATE_LIMITED", "too many login attempts, retry later")
return
}
normalized := service.NormalizeUsername(req.Username)
user, userErr := Store.Repository.Users.GetByUsernameNormalized(normalized)
// Même durée de traitement que le compte existe ou non (username inconnu =>
// stored vide → vérification contre dummyHash).
// stored vide → vérification contre dummyHash aléatoire par boot).
stored := ""
if userErr == nil && user != nil {
stored = user.PasswordHash
@@ -69,6 +127,12 @@ func AuthLogin(c *gin.Context) {
api.Error(c, http.StatusInternalServerError, "INTERNAL", "could not verify credentials")
return
}
// A1 : ne jamais déréférencer user si inconnu — même si Verify (par
// extraordinaire) réussissait, on reste en 401.
if userErr != nil || user == nil {
api.Error(c, http.StatusUnauthorized, "UNAUTHORIZED", "invalid credentials")
return
}
exists, err := Store.Repository.Devices.Exists(req.DeviceID)
if err != nil {
@@ -76,24 +140,31 @@ func AuthLogin(c *gin.Context) {
return
}
if !exists {
api.Error(c, http.StatusBadRequest, "INVALID_DEVICE_ID", "device not registered")
// Volontairement indistinguable d'un mauvais password (anti-oracle).
api.Error(c, http.StatusUnauthorized, "UNAUTHORIZED", "invalid credentials")
return
}
if err := Store.Repository.Devices.MarkUser(req.DeviceID, user.ID); err != nil {
if errors.Is(err, repository.ErrNotFound) {
// Course : device supprimé entre Exists et MarkUser → même 401
// indistinguable, jamais de token pour un device fantôme.
api.Error(c, http.StatusUnauthorized, "UNAUTHORIZED", "invalid credentials")
return
}
api.Error(c, http.StatusInternalServerError, "INTERNAL", "could not update device")
return
}
token, err := Auth.Issue(user.ID, req.DeviceID)
token, expiresAt, err := Auth.IssueWithExpiry(user.ID, req.DeviceID)
if err != nil {
api.Error(c, http.StatusInternalServerError, "TOKEN_ERROR", "could not issue token")
api.Error(c, http.StatusInternalServerError, "INTERNAL", "could not issue token")
return
}
api.OK(c, LoginResponse{
Token: token,
ExpiresAt: time.Now().Add(auth.TokenTTL).UnixMilli(),
ExpiresAt: expiresAt.UnixMilli(),
User: LoginUserDTO{
ID: user.ID,
Username: user.Username,