package handlers import ( "net/http" "strconv" "github.com/gin-gonic/gin" "github.com/kazier/backend/pkg/api" "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 : la pagination (files.go) répond 400 sur page/pageSize malformés, // jamais de repli silencieux vers un défaut (un curseur malformé pris pour // « sync complet » masquerait une désynchro client). 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") return } 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 { writeError(c, err) return } api.OK(c, result) } func SyncPermissionsGet(c *gin.Context) { if Store == nil { api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized") return } userID := c.GetString(UserIDKey) 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 { writeError(c, err) return } api.OK(c, perms) }