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

587 lines
19 KiB
Go

package service
import (
"fmt"
"math"
"math/rand"
"reflect"
"sort"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/phishingclub/phishingclub/data"
"github.com/phishingclub/phishingclub/repository"
)
// TestProgramFactsRereadAfterRecipientDelete checks a send read again after
// its recipient was deleted, now with a new pseudonym and no recipient id, is
// found by its row id and not counted twice, and that an event with the new
// pseudonym lands on it
func TestProgramFactsRereadAfterRecipientDelete(t *testing.T) {
campaignID, rowID, recipientID, pseudonym := uuid.New(), uuid.New(), uuid.New(), uuid.New()
st := newProgramFactsStore(uuid.New(), false)
st.addCampaign(repository.ProgramCampaignInfo{ID: campaignID})
sentAt := time.Now()
st.addRow(&repository.ProgramSendRow{ID: rowID, CampaignID: campaignID, RecipientID: &recipientID, SentAt: sentAt}, math.MinInt64)
st.addRow(&repository.ProgramSendRow{ID: rowID, CampaignID: campaignID, AnonymizedID: &pseudonym, SentAt: sentAt}, math.MinInt64)
if st.size() != 1 {
t.Fatalf("sends %d, want 1", st.size())
}
ids := programResultEventIDs()
visit := eventIDFor(data.EVENT_CAMPAIGN_RECIPIENT_PAGE_VISITED)
ids.visit = &visit
st.applyEvent(&repository.ProgramEventRow{CampaignID: campaignID, AnonymizedID: &pseudonym, EventID: visit, CreatedAt: sentAt}, ids)
if !st.sends[0].has(factClicked) || len(st.pending) != 0 {
t.Fatal("the event with the new pseudonym must land on the send")
}
// a row id older than the recent bound is forgotten
st.pruneRecent(unixNanos(sentAt.Add(time.Minute)))
if len(st.recent) != 0 {
t.Fatalf("recent %d, want 0", len(st.recent))
}
}
// seededProgramFacts builds a named program of n people over about two years
// with phishing and training sends and random outcomes
func seededProgramFacts(seed int64, n int, now time.Time) *programFacts {
rng := rand.New(rand.NewSource(seed))
facts := &programFacts{templateNames: map[string]string{}}
templates := []string{"", "t-deleted"}
for i := 0; i < 6; i++ {
key := uuid.NewString()
templates = append(templates, key)
facts.templateNames[key] = fmt.Sprintf("Template %d", i)
}
ps := people(n)
start := now.AddDate(-2, 0, 0)
span := int64(now.Add(5*24*time.Hour).Sub(start) / time.Second)
for _, p := range ps {
sends := 4 + rng.Intn(20)
for i := 0; i < sends; i++ {
sd := &programSend{
Person: p,
Campaign: uuid.New(),
Template: templates[rng.Intn(len(templates))],
SentAt: start.Add(time.Duration(rng.Int63n(span))*time.Second + time.Duration(rng.Intn(1e9))),
Training: rng.Intn(6) == 0,
}
after := func() *time.Time {
t := sd.SentAt.Add(time.Duration(rng.Int63n(int64(40 * 24 * time.Hour))))
return &t
}
if sd.Training {
if rng.Intn(2) == 0 {
sd.TrainingStartedAt = after()
if rng.Intn(2) == 0 {
sd.TrainingCompletedAt = after()
}
}
} else {
if rng.Intn(3) == 0 {
sd.ClickedAt = after()
}
if rng.Intn(6) == 0 {
sd.SubmittedAt = after()
}
if rng.Intn(5) == 0 {
sd.ReportedAt = after()
}
}
facts.sends = append(facts.sends, sd)
}
}
return facts
}
// sameResults reports the first difference between two results, the last
// send compared as an instant
func sameResults(t *testing.T, label string, want, got *ProgramResults) {
t.Helper()
w, g := *want, *got
if (w.LastSentAt == nil) != (g.LastSentAt == nil) || (w.LastSentAt != nil && !w.LastSentAt.Equal(*g.LastSentAt)) {
t.Fatalf("%s: last sent %v, want %v", label, g.LastSentAt, w.LastSentAt)
}
w.LastSentAt, g.LastSentAt = nil, nil
if !reflect.DeepEqual(w.Summary, g.Summary) {
t.Fatalf("%s: summary\n got %+v\nwant %+v", label, g.Summary, w.Summary)
}
if !reflect.DeepEqual(w.Months, g.Months) {
t.Fatalf("%s: months differ", label)
}
if !reflect.DeepEqual(w.Templates, g.Templates) {
for i := range w.Templates {
t.Logf("want %+v got %+v", w.Templates[i], g.Templates[i])
}
t.Fatalf("%s: templates differ", label)
}
if !reflect.DeepEqual(w, g) {
t.Fatalf("%s: results differ\n got %+v\nwant %+v", label, g, w)
}
}
// TestProgramResultsMatchReference checks the facts store gives a named
// program the same results and tiles as the computation it replaced, for the
// whole program, report periods and every time range
func TestProgramResultsMatchReference(t *testing.T) {
loc, err := time.LoadLocation("Europe/Copenhagen")
if err != nil {
t.Skip("no time zone data")
}
now := time.Date(2026, 3, 29, 14, 30, 0, 0, loc)
facts := seededProgramFacts(7, 80, now)
started := now.AddDate(-2, 0, 3)
closedAt := now.AddDate(0, 0, -2)
day := func(y int, m time.Month, d int) *time.Time {
t := time.Date(y, m, d, 0, 0, 0, 0, loc)
return &t
}
periods := []struct{ from, to *time.Time }{
{nil, nil},
{day(2025, 1, 1), day(2025, 7, 1)},
{day(2025, 3, 15), nil},
{nil, day(2025, 10, 31)},
{day(2026, 3, 1), day(2026, 5, 1)},
}
for _, closed := range []*time.Time{nil, &closedAt} {
for _, months := range []int{12, 3} {
for i, period := range periods {
in := programResultsInput{
loc: loc, now: now, from: period.from, to: period.to,
recipients: 80, enrollment: programEnrollmentCounts{total: 80, active: 70, completed: 6, exited: 4},
hasTraining: i%2 == 0, hasPhishing: i%3 == 0, repeatMonths: months, startedAt: &started, closedAt: closed,
}
label := fmt.Sprintf("period %d months %d closed %v", i, months, closed != nil)
want := refBuildProgramResults(facts, in)
got := buildProgramResults(facts, in)
sameResults(t, label, want, got)
if period.from != nil || period.to != nil {
continue
}
for _, key := range []string{ProgramTimeRange30Days, ProgramTimeRange90Days, ProgramTimeRange12Months, ProgramTimeRangeAll} {
tin := in
tin.hasTraining = want.Summary.HasTraining
tin.hasPhishing = want.Summary.HasPhishing
tp := programTilesPeriod{key: key, from: programTimeRangeFrom(key, now, loc)}
wantTiles := refBuildProgramTiles(facts, tin, tp, closed != nil, want.Summary)
gotTiles := buildProgramTiles(facts, tin, tp, closed != nil, got.Summary)
if !reflect.DeepEqual(wantTiles, gotTiles) {
t.Fatalf("%s tiles %s\n got %+v\nwant %+v", label, key, gotTiles, wantTiles)
}
}
}
}
}
}
// TestProgramFactsStoreKeepsFirstOutcome checks an event applied twice or out
// of order keeps the first time of an outcome
func TestProgramFactsStoreKeepsFirstOutcome(t *testing.T) {
var cur = programFactNone
setEarliest(&cur, 20)
setEarliest(&cur, 30)
setEarliest(&cur, 10)
setEarliest(&cur, 10)
if cur != 10 {
t.Fatalf("earliest %d, want 10", cur)
}
}
// TestSentRereadFrom checks the bound a refresh reads sends after is written
// in the form the mark is stored in
func TestSentRereadFrom(t *testing.T) {
cases := map[string]string{
"": "",
"2026-11-13T10:43:50.023172473Z": "2026-11-13T10:41:50Z",
"2026-11-13 10:43:50.5+00:00": "2026-11-13 10:41:50+00:00",
"2026-11-13 10:43:50+00:00": "2026-11-13 10:41:50+00:00",
"not a time": "not a time",
"2026-01-01T00:01:00Z": "2025-12-31T23:59:00Z",
"2026-11-13T10:43:50.023172473+02:00": "2026-11-13T08:41:50Z",
}
for in, want := range cases {
if got := sentRereadFrom(in); got != want {
t.Fatalf("sentRereadFrom(%q) = %q, want %q", in, got, want)
}
}
}
// TestAnonymousTemplateRowsHiddenLast checks a withheld template row of an
// anonymous program comes after every shown row, sorted by name and not by
// its size, while the shown rows and the rows of a named program keep the
// most sent first
func TestAnonymousTemplateRowsHiddenLast(t *testing.T) {
counts := []programRowSends{
{used: true, sent: 3},
{used: true, sent: 90},
{used: true, sent: 40},
{used: true, sent: 50},
{used: true, sent: 1},
}
names := []string{"d hidden", "a shown", "c shown", "b hidden", "e hidden"}
hidden := map[int]bool{0: true, 3: true, 4: true}
row := func(i int, c *programRowSends) *ProgramResultRow {
return &ProgramResultRow{Key: names[i], Name: names[i], Suppressed: hidden[i]}
}
order := func(rows []*ProgramResultRow) string {
out := []string{}
for _, r := range rows {
out = append(out, r.Name)
}
return strings.Join(out, ",")
}
anon := newProgramFactsStore(uuid.New(), true)
if got := order(anon.sortedTemplateRows(counts, row)); got != "a shown,c shown,b hidden,d hidden,e hidden" {
t.Fatalf("anonymous order: %s", got)
}
named := newProgramFactsStore(uuid.New(), false)
if got := order(named.sortedTemplateRows(counts, row)); got != "a shown,b hidden,c shown,d hidden,e hidden" {
t.Fatalf("named order: %s", got)
}
}
// offendedSince reports whether the person clicked or submitted data on the
// send at or after since, the repeat offender rule of the recipient pages
func (s *programSend) offendedSince(since time.Time) bool {
return (s.ClickedAt != nil && !s.ClickedAt.Before(since)) ||
(s.SubmittedAt != nil && !s.SubmittedAt.Before(since))
}
// programTally counts sends and the people behind them
type programTally struct {
sends int
people map[uuid.UUID]struct{}
}
func (t *programTally) add(person uuid.UUID) {
t.sends++
if t.people == nil {
t.people = map[uuid.UUID]struct{}{}
}
t.people[person] = struct{}{}
}
// persons returns how many people the tally holds
func (t *programTally) persons() int {
return len(t.people)
}
// resultCounts adds up sends and the people behind them before they become a
// result row
type resultCounts struct {
sent, clicked, submitted, reported programTally
trainingSent, trainingStarted, trainingCompleted programTally
}
func (c *resultCounts) add(s *programSend) {
if s.Training {
c.trainingSent.add(s.Person)
// a completed training counts as started
if s.TrainingStartedAt != nil || s.TrainingCompletedAt != nil {
c.trainingStarted.add(s.Person)
}
if s.TrainingCompletedAt != nil {
c.trainingCompleted.add(s.Person)
}
return
}
c.sent.add(s.Person)
if s.Clicked() {
c.clicked.add(s.Person)
}
if s.SubmittedAt != nil {
c.submitted.add(s.Person)
}
if s.ReportedAt != nil {
c.reported.add(s.Person)
}
}
// tooFew reports whether an anonymous program must withhold the whole group
func (c *resultCounts) tooFew(anonymous bool) bool {
return anonymous && c.sent.persons() < programMinGroup
}
// row turns the counts into a result row. An anonymous program shows the
// sends only, and withholds them too for a small group. A named program shows
// the phishing counts when phishing is set and the training counts when
// training is set.
func (c *resultCounts) row(key, name string, anonymous, phishing, training bool) *ProgramResultRow {
r := &ProgramResultRow{Key: key, Name: name, OutcomesHidden: anonymous}
if c.tooFew(anonymous) {
r.Suppressed = true
return r
}
if anonymous {
r.Sent = intPtr(c.sent.sends)
return r
}
if phishing {
r.Sent = intPtr(c.sent.sends)
r.Clicked = intPtr(c.clicked.sends)
r.Submitted = intPtr(c.submitted.sends)
r.Reported = intPtr(c.reported.sends)
}
if training {
r.TrainingSent = intPtr(c.trainingSent.sends)
r.TrainingStarted = intPtr(c.trainingStarted.sends)
r.TrainingCompleted = intPtr(c.trainingCompleted.sends)
}
return r
}
// inPeriod reports whether a send went out in the period from, inclusive, to
// to, exclusive. A nil bound is open.
func inPeriod(sd *programSend, from, to *time.Time) bool {
if from != nil && sd.SentAt.Before(*from) {
return false
}
if to != nil && !sd.SentAt.Before(*to) {
return false
}
return true
}
// refBuildProgramResults computes the results from the facts. Only sends in
// [from, to) count when a bound is set. Month names use loc. An anonymous
// program counts only settled sends and outcomes, see programSettleCutoff, and
// reads now as the start of the day in loc.
func refBuildProgramResults(facts *programFacts, in programResultsInput) *ProgramResults {
anonymous := facts.anonymous
loc, now := in.loc, in.now
if anonymous {
now = startOfDay(now, loc)
}
out := &ProgramResults{Anonymous: anonymous, Months: []*ProgramResultRow{}, Templates: []*ProgramResultRow{}}
sends := []*programSend{}
for _, sd := range facts.sends {
if inPeriod(sd, in.from, in.to) {
sends = append(sends, sd)
}
}
out.Summary = refProgramSummary(sends, in, now, anonymous)
months := map[string]*resultCounts{}
monthStarts := map[string]time.Time{}
templates := map[string]*resultCounts{}
for _, sd := range sends {
if out.LastSentAt == nil || sd.SentAt.After(*out.LastSentAt) {
t := sd.SentAt
out.LastSentAt = &t
}
if sd.Training && anonymous {
continue
}
local := sd.SentAt.In(loc)
month := local.Format("2006-01")
if months[month] == nil {
months[month] = &resultCounts{}
monthStarts[month] = time.Date(local.Year(), local.Month(), 1, 0, 0, 0, 0, loc)
}
months[month].add(sd)
if templates[sd.Template] == nil {
templates[sd.Template] = &resultCounts{}
}
templates[sd.Template].add(sd)
}
// the months the program or the period covers only in part
runFrom := in.startedAt
if in.from != nil && (runFrom == nil || in.from.After(*runFrom)) {
runFrom = in.from
}
runTo := now
if in.closedAt != nil && in.closedAt.Before(runTo) {
runTo = *in.closedAt
}
if in.to != nil && in.to.Before(runTo) {
runTo = *in.to
}
for key, c := range months {
r := c.row(key, monthStarts[key].Format("Jan 2006"), anonymous, out.Summary.HasPhishing, out.Summary.HasTraining)
start := monthStarts[key]
end := start.AddDate(0, 1, 0)
r.Partial = (runFrom != nil && runFrom.After(start)) || runTo.Before(end)
out.Months = append(out.Months, r)
}
sort.Slice(out.Months, func(i, j int) bool { return out.Months[i].Key < out.Months[j].Key })
type templateRow struct {
row *ProgramResultRow
sent int
}
trows := []templateRow{}
for key, c := range templates {
name, ok := facts.templateNames[key]
if !ok {
name = programDeletedTemplateName
}
r := c.row(key, name, anonymous, c.sent.sends > 0, out.Summary.HasTraining && c.trainingSent.sends > 0)
trows = append(trows, templateRow{r, c.sent.sends + c.trainingSent.sends})
}
sort.Slice(trows, func(i, j int) bool {
if trows[i].sent != trows[j].sent {
return trows[i].sent > trows[j].sent
}
return trows[i].row.Name < trows[j].row.Name
})
for _, t := range trows {
out.Templates = append(out.Templates, t.row)
}
// an anonymous program shows the day of the last send, not the time
if anonymous && out.LastSentAt != nil {
day := startOfDay(*out.LastSentAt, loc)
out.LastSentAt = &day
}
return out
}
// refProgramSummary counts the recipients of the sends, each once. Repeat
// offenders are counted back from the end of the period, or now. An anonymous
// program withholds every outcome when fewer than programMinGroup people were
// sent to, and any count withholdCount hides out of the people sent to.
func refProgramSummary(sends []*programSend, in programResultsInput, now time.Time, anonymous bool) *ProgramSummary {
months := in.repeatMonths
if months <= 0 {
months = programRepeatOffenderMonthsDefault
}
out := &ProgramSummary{
Recipients: in.recipients,
RepeatOffenderMonths: months,
HasTraining: in.hasTraining,
HasPhishing: in.hasPhishing,
}
end := now
if in.to != nil && in.to.Before(end) {
end = *in.to
}
since := end.AddDate(0, -months, 0)
var sent, clicked, submitted, reported, trainingSent, trainingStarted, trainingCompleted programTally
offences := map[uuid.UUID]int{}
for _, sd := range sends {
out.SentTotal++
out.HasSent = true
if sd.Training {
out.HasTraining = true
trainingSent.add(sd.Person)
// a completed training counts as started
if sd.TrainingStartedAt != nil || sd.TrainingCompletedAt != nil {
trainingStarted.add(sd.Person)
}
if sd.TrainingCompletedAt != nil {
trainingCompleted.add(sd.Person)
}
continue
}
out.HasPhishing = true
sent.add(sd.Person)
if sd.Clicked() {
clicked.add(sd.Person)
}
if sd.SubmittedAt != nil {
submitted.add(sd.Person)
}
if sd.ReportedAt != nil {
reported.add(sd.Person)
}
if sd.offendedSince(since) {
offences[sd.Person]++
}
}
offenders := 0
for _, n := range offences {
if n >= 2 {
offenders++
}
}
// count returns n, or nil when an anonymous program withholds it out of group
count := func(n, group int) *int {
if anonymous && (group < programMinGroup || withholdCount(group, n)) {
out.Suppressed = true
return nil
}
return intPtr(n)
}
out.Sent = intPtr(sent.persons())
out.ClickedLink = count(clicked.persons(), sent.persons())
out.SubmittedData = count(submitted.persons(), sent.persons())
out.Reported = count(reported.persons(), sent.persons())
out.RepeatOffenders = count(offenders, sent.persons())
// repeat offenders clicked or submitted, so the count would give away a
// hidden clicked or submitted count
if anonymous && (out.ClickedLink == nil || out.SubmittedData == nil) {
out.RepeatOffenders = nil
out.Suppressed = true
}
if out.HasTraining {
out.TrainingSent = intPtr(trainingSent.persons())
out.TrainingStarted = count(trainingStarted.persons(), trainingSent.persons())
out.TrainingCompleted = count(trainingCompleted.persons(), trainingSent.persons())
}
return out
}
// refBuildProgramTiles counts the tiles of a named program the way the
// program page did before the facts store
func refBuildProgramTiles(
facts *programFacts,
in programResultsInput,
period programTilesPeriod,
closed bool,
all *ProgramSummary,
) *ProgramTiles {
out := &ProgramTiles{
Range: period.key,
Recipients: in.enrollment.active,
Completed: in.enrollment.completed,
Removed: in.enrollment.exited,
HasTraining: in.hasTraining,
HasPhishing: in.hasPhishing,
}
if closed {
out.Recipients = in.enrollment.stopped
}
var sent, clicked, submitted, reported, trainingSent, trainingStarted, trainingCompleted programTally
for _, sd := range facts.sends {
if !inPeriod(sd, period.from, nil) {
continue
}
if sd.Training {
trainingSent.add(sd.Person)
// a completed training counts as started
if sd.TrainingStartedAt != nil || sd.TrainingCompletedAt != nil {
trainingStarted.add(sd.Person)
}
if sd.TrainingCompletedAt != nil {
trainingCompleted.add(sd.Person)
}
continue
}
sent.add(sd.Person)
if sd.Clicked() {
clicked.add(sd.Person)
}
if sd.SubmittedAt != nil {
submitted.add(sd.Person)
}
if sd.ReportedAt != nil {
reported.add(sd.Person)
}
}
out.Sent = intPtr(sent.sends)
out.ClickedLink = intPtr(clicked.sends)
out.SubmittedData = intPtr(submitted.sends)
out.Reported = intPtr(reported.sends)
if out.HasTraining {
out.TrainingSent = intPtr(trainingSent.sends)
out.TrainingStarted = intPtr(trainingStarted.sends)
out.TrainingCompleted = intPtr(trainingCompleted.sends)
}
if all != nil {
out.RepeatOffenders = all.RepeatOffenders
out.RepeatOffenderMonths = all.RepeatOffenderMonths
if all.RepeatOffenders == nil {
out.Suppressed = true
}
}
return out
}