package projects import ( "context" "errors" "strings" "sync" "testing" "time" "github.com/omnex/control-plane/api/internal/demos" ) // fakeProv enregistre les appels au cluster ; provisioned est fermé une fois // le déploiement (asynchrone) terminé. type fakeProv struct { mu sync.Mutex specs []demos.ProjectSpec tornDown []string provErr error state demos.ResourceState stateErr error stateCalls []string domainSpecs []demos.ProjectDomainSpec domainErr error missing map[string]bool // namespaces absents du cluster simulé existsErr error provisioned chan struct{} } func newFakeProv() *fakeProv { return &fakeProv{provisioned: make(chan struct{}, 8)} } func (f *fakeProv) ProvisionProject(s demos.ProjectSpec) error { f.mu.Lock() f.specs = append(f.specs, s) f.mu.Unlock() defer func() { f.provisioned <- struct{}{} }() return f.provErr } func (f *fakeProv) TeardownProject(ns string) error { f.mu.Lock() defer f.mu.Unlock() f.tornDown = append(f.tornDown, ns) return nil } func (f *fakeProv) ProjectState(_ context.Context, ns string) (demos.ResourceState, error) { f.mu.Lock() defer f.mu.Unlock() f.stateCalls = append(f.stateCalls, ns) return f.state, f.stateErr } func (f *fakeProv) NamespaceExists(_ context.Context, ns string) (bool, error) { f.mu.Lock() defer f.mu.Unlock() if f.existsErr != nil { return false, f.existsErr } return !f.missing[ns], nil } func (f *fakeProv) UpdateProjectDomain(s demos.ProjectDomainSpec) error { f.mu.Lock() defer f.mu.Unlock() f.domainSpecs = append(f.domainSpecs, s) return f.domainErr } var t0 = time.Date(2026, time.September, 20, 12, 0, 0, 0, time.UTC) func newTestService(t *testing.T) (*Service, *fakeProv, *time.Time) { t.Helper() prov := newFakeProv() svc := NewService(NewMemStore(), prov, Config{Domain: "vitrine-omnex.club", ReservedDomains: []string{"omnex.sbs"}}) now := t0 svc.now = func() time.Time { return now } return svc, prov, &now } func validInput() CreateInput { return CreateInput{ClientName: "Boutique Dupont", Months: 3, AdminUsername: "admin", AdminPassword: "un-mot-de-passe-solide"} } // createReady crée un projet et attend la fin de son déploiement simulé. func createReady(t *testing.T, svc *Service, prov *fakeProv, in CreateInput) Project { t.Helper() p, err := svc.Create(in) if err != nil { t.Fatalf("Create: %v", err) } select { case <-prov.provisioned: case <-time.After(2 * time.Second): t.Fatal("déploiement simulé non terminé") } // La goroutine de Create met le statut à jour après ProvisionProject : // prendre le verrou attend qu'elle ait fini. svc.mu.Lock() svc.mu.Unlock() //nolint:staticcheck // barrière de synchronisation got, err := svc.Get(p.ID) if err != nil { t.Fatal(err) } return got } func TestCreate_MonthsBounds(t *testing.T) { svc, _, _ := newTestService(t) for _, months := range []int{-1, 0, 13, 100} { in := validInput() in.Months = months if _, err := svc.Create(in); !errors.Is(err, ErrInvalidMonths) { t.Errorf("months=%d : erreur %v, attendu ErrInvalidMonths", months, err) } } } func TestCreate_ExpiryIsCalendarMonths(t *testing.T) { for _, months := range []int{1, 6, 12} { svc, prov, _ := newTestService(t) in := validInput() in.Months = months p := createReady(t, svc, prov, in) want := t0.AddDate(0, months, 0) if !p.ExpiresAt.Equal(want) { t.Errorf("months=%d : ExpiresAt=%v, attendu %v", months, p.ExpiresAt, want) } if p.MonthsPurchased != months { t.Errorf("MonthsPurchased=%d, attendu %d", p.MonthsPurchased, months) } } } func TestCreate_ValidatesInput(t *testing.T) { svc, _, _ := newTestService(t) cases := map[string]struct { mutate func(*CreateInput) want error }{ "client vide": {func(i *CreateInput) { i.ClientName = " " }, ErrInvalidClient}, "admin invalide": {func(i *CreateInput) { i.AdminUsername = "a b" }, ErrInvalidAdmin}, "admin trop court": {func(i *CreateInput) { i.AdminUsername = "ab" }, ErrInvalidAdmin}, "mot de passe": {func(i *CreateInput) { i.AdminPassword = "court" }, ErrWeakAdminPass}, "nb admin trop": {func(i *CreateInput) { i.AdminNumber = 21 }, ErrInvalidAdminSize}, "nb admin négatif": {func(i *CreateInput) { i.AdminNumber = -1 }, ErrInvalidAdminSize}, } for name, c := range cases { in := validInput() c.mutate(&in) if _, err := svc.Create(in); !errors.Is(err, c.want) { t.Errorf("%s : erreur %v, attendu %v", name, err, c.want) } } } func TestCreate_PassesAdminSettingsToProvisioner(t *testing.T) { svc, prov, _ := newTestService(t) in := validInput() in.AdminNumber = 3 p := createReady(t, svc, prov, in) if len(prov.specs) != 1 { t.Fatalf("%d déploiements, attendu 1", len(prov.specs)) } spec := prov.specs[0] if spec.AdminNumber != 3 || spec.AdminUsername != "admin" || spec.AdminPassword != in.AdminPassword { t.Errorf("spec inattendue : %+v", spec) } if spec.Host != p.Namespace+".vitrine-omnex.club" || spec.URL != "https://"+spec.Host { t.Errorf("host/URL inattendus : %q %q", spec.Host, spec.URL) } if p.Status != StatusReady { t.Errorf("statut %s, attendu ready", p.Status) } } func TestCreate_DefaultAdminNumberIsOne(t *testing.T) { svc, prov, _ := newTestService(t) p := createReady(t, svc, prov, validInput()) if p.AdminNumber != 1 || prov.specs[0].AdminNumber != 1 { t.Errorf("AdminNumber=%d / spec=%d, attendu 1", p.AdminNumber, prov.specs[0].AdminNumber) } } func TestCreate_ProvisionFailureMarksFailed(t *testing.T) { svc, prov, _ := newTestService(t) prov.provErr = errors.New("helm en échec") p := createReady(t, svc, prov, validInput()) if p.Status != StatusFailed { t.Errorf("statut %s, attendu failed", p.Status) } if _, err := svc.Extend(p.ID, 1); !errors.Is(err, ErrNotExtendable) { t.Errorf("Extend sur un projet failed : %v, attendu ErrNotExtendable", err) } } func TestExtend_AddsMonthsFromCurrentExpiry(t *testing.T) { svc, prov, _ := newTestService(t) p := createReady(t, svc, prov, validInput()) // 3 mois got, err := svc.Extend(p.ID, 12) if err != nil { t.Fatal(err) } want := t0.AddDate(0, 3, 0).AddDate(0, 12, 0) if !got.ExpiresAt.Equal(want) { t.Errorf("ExpiresAt=%v, attendu %v (échéance courante + 12 mois)", got.ExpiresAt, want) } if got.MonthsPurchased != 15 { t.Errorf("MonthsPurchased=%d, attendu 15", got.MonthsPurchased) } } func TestExtend_MonthsBounds(t *testing.T) { svc, prov, _ := newTestService(t) p := createReady(t, svc, prov, validInput()) for _, months := range []int{0, 13, -2} { if _, err := svc.Extend(p.ID, months); !errors.Is(err, ErrInvalidMonths) { t.Errorf("months=%d : %v, attendu ErrInvalidMonths", months, err) } } got, _ := svc.Get(p.ID) if !got.ExpiresAt.Equal(p.ExpiresAt) { t.Error("une prolongation refusée a modifié l'échéance") } } func TestExtend_UnknownProject(t *testing.T) { svc, _, _ := newTestService(t) if _, err := svc.Extend("inconnu", 1); !errors.Is(err, ErrNotFound) { t.Errorf("erreur %v, attendu ErrNotFound", err) } } func TestExpiration_DeletesAtExpiry(t *testing.T) { svc, prov, now := newTestService(t) p := createReady(t, svc, prov, validInput()) // 3 mois // Avant l'échéance : rien ne bouge. *now = p.ExpiresAt.Add(-time.Hour) svc.expireOverdue() if len(prov.tornDown) != 0 { t.Fatal("suppression avant l'échéance") } // À l'échéance : supprimé, sans délai de grâce. *now = p.ExpiresAt.Add(time.Minute) svc.expireOverdue() got, _ := svc.Get(p.ID) if got.Status != StatusDeleted || len(prov.tornDown) != 1 || prov.tornDown[0] != p.Namespace { t.Errorf("statut %s, supprimés=%v", got.Status, prov.tornDown) } // Déjà supprimé : la boucle ne rappelle pas le cluster. svc.expireOverdue() if len(prov.tornDown) != 1 { t.Errorf("teardown répété : %v", prov.tornDown) } } func TestExtend_BeforeExpiryKeepsProject(t *testing.T) { svc, prov, now := newTestService(t) p := createReady(t, svc, prov, validInput()) *now = p.ExpiresAt.Add(-time.Hour) got, err := svc.Extend(p.ID, 1) if err != nil { t.Fatal(err) } if want := p.ExpiresAt.AddDate(0, 1, 0); !got.ExpiresAt.Equal(want) { t.Errorf("ExpiresAt=%v, attendu %v", got.ExpiresAt, want) } // L'ancienne échéance est passée : le projet renouvelé ne doit pas être supprimé. *now = p.ExpiresAt.Add(time.Minute) svc.expireOverdue() if len(prov.tornDown) != 0 { t.Errorf("suppression d'un projet renouvelé : %v", prov.tornDown) } } func TestExtend_DeletedProjectNotExtendable(t *testing.T) { svc, prov, now := newTestService(t) p := createReady(t, svc, prov, validInput()) *now = p.ExpiresAt.Add(time.Minute) svc.expireOverdue() if _, err := svc.Extend(p.ID, 1); !errors.Is(err, ErrNotExtendable) { t.Errorf("erreur %v, attendu ErrNotExtendable", err) } } func TestDelete_IsIdempotentAndImmediate(t *testing.T) { svc, prov, _ := newTestService(t) p := createReady(t, svc, prov, validInput()) got, err := svc.Delete(p.ID) if err != nil || got.Status != StatusDeleted { t.Fatalf("Delete: %v, statut %s", err, got.Status) } if _, err := svc.Delete(p.ID); err != nil { t.Fatalf("second Delete: %v", err) } if len(prov.tornDown) != 1 { t.Errorf("teardown appelé %d fois, attendu 1", len(prov.tornDown)) } if _, err := svc.Delete("inconnu"); !errors.Is(err, ErrNotFound) { t.Errorf("erreur %v, attendu ErrNotFound", err) } } func TestState_ReadyProjectQueriesItsOwnNamespace(t *testing.T) { svc, prov, _ := newTestService(t) prov.state = demos.ResourceState{API: demos.ComponentState{Phase: "Running", CPUMilli: 12}} p := createReady(t, svc, prov, validInput()) got, state, err := svc.State(context.Background(), p.ID) if err != nil { t.Fatal(err) } if got.Namespace != p.Namespace || state.API.Phase != "Running" || state.API.CPUMilli != 12 { t.Errorf("namespace=%q state=%+v", got.Namespace, state) } if len(prov.stateCalls) != 1 || prov.stateCalls[0] != p.Namespace { t.Errorf("namespace interrogé=%v, attendu [%s]", prov.stateCalls, p.Namespace) } } func TestState_NoClusterCallWithoutPods(t *testing.T) { svc, prov, _ := newTestService(t) p := createReady(t, svc, prov, validInput()) if _, err := svc.Delete(p.ID); err != nil { t.Fatal(err) } _, state, err := svc.State(context.Background(), p.ID) if err != nil || state != (demos.ResourceState{}) { t.Errorf("err=%v state=%+v, attendu un état vide", err, state) } if len(prov.stateCalls) != 0 { t.Errorf("cluster interrogé pour un projet supprimé : %v", prov.stateCalls) } } func TestState_UnknownProjectAndClusterError(t *testing.T) { svc, prov, _ := newTestService(t) if _, _, err := svc.State(context.Background(), "inconnu"); !errors.Is(err, ErrNotFound) { t.Errorf("erreur %v, attendu ErrNotFound", err) } p := createReady(t, svc, prov, validInput()) prov.stateErr = errors.New("api k8s indisponible") if _, _, err := svc.State(context.Background(), p.ID); err == nil { t.Error("erreur du cluster avalée") } } func TestSetDomain_SetsServedDomainAndKeepsDefaultHost(t *testing.T) { svc, prov, _ := newTestService(t) p := createReady(t, svc, prov, validInput()) got, err := svc.SetDomain(p.ID, " Boutique.Client.FR ") if err != nil { t.Fatal(err) } if got.CustomDomain != "boutique.client.fr" || got.URL != "https://boutique.client.fr" { t.Errorf("domaine=%q url=%q", got.CustomDomain, got.URL) } if got.Host != p.Host { t.Errorf("l'hôte par défaut a changé : %q", got.Host) } want := demos.ProjectDomainSpec{Namespace: p.Namespace, Host: p.Host, CustomDomain: "boutique.client.fr", URL: "https://boutique.client.fr"} if len(prov.domainSpecs) != 1 || prov.domainSpecs[0] != want { t.Errorf("spec envoyée au cluster : %+v", prov.domainSpecs) } stored, _ := svc.Get(p.ID) if stored.CustomDomain != "boutique.client.fr" { t.Errorf("non persisté : %+v", stored) } // Domaine vide : retour à l'adresse par défaut. got, err = svc.SetDomain(p.ID, "") if err != nil || got.CustomDomain != "" || got.URL != p.URL { t.Errorf("retrait : err=%v domaine=%q url=%q (attendu %q)", err, got.CustomDomain, got.URL, p.URL) } } func TestSetDomain_RejectsInvalidAndReservedDomains(t *testing.T) { svc, prov, _ := newTestService(t) p := createReady(t, svc, prov, validInput()) other := createReady(t, svc, prov, validInput()) invalid := []string{"pas un domaine", "http://x.fr", "x.fr/chemin", "localhost", "*.client.fr", "10.0.0.1", "-a.fr"} for _, d := range invalid { if _, err := svc.SetDomain(p.ID, d); !errors.Is(err, demos.ErrInvalidDomain) { t.Errorf("%q : erreur %v, attendu ErrInvalidDomain", d, err) } } reserved := []string{"vitrine-omnex.club", other.Host, "x.vitrine-omnex.club", "omnex.sbs", "demo-1.omnex.sbs"} for _, d := range reserved { if _, err := svc.SetDomain(p.ID, d); !errors.Is(err, ErrDomainReserved) { t.Errorf("%q : erreur %v, attendu ErrDomainReserved", d, err) } } // Un domaine qui finit par la même chaîne sans être un sous-domaine reste permis. if _, err := svc.SetDomain(p.ID, "monomnex.sbs"); err != nil { t.Errorf("monomnex.sbs refusé à tort : %v", err) } if len(prov.domainSpecs) != 1 { t.Errorf("le cluster ne doit être appelé que pour le domaine valide : %d appels", len(prov.domainSpecs)) } } func TestSetDomain_DomainAlreadyUsedByAnotherProject(t *testing.T) { svc, prov, _ := newTestService(t) a := createReady(t, svc, prov, validInput()) b := createReady(t, svc, prov, validInput()) if _, err := svc.SetDomain(a.ID, "boutique.client.fr"); err != nil { t.Fatal(err) } if _, err := svc.SetDomain(b.ID, "boutique.client.fr"); !errors.Is(err, ErrDomainTaken) { t.Errorf("erreur %v, attendu ErrDomainTaken", err) } // Le même projet peut le redéfinir (idempotent). if _, err := svc.SetDomain(a.ID, "boutique.client.fr"); err != nil { t.Errorf("redéfinition par le propriétaire : %v", err) } // Une fois le premier projet supprimé, le domaine est libre. if _, err := svc.Delete(a.ID); err != nil { t.Fatal(err) } if _, err := svc.SetDomain(b.ID, "boutique.client.fr"); err != nil { t.Errorf("domaine d'un projet supprimé toujours bloqué : %v", err) } } func TestSetDomain_StateAndClusterErrors(t *testing.T) { svc, prov, _ := newTestService(t) if _, err := svc.SetDomain("inconnu", "x.client.fr"); !errors.Is(err, ErrNotFound) { t.Errorf("erreur %v, attendu ErrNotFound", err) } p := createReady(t, svc, prov, validInput()) prov.domainErr = errors.New("helm indisponible") if _, err := svc.SetDomain(p.ID, "x.client.fr"); err == nil { t.Fatal("erreur du cluster avalée") } if got, _ := svc.Get(p.ID); got.CustomDomain != "" || got.URL != p.URL { t.Errorf("échec du cluster mais projet modifié : %+v", got) } prov.domainErr = nil if _, err := svc.Delete(p.ID); err != nil { t.Fatal(err) } if _, err := svc.SetDomain(p.ID, "x.client.fr"); !errors.Is(err, ErrNotReady) { t.Errorf("projet supprimé : erreur %v, attendu ErrNotReady", err) } } // --- Réconciliation base / cluster --- // setStatus force le statut d'un projet en base (simule un état hérité). func setStatus(t *testing.T, svc *Service, id string, st Status) Project { t.Helper() p, ok := svc.store.Get(id) if !ok { t.Fatalf("projet %s introuvable", id) } p.Status = st if _, err := svc.store.Update(p); err != nil { t.Fatal(err) } return p } func TestReconcile_PurgesDeletingAndDeletedWhenNamespaceIsGone(t *testing.T) { for _, st := range []Status{StatusDeleting, StatusDeleted} { svc, prov, _ := newTestService(t) p := createReady(t, svc, prov, validInput()) setStatus(t, svc, p.ID, st) prov.missing = map[string]bool{p.Namespace: true} svc.reconcile() if _, ok := svc.store.Get(p.ID); ok { t.Errorf("statut %s : ligne conservée alors que le namespace n'existe plus", st) } } } func TestReconcile_KeepsRowWhileNamespaceExists(t *testing.T) { svc, prov, _ := newTestService(t) p := createReady(t, svc, prov, validInput()) setStatus(t, svc, p.ID, StatusDeleting) // namespace encore là (Terminating compris) svc.reconcile() if got, ok := svc.store.Get(p.ID); !ok || got.Status != StatusDeleting { t.Errorf("ligne purgée alors que le namespace existe : ok=%v %+v", ok, got) } } func TestReconcile_ReadyWithoutNamespaceBecomesFailedNeverDeleted(t *testing.T) { svc, prov, _ := newTestService(t) p := createReady(t, svc, prov, validInput()) prov.missing = map[string]bool{p.Namespace: true} svc.reconcile() got, ok := svc.store.Get(p.ID) if !ok { t.Fatal("un projet en ligne ne doit jamais être purgé") } if got.Status != StatusFailed { t.Errorf("statut %s, attendu failed", got.Status) } } func TestReconcile_LeavesFailedProvisioningAndPendingAlone(t *testing.T) { for _, st := range []Status{StatusFailed, StatusProvisioning, StatusPending} { svc, prov, _ := newTestService(t) p := createReady(t, svc, prov, validInput()) setStatus(t, svc, p.ID, st) prov.missing = map[string]bool{p.Namespace: true} svc.reconcile() if got, ok := svc.store.Get(p.ID); !ok || got.Status != st { t.Errorf("statut %s : ligne modifiée ou purgée (%v %+v)", st, ok, got) } } } func TestReconcile_APIErrorWritesNothing(t *testing.T) { svc, prov, _ := newTestService(t) gone := createReady(t, svc, prov, validInput()) live := createReady(t, svc, prov, validInput()) setStatus(t, svc, gone.ID, StatusDeleted) prov.missing = map[string]bool{gone.Namespace: true} prov.existsErr = errors.New("api k8s injoignable") svc.reconcile() if _, ok := svc.store.Get(gone.ID); !ok { t.Error("ligne purgée alors que le cluster était injoignable") } if got, _ := svc.store.Get(live.ID); got.Status != StatusReady { t.Errorf("projet en ligne modifié sur une simple erreur d'API : %s", got.Status) } } func TestReconcile_OnlyTargetsMissingNamespaces(t *testing.T) { svc, prov, _ := newTestService(t) a := createReady(t, svc, prov, validInput()) b := createReady(t, svc, prov, validInput()) setStatus(t, svc, a.ID, StatusDeleted) setStatus(t, svc, b.ID, StatusDeleted) prov.missing = map[string]bool{a.Namespace: true} svc.reconcile() if _, ok := svc.store.Get(a.ID); ok { t.Error("la ligne au namespace absent aurait dû être purgée") } if _, ok := svc.store.Get(b.ID); !ok { t.Error("la ligne au namespace existant ne doit pas être purgée") } } func TestStoreDelete_IsIdempotent(t *testing.T) { st := NewMemStore() if _, err := st.Create(Project{ID: "p1"}); err != nil { t.Fatal(err) } if err := st.Delete("p1"); err != nil { t.Fatal(err) } if _, ok := st.Get("p1"); ok { t.Error("ligne toujours présente après Delete") } if err := st.Delete("p1"); err != nil { t.Errorf("second Delete : %v, attendu nil", err) } } func TestRunExpirationLoop_ReconcilesOnEachTick(t *testing.T) { svc, prov, _ := newTestService(t) p := createReady(t, svc, prov, validInput()) setStatus(t, svc, p.ID, StatusDeleting) prov.missing = map[string]bool{p.Namespace: true} ctx, cancel := context.WithCancel(context.Background()) done := make(chan struct{}) go func() { svc.RunExpirationLoop(ctx, 5*time.Millisecond) close(done) }() deadline := time.After(2 * time.Second) for { if _, ok := svc.store.Get(p.ID); !ok { break } select { case <-deadline: t.Fatal("la boucle n'a pas purgé la ligne : reconcile() n'est pas appelé") case <-time.After(5 * time.Millisecond): } } cancel() <-done } // --- Alerte d'incident --- // captureAlerts branche un Alert de test ; chaque message arrive sur le canal. func captureAlerts(svc *Service) chan string { ch := make(chan string, 8) svc.cfg.Alert = func(m string) { ch <- m } return ch } func waitAlert(t *testing.T, ch chan string) string { t.Helper() select { case m := <-ch: return m case <-time.After(2 * time.Second): t.Fatal("aucune alerte reçue") return "" } } func TestReconcile_ReadyWithoutNamespaceAlertsAdminsOnce(t *testing.T) { svc, prov, _ := newTestService(t) alerts := captureAlerts(svc) p := createReady(t, svc, prov, validInput()) prov.missing = map[string]bool{p.Namespace: true} svc.reconcile() msg := waitAlert(t, alerts) for _, want := range []string{p.Namespace, p.Host, "Boutique Dupont"} { if !strings.Contains(msg, want) { t.Errorf("l'alerte ne mentionne pas %q : %s", want, msg) } } // Le projet est passé en échec : les tours suivants ne renvoient rien. svc.reconcile() svc.reconcile() select { case m := <-alerts: t.Errorf("alerte répétée : %s", m) case <-time.After(100 * time.Millisecond): } } func TestReconcile_NoAlertForRoutinePurgesOrAPIErrors(t *testing.T) { svc, prov, _ := newTestService(t) alerts := captureAlerts(svc) gone := createReady(t, svc, prov, validInput()) setStatus(t, svc, gone.ID, StatusDeleting) prov.missing = map[string]bool{gone.Namespace: true} svc.reconcile() // purge normale live := createReady(t, svc, prov, validInput()) prov.missing = map[string]bool{live.Namespace: true} prov.existsErr = errors.New("api k8s injoignable") svc.reconcile() // cluster injoignable : aucun incident à déclarer select { case m := <-alerts: t.Errorf("alerte inutile : %s", m) case <-time.After(100 * time.Millisecond): } } func TestReconcile_WithoutAlertHookStillMarksFailed(t *testing.T) { svc, prov, _ := newTestService(t) // Config.Alert == nil p := createReady(t, svc, prov, validInput()) prov.missing = map[string]bool{p.Namespace: true} svc.reconcile() // ne doit pas paniquer if got, _ := svc.store.Get(p.ID); got.Status != StatusFailed { t.Errorf("statut %s, attendu failed", got.Status) } } func TestAlertText_NeutralisesMentionsAndLineBreaks(t *testing.T) { got := alertText("a@everyone\nb\tc") if strings.Contains(got, "@") || strings.ContainsAny(got, "\n\t") { t.Errorf("texte non neutralisé : %q", got) } }