Files
phishingclub/backend/service/recipientFieldValues_db_test.go
2026-12-01 21:25:01 +01:00

144 lines
6.5 KiB
Go

package service
import (
"errors"
"strings"
"testing"
"github.com/google/uuid"
"github.com/phishingclub/phishingclub/database"
"github.com/phishingclub/phishingclub/errs"
"github.com/phishingclub/phishingclub/model"
"github.com/phishingclub/phishingclub/repository"
"github.com/phishingclub/phishingclub/utils"
)
// TestRecipientFieldValues checks the field values of groups are merged by
// normalized key, counted once per recipient, sorted by count, capped and
// read only from groups the company may use
func TestRecipientFieldValues(t *testing.T) {
f := newLanguagePoolFixture(t)
if err := f.db.AutoMigrate(&database.Company{}); err != nil {
t.Fatalf("migrate: %v", err)
}
svc := &RecipientGroup{Common: f.svc.Common, RecipientGroupRepository: f.svc.RecipientGroupRepository}
static, ids := f.countryGroup("Denmark", " denmark ", "Germany", "Åland", "", "Denmark")
// a dynamic group of every German recipient, one of them also in the
// static group
dynamicID := uuid.New()
if err := f.db.Create(&database.RecipientGroup{
ID: &dynamicID, CreatedAt: &f.now, UpdatedAt: &f.now, Name: "dynamic", IsDynamic: true,
FilterField: "country", FilterValue: "Germany",
}).Error; err != nil {
t.Fatalf("insert dynamic group: %v", err)
}
other := f.group(nil)
f.addCountries(other, "Germany")
// a deleted recipient is left out
f.db.Model(&database.Recipient{}).Where("id = ?", ids[5]).Update("deleted_at", utils.NowRFC3339UTC())
got, err := svc.GetFieldValues(f.ctx, f.session, nil, model.LanguageRouteCountry, []*uuid.UUID{&static, &dynamicID})
if err != nil {
t.Fatalf("field values: %v", err)
}
if got.EmptyCount != 1 || got.Total != 3 || got.Truncated || got.UnlistedCount != 0 {
t.Fatalf("totals: %+v", got)
}
if got.Values[0].Key != "denmark" || got.Values[0].Count != 2 || len(got.Values[0].Values) != 2 {
t.Fatalf("first value: %+v", got.Values[0])
}
if got.Values[1].Key != "germany" || got.Values[1].Count != 2 {
t.Fatalf("Germany counts each recipient once: %+v", got.Values[1])
}
if got.Values[2].Key != "åland" || got.Values[2].Count != 1 {
t.Fatalf("NFD value not merged: %+v", got.Values[2])
}
if _, err := svc.GetFieldValues(f.ctx, f.session, nil, "email", []*uuid.UUID{&static}); !isValidationError(err) {
t.Fatalf("a field that is not a route field: want validation error, got %v", err)
}
// a group of a company is refused in the global view and in another
// company
companyID, otherCompany := uuid.New(), uuid.New()
for _, id := range []uuid.UUID{companyID, otherCompany} {
id := id
f.db.Create(&database.Company{ID: id, CreatedAt: &f.now, UpdatedAt: &f.now, Name: "c " + id.String()[:8], AssetsKey: id.String()[:8]})
}
f.db.Model(&database.RecipientGroup{}).Where("id = ?", other).Update("company_id", companyID)
if _, err := svc.GetFieldValues(f.ctx, f.session, nil, model.LanguageRouteCountry, []*uuid.UUID{&other}); !isValidationError(err) {
t.Fatalf("company group in the global view: want validation error, got %v", err)
}
if _, err := svc.GetFieldValues(f.ctx, f.session, &otherCompany, model.LanguageRouteCountry, []*uuid.UUID{&other}); !isValidationError(err) {
t.Fatalf("company group in another company: want validation error, got %v", err)
}
if got, err := svc.GetFieldValues(f.ctx, f.session, &companyID, model.LanguageRouteCountry, []*uuid.UUID{&other}); err != nil || got.Total != 1 {
t.Fatalf("company group in its company: %+v %v", got, err)
}
if _, err := svc.GetFieldValues(f.ctx, unauthorizedSession(t), nil, model.LanguageRouteCountry, []*uuid.UUID{&static}); !errors.Is(err, errs.ErrAuthorizationFailed) {
t.Fatalf("a company user: want authorization failure, got %v", err)
}
}
// TestFieldValuesRawCutMergesToFewValues checks the raw values are cut at
// MaxFieldValueRows also when they merge into fewer listed values than the
// cap: truncated stays set, the total is more than the listed values and the
// members of the values that were not read are counted as unlisted
func TestFieldValuesRawCutMergesToFewValues(t *testing.T) {
f := newLanguagePoolFixture(t)
svc := &RecipientGroup{Common: f.svc.Common, RecipientGroupRepository: f.svc.RecipientGroupRepository}
groupID := f.group(nil)
// every value is "x" with other spaces around it, so they all merge
values := []string{}
for i := 0; len(values) < repository.MaxFieldValueRows+5; i++ {
for j := 0; j <= i && len(values) < repository.MaxFieldValueRows+5; j++ {
values = append(values, strings.Repeat(" ", j)+"x"+strings.Repeat(" ", i-j))
}
}
recipients := make([]database.Recipient, 0, len(values))
members := make([]database.RecipientGroupRecipient, 0, len(values))
for _, v := range values {
rid := uuid.New()
email := rid.String() + "@cut.test"
recipients = append(recipients, database.Recipient{ID: &rid, CreatedAt: &f.now, UpdatedAt: &f.now, Email: &email, City: v})
members = append(members, database.RecipientGroupRecipient{RecipientID: &rid, RecipientGroupID: &groupID})
}
if err := f.db.CreateInBatches(recipients, 200).Error; err != nil {
t.Fatal(err)
}
if err := f.db.CreateInBatches(members, 200).Error; err != nil {
t.Fatal(err)
}
got, err := svc.GetFieldValues(f.ctx, f.session, nil, model.LanguageRouteCity, []*uuid.UUID{&groupID})
if err != nil {
t.Fatalf("field values: %v", err)
}
if len(got.Values) != 1 || got.Values[0].Key != "x" || got.Values[0].Count != repository.MaxFieldValueRows {
t.Fatalf("values: %+v", got.Values)
}
if !got.Truncated || got.Total <= len(got.Values) {
t.Fatalf("a cut must stay visible: truncated %v, total %d", got.Truncated, got.Total)
}
if got.UnlistedCount != 5 || got.EmptyCount != 0 {
t.Fatalf("unlisted %d and empty %d, want 5 and 0", got.UnlistedCount, got.EmptyCount)
}
}
// TestFieldValuesByLanguage checks the field values endpoint reads the
// language field: codes counted, no language counted as empty
func TestFieldValuesByLanguage(t *testing.T) {
f := newPoolFixture(t)
groupID := f.group(nil)
for _, l := range []*string{strPtr("da"), strPtr("da"), strPtr("de"), nil} {
f.languageRecipient(groupID, l)
}
svc := &RecipientGroup{Common: f.svc.Common, RecipientGroupRepository: &repository.RecipientGroup{DB: f.db}}
got, err := svc.GetFieldValues(f.ctx, f.session, nil, model.LanguageRouteLanguage, []*uuid.UUID{&groupID})
if err != nil {
t.Fatalf("field values: %v", err)
}
if len(got.Values) != 2 || got.Values[0].Key != "da" || got.Values[0].Count != 2 ||
got.Values[1].Key != "de" || got.Values[1].Count != 1 || got.EmptyCount != 1 {
t.Fatalf("values %+v empty %d", got.Values, got.EmptyCount)
}
}