mirror of
https://github.com/phishingclub/phishingclub.git
synced 2026-12-06 01:53:42 +01:00
418 lines
15 KiB
Go
418 lines
15 KiB
Go
package service
|
|
|
|
import (
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/phishingclub/phishingclub/data"
|
|
"github.com/phishingclub/phishingclub/database"
|
|
"github.com/phishingclub/phishingclub/testdb"
|
|
)
|
|
|
|
// coldResults computes the results of the fixture program with an empty
|
|
// cache, reading every send and event again
|
|
func (f *resultsFixture) coldResults(now time.Time) *ProgramResults {
|
|
f.t.Helper()
|
|
program := f.loadProgram(f.programID)
|
|
st, err := f.svc.loadProgramFactsStore(f.ctx, program, now)
|
|
if err != nil {
|
|
f.t.Fatalf("load facts: %v", err)
|
|
}
|
|
in, kinds, err := f.svc.programResultsInputs(f.ctx, program, now, nil, nil)
|
|
if err != nil {
|
|
f.t.Fatalf("inputs: %v", err)
|
|
}
|
|
in.hasTraining = kinds.training || st.hasTraining
|
|
in.hasPhishing = kinds.phishing || st.hasPhishing
|
|
return st.programResults(in, nil, program.IsClosed())
|
|
}
|
|
|
|
// keptFacts returns the kept facts of the fixture program
|
|
func (f *resultsFixture) keptFacts() *programFactsStore {
|
|
f.svc.resultsCache.mu.Lock()
|
|
defer f.svc.resultsCache.mu.Unlock()
|
|
return f.svc.resultsCache.facts[f.programID]
|
|
}
|
|
|
|
// TestProgramFactsRefreshMatchesFullRead checks facts brought up to date with
|
|
// new sends and events give the same results as reading everything again,
|
|
// and that a removed send is found once the facts are counted again
|
|
func TestProgramFactsRefreshMatchesFullRead(t *testing.T) {
|
|
f := newResultsFixture(newProgramServiceTest(t))
|
|
now := time.Now()
|
|
first := f.sentTo(now.Add(-48 * time.Hour))
|
|
second := f.sentTo(now.Add(-24 * time.Hour))
|
|
f.event(first, data.EVENT_CAMPAIGN_RECIPIENT_PAGE_VISITED)
|
|
f.results(now)
|
|
kept := f.keptFacts()
|
|
if kept == nil {
|
|
t.Fatal("the facts must be kept")
|
|
}
|
|
// new outcomes on old sends and a new send with its own outcomes
|
|
f.event(second, data.EVENT_CAMPAIGN_RECIPIENT_SUBMITTED_DATA)
|
|
f.event(first, data.EVENT_CAMPAIGN_RECIPIENT_REPORTED)
|
|
third := f.sentTo(now.Add(time.Second))
|
|
f.event(third, data.EVENT_CAMPAIGN_RECIPIENT_PAGE_VISITED)
|
|
at := now.Add(2 * time.Second)
|
|
warm := f.results(at)
|
|
if f.keptFacts() != kept {
|
|
t.Fatal("new sends and events must be added to the kept facts, not read again")
|
|
}
|
|
sameResults(t, "after refresh", f.coldResults(at), warm)
|
|
if warm.Summary.SentTotal != 3 || *warm.Summary.ClickedLink != 3 || *warm.Summary.SubmittedData != 1 || *warm.Summary.Reported != 1 {
|
|
t.Fatalf("refreshed summary: %+v", warm.Summary)
|
|
}
|
|
// a removed send is not seen by the marks, the count finds it
|
|
if err := f.db.Where("campaign_id = ? AND recipient_id = ?", f.campaignID, third).
|
|
Delete(&database.CampaignRecipient{}).Error; err != nil {
|
|
t.Fatalf("delete: %v", err)
|
|
}
|
|
later := now.Add(programResultsNamedMaxAge + 3*time.Second)
|
|
r := f.results(later)
|
|
if r.Summary.SentTotal != 2 {
|
|
t.Fatalf("after a delete sent total %d, want 2", r.Summary.SentTotal)
|
|
}
|
|
if f.keptFacts() == kept {
|
|
t.Fatal("the facts must be read again after a delete")
|
|
}
|
|
sameResults(t, "after delete", f.coldResults(later), r)
|
|
}
|
|
|
|
// TestProgramFactsInvalidateDropsFacts checks a full invalidation of the
|
|
// cache drops the kept facts of the program
|
|
func TestProgramFactsInvalidateDropsFacts(t *testing.T) {
|
|
f := newResultsFixture(newProgramServiceTest(t))
|
|
now := time.Now()
|
|
f.sentTo(now.Add(-time.Hour))
|
|
f.results(now)
|
|
if f.keptFacts() == nil {
|
|
t.Fatal("the facts must be kept")
|
|
}
|
|
f.svc.resultsCache.invalidate(f.programID)
|
|
if f.keptFacts() != nil {
|
|
t.Fatal("an invalidation must drop the facts")
|
|
}
|
|
}
|
|
|
|
// TestProgramFactsFindEventOnReusedRowID proves an event stored with a row id
|
|
// given out again is found. The newest campaign event belongs to another
|
|
// campaign; once it is deleted SQLite gives its row id to the next event, a
|
|
// click on the program at or below the mark the kept facts read up to. The
|
|
// mark can not see it, the recheck counts the events up to the mark and
|
|
// reads the facts again. postgres never gives a seq out again, there the
|
|
// click is above the mark and the refresh reads it.
|
|
func TestProgramFactsFindEventOnReusedRowID(t *testing.T) {
|
|
f := newResultsFixture(newProgramServiceTest(t))
|
|
maxRowID := "SELECT MAX(rowid) FROM campaign_events"
|
|
if testdb.IsPostgres() {
|
|
maxRowID = "SELECT MAX(seq) FROM campaign_events"
|
|
}
|
|
now := time.Now()
|
|
rid := f.sentTo(now.Add(-time.Hour))
|
|
f.sentTo(now.Add(-time.Hour))
|
|
visit := eventIDFor(data.EVENT_CAMPAIGN_RECIPIENT_PAGE_VISITED)
|
|
other, otherEvent, created := uuid.New(), uuid.New(), now.UTC()
|
|
f.create(&database.CampaignEvent{
|
|
ID: &otherEvent, CreatedAt: &created, UpdatedAt: &created,
|
|
CampaignID: &other, EventID: &visit,
|
|
})
|
|
var topRowID int64
|
|
if err := f.db.Raw(maxRowID).Scan(&topRowID).Error; err != nil {
|
|
t.Fatalf("max rowid: %v", err)
|
|
}
|
|
if r := f.results(now); r.Summary.ClickedLink == nil || *r.Summary.ClickedLink != 0 {
|
|
t.Fatalf("no click yet: %+v", r.Summary)
|
|
}
|
|
kept := f.keptFacts()
|
|
if kept == nil || kept.eventMark != topRowID {
|
|
t.Fatalf("the facts must be kept up to row id %d", topRowID)
|
|
}
|
|
if err := f.db.Where("id = ?", otherEvent).Delete(&database.CampaignEvent{}).Error; err != nil {
|
|
t.Fatalf("delete: %v", err)
|
|
}
|
|
f.event(rid, data.EVENT_CAMPAIGN_RECIPIENT_PAGE_VISITED)
|
|
var clickRowID int64
|
|
if err := f.db.Raw(maxRowID).Scan(&clickRowID).Error; err != nil {
|
|
t.Fatalf("max rowid: %v", err)
|
|
}
|
|
if testdb.IsPostgres() {
|
|
if clickRowID <= topRowID {
|
|
t.Fatalf("postgres must not give a seq out again: %d <= %d", clickRowID, topRowID)
|
|
}
|
|
} else if clickRowID > topRowID {
|
|
t.Fatalf("the click must reuse a row id: %d > %d", clickRowID, topRowID)
|
|
}
|
|
// the recheck runs once the facts are older than the named max age
|
|
later := now.Add(programResultsNamedMaxAge + 3*time.Second)
|
|
r := f.results(later)
|
|
if r.Summary.ClickedLink == nil || *r.Summary.ClickedLink != 1 {
|
|
t.Fatalf("the click on a reused row id must be counted: %+v", r.Summary)
|
|
}
|
|
sameResults(t, "after a reused row id", f.coldResults(later), r)
|
|
// facts that match the database are kept by the recheck
|
|
again := f.keptFacts()
|
|
f.results(later.Add(programResultsNamedMaxAge + 3*time.Second))
|
|
if f.keptFacts() != again {
|
|
t.Fatal("facts that match the database must be kept")
|
|
}
|
|
}
|
|
|
|
// TestProgramFactsInvalidateKeepsFacts checks a change to the program keeps
|
|
// the facts when the sends still match, and reads them again at once when a
|
|
// send was removed, without waiting for the count interval
|
|
func TestProgramFactsInvalidateKeepsFacts(t *testing.T) {
|
|
f := newResultsFixture(newProgramServiceTest(t))
|
|
now := time.Now()
|
|
f.sentTo(now.Add(-2 * time.Hour))
|
|
gone := f.sentTo(now.Add(-time.Hour))
|
|
f.results(now)
|
|
kept := f.keptFacts()
|
|
if kept == nil {
|
|
t.Fatal("the facts must be kept")
|
|
}
|
|
f.svc.invalidateResults(&f.programID)
|
|
if f.keptFacts() != kept {
|
|
t.Fatal("an invalidation must keep the facts")
|
|
}
|
|
if got := f.results(now.Add(time.Second)).Summary.SentTotal; got != 2 {
|
|
t.Fatalf("sent total %d, want 2", got)
|
|
}
|
|
if f.keptFacts() != kept {
|
|
t.Fatal("facts that still match must not be read again")
|
|
}
|
|
if err := f.db.Where("campaign_id = ? AND recipient_id = ?", f.campaignID, gone).
|
|
Delete(&database.CampaignRecipient{}).Error; err != nil {
|
|
t.Fatalf("delete: %v", err)
|
|
}
|
|
f.svc.invalidateResults(&f.programID)
|
|
if got := f.results(now.Add(2 * time.Second)).Summary.SentTotal; got != 1 {
|
|
t.Fatalf("after a delete and an invalidation sent total %d, want 1", got)
|
|
}
|
|
if f.keptFacts() == kept {
|
|
t.Fatal("facts that no longer match must be read again")
|
|
}
|
|
}
|
|
|
|
// TestProgramFactsPendingEvent checks an event read before its send is known
|
|
// is kept and lands on the send once a refresh reads it
|
|
func TestProgramFactsPendingEvent(t *testing.T) {
|
|
f := newResultsFixture(newProgramServiceTest(t))
|
|
now := time.Now()
|
|
f.sentTo(now.Add(-time.Hour))
|
|
f.results(now)
|
|
// a send whose sent time is stored after its event was read
|
|
late := f.recipient(uuid.NewString() + "@example.com")
|
|
sendID := f.send(f.campaignID, late, false)
|
|
f.event(late, data.EVENT_CAMPAIGN_RECIPIENT_PAGE_VISITED)
|
|
r := f.results(now.Add(time.Second))
|
|
if r.Summary.SentTotal != 1 || len(f.keptFacts().pending) != 1 {
|
|
t.Fatalf("sent total %d pending %d, want 1 and 1", r.Summary.SentTotal, len(f.keptFacts().pending))
|
|
}
|
|
if err := f.db.Model(&database.CampaignRecipient{}).Where("id = ?", sendID).
|
|
Update("sent_at", now.Add(time.Minute).UTC()).Error; err != nil {
|
|
t.Fatalf("set sent_at: %v", err)
|
|
}
|
|
r = f.results(now.Add(2 * time.Second))
|
|
if r.Summary.SentTotal != 2 || r.Summary.ClickedLink == nil || *r.Summary.ClickedLink != 1 {
|
|
t.Fatalf("after the send: sent %d clicked %v", r.Summary.SentTotal, r.Summary.ClickedLink)
|
|
}
|
|
if len(f.keptFacts().pending) != 0 {
|
|
t.Fatal("the applied event must leave pending")
|
|
}
|
|
sameResults(t, "pending", f.coldResults(now.Add(2*time.Second)), r)
|
|
}
|
|
|
|
// TestProgramFactsNewTemplateNamed checks a send on a new campaign with a new
|
|
// template is named in the same refresh that adds it
|
|
func TestProgramFactsNewTemplateNamed(t *testing.T) {
|
|
f := newResultsFixture(newProgramServiceTest(t))
|
|
now := time.Now()
|
|
f.sentTo(now.Add(-time.Hour))
|
|
f.results(now)
|
|
stepID := f.step(f.programID, 1, true)
|
|
campaignID := f.stepCampaign(f.programID, stepID, 0)
|
|
f.linkTemplate(campaignID, stepID)
|
|
rid := f.recipient(uuid.NewString() + "@example.com")
|
|
id := f.send(campaignID, rid, true)
|
|
if err := f.db.Model(&database.CampaignRecipient{}).Where("id = ?", id).Update("sent_at", now.Add(time.Minute).UTC()).Error; err != nil {
|
|
t.Fatalf("set sent_at: %v", err)
|
|
}
|
|
r := f.results(now.Add(time.Second))
|
|
want := f.templateNameOf(stepID)
|
|
found := false
|
|
key := f.stepTemplate(stepID).String()
|
|
for _, row := range r.Templates {
|
|
if row.Key == key {
|
|
found = row.Name == want
|
|
}
|
|
}
|
|
if !found {
|
|
t.Fatalf("the new template must be named %q when it is added", want)
|
|
}
|
|
}
|
|
|
|
// TestProgramFactsLateCommitCountedOnce proves the facts refresh on postgres
|
|
// never skips an event whose transaction commits after one with a higher
|
|
// seq. Transaction A adds a click and stays open, so it holds the lower seq;
|
|
// transaction B adds a click with a higher seq and commits. A refresh then
|
|
// reads the mark: it waits for A, so the mark never passes the open seq. Once
|
|
// A commits both clicks are counted, exactly once, also by later refreshes
|
|
// and the recheck. sqlite has one writer, an open insert there blocks every
|
|
// other insert, so the case does not exist.
|
|
func TestProgramFactsLateCommitCountedOnce(t *testing.T) {
|
|
testdb.SkipUnlessPostgres(t)
|
|
f := newResultsFixture(newProgramServiceTest(t))
|
|
now := time.Now()
|
|
first := f.sentTo(now.Add(-time.Hour))
|
|
second := f.sentTo(now.Add(-time.Hour))
|
|
if r := f.results(now); r.Summary.ClickedLink == nil || *r.Summary.ClickedLink != 0 {
|
|
t.Fatalf("no click yet: %+v", r.Summary)
|
|
}
|
|
if f.keptFacts() == nil {
|
|
t.Fatal("the facts must be kept")
|
|
}
|
|
visit := eventIDFor(data.EVENT_CAMPAIGN_RECIPIENT_PAGE_VISITED)
|
|
|
|
txA := f.db.Begin()
|
|
committed := false
|
|
defer func() {
|
|
if !committed {
|
|
txA.Rollback()
|
|
}
|
|
}()
|
|
idA, created := uuid.New(), time.Now().UTC()
|
|
if err := txA.Create(&database.CampaignEvent{
|
|
ID: &idA, CreatedAt: &created, UpdatedAt: &created,
|
|
CampaignID: &f.campaignID, RecipientID: &first, EventID: &visit,
|
|
}).Error; err != nil {
|
|
t.Fatalf("insert A: %v", err)
|
|
}
|
|
var seqA int64
|
|
if err := txA.Raw("SELECT seq FROM campaign_events WHERE id = ?", idA).Scan(&seqA).Error; err != nil {
|
|
t.Fatalf("seq A: %v", err)
|
|
}
|
|
f.event(second, data.EVENT_CAMPAIGN_RECIPIENT_PAGE_VISITED)
|
|
var seqB int64
|
|
if err := f.db.Raw("SELECT MAX(seq) FROM campaign_events").Scan(&seqB).Error; err != nil {
|
|
t.Fatalf("seq B: %v", err)
|
|
}
|
|
if seqB <= seqA {
|
|
t.Fatalf("B must hold the higher seq: A %d B %d", seqA, seqB)
|
|
}
|
|
|
|
// the refresh sees B and reads the mark, which waits for A
|
|
type outcome struct {
|
|
r *ProgramResults
|
|
err error
|
|
}
|
|
done := make(chan outcome, 1)
|
|
go func() {
|
|
r, err := f.svc.programResults(f.ctx, nil, f.loadProgram(f.programID), now.Add(time.Second), nil, nil)
|
|
done <- outcome{r, err}
|
|
}()
|
|
select {
|
|
case o := <-done:
|
|
t.Fatalf("the refresh must wait for the open insert, it returned %+v %v", o.r, o.err)
|
|
case <-time.After(500 * time.Millisecond):
|
|
}
|
|
if err := txA.Commit().Error; err != nil {
|
|
t.Fatalf("commit A: %v", err)
|
|
}
|
|
committed = true
|
|
var o outcome
|
|
select {
|
|
case o = <-done:
|
|
case <-time.After(20 * time.Second):
|
|
t.Fatal("the refresh did not end after A committed")
|
|
}
|
|
if o.err != nil {
|
|
t.Fatalf("refresh: %v", o.err)
|
|
}
|
|
if o.r.Summary.ClickedLink == nil || *o.r.Summary.ClickedLink != 2 {
|
|
t.Fatalf("both clicks must be counted: %+v", o.r.Summary)
|
|
}
|
|
|
|
// a refresh with nothing new and the recheck count each click once
|
|
r := f.results(now.Add(2 * time.Second))
|
|
if r.Summary.ClickedLink == nil || *r.Summary.ClickedLink != 2 {
|
|
t.Fatalf("second refresh: %+v", r.Summary)
|
|
}
|
|
kept := f.keptFacts()
|
|
if kept == nil || kept.eventMark < seqB || kept.eventsUpToMark != 2 {
|
|
t.Fatalf("facts must be kept up to seq %d with 2 events", seqB)
|
|
}
|
|
later := now.Add(programResultsNamedMaxAge + 3*time.Second)
|
|
r = f.results(later)
|
|
if r.Summary.ClickedLink == nil || *r.Summary.ClickedLink != 2 {
|
|
t.Fatalf("after the recheck: %+v", r.Summary)
|
|
}
|
|
if f.keptFacts() != kept {
|
|
t.Fatal("facts that match the database must be kept by the recheck")
|
|
}
|
|
sameResults(t, "after a late commit", f.coldResults(later), r)
|
|
}
|
|
|
|
// TestProgramFactsMarkTimeoutLosesNothing checks a refresh whose mark read
|
|
// gives up on an insert held open past the lock timeout returns without
|
|
// waiting for it, and that once the insert commits a refresh counts both
|
|
// clicks exactly once, as the cold read does
|
|
func TestProgramFactsMarkTimeoutLosesNothing(t *testing.T) {
|
|
testdb.SkipUnlessPostgres(t)
|
|
f := newResultsFixture(newProgramServiceTest(t))
|
|
now := time.Now()
|
|
first := f.sentTo(now.Add(-time.Hour))
|
|
second := f.sentTo(now.Add(-time.Hour))
|
|
if r := f.results(now); r.Summary.ClickedLink == nil || *r.Summary.ClickedLink != 0 {
|
|
t.Fatalf("no click yet: %+v", r.Summary)
|
|
}
|
|
visit := eventIDFor(data.EVENT_CAMPAIGN_RECIPIENT_PAGE_VISITED)
|
|
|
|
txA := f.db.Begin()
|
|
committed := false
|
|
defer func() {
|
|
if !committed {
|
|
txA.Rollback()
|
|
}
|
|
}()
|
|
idA, created := uuid.New(), time.Now().UTC()
|
|
if err := txA.Create(&database.CampaignEvent{
|
|
ID: &idA, CreatedAt: &created, UpdatedAt: &created,
|
|
CampaignID: &f.campaignID, RecipientID: &first, EventID: &visit,
|
|
}).Error; err != nil {
|
|
t.Fatalf("insert A: %v", err)
|
|
}
|
|
f.event(second, data.EVENT_CAMPAIGN_RECIPIENT_PAGE_VISITED)
|
|
|
|
start := time.Now()
|
|
r, err := f.svc.programResults(f.ctx, nil, f.loadProgram(f.programID), now.Add(time.Second), nil, nil)
|
|
if err != nil {
|
|
t.Fatalf("refresh while A is open: %v", err)
|
|
}
|
|
if took := time.Since(start); took > 10*time.Second {
|
|
t.Fatalf("the refresh took %v, the lock timeout must end its wait", took)
|
|
}
|
|
if r.Summary.ClickedLink == nil || *r.Summary.ClickedLink > 1 {
|
|
t.Fatalf("only the committed click can count yet: %+v", r.Summary)
|
|
}
|
|
|
|
if err := txA.Commit().Error; err != nil {
|
|
t.Fatalf("commit A: %v", err)
|
|
}
|
|
committed = true
|
|
// the refresh waited the lock timeout, which makes it a slow compute
|
|
// whose result is kept for programResultsNamedMinAge
|
|
after := now.Add(programResultsNamedMinAge + 2*time.Second)
|
|
r = f.results(after)
|
|
if r.Summary.ClickedLink == nil || *r.Summary.ClickedLink != 2 {
|
|
t.Fatalf("both clicks must be counted after A commits: %+v", r.Summary)
|
|
}
|
|
r = f.results(after.Add(time.Second))
|
|
if r.Summary.ClickedLink == nil || *r.Summary.ClickedLink != 2 {
|
|
t.Fatalf("a further refresh: %+v", r.Summary)
|
|
}
|
|
later := after.Add(programResultsNamedMaxAge + 2*time.Second)
|
|
r = f.results(later)
|
|
sameResults(t, "after a mark timeout", f.coldResults(later), r)
|
|
}
|