Files
omnex/control-plane/api/internal/projects/requests_test.go
T
Xor290 89bf45f738
ci-web / test (push) Canceled after 0s
ci-api / test (push) Successful in 23m8s
chore: build
2026-10-04 17:39:39 +02:00

334 lines
11 KiB
Go

package projects
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/omnex/control-plane/api/internal/auth"
"github.com/omnex/control-plane/api/internal/session"
)
func newRequestService(t *testing.T) (*RequestService, *Service, *fakeProv) {
t.Helper()
psvc, prov, _ := newTestService(t)
return NewRequestService(NewMemRequestStore(), psvc), psvc, prov
}
func goodRequest() RequestInput {
return RequestInput{SiteName: "Boutique Dupont", Months: 6, Message: "Livraison à Lyon"}
}
func goodApproval() ApproveInput {
return ApproveInput{AdminUsername: "dupont", AdminPassword: "un-mot-de-passe-solide", AdminNumber: 2}
}
func TestRequest_CreateNormalizesUserAndValidatesInput(t *testing.T) {
svc, _, _ := newRequestService(t)
r, err := svc.Create(" Alice ", goodRequest())
if err != nil {
t.Fatal(err)
}
if r.Username != "alice" || r.Status != RequestPending || r.Months != 6 || r.ID == "" {
t.Errorf("demande inattendue : %+v", r)
}
bad := []RequestInput{
{SiteName: " ", Months: 1},
{SiteName: strings.Repeat("x", 65), Months: 1},
{SiteName: "ok", Months: 0},
{SiteName: "ok", Months: 13},
{SiteName: "ok", Months: 1, Message: strings.Repeat("m", 501)},
}
for i, in := range bad {
if _, err := svc.Create("alice", in); err == nil {
t.Errorf("saisie invalide n°%d acceptée : %+v", i, in)
}
}
}
func TestRequest_PendingLimitPerClient(t *testing.T) {
svc, _, _ := newRequestService(t)
for i := 0; i < MaxPendingRequests; i++ {
if _, err := svc.Create("alice", goodRequest()); err != nil {
t.Fatal(err)
}
}
if _, err := svc.Create("alice", goodRequest()); !errors.Is(err, ErrTooManyRequests) {
t.Errorf("erreur %v, attendu ErrTooManyRequests", err)
}
// La limite est par client.
if _, err := svc.Create("bob", goodRequest()); err != nil {
t.Errorf("un autre client est bloqué : %v", err)
}
// Une demande traitée libère une place.
mine, _ := svc.ListMine("alice")
if _, err := svc.Reject(mine[0].ID, "non"); err != nil {
t.Fatal(err)
}
if _, err := svc.Create("alice", goodRequest()); err != nil {
t.Errorf("place non libérée après refus : %v", err)
}
}
func TestRequest_ListMineIsolatesClients(t *testing.T) {
svc, _, _ := newRequestService(t)
if _, err := svc.Create("alice", goodRequest()); err != nil {
t.Fatal(err)
}
if _, err := svc.Create("bob", goodRequest()); err != nil {
t.Fatal(err)
}
mine, _ := svc.ListMine("ALICE")
if len(mine) != 1 || mine[0].Username != "alice" {
t.Errorf("fuite entre clients : %+v", mine)
}
if all, _ := svc.List(); len(all) != 2 {
t.Errorf("l'admin doit tout voir : %d", len(all))
}
}
func TestRequest_ApproveDeploysSiteOwnedByRequester(t *testing.T) {
svc, psvc, prov := newRequestService(t)
r, _ := svc.Create("alice", goodRequest())
got, p, err := svc.Approve(r.ID, goodApproval())
if err != nil {
t.Fatal(err)
}
<-prov.provisioned
if got.Status != RequestApproved || got.ProjectID != p.ID || got.DecidedAt == nil {
t.Errorf("demande après validation : %+v", got)
}
if p.OwnerUsername != "alice" || p.ClientName != "Boutique Dupont" || p.MonthsPurchased != 6 {
t.Errorf("projet : owner=%q nom=%q mois=%d (durée demandée attendue)", p.OwnerUsername, p.ClientName, p.MonthsPurchased)
}
mine, _ := psvc.ListForOwner("alice")
if len(mine) != 1 || mine[0].ID != p.ID {
t.Errorf("le client ne voit pas son site : %+v", mine)
}
if other, _ := psvc.ListForOwner("bob"); len(other) != 0 {
t.Errorf("un autre client voit le site : %+v", other)
}
}
func TestRequest_ApproveCanOverrideMonthsAndOnlyOnce(t *testing.T) {
svc, _, prov := newRequestService(t)
r, _ := svc.Create("alice", goodRequest())
in := goodApproval()
in.Months = 12
_, p, err := svc.Approve(r.ID, in)
if err != nil || p.MonthsPurchased != 12 {
t.Fatalf("err=%v mois=%d, attendu 12", err, p.MonthsPurchased)
}
<-prov.provisioned
if _, _, err := svc.Approve(r.ID, goodApproval()); !errors.Is(err, ErrRequestDecided) {
t.Errorf("double validation : %v, attendu ErrRequestDecided", err)
}
if _, err := svc.Reject(r.ID, "trop tard"); !errors.Is(err, ErrRequestDecided) {
t.Errorf("refus après validation : %v", err)
}
if len(prov.specs) != 1 {
t.Errorf("%d sites déployés pour une seule demande", len(prov.specs))
}
}
func TestRequest_InvalidApprovalKeepsRequestPending(t *testing.T) {
svc, psvc, _ := newRequestService(t)
r, _ := svc.Create("alice", goodRequest())
weak := goodApproval()
weak.AdminPassword = "court"
if _, _, err := svc.Approve(r.ID, weak); !errors.Is(err, ErrWeakAdminPass) {
t.Fatalf("erreur %v, attendu ErrWeakAdminPass", err)
}
if got, _ := svc.store.Get(r.ID); got.Status != RequestPending || got.ProjectID != "" {
t.Errorf("la demande a changé malgré l'échec : %+v", got)
}
if all, _ := psvc.List(); len(all) != 0 {
t.Errorf("projet créé malgré l'échec : %+v", all)
}
if _, _, err := svc.Approve("inconnue", goodApproval()); !errors.Is(err, ErrRequestNotFound) {
t.Errorf("erreur %v, attendu ErrRequestNotFound", err)
}
}
func TestRequest_RejectStoresNote(t *testing.T) {
svc, _, _ := newRequestService(t)
r, _ := svc.Create("alice", goodRequest())
got, err := svc.Reject(r.ID, " Paiement non reçu ")
if err != nil || got.Status != RequestRejected || got.AdminNote != "Paiement non reçu" || got.DecidedAt == nil {
t.Errorf("err=%v demande=%+v", err, got)
}
if _, err := svc.Reject(r.ID, strings.Repeat("n", 501)); !errors.Is(err, ErrRequestDecided) && !errors.Is(err, ErrInvalidMessage) {
t.Errorf("erreur inattendue : %v", err)
}
}
// --- HTTP : autorisations réelles (JWT + session + rôle), comme en production ---
type httpFixture struct {
r *gin.Engine
tokens map[string]string
prov *fakeProv
}
func newHTTPFixture(t *testing.T) *httpFixture {
t.Helper()
gin.SetMode(gin.TestMode)
psvc, prov, _ := newTestService(t)
h := NewHandler(psvc)
rh := NewRequestHandler(NewRequestService(NewMemRequestStore(), psvc), h)
iss := auth.NewIssuer([]byte("0123456789abcdef0123456789abcdef"), time.Hour)
mgr := session.NewMemManager(time.Hour)
tokens := map[string]string{}
for user, role := range map[string]auth.Role{"alice": auth.RoleClient, "bob": auth.RoleClient, "root": auth.RoleAdmin} {
sid, err := mgr.Create(context.Background(), session.Session{UserID: user, Role: string(role)})
if err != nil {
t.Fatal(err)
}
tok, err := iss.Issue(user, user, role, sid)
if err != nil {
t.Fatal(err)
}
tokens[user] = tok
}
r := gin.New()
authed := r.Group("")
authed.Use(auth.RequireAuth(iss, mgr))
client := authed.Group("")
client.Use(auth.RequireRole(auth.RoleClient))
client.POST("/project-requests", rh.Create)
client.GET("/project-requests/mine", rh.ListMine)
client.GET("/projects/mine", h.ListMine)
admin := authed.Group("")
admin.Use(auth.RequireRole(auth.RoleAdmin))
admin.GET("/project-requests", rh.List)
admin.POST("/project-requests/:id/approve", rh.Approve)
admin.POST("/project-requests/:id/reject", rh.Reject)
return &httpFixture{r: r, tokens: tokens, prov: prov}
}
func (f *httpFixture) do(user, method, path, body string) *httptest.ResponseRecorder {
req := httptest.NewRequest(method, path, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
if tok, ok := f.tokens[user]; ok {
req.Header.Set("Authorization", "Bearer "+tok)
}
w := httptest.NewRecorder()
f.r.ServeHTTP(w, req)
return w
}
const requestJSON = `{"site_name":"Boutique Dupont","months":3,"message":"bonjour"}`
const approveJSON = `{"admin_username":"dupont","admin_password":"un-mot-de-passe-solide"}`
func TestHTTPRequests_AuthorizationMatrix(t *testing.T) {
f := newHTTPFixture(t)
// Sans compte : rien n'est accessible.
for _, c := range []struct{ method, path string }{
{"POST", "/project-requests"}, {"GET", "/project-requests/mine"}, {"GET", "/projects/mine"},
{"GET", "/project-requests"}, {"POST", "/project-requests/x/approve"}, {"POST", "/project-requests/x/reject"},
} {
if w := f.do("", c.method, c.path, `{}`); w.Code != http.StatusUnauthorized {
t.Errorf("anonyme %s %s : %d, attendu 401", c.method, c.path, w.Code)
}
}
w := f.do("alice", "POST", "/project-requests", requestJSON)
if w.Code != http.StatusCreated {
t.Fatalf("création : %d %s", w.Code, w.Body)
}
var created Request
_ = json.Unmarshal(w.Body.Bytes(), &created)
// Un client ne décide jamais et ne voit pas la liste globale.
for _, c := range []struct{ method, path, body string }{
{"GET", "/project-requests", ""},
{"POST", "/project-requests/" + created.ID + "/approve", approveJSON},
{"POST", "/project-requests/" + created.ID + "/reject", `{}`},
} {
if w := f.do("alice", c.method, c.path, c.body); w.Code != http.StatusForbidden {
t.Errorf("client %s %s : %d, attendu 403", c.method, c.path, w.Code)
}
}
if len(f.prov.specs) != 0 {
t.Fatal("un client a déclenché un déploiement")
}
// Bob ne voit pas la demande d'Alice.
w = f.do("bob", "GET", "/project-requests/mine", "")
var bob struct{ Items []Request }
_ = json.Unmarshal(w.Body.Bytes(), &bob)
if w.Code != http.StatusOK || len(bob.Items) != 0 {
t.Errorf("bob voit la demande d'alice : %d %s", w.Code, w.Body)
}
}
func TestHTTPRequests_ApproveFlowAndOwnership(t *testing.T) {
f := newHTTPFixture(t)
w := f.do("alice", "POST", "/project-requests", requestJSON)
var created Request
_ = json.Unmarshal(w.Body.Bytes(), &created)
if w := f.do("root", "POST", "/project-requests/"+created.ID+"/approve", `{"admin_username":"x","admin_password":"court"}`); w.Code != http.StatusBadRequest {
t.Errorf("saisie invalide : %d, attendu 400", w.Code)
}
w = f.do("root", "POST", "/project-requests/"+created.ID+"/approve", approveJSON)
if w.Code != http.StatusAccepted {
t.Fatalf("validation : %d %s", w.Code, w.Body)
}
<-f.prov.provisioned
if strings.Contains(w.Body.String(), "un-mot-de-passe-solide") {
t.Error("le mot de passe admin est renvoyé dans la réponse")
}
if w := f.do("root", "POST", "/project-requests/"+created.ID+"/approve", approveJSON); w.Code != http.StatusConflict {
t.Errorf("double validation : %d, attendu 409", w.Code)
}
w = f.do("alice", "GET", "/projects/mine", "")
var mine struct{ Items []Project }
_ = json.Unmarshal(w.Body.Bytes(), &mine)
if len(mine.Items) != 1 || mine.Items[0].OwnerUsername != "alice" {
t.Errorf("sites d'alice : %s", w.Body)
}
w = f.do("bob", "GET", "/projects/mine", "")
_ = json.Unmarshal(w.Body.Bytes(), &mine)
if len(mine.Items) != 0 {
t.Errorf("bob voit le site d'alice : %s", w.Body)
}
}
func TestHTTPRequests_ValidationAndRateLimitCodes(t *testing.T) {
f := newHTTPFixture(t)
for _, body := range []string{`{`, `{"site_name":"","months":3}`, `{"site_name":"x","months":13}`, `{"site_name":"x","months":0}`} {
if w := f.do("alice", "POST", "/project-requests", body); w.Code != http.StatusBadRequest {
t.Errorf("%s : %d, attendu 400", body, w.Code)
}
}
for i := 0; i < MaxPendingRequests; i++ {
if w := f.do("alice", "POST", "/project-requests", requestJSON); w.Code != http.StatusCreated {
t.Fatalf("demande %d : %d", i, w.Code)
}
}
if w := f.do("alice", "POST", "/project-requests", requestJSON); w.Code != http.StatusTooManyRequests {
t.Errorf("au-delà de la limite : %d, attendu 429", w.Code)
}
if w := f.do("root", "POST", "/project-requests/inconnue/reject", `{}`); w.Code != http.StatusNotFound {
t.Errorf("demande inconnue : %d, attendu 404", w.Code)
}
}