package service import ( "errors" "testing" "time" "github.com/google/uuid" "github.com/phishingclub/phishingclub/cache" "github.com/phishingclub/phishingclub/data" "github.com/phishingclub/phishingclub/database" "github.com/phishingclub/phishingclub/errs" "github.com/phishingclub/phishingclub/model" "github.com/phishingclub/phishingclub/repository" "github.com/phishingclub/phishingclub/vo" ) // audienceProgram creates a program that has not started, scheduled when // startAt is set and a draft otherwise func (p *programTest) audienceProgram(companyID *uuid.UUID, startAt *time.Time) uuid.UUID { p.t.Helper() id := uuid.New() now := time.Now().UTC() p.create(&database.Program{ ID: &id, CreatedAt: &now, UpdatedAt: &now, Name: "audience " + id.String(), CompanyID: companyID, LoopMode: model.ProgramLoopLoop, OrderMode: model.ProgramOrderSequential, StartAt: startAt, }) return id } // audiencePerson stores a recipient of a company with a name and department func (p *programTest) audiencePerson(companyID *uuid.UUID, email, first, department string, scimDisabled bool) uuid.UUID { p.t.Helper() now := time.Now().UTC() id := uuid.New() r := &database.Recipient{ ID: &id, CreatedAt: &now, UpdatedAt: &now, Email: &email, FirstName: first, Department: department, CompanyID: companyID, } if scimDisabled { r.ScimSoftDeletedAt = &now } p.create(r) return id } // TestProgramAudienceNotStarted checks a draft or scheduled program lists the // members of its groups as not started people: static and dynamic groups, // SCIM disabled left out, each person once, the dynamic rule kept to the // group company, paged, searched and sorted, and nothing per person for an // anonymous program func TestProgramAudienceNotStarted(t *testing.T) { p := newProgramLifecycleTest(t) session := authorizedSession(t) now := time.Now().UTC() companyA, companyB := uuid.New(), uuid.New() staticID, dynamicID := uuid.New(), uuid.New() p.create(&database.RecipientGroup{ID: &staticID, CreatedAt: &now, UpdatedAt: &now, Name: "static", CompanyID: &companyA}) p.create(&database.RecipientGroup{ ID: &dynamicID, CreatedAt: &now, UpdatedAt: &now, Name: "dynamic", CompanyID: &companyA, IsDynamic: true, FilterField: "department", FilterValue: "sales", }) anna := p.audiencePerson(&companyA, "anna@example.com", "Anna", "", false) bert := p.audiencePerson(&companyA, "bert@example.com", "Bert", "sales", false) carl := p.audiencePerson(&companyA, "carl@example.com", "Carl", "sales", false) gone := p.audiencePerson(&companyA, "gone@example.com", "Gone", "", true) // SCIM disabled in the dynamic group, and a sales person of another company p.audiencePerson(&companyA, "gonesales@example.com", "Gonesales", "sales", true) p.audiencePerson(&companyB, "other@example.com", "Other", "sales", false) p.addToGroup(staticID, anna) p.addToGroup(staticID, bert) p.addToGroup(staticID, gone) programID := p.audienceProgram(&companyA, nil) p.assignGroup(programID, staticID) p.assignGroup(programID, dynamicID) view, err := p.svc.GetRecipientsView(p.ctx, session, &programID, &vo.QueryArgs{ OrderBy: repository.ProgramEnrollmentSortColumns["email"], }) if err != nil { t.Fatalf("audience: %v", err) } want := []uuid.UUID{anna, bert, carl} if view.Count != 3 || len(view.Rows) != 3 || view.Total != 0 { t.Fatalf("expected 3 people once each, got count %d rows %+v", view.Count, view.Rows) } for i, row := range view.Rows { if row.RecipientID != want[i].String() { t.Fatalf("row %d: expected %s, got %s", i, want[i], row.RecipientID) } if row.Status != ProgramAudienceNotStarted || row.Sends != 0 || row.LastTemplateName != nil || row.NextTemplateName != nil || row.NextDueAt != nil { t.Fatalf("expected a not started row, got %+v", row) } } if view.Rows[0].Name != "Anna" || view.Rows[0].Email != "anna@example.com" { t.Fatalf("expected the recipient name and email, got %+v", view.Rows[0]) } // paging, descending sort and search view, err = p.svc.GetRecipientsView(p.ctx, session, &programID, &vo.QueryArgs{ OrderBy: repository.ProgramEnrollmentSortColumns["name"], Desc: true, Limit: 2, }) if err != nil || view.Count != 3 || len(view.Rows) != 2 || !view.HasNextPage || view.Rows[0].Name != "Carl" { t.Fatalf("expected first page of 2 starting with Carl, got %+v (%v)", view, err) } view, err = p.svc.GetRecipientsView(p.ctx, session, &programID, &vo.QueryArgs{ OrderBy: repository.ProgramEnrollmentSortColumns["name"], Desc: true, Limit: 2, Offset: 2, }) if err != nil || len(view.Rows) != 1 || view.HasNextPage || view.Rows[0].Name != "Anna" { t.Fatalf("expected the last page with Anna, got %+v (%v)", view, err) } view, err = p.svc.GetRecipientsView(p.ctx, session, &programID, &vo.QueryArgs{Search: "ber"}) if err != nil || view.Count != 1 || len(view.Rows) != 1 || view.Rows[0].RecipientID != bert.String() { t.Fatalf("expected search to find bert, got %+v (%v)", view, err) } // a sort that does not apply to people not yet enrolled is left out view, err = p.svc.GetRecipientsView(p.ctx, session, &programID, &vo.QueryArgs{ OrderBy: repository.ProgramEnrollmentSortColumns["next_due_at"], }) if err != nil || view.Count != 3 { t.Fatalf("expected the status sort to be ignored, got %+v (%v)", view, err) } // a scheduled program lists the same people future := now.Add(48 * time.Hour) scheduledID := p.audienceProgram(&companyA, &future) p.assignGroup(scheduledID, dynamicID) view, err = p.svc.GetRecipientsView(p.ctx, session, &scheduledID, &vo.QueryArgs{}) if err != nil || view.Count != 2 || len(view.Rows) != 2 { t.Fatalf("expected the 2 sales people of company A, got %+v (%v)", view, err) } // an anonymous program gives no people p.setProgram(programID, map[string]any{"is_anonymous": true}) view, err = p.svc.GetRecipientsView(p.ctx, session, &programID, &vo.QueryArgs{}) if err != nil || !view.Anonymous || len(view.Rows) != 0 || view.Count != 0 { t.Fatalf("expected no people for an anonymous program, got %+v (%v)", view, err) } p.setProgram(programID, map[string]any{"is_anonymous": false}) // a started program lists its enrollments, not its groups started := now.Add(-time.Hour) p.setProgram(scheduledID, map[string]any{"start_at": started, "started_at": started}) view, err = p.svc.GetRecipientsView(p.ctx, session, &scheduledID, &vo.QueryArgs{}) if err != nil || view.Count != 0 || len(view.Rows) != 0 { t.Fatalf("expected a started program without enrollments to list nobody, got %+v (%v)", view, err) } if _, err := p.svc.GetRecipientsView(p.ctx, unauthorizedSession(t), &programID, &vo.QueryArgs{}); !errors.Is(err, errs.ErrAuthorizationFailed) { t.Fatalf("expected an unauthorized session refused, got %v", err) } } // randomProgram creates a started program in random order with n templates func (p *programTest) randomProgram(n int) (uuid.UUID, []uuid.UUID) { p.t.Helper() programID := p.program(model.ProgramLoopLoop) p.setProgram(programID, map[string]any{"order_mode": model.ProgramOrderShuffle}) steps := make([]uuid.UUID, 0, n) for i := 0; i < n; i++ { steps = append(steps, p.step(programID, i, true)) } return programID, steps } // sentSteps marks the given steps sent to a recipient in loop 0 func (p *programTest) sentSteps(programID, recipientID uuid.UUID, steps ...uuid.UUID) { p.t.Helper() base := time.Now().UTC().Add(-time.Hour).Truncate(time.Second) for i, st := range steps { at := base.Add(time.Duration(i) * time.Minute) p.linkTemplate(p.sentWithEvent(programID, st, recipientID, 0, at, "", at), st) } } // nextTemplateOf returns the next template name of a recipient row func (p *programTest) nextTemplateOf(programID, recipientID uuid.UUID) *string { p.t.Helper() view, err := p.svc.GetRecipientsView(p.ctx, authorizedSession(p.t), &programID, &vo.QueryArgs{Limit: 10}) if err != nil { p.t.Fatalf("recipients: %v", err) } for _, r := range view.Rows { if r.RecipientID == recipientID.String() { return r.NextTemplateName } } p.t.Fatalf("recipient %s not listed", recipientID) return nil } // TestRandomOrderOneLeftIsDecided checks that in random order the next // template is named when only one is left in the round, is left open while two // or more are, opens again when the round starts over and is always named in // a one template program func TestRandomOrderOneLeftIsDecided(t *testing.T) { t.Run("two left", func(t *testing.T) { p := newProgramServiceTest(t) programID, steps := p.randomProgram(3) anna := p.recipient("anna@example.com") p.enroll(programID, anna, 0) p.sentSteps(programID, anna, steps[0]) if n := p.nextTemplateOf(programID, anna); n != nil { t.Fatalf("two left is picked at send time, got %s", *n) } }) t.Run("one left", func(t *testing.T) { p := newProgramServiceTest(t) programID, steps := p.randomProgram(3) anna := p.recipient("anna@example.com") p.enroll(programID, anna, 0) p.sentSteps(programID, anna, steps[2], steps[0]) n := p.nextTemplateOf(programID, anna) if n == nil || *n != p.templateNameOf(steps[1]) { t.Fatalf("the one left is decided, got %v", n) } }) t.Run("start over", func(t *testing.T) { p := newProgramServiceTest(t) programID, steps := p.randomProgram(3) anna := p.recipient("anna@example.com") p.enroll(programID, anna, 0) p.sentSteps(programID, anna, steps...) if n := p.nextTemplateOf(programID, anna); n != nil { t.Fatalf("a round that starts over is picked at send time, got %s", *n) } }) t.Run("one template", func(t *testing.T) { p := newProgramServiceTest(t) programID, steps := p.randomProgram(1) anna := p.recipient("anna@example.com") bob := p.recipient("bob@example.com") p.enroll(programID, anna, 0) p.enroll(programID, bob, 0) p.sentSteps(programID, anna, steps[0]) want := p.templateNameOf(steps[0]) if n := p.nextTemplateOf(programID, bob); n == nil || *n != want { t.Fatalf("a one template program is decided, got %v", n) } if n := p.nextTemplateOf(programID, anna); n == nil || *n != want { t.Fatalf("a one template program is decided when it starts over, got %v", n) } }) } // eventIDFor returns the cached id of an event name, adding one when missing func eventIDFor(name string) uuid.UUID { if id := cache.EventIDByName[name]; id != nil { cache.EventNameByID[id.String()] = name return *id } id := uuid.New() cache.EventIDByName[name] = &id cache.EventNameByID[id.String()] = name return id } // sentWithEvent adds a send at sentAt to a new campaign of the step and, // when event is set, the event at eventAt as its notable event func (p *programTest) sentWithEvent(programID, stepID, recipientID uuid.UUID, loop int, sentAt time.Time, event string, eventAt time.Time) uuid.UUID { p.t.Helper() campaignID := p.stepCampaign(programID, stepID, loop) id := p.send(campaignID, recipientID, true) fields := map[string]any{"sent_at": sentAt} if event != "" { eventID := eventIDFor(event) fields["notable_event_id"] = eventID now := time.Now().UTC() rowID := uuid.New() rid := recipientID p.create(&database.CampaignEvent{ ID: &rowID, CreatedAt: &eventAt, UpdatedAt: &now, CampaignID: &campaignID, RecipientID: &rid, EventID: &eventID, }) } if err := p.db.Model(&database.CampaignRecipient{}).Where("id = ?", id).Updates(fields).Error; err != nil { p.t.Fatalf("update send: %v", err) } return campaignID } // linkTemplate sets the template a hidden campaign sends to the template of // its step, as a real step campaign has func (p *programTest) linkTemplate(campaignID, stepID uuid.UUID) { p.t.Helper() templateID := p.stepTemplate(stepID) if err := p.db.Model(&database.Campaign{}).Where("id = ?", campaignID).Update("campaign_template_id", templateID).Error; err != nil { p.t.Fatalf("link template: %v", err) } } // templateNameOf returns the stored name of the template of a step func (p *programTest) templateNameOf(stepID uuid.UUID) string { p.t.Helper() var row database.CampaignTemplate if err := p.db.Where("id = ?", p.stepTemplate(stepID)).First(&row).Error; err != nil { p.t.Fatalf("load template: %v", err) } return row.Name } // queue adds a send of a step that waits in the queue func (p *programTest) queue(programID, stepID, recipientID uuid.UUID, loop int, sendAt time.Time) uuid.UUID { p.t.Helper() campaignID := p.stepCampaign(programID, stepID, loop) p.linkTemplate(campaignID, stepID) id := p.send(campaignID, recipientID, false) if err := p.db.Model(&database.CampaignRecipient{}).Where("id = ?", id).Update("send_at", sendAt).Error; err != nil { p.t.Fatalf("queue: %v", err) } return campaignID } // TestGetRecipientProgramsTotals checks the program totals of a recipient // count their own outcomes and an anonymous program gives only its name and // status func TestGetRecipientProgramsTotals(t *testing.T) { p := newProgramServiceTest(t) session := authorizedSession(t) programID := p.program(model.ProgramLoopLoop) stepID := p.step(programID, 0, true) anna := p.recipient("anna@example.com") p.enroll(programID, anna, 0) base := time.Now().UTC().AddDate(0, 0, -30).Truncate(time.Second) for i := 0; i < 12; i++ { sentAt := base.AddDate(0, 0, i) event := data.EVENT_CAMPAIGN_RECIPIENT_MESSAGE_SENT eventAt := sentAt switch i { case 11: event = data.EVENT_CAMPAIGN_RECIPIENT_REPORTED eventAt = sentAt.Add(2 * time.Hour) case 10: event = data.EVENT_CAMPAIGN_RECIPIENT_PAGE_VISITED eventAt = sentAt.Add(time.Hour) } p.sentWithEvent(programID, stepID, anna, i, sentAt, event, eventAt) } programs, err := p.svc.GetRecipientPrograms(p.ctx, session, &anna, nil) if err != nil { t.Fatalf("programs: %v", err) } if len(programs.Rows) != 1 || programs.Rows[0].Totals == nil { t.Fatalf("expected one program with totals, got %+v", programs) } if tot := programs.Rows[0].Totals; tot.Sent != 12 || tot.Clicked != 1 || tot.Reported != 1 || tot.Submitted != 0 { t.Fatalf("unexpected totals %+v", tot) } if _, err := p.svc.GetRecipientPrograms(p.ctx, unauthorizedSession(t), &anna, nil); !errors.Is(err, errs.ErrAuthorizationFailed) { t.Fatalf("expected an unauthorized session refused, got %v", err) } p.setProgram(programID, map[string]any{"is_anonymous": true}) programs, err = p.svc.GetRecipientPrograms(p.ctx, session, &anna, nil) if err != nil { t.Fatalf("anonymous programs: %v", err) } if len(programs.Rows) != 1 || !programs.Rows[0].Anonymous || programs.Rows[0].Totals != nil || programs.Rows[0].NextDueAt != nil { t.Fatalf("expected only the name and status of an anonymous program, got %+v", programs.Rows[0]) } } // TestRecipientsViewLastAndNextTemplate checks the recipient rows name the // last sent template, the next template when it is known and leave it empty // when it is picked at send time func TestRecipientsViewLastAndNextTemplate(t *testing.T) { p := newProgramWriteTest(t) session := authorizedSession(t) programID := p.program(model.ProgramLoopLoop) first := p.step(programID, 0, true) second := p.step(programID, 1, true) third := p.step(programID, 2, true) anna := p.recipient("anna@example.com") bob := p.recipient("bob@example.com") p.enroll(programID, anna, 0) p.enroll(programID, bob, 0) sentAt := time.Now().UTC().Add(-time.Hour).Truncate(time.Second) p.linkTemplate(p.sentWithEvent(programID, first, anna, 0, sentAt, "", sentAt), first) p.linkTemplate(p.sentWithEvent(programID, first, bob, 0, sentAt, "", sentAt), first) // bob has the second template waiting in the queue queuedAt := time.Now().UTC().Add(time.Hour).Truncate(time.Second) p.queue(programID, second, bob, 0, queuedAt) rowsOf := func() map[string]ProgramEnrollmentRow { view, err := p.svc.GetRecipientsView(p.ctx, session, &programID, &vo.QueryArgs{Limit: 10}) if err != nil { t.Fatalf("recipients: %v", err) } out := map[string]ProgramEnrollmentRow{} for _, r := range view.Rows { out[r.Email] = r } return out } rows := rowsOf() a := rows["anna@example.com"] if a.LastTemplateName == nil || *a.LastTemplateName != p.templateNameOf(first) || a.LastSentAt == nil || !a.LastSentAt.Equal(sentAt) { t.Fatalf("expected the first template as the last one, got %+v", a) } if a.NextTemplateName == nil || *a.NextTemplateName != p.templateNameOf(second) { t.Fatalf("in the same order the next template is known, got %+v", a.NextTemplateName) } b := rows["bob@example.com"] if b.NextTemplateName == nil || *b.NextTemplateName != p.templateNameOf(second) || b.NextDueAt == nil || !b.NextDueAt.Equal(queuedAt) { t.Fatalf("a queued send names the next template and its time, got %+v", b) } p.setProgram(programID, map[string]any{"order_mode": model.ProgramOrderShuffle}) rows = rowsOf() if rows["anna@example.com"].NextTemplateName != nil { t.Fatalf("in random order the next template is picked at send time, got %v", *rows["anna@example.com"].NextTemplateName) } if n := rows["bob@example.com"].NextTemplateName; n == nil || *n != p.templateNameOf(second) { t.Fatalf("a queued send is known in random order too, got %v", n) } _ = third } // TestGetRecipientProgramsPage checks the programs of a recipient are paged // and sorted by the server, leave out programs of another company, and refuse // a sort outside the allowlist func TestGetRecipientProgramsPage(t *testing.T) { p := newProgramServiceTest(t) session := authorizedSession(t) anna := p.recipient("anna@example.com") company, other := uuid.New(), uuid.New() if err := p.db.Model(&database.Recipient{}).Where("id = ?", anna).Update("company_id", company).Error; err != nil { t.Fatalf("set recipient company: %v", err) } for _, def := range []struct { name string company *uuid.UUID }{{"bravo", &company}, {"alpha", nil}, {"charlie", &company}, {"other", &other}} { id := p.program(model.ProgramLoopLoop) p.setProgram(id, map[string]any{"name": def.name, "company_id": def.company}) p.enroll(id, anna, 0) } names := func(r *model.Result[ProgramRecipientActivity]) []string { out := []string{} for _, row := range r.Rows { out = append(out, row.Name) } return out } page, err := p.svc.GetRecipientPrograms(p.ctx, session, &anna, &vo.QueryArgs{Limit: 2}) if err != nil { t.Fatalf("first page: %v", err) } if got := names(page); !page.HasNextPage || len(got) != 2 || got[0] != "alpha" || got[1] != "bravo" { t.Fatalf("expected alpha, bravo and a next page, got %v next %v", got, page.HasNextPage) } page, err = p.svc.GetRecipientPrograms(p.ctx, session, &anna, &vo.QueryArgs{Offset: 2, Limit: 2}) if err != nil { t.Fatalf("second page: %v", err) } if got := names(page); page.HasNextPage || len(got) != 1 || got[0] != "charlie" { t.Fatalf("expected only charlie without a next page, got %v next %v", got, page.HasNextPage) } page, err = p.svc.GetRecipientPrograms(p.ctx, session, &anna, &vo.QueryArgs{OrderBy: "name", Desc: true, Limit: 1}) if err != nil { t.Fatalf("sorted page: %v", err) } if got := names(page); len(got) != 1 || got[0] != "charlie" { t.Fatalf("expected charlie first by name descending, got %v", got) } if _, err := p.svc.GetRecipientPrograms(p.ctx, session, &anna, &vo.QueryArgs{OrderBy: "next_due_at"}); err == nil { t.Fatalf("expected a sort outside the allowlist to be refused") } }