245 lines
8.3 KiB
Go
245 lines
8.3 KiB
Go
// Tests du statut "rate_limited" exposé par GET /all/clients et de la levée
|
|
// des rate limits par un admin (POST /client/:username/ratelimit/reset).
|
|
// Couvre les trois limites client : requêtes panier/commande (Redis),
|
|
// annulations et modification d'adresse (mémoire).
|
|
package tests
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"net/url"
|
|
"strings"
|
|
"testing"
|
|
|
|
"gestion/db"
|
|
"gestion/handlers"
|
|
"gestion/middleware"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func clientID(t *testing.T, username string) int {
|
|
t.Helper()
|
|
cl, err := testDB.GetClientByUsername(username)
|
|
if err != nil || cl == nil {
|
|
t.Fatalf("client %q introuvable: %v", username, err)
|
|
}
|
|
return cl.ID
|
|
}
|
|
|
|
func setRequestCount(t *testing.T, username string, count int) {
|
|
t.Helper()
|
|
key := middleware.ClientRateLimitKey(clientID(t, username))
|
|
if err := db.Redis.Set(db.RedisCtx, key, count, 0).Err(); err != nil {
|
|
t.Fatalf("set compteur redis: %v", err)
|
|
}
|
|
t.Cleanup(func() { db.Redis.Del(db.RedisCtx, key) })
|
|
}
|
|
|
|
// rateLimitedStatus renvoie le champ rate_limited de chaque client de la
|
|
// première page de GET /all/clients.
|
|
func rateLimitedStatus(t *testing.T) map[string]bool {
|
|
t.Helper()
|
|
c, rec := clientsListContext("admin", url.Values{})
|
|
handlers.GetAllClients(c)
|
|
if rec.Code != http.StatusOK {
|
|
t.Fatalf("GetAllClients: got=%d body=%s", rec.Code, rec.Body.String())
|
|
}
|
|
var resp struct {
|
|
Clients []struct {
|
|
Username string `json:"username"`
|
|
RateLimited bool `json:"rate_limited"`
|
|
} `json:"clients"`
|
|
}
|
|
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
|
t.Fatalf("décodage réponse: %v", err)
|
|
}
|
|
status := make(map[string]bool, len(resp.Clients))
|
|
for _, cl := range resp.Clients {
|
|
status[cl.Username] = cl.RateLimited
|
|
}
|
|
return status
|
|
}
|
|
|
|
func resetRateLimit(t *testing.T, role, username string) *httptest.ResponseRecorder {
|
|
t.Helper()
|
|
rec := httptest.NewRecorder()
|
|
c, _ := gin.CreateTestContext(rec)
|
|
c.Request = httptest.NewRequest(http.MethodPost, "/api/v2/admin/protected/client/"+username+"/ratelimit/reset", nil)
|
|
c.Set("database", testDB)
|
|
c.Set("role", role)
|
|
c.Set("username", testUserPrefix+"rl_admin")
|
|
c.Params = gin.Params{{Key: "username", Value: username}}
|
|
handlers.ResetClientRateLimitAdmin(c)
|
|
return rec
|
|
}
|
|
|
|
func clientContext(username, method, path string, body string) (*gin.Context, *httptest.ResponseRecorder) {
|
|
rec := httptest.NewRecorder()
|
|
c, _ := gin.CreateTestContext(rec)
|
|
c.Request = httptest.NewRequest(method, path, strings.NewReader(body))
|
|
c.Request.Header.Set("Content-Type", "application/json")
|
|
c.Set("database", testDB)
|
|
c.Set("geoService", ensureTestGeoService())
|
|
c.Set("role", "client")
|
|
c.Set("username", username)
|
|
// id=0 est rejeté après le contrôle du rate limit : chaque appel compte
|
|
// une tentative sans toucher à une vraie commande.
|
|
c.Params = gin.Params{{Key: "id", Value: "0"}}
|
|
return c, rec
|
|
}
|
|
|
|
func cancelAttempt(username string) int {
|
|
c, rec := clientContext(username, http.MethodPost, "/api/v1/commands/0/cancel", `{}`)
|
|
handlers.CancelCommandByClient(c)
|
|
return rec.Code
|
|
}
|
|
|
|
func addressAttempt(username string) int {
|
|
c, rec := clientContext(username, http.MethodPut, "/api/v1/commands/0/address", `{"delivery_address":"1 rue test"}`)
|
|
handlers.UpdateOwnCommandAddress(c)
|
|
return rec.Code
|
|
}
|
|
|
|
// ── Statut rate_limited (Redis) ────────────────────────────────────────────
|
|
|
|
func TestGetAllClients_RateLimitedReflectsRequestCounter(t *testing.T) {
|
|
cleanupStockTestData(t)
|
|
blocked := newTestClient(t, "rl_blocked")
|
|
atLimit := newTestClient(t, "rl_at_limit")
|
|
free := newTestClient(t, "rl_free")
|
|
|
|
setRequestCount(t, blocked, middleware.ClientRateLimitMax+1)
|
|
// Le middleware ne bloque qu'au-delà du max : pile au max, la requête passe encore.
|
|
setRequestCount(t, atLimit, middleware.ClientRateLimitMax)
|
|
|
|
status := rateLimitedStatus(t)
|
|
if !status[blocked] {
|
|
t.Errorf("%s (compteur > max) doit être rate_limited", blocked)
|
|
}
|
|
if status[atLimit] {
|
|
t.Errorf("%s (compteur = max) ne doit pas être rate_limited", atLimit)
|
|
}
|
|
if status[free] {
|
|
t.Errorf("%s (aucun compteur) ne doit pas être rate_limited", free)
|
|
}
|
|
}
|
|
|
|
// ── Levée du rate limit ─────────────────────────────────────────────────────
|
|
|
|
func TestResetClientRateLimit_ClearsRequestCounter(t *testing.T) {
|
|
cleanupStockTestData(t)
|
|
username := newTestClient(t, "rl_reset_redis")
|
|
setRequestCount(t, username, middleware.ClientRateLimitMax+50)
|
|
|
|
if rec := resetRateLimit(t, "admin", username); rec.Code != http.StatusOK {
|
|
t.Fatalf("reset: got=%d body=%s", rec.Code, rec.Body.String())
|
|
}
|
|
|
|
key := middleware.ClientRateLimitKey(clientID(t, username))
|
|
if n, _ := db.Redis.Exists(db.RedisCtx, key).Result(); n != 0 {
|
|
t.Errorf("le compteur Redis doit être supprimé après le reset")
|
|
}
|
|
if rateLimitedStatus(t)[username] {
|
|
t.Errorf("%s ne doit plus être rate_limited après le reset", username)
|
|
}
|
|
}
|
|
|
|
func TestResetClientRateLimit_ClearsCancelLimit(t *testing.T) {
|
|
cleanupStockTestData(t)
|
|
username := newTestClient(t, "rl_reset_cancel")
|
|
t.Cleanup(func() { resetRateLimit(t, "admin", username) })
|
|
|
|
for i := 0; i < 5; i++ {
|
|
cancelAttempt(username)
|
|
}
|
|
if code := cancelAttempt(username); code != http.StatusTooManyRequests {
|
|
t.Fatalf("6e annulation doit être bloquée: got=%d want=429", code)
|
|
}
|
|
if !rateLimitedStatus(t)[username] {
|
|
t.Fatalf("%s bloqué sur les annulations doit être rate_limited", username)
|
|
}
|
|
|
|
if rec := resetRateLimit(t, "admin", username); rec.Code != http.StatusOK {
|
|
t.Fatalf("reset: got=%d body=%s", rec.Code, rec.Body.String())
|
|
}
|
|
|
|
if rateLimitedStatus(t)[username] {
|
|
t.Errorf("%s ne doit plus être rate_limited après le reset", username)
|
|
}
|
|
if code := cancelAttempt(username); code == http.StatusTooManyRequests {
|
|
t.Errorf("après le reset, l'annulation ne doit plus être bloquée par le rate limit")
|
|
}
|
|
}
|
|
|
|
func TestResetClientRateLimit_ClearsAddressLimit(t *testing.T) {
|
|
cleanupStockTestData(t)
|
|
username := newTestClient(t, "rl_reset_addr")
|
|
t.Cleanup(func() { resetRateLimit(t, "admin", username) })
|
|
|
|
for i := 0; i < 10; i++ {
|
|
addressAttempt(username)
|
|
}
|
|
if code := addressAttempt(username); code != http.StatusTooManyRequests {
|
|
t.Fatalf("11e modification d'adresse doit être bloquée: got=%d want=429", code)
|
|
}
|
|
if !rateLimitedStatus(t)[username] {
|
|
t.Fatalf("%s bloqué sur les modifications d'adresse doit être rate_limited", username)
|
|
}
|
|
|
|
if rec := resetRateLimit(t, "admin", username); rec.Code != http.StatusOK {
|
|
t.Fatalf("reset: got=%d body=%s", rec.Code, rec.Body.String())
|
|
}
|
|
|
|
if rateLimitedStatus(t)[username] {
|
|
t.Errorf("%s ne doit plus être rate_limited après le reset", username)
|
|
}
|
|
if code := addressAttempt(username); code == http.StatusTooManyRequests {
|
|
t.Errorf("après le reset, la modification d'adresse ne doit plus être bloquée par le rate limit")
|
|
}
|
|
}
|
|
|
|
// Le reset d'un client ne doit pas débloquer les autres.
|
|
func TestResetClientRateLimit_OnlyAffectsTargetClient(t *testing.T) {
|
|
cleanupStockTestData(t)
|
|
target := newTestClient(t, "rl_target")
|
|
other := newTestClient(t, "rl_other")
|
|
setRequestCount(t, target, middleware.ClientRateLimitMax+1)
|
|
setRequestCount(t, other, middleware.ClientRateLimitMax+1)
|
|
|
|
if rec := resetRateLimit(t, "admin", target); rec.Code != http.StatusOK {
|
|
t.Fatalf("reset: got=%d body=%s", rec.Code, rec.Body.String())
|
|
}
|
|
|
|
status := rateLimitedStatus(t)
|
|
if status[target] {
|
|
t.Errorf("%s doit être débloqué", target)
|
|
}
|
|
if !status[other] {
|
|
t.Errorf("%s ne doit pas être affecté par le reset d'un autre client", other)
|
|
}
|
|
}
|
|
|
|
func TestResetClientRateLimit_RejectsNonAdmin(t *testing.T) {
|
|
cleanupStockTestData(t)
|
|
username := newTestClient(t, "rl_forbidden")
|
|
setRequestCount(t, username, middleware.ClientRateLimitMax+1)
|
|
|
|
for _, role := range []string{"cabine", "livreur", "client"} {
|
|
if rec := resetRateLimit(t, role, username); rec.Code != http.StatusForbidden {
|
|
t.Errorf("role %s doit être refusé: got=%d want=403", role, rec.Code)
|
|
}
|
|
}
|
|
if !rateLimitedStatus(t)[username] {
|
|
t.Errorf("un reset refusé ne doit pas débloquer le client")
|
|
}
|
|
}
|
|
|
|
func TestResetClientRateLimit_UnknownClientReturns404(t *testing.T) {
|
|
rec := resetRateLimit(t, "admin", testUserPrefix+"rl_does_not_exist")
|
|
if rec.Code != http.StatusNotFound {
|
|
t.Errorf("client inconnu: got=%d want=404", rec.Code)
|
|
}
|
|
}
|