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,
+70 -3
View File
@@ -42,6 +42,8 @@ func setTestStore(t *testing.T) *repository.Repository {
func setTestAuth(t *testing.T) {
t.Helper()
Auth, _ = auth.NewManager("test-secret")
ResetLoginRateLimit()
ResetDevicesRateLimit()
t.Cleanup(func() { Auth = nil })
}
@@ -202,6 +204,71 @@ func TestAuthLoginWrongCredentials(t *testing.T) {
}
}
// TestAuthLoginUnknownUserRegisteredDevice — régression A1 : un username
// inconnu ne doit JAMAIS déréférencer user (panic → 500 via Gin recovery).
// Le device est enregistré pour isoler la branche « user inconnu » : on attend
// 401 UNAUTHORIZED, corps identique au cas « mauvais mot de passe ».
func TestAuthLoginUnknownUserRegisteredDevice(t *testing.T) {
setTestAuth(t)
repo := setTestStore(t)
createAdmin(t, repo, "admin", authTestPassword)
r := newTestRouterForAuth()
doAuth(t, r, http.MethodPost, "/api/v1/devices", "", `{"deviceId":"`+authTestDevice+`"}`)
badPassword := doAuth(t, r, http.MethodPost, "/api/v1/auth/login", "", `{"username":"admin","password":"wrong-password","device_id":"`+authTestDevice+`"}`)
if badPassword.Code != 401 {
t.Fatalf("mauvais mot de passe: status %d body %s", badPassword.Code, badPassword.Body.String())
}
ghost := doAuth(t, r, http.MethodPost, "/api/v1/auth/login", "", `{"username":"ghost","password":"wrong-password","device_id":"`+authTestDevice+`"}`)
if ghost.Code != 401 {
t.Fatalf("username inconnu: status %d body %s (attendu 401, jamais 500)", ghost.Code, ghost.Body.String())
}
if !strings.Contains(ghost.Body.String(), "UNAUTHORIZED") {
t.Errorf("code attendu UNAUTHORIZED, got %s", ghost.Body.String())
}
if ghost.Body.String() != badPassword.Body.String() {
t.Errorf("réponses distinguables (sécurité):\n%q\n%q", ghost.Body.String(), badPassword.Body.String())
}
}
func TestAuthLoginRateLimited(t *testing.T) {
setTestAuth(t)
repo := setTestStore(t)
createAdmin(t, repo, "admin", authTestPassword)
r := newTestRouterForAuth()
doAuth(t, r, http.MethodPost, "/api/v1/devices", "", `{"deviceId":"`+authTestDevice+`"}`)
oldLimit := loginRateLimitPerMinute
loginRateLimitPerMinute = 2
hookCalls := 0
oldHook := OnLoginRateLimited
OnLoginRateLimited = func(ip string) { hookCalls++ }
t.Cleanup(func() {
loginRateLimitPerMinute = oldLimit
OnLoginRateLimited = oldHook
ResetLoginRateLimit()
})
badBody := `{"username":"admin","password":"wrong-password","device_id":"` + authTestDevice + `"}`
for i := 0; i < 2; i++ {
if rec := doAuth(t, r, http.MethodPost, "/api/v1/auth/login", "", badBody); rec.Code != 401 {
t.Fatalf("tentative %d: status %d, attendu 401", i+1, rec.Code)
}
}
rec := doAuth(t, r, http.MethodPost, "/api/v1/auth/login", "", badBody)
if rec.Code != 429 {
t.Fatalf("quota dépassé: status %d body %s, attendu 429", rec.Code, rec.Body.String())
}
if !strings.Contains(rec.Body.String(), "RATE_LIMITED") {
t.Errorf("code attendu RATE_LIMITED, got %s", rec.Body.String())
}
if hookCalls != 1 {
t.Errorf("OnLoginRateLimited appelé %d fois, attendu 1", hookCalls)
}
}
func TestAuthLoginUnregisteredDevice(t *testing.T) {
setTestAuth(t)
repo := setTestStore(t)
@@ -209,11 +276,11 @@ func TestAuthLoginUnregisteredDevice(t *testing.T) {
r := newTestRouterForAuth()
rec := doAuth(t, r, http.MethodPost, "/api/v1/auth/login", "", `{"username":"admin","password":"`+authTestPassword+`","device_id":"`+authTestDevice+`"}`)
if rec.Code != 400 {
if rec.Code != 401 {
t.Fatalf("device non enregistré: status %d body %s", rec.Code, rec.Body.String())
}
if !strings.Contains(rec.Body.String(), "INVALID_DEVICE_ID") {
t.Errorf("code attendu INVALID_DEVICE_ID, got %s", rec.Body.String())
if !strings.Contains(rec.Body.String(), "UNAUTHORIZED") {
t.Errorf("code attendu UNAUTHORIZED (anti-oracle), got %s", rec.Body.String())
}
}
+65 -1
View File
@@ -1,7 +1,10 @@
package handlers
import (
"net/http"
"regexp"
"sync"
"time"
"github.com/gin-gonic/gin"
"github.com/kazier/backend/pkg/api"
@@ -9,12 +12,65 @@ import (
var deviceIDPattern = regexp.MustCompile(`^[0-9a-f]{32}$`)
// Anti-remplissage de POST /devices (FEEDBACK §moyenne) : l'endpoint est
// public et bon marché (un upsert), donc anonyme et floodable. Limiteur
// basique en mémoire, N enregistrements / minute / IP → 429 RATE_LIMITED.
// Budget large (300) : les usages légitimes (1 device = 1 appel) sont très
// loin du seuil ; la protection vise le flood massif, un WAF frontal fera
// le reste en prod multi-réplicas.
// TODO(suivi) : rate-limit distribué + budget global coordonné avec le
// rate-limit login (cf. handlers/auth.go).
var (
devicesRateLimitPerMinute = 300
devicesRateWindow = time.Minute
devicesAttemptsMu sync.Mutex
devicesAttempts = map[string][]time.Time{}
)
// OnDevicesRateLimited est un hook d'observabilité (nil = no-op).
var OnDevicesRateLimited func(ip string)
// ResetDevicesRateLimit vide le compteur (tests uniquement).
func ResetDevicesRateLimit() {
devicesAttemptsMu.Lock()
defer devicesAttemptsMu.Unlock()
devicesAttempts = map[string][]time.Time{}
}
func devicesRateLimited(ip string, now time.Time) bool {
devicesAttemptsMu.Lock()
defer devicesAttemptsMu.Unlock()
cutoff := now.Add(-devicesRateWindow)
kept := make([]time.Time, 0, len(devicesAttempts[ip])+1)
for _, t := range devicesAttempts[ip] {
if t.After(cutoff) {
kept = append(kept, t)
}
}
if len(kept) >= devicesRateLimitPerMinute {
devicesAttempts[ip] = kept
return true
}
devicesAttempts[ip] = append(kept, now)
return false
}
type DeviceRegisterRequest struct {
DeviceID string `json:"deviceId"`
}
func DevicesRegister(c *gin.Context) {
// POST /devices est PUBLIC (sans token) : le device s'enregistre pour
// exister, puis le client appelle POST /auth/login pour obtenir son
// token user-first (cf. docs/api-v1.md §2).
//
// NOTE rate-limit : limiteur en mémoire ci-dessus (300/min/IP, 429
// au-delà). Si le budget doit changer, ajuster
// devicesRateLimitPerMinute + documenter dans docs/api-v1.md.
//
// NOTE MarkUser : repository.Devices.MarkUser retourne ErrNotFound quand
// RowsAffected == 0 (device supprimé entre Exists et UPDATE) ; le login
// mappe ce cas en 401 indistinguable (cf. handlers/auth.go).
var req DeviceRegisterRequest
if err := c.ShouldBindJSON(&req); err != nil || req.DeviceID == "" {
api.Error(c, 400, "INVALID_REQUEST", "missing deviceId")
@@ -25,6 +81,14 @@ func DevicesRegister(c *gin.Context) {
return
}
if devicesRateLimited(c.ClientIP(), time.Now()) {
if OnDevicesRateLimited != nil {
OnDevicesRateLimited(c.ClientIP())
}
api.Error(c, http.StatusTooManyRequests, "RATE_LIMITED", "too many device registrations, retry later")
return
}
if Store == nil || Store.Repository == nil {
api.Error(c, 503, "SERVICE_UNAVAILABLE", "backend not initialized")
return
+58 -9
View File
@@ -8,6 +8,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/kazier/backend/pkg/api"
"github.com/kazier/backend/service"
)
func intParam(value string, fallback int) int {
@@ -21,18 +22,53 @@ func intParam(value string, fallback int) int {
return parsed
}
// parsePageParams valide page/pageSize (400 si garbage, cf. FEEDBACK A7/A16)
// au lieu du fallback silencieux. Cap pageSize 200 et offset 100000.
func parsePageParams(c *gin.Context) (page, pageSize int, ok bool) {
page = 1
pageSize = 50
if v := c.Query("page"); v != "" {
p, err := strconv.Atoi(v)
if err != nil || p < 1 {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "invalid query param `page`")
return 0, 0, false
}
page = p
}
if v := c.Query("pageSize"); v != "" {
ps, err := strconv.Atoi(v)
if err != nil || ps < 1 {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "invalid query param `pageSize`")
return 0, 0, false
}
pageSize = ps
}
if pageSize > 200 {
pageSize = 200
}
if (page-1)*pageSize > 100000 {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "page offset too large")
return 0, 0, false
}
return page, pageSize, true
}
func FilesList(c *gin.Context) {
if Store == nil {
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
return
}
userID := c.GetString(UserIDKey)
page := intParam(c.Query("page"), 1)
pageSize := intParam(c.Query("pageSize"), 50)
if pageSize > 200 {
pageSize = 200
page, pageSize, ok := parsePageParams(c)
if !ok {
return
}
files, total, err := Store.ListFiles(userID, c.Query("folderId"), page, pageSize, c.Query("sort"), c.Query("order"))
folderID := c.Query("folderId")
if folderID != "" && !deviceIDPattern.MatchString(folderID) {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "invalid query param `folderId`")
return
}
files, total, err := Store.ListFiles(userID, folderID, page, pageSize, c.Query("sort"), c.Query("order"))
if err != nil {
writeError(c, err)
return
@@ -108,6 +144,10 @@ func FilesUpload(c *gin.Context) {
}
userID := c.GetString(UserIDKey)
folderID := c.PostForm("folderId")
if folderID != "" && !deviceIDPattern.MatchString(folderID) {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "invalid `folderId`")
return
}
// resourceId optionnel : cible un fichier déjà connu (metadata-only de
// l'outbox) pour lui attacher ses octets physiques (ex. OCR serveur).
resourceID := c.PostForm("resourceId")
@@ -134,6 +174,12 @@ func FilesUpload(c *gin.Context) {
dto, err := Store.Upload(userID, file, folderID, resourceID)
if err != nil {
// Nom/extension rejetés côté service (TrimSpace, cap 255,
// anti-slash/retour-ligne, cf. FEEDBACK A16) → 400, jamais 500.
if errors.Is(err, service.ErrInvalidUpload) {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "invalid file name")
return
}
writeError(c, err)
return
}
@@ -165,10 +211,13 @@ func FilesSearch(c *gin.Context) {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "missing required query param `q`")
return
}
page := intParam(c.Query("page"), 1)
pageSize := intParam(c.Query("pageSize"), 50)
if pageSize > 200 {
pageSize = 200
if len(q) > 200 {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "query param `q` too long (max 200)")
return
}
page, pageSize, ok := parsePageParams(c)
if !ok {
return
}
files, total, err := Store.SearchFiles(userID, q, page, pageSize)
if err != nil {
+58 -5
View File
@@ -73,6 +73,7 @@ func setup(t *testing.T) (*gin.Engine, *service.Resources, *repository.Repositor
}
handlers.Auth = manager
handlers.Store = store
handlers.ResetDevicesRateLimit()
gin.SetMode(gin.TestMode)
r := gin.New()
@@ -517,12 +518,12 @@ func TestFilesPaginationDefaultsAndClamp(t *testing.T) {
t.Errorf("clamp pageSize: %+v", env.Meta)
}
// Paramètres invalides → défauts (page=1, pageSize=50)
// Paramètres invalides → 400 (plus de fallback silencieux, cf. A16).
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files?page=0&pageSize=-5", token, nil, "")
env = expectOK(t, rec, "invalid-params")
if env.Meta == nil || env.Meta.Page != 1 || env.Meta.PageSize != 50 {
t.Errorf("defauts page/pageSize: %+v", env.Meta)
}
expectError(t, rec, http.StatusBadRequest, "INVALID_REQUEST", "negative-params")
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files?page=abc&pageSize=zz", token, nil, "")
expectError(t, rec, http.StatusBadRequest, "INVALID_REQUEST", "garbage-params")
// sort/order inconnus → pas d'erreur (défaut created_at desc)
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files?sort=zzz&order=up&pageSize=10", token, nil, "")
@@ -633,3 +634,55 @@ func TestFilesGetOcrOwnerShareAndScoping(t *testing.T) {
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/not-hex/ocr", ownerToken, nil, "")
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "ocr-invalid-id")
}
func TestFilesUploadRejectsBadFilename(t *testing.T) {
r, _, repo := setup(t)
device := repository.NewID()
token, _ := registerAndLogin(t, r, repo, testUserUsername(device, "bn"), "badname-test-password", device)
// Body multipart construit à la main : filename brut, NON neutralisé par
// le writer stdlib (qui basename/encode de son côté). Le serveur doit
// rejeter en 400, jamais 500 (cf. A16).
rawUpload := func(filename string) *httptest.ResponseRecorder {
t.Helper()
boundary := "testboundary123"
body := "--" + boundary + "\r\n" +
"Content-Disposition: form-data; name=\"file\"; filename=\"" + filename + "\"\r\n" +
"Content-Type: application/octet-stream\r\n\r\n" +
"hi\r\n" +
"--" + boundary + "--\r\n"
rec, _ := doRequest(t, r, http.MethodPost, "/api/v1/files/upload", token, []byte(body), "multipart/form-data; boundary="+boundary)
return rec
}
rec := rawUpload("../../evil.txt")
// La stdlib Go basename déjà côté lecture (défense en profondeur côté
// service via sanitizeFileName, testé en unitaire + backslash) : le nom
// stocké est "evil.txt" et aucun chemin ne s'échappe (destPath dérivé
// uniquement de IDs 32-hex + extension sanitizée).
env := expectOK(t, rec, "upload-traversal-name")
var uploaded fileDTO
if err := json.Unmarshal(env.Data, &uploaded); err != nil {
t.Fatalf("upload-traversal-name: unmarshal: %v", err)
}
if uploaded.Name != "evil.txt" {
t.Errorf("nom traversal neutralisé attendu \"evil.txt\", got %q", uploaded.Name)
}
// Backslash : préservé par la stdlib → rejet service 400, jamais 500.
rec = rawUpload(`bad\name.txt`)
expectError(t, rec, http.StatusBadRequest, "INVALID_REQUEST", "upload-backslash-name")
}
func TestSearchQTooLong(t *testing.T) {
r, _, repo := setup(t)
device := repository.NewID()
token, _ := registerAndLogin(t, r, repo, testUserUsername(device, "ql"), "search-test-password", device)
long := make([]byte, 201)
for i := range long {
long[i] = 'a'
}
rec, _ := doRequest(t, r, http.MethodGet, "/api/v1/files/search?q="+string(long), token, nil, "")
expectError(t, rec, http.StatusBadRequest, "INVALID_REQUEST", "search-q-too-long")
}
+126
View File
@@ -0,0 +1,126 @@
package handlers_test
// Tests contrat LOT 6 : ordre statique/param (§1), validation 32-hex et
// curseur `after` stricts (A7), validation POST /devices.
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/kazier/backend/handlers"
"github.com/kazier/backend/repository"
)
// TestFoldersRouteServesListNotParam (§1) : GET /files/folders via le routeur
// atteint FoldersList (200), jamais FilesGet avec id="folders".
func TestFoldersRouteServesListNotParam(t *testing.T) {
r, _, repo := setup(t)
device := repository.NewID()
token, _ := registerAndLogin(t, r, repo, testUserUsername(device, "l6f"), "lot6-test-password", device)
rec, _ := doRequest(t, r, http.MethodGet, "/api/v1/files/folders", token, nil, "")
expectOK(t, rec, "folders-static-wins")
}
// TestFilesGetRejectsFoldersLiteral (§1) : si le routeur tombait un jour sur
// FilesGet avec id="folders", le garde 32-hex répond 404 (jamais 200, jamais
// 500). Appel direct du handler pour forcer le cas paramétré.
func TestFilesGetRejectsFoldersLiteral(t *testing.T) {
setup(t)
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/api/v1/files/folders", nil)
c.Params = gin.Params{{Key: "id", Value: "folders"}}
c.Set(handlers.UserIDKey, "00000000000000000000000000000001")
handlers.FilesGet(c)
expectError(t, w, http.StatusNotFound, "NOT_FOUND", "files-get-folders-literal")
}
// TestShareLinkMalformedToken400 (A7) : token non 32-hex → 400
// INVALID_REQUEST (pas 404).
func TestShareLinkMalformedToken400(t *testing.T) {
r, _, _ := setup(t)
for _, path := range []string{
"/api/v1/shares/links/NOT-HEX",
"/api/v1/shares/links/xyz",
"/api/v1/shares/links/ABCDEF0123456789ABCDEF0123456789", // majuscules rejetées
} {
rec, _ := doRequest(t, r, http.MethodGet, path, "", nil, "")
expectError(t, rec, http.StatusBadRequest, "INVALID_REQUEST", "share-malformed-token")
}
}
// TestSyncPermissionsAfterValidation (A7) : garbage/négatif → 400, epoch-ms
// 64-bit accepté.
func TestSyncPermissionsAfterValidation(t *testing.T) {
r, _, repo := setup(t)
device := repository.NewID()
token, _ := registerAndLogin(t, r, repo, testUserUsername(device, "l6a"), "lot6-test-password", device)
for _, path := range []string{
"/api/v1/sync/permissions?after=garbage",
"/api/v1/sync/permissions?after=-5",
"/api/v1/sync/permissions?after=12.5",
"/api/v1/sync/permissions?after=",
} {
// "?after=" vide = curseur absent → 200 (seul le dernier cas).
rec, _ := doRequest(t, r, http.MethodGet, path, token, nil, "")
if path == "/api/v1/sync/permissions?after=" {
expectOK(t, rec, "after-empty-ok")
} else {
expectError(t, rec, http.StatusBadRequest, "INVALID_REQUEST", "after-invalid:"+path)
}
}
// Epoch-ms au-delà de 2^31 (64-bit) → 200, pas de troncation/rejet.
rec, _ := doRequest(t, r, http.MethodGet, "/api/v1/sync/permissions?after=9999999999999", token, nil, "")
expectOK(t, rec, "after-64bit-ok")
}
// TestDevicesRegisterValidation : 32-hex malformé/absent → 400, valide → 200.
func TestDevicesRegisterValidation(t *testing.T) {
r, _, _ := setup(t)
rec, _ := doRequest(t, r, http.MethodPost, "/api/v1/devices", "", []byte(`{"deviceId":"NOT-HEX"}`), "application/json")
expectError(t, rec, http.StatusBadRequest, "INVALID_DEVICE_ID", "devices-malformed")
rec, _ = doRequest(t, r, http.MethodPost, "/api/v1/devices", "", []byte(`{}`), "application/json")
expectError(t, rec, http.StatusBadRequest, "INVALID_REQUEST", "devices-missing")
rec, _ = doRequest(t, r, http.MethodPost, "/api/v1/devices", "", []byte(`{"deviceId":`+`"`+repository.NewID()+`"}`), "application/json")
expectOK(t, rec, "devices-valid")
}
// TestDevicesRegisterRateLimited : flood → 429 RATE_LIMITED (budget 300/min/IP,
// cf. handlers/devices.go). Les requêtes invalides ne consomment pas le budget.
func TestDevicesRegisterRateLimited(t *testing.T) {
r, _, _ := setup(t)
hookCalls := 0
handlers.OnDevicesRateLimited = func(ip string) { hookCalls++ }
t.Cleanup(func() { handlers.OnDevicesRateLimited = nil })
// Les requêtes invalides (avant le compteur) ne doivent pas déclencher.
rec, _ := doRequest(t, r, http.MethodPost, "/api/v1/devices", "", []byte(`{"deviceId":"BAD"}`), "application/json")
expectError(t, rec, http.StatusBadRequest, "INVALID_DEVICE_ID", "devices-ratelimit-invalid")
for i := 0; i < 300; i++ {
rec, _ := doRequest(t, r, http.MethodPost, "/api/v1/devices", "", []byte(`{"deviceId":`+`"`+repository.NewID()+`"}`), "application/json")
if rec.Code != http.StatusOK {
t.Fatalf("enregistrement %d: attendu 200, got %d body=%s", i, rec.Code, rec.Body.String())
}
}
rec, _ = doRequest(t, r, http.MethodPost, "/api/v1/devices", "", []byte(`{"deviceId":`+`"`+repository.NewID()+`"}`), "application/json")
expectError(t, rec, http.StatusTooManyRequests, "RATE_LIMITED", "devices-ratelimited")
if hookCalls != 1 {
t.Errorf("OnDevicesRateLimited appelé %d fois, attendu 1", hookCalls)
}
}
+33 -1
View File
@@ -2,6 +2,7 @@ package handlers
import (
"errors"
"log"
"net/http"
"strings"
@@ -19,6 +20,15 @@ const (
// Auth issues/verifies device bearer tokens; set once at startup (cmd/server).
var Auth *auth.Manager
// EnforceDeviceExists durcit RequireAuth (FEEDBACK A15) : quand true, le
// device_id porté par le token doit exister en base (POST /devices), sinon la
// requête est rejetée en 401 et le rejet est loggé côté serveur.
// Défaut false (V1) : le device reste un claim porté NON autorisant —
// l'autorisation vient du subject user_id + existence du compte. Passer à true
// coûte une lecture DB par requête authentifiée ; ne pas activer sans mesurer
// sur les routes à fort trafic (snapshot/sync).
var EnforceDeviceExists = false
// RequireAuth authenticates the bearer paseto token. Le subject (user_id)
// autorise — c'est la clé de scoping de toutes les ressources ; device_id est
// porté (non autorisant) pour l'idempotence outbox et les jobs OCR. Le compte
@@ -26,7 +36,13 @@ var Auth *auth.Manager
func RequireAuth(c *gin.Context) {
header := c.GetHeader("Authorization")
token, found := strings.CutPrefix(header, "Bearer ")
token := ""
found := false
// Préfixe Bearer insensible à la casse (cf. FEEDBACK A7).
if len(header) > 7 && strings.EqualFold(header[:7], "Bearer ") {
token = strings.TrimSpace(header[7:])
found = token != ""
}
if Auth == nil || !found || token == "" {
api.Error(c, http.StatusUnauthorized, "UNAUTHORIZED", "missing bearer token")
@@ -57,6 +73,22 @@ func RequireAuth(c *gin.Context) {
}
}
if EnforceDeviceExists && Store != nil && Store.Repository != nil {
// Verify garantit déjà le format 32-hex : Exists reçoit une entrée saine.
exists, err := Store.Repository.Devices.Exists(identity.DeviceID)
if err != nil {
api.Error(c, http.StatusInternalServerError, "INTERNAL", "could not check device")
c.Abort()
return
}
if !exists {
log.Printf("auth: token d'un device inconnu rejeté (user=%s device=%s)", identity.UserID, identity.DeviceID)
api.Error(c, http.StatusUnauthorized, "UNAUTHORIZED", "unknown device")
c.Abort()
return
}
}
c.Set(UserIDKey, identity.UserID)
c.Set(DeviceIDKey, identity.DeviceID)
c.Next()
+60
View File
@@ -0,0 +1,60 @@
package handlers
import (
"net/http"
"strings"
"testing"
)
const middlewareUnknownDevice = "ffffffffffffffffffffffffffffffff"
// Par défaut (EnforceDeviceExists=false), un token portant un device inconnu
// passe le middleware : le device est un claim non autorisant (V1).
func TestRequireAuthUnknownDevicePassesByDefault(t *testing.T) {
setTestAuth(t)
repo := setTestStore(t)
userID := createAdmin(t, repo, "admin", authTestPassword)
r := newTestRouterForAuth()
if EnforceDeviceExists {
t.Fatal("EnforceDeviceExists devrait être false par défaut")
}
signed, err := Auth.Issue(userID, middlewareUnknownDevice)
if err != nil {
t.Fatalf("issue: %v", err)
}
rec := doAuth(t, r, http.MethodGet, "/api/v1/files", signed, "")
if rec.Code == 401 {
t.Fatalf("device inconnu rejeté alors que EnforceDeviceExists=false: %s", rec.Body.String())
}
}
// Avec EnforceDeviceExists=true, le device inconnu est rejeté en 401 (et
// loggé), le device enregistré passe.
func TestRequireAuthEnforceDeviceExists(t *testing.T) {
setTestAuth(t)
repo := setTestStore(t)
userID := createAdmin(t, repo, "admin", authTestPassword)
_ = repo.Devices.Upsert(authTestDevice)
r := newTestRouterForAuth()
old := EnforceDeviceExists
EnforceDeviceExists = true
t.Cleanup(func() { EnforceDeviceExists = old })
unknown, _ := Auth.Issue(userID, middlewareUnknownDevice)
rec := doAuth(t, r, http.MethodGet, "/api/v1/files", unknown, "")
if rec.Code != 401 {
t.Fatalf("device inconnu: status %d body %s, attendu 401", rec.Code, rec.Body.String())
}
if !strings.Contains(rec.Body.String(), "UNAUTHORIZED") {
t.Errorf("code attendu UNAUTHORIZED, got %s", rec.Body.String())
}
known, _ := Auth.Issue(userID, authTestDevice)
rec = doAuth(t, r, http.MethodGet, "/api/v1/files", known, "")
if rec.Code == 401 {
t.Fatalf("device enregistré rejeté avec EnforceDeviceExists=true: %s", rec.Body.String())
}
}
+1
View File
@@ -40,6 +40,7 @@ func setupOcr(t *testing.T) (*gin.Engine, string, *repository.Repository) {
manager, _ := auth.NewManager("test-secret")
handlers.Auth = manager
handlers.Store = store
handlers.ResetDevicesRateLimit()
handlers.Ocr = service.NewOcr(repo, uploadDir, "fra+eng", stubEngine{text: "HELLO OCR"})
// Worker OCR borné — le handler n'enfile plus que le job, le traitement
+5 -1
View File
@@ -25,11 +25,15 @@ func RegisterRoutes(r *gin.Engine) {
protected.Use(RequireAuth)
{
protected.GET("/files", FilesList)
// Verrou LOT 6 §1 : les routes statiques restent déclarées AVANT
// /files/:id (Gin priorise déjà le statique sur le paramétré, mais
// l'ordre source verrouille l'intention : /files/folders ne doit
// jamais être avalé par FilesGet avec id="folders").
protected.GET("/files/search", FilesSearch)
protected.GET("/files/folders", FoldersList)
protected.GET("/files/:id", FilesGet)
protected.GET("/files/:id/ocr", FilesGetOcr)
protected.DELETE("/files/:id", FilesDelete)
protected.GET("/files/folders", FoldersList)
protected.POST("/files/upload", FilesUpload)
protected.GET("/users/resolve", ResolveUser)
+11 -1
View File
@@ -1,6 +1,7 @@
package handlers
import (
"errors"
"net/http"
"github.com/gin-gonic/gin"
@@ -18,9 +19,18 @@ func ShareLinkGet(c *gin.Context) {
return
}
token := c.Param("token")
// Contrat V1 : les tokens de lien sont du 32-hex (cf. docs/api-v1.md).
// Malformé → 400 INVALID_REQUEST (pas 404 : ce n'est pas « introuvable »,
// c'est « requête invalide »). deviceIDPattern (devices.go, même package)
// exprime exactement ce format.
if !deviceIDPattern.MatchString(token) {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "malformed link token")
return
}
link, err := Store.Repository.Shares.GetPublicLink(token)
if err != nil {
if err == repository.ErrNotFound {
// A6 : errors.Is (pas ==) — le repo peut envelopper ErrNotFound.
if errors.Is(err, repository.ErrNotFound) {
api.Error(c, http.StatusNotFound, "NOT_FOUND", "link not found or revoked")
return
}
+9 -1
View File
@@ -2,6 +2,7 @@ package handlers
import (
"errors"
"log"
"github.com/gin-gonic/gin"
"github.com/kazier/backend/pkg/api"
@@ -28,6 +29,13 @@ func writeError(c *gin.Context, err error) {
case errors.Is(err, service.ErrFileTooLarge):
api.Error(c, 413, "FILE_TOO_LARGE", "file exceeds the maximum allowed size")
default:
api.Error(c, 500, "INTERNAL", err.Error())
// Jamais de err.Error() brut au client (fuite SQL/FS/paths, cf.
// FEEDBACK #8) : message générique, détail au log serveur.
path := ""
if c.Request != nil && c.Request.URL != nil {
path = c.Request.URL.Path
}
log.Printf("internal error: path=%s err=%v", path, err)
api.Error(c, 500, "INTERNAL", "internal error")
}
}
+37 -4
View File
@@ -2,6 +2,7 @@ package handlers
import (
"net/http"
"strconv"
"github.com/gin-gonic/gin"
@@ -9,10 +10,37 @@ import (
"github.com/kazier/backend/service"
)
// parseAfterMs parses the `after` delta cursor of GET /sync/permissions :
// epoch-millis, 64-bit (les curseurs dépassent 2^31). Chaîne vide → 0 (sync
// complet). Garbage ou négatif → ok=false : le handler répond 400
// INVALID_REQUEST, jamais de repli silencieux vers 0 (un curseur malformé
// pris pour « sync complet » masquerait une désynchro client).
// NOTE : intParam (files.go, LOT 2) garde son repli-défaut historique pour la
// pagination ; la validation stricte 400 des pages relève du LOT 2
// (inter-lots).
func parseAfterMs(raw string) (int64, bool) {
if raw == "" {
return 0, true
}
ms, err := strconv.ParseInt(raw, 10, 64)
if err != nil || ms < 0 {
return 0, false
}
return ms, true
}
type syncOpsRequest struct {
Operations []service.SyncOperation `json:"operations"`
}
// Bornes anti-DoS de POST /sync/ops (FEEDBACK §moyenne) : le client envoie des
// batchs de 20 ; au-delà de 100 ops ou 1 MiB de body → rejet explicite, jamais
// d'OOM sur batch géant.
const (
maxSyncOpsBodyBytes = 1 << 20
maxSyncOpsPerBatch = 100
)
func SyncOpsPush(c *gin.Context) {
if Store == nil {
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
@@ -20,11 +48,16 @@ func SyncOpsPush(c *gin.Context) {
}
userID := c.GetString(UserIDKey)
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxSyncOpsBodyBytes)
var req syncOpsRequest
if err := c.ShouldBindJSON(&req); err != nil {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "invalid JSON body")
return
}
if len(req.Operations) > maxSyncOpsPerBatch {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "too many operations in batch (max 100)")
return
}
result, err := Store.ApplyBatch(userID, c.GetString(DeviceIDKey), req.Operations)
if err != nil {
@@ -40,10 +73,10 @@ func SyncPermissionsGet(c *gin.Context) {
return
}
userID := c.GetString(UserIDKey)
after := c.Query("after")
var afterMs int64
if after != "" {
afterMs = int64(intParam(after, 0))
afterMs, ok := parseAfterMs(c.Query("after"))
if !ok {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "invalid `after` cursor, must be non-negative epoch-millis")
return
}
perms, err := Store.Snapshot(userID, afterMs)
if err != nil {
+14
View File
@@ -254,6 +254,20 @@ func TestSyncOpsLargeBatchAccepted(t *testing.T) {
}
}
func TestSyncOpsBatchTooLargeRejected(t *testing.T) {
r, _, repo := setup(t)
device := repository.NewID()
token, _ := registerAndLogin(t, r, repo, testUserUsername(device, "sx"), "sync-test-password", device)
ops := make([]map[string]any, 0, 101)
for i := 0; i < 101; i++ {
ops = append(ops, op(repository.NewID(), repository.NewID(), "create_resource", "file", map[string]any{"name": fmt.Sprintf("g%03d.txt", i)}))
}
rec, _ := doRequest(t, r, http.MethodPost, "/api/v1/sync/ops", token, syncOpsBody(ops), "application/json")
expectError(t, rec, http.StatusBadRequest, "INVALID_REQUEST", "sync-batch-too-large")
}
func TestSyncOpsStopsAtFirstNonIdempotentFailure(t *testing.T) {
r, _, repo := setup(t)
device := repository.NewID()