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
108 lines
3.5 KiB
Go
108 lines
3.5 KiB
Go
package handlers
|
|
|
|
import (
|
|
"net/http"
|
|
"regexp"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/kazier/backend/pkg/api"
|
|
)
|
|
|
|
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")
|
|
return
|
|
}
|
|
if !deviceIDPattern.MatchString(req.DeviceID) {
|
|
api.Error(c, 400, "INVALID_DEVICE_ID", "deviceId must be 32 lowercase hex chars")
|
|
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
|
|
}
|
|
if err := Store.Repository.Devices.Upsert(req.DeviceID); err != nil {
|
|
api.Error(c, 500, "INTERNAL", "could not persist device")
|
|
return
|
|
}
|
|
|
|
// POST /devices n'émet PLUS de token : de l'identité user-first (V1), le
|
|
// device s'enregistre pour exister, puis le client appelle POST /auth/login
|
|
// avec username/password + device_id pour obtenir son token (cf.
|
|
// docs/api-v1.md §2). Réponse : { deviceId } uniquement.
|
|
api.OK(c, gin.H{"deviceId": req.DeviceID})
|
|
|
|
}
|