Files
phishingclub/backend/repository/programResults_db_test.go
2026-12-01 21:25:01 +01:00

319 lines
11 KiB
Go

package repository
import (
"context"
"strings"
"sync"
"testing"
"time"
"github.com/google/uuid"
"github.com/phishingclub/phishingclub/database"
"github.com/phishingclub/phishingclub/model"
"github.com/phishingclub/phishingclub/testdb"
"github.com/phishingclub/phishingclub/utils"
"github.com/phishingclub/phishingclub/vo"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
// TestProgramSentRowsReadStoredTime checks the sent and event times read as
// text give the stored instant in both stored forms
func TestProgramSentRowsReadStoredTime(t *testing.T) {
db := newProgramTestDB(t)
ctx := context.Background()
repo := &Program{DB: db}
programID := createProgram(t, db, "p", nil)
campaign := ptrUUID()
createHiddenCampaign(t, db, campaign, programID)
at := time.Date(2026, 3, 4, 5, 6, 7, 891000000, time.UTC)
a := addCampaignRecipient(t, db, campaign, ptrUUID(), nil, true)
b := addCampaignRecipient(t, db, campaign, ptrUUID(), nil, true)
// one row in the form of the driver, one as RFC 3339 text
db.Model(&database.CampaignRecipient{}).Where("id = ?", a).Update("sent_at", at)
db.Model(&database.CampaignRecipient{}).Where("id = ?", b).Update("sent_at", at.Format(time.RFC3339Nano))
rows, err := repo.GetSentRows(ctx, programID, nil)
if err != nil {
t.Fatalf("sent rows: %v", err)
}
if len(rows) != 2 {
t.Fatalf("rows %d, want 2", len(rows))
}
for _, r := range rows {
if !r.SentAt.Equal(at) {
t.Fatalf("sent at %v, want %v", r.SentAt, at)
}
}
}
// planLogger keeps the last statement run
type planLogger struct {
logger.Interface
sql *string
}
func (l planLogger) Trace(_ context.Context, _ time.Time, fc func() (string, int64), _ error) {
*l.sql, _ = fc()
}
// TestCountSentRowsCoveringIndex checks the sent row count of a program reads
// the partial index. Its predicates are implied by the index, so SQLite does
// not test them and never seeks the table rows.
func TestCountSentRowsCoveringIndex(t *testing.T) {
testdb.SkipUnlessSQLite(t, "reads the sqlite query plan")
db := newProgramTestDB(t)
if err := (database.CampaignRecipient{}).Migrate(db); err != nil {
t.Fatalf("migrate: %v", err)
}
ctx := context.Background()
programID := createProgram(t, db, "p", nil)
campaign := ptrUUID()
createHiddenCampaign(t, db, campaign, programID)
addCampaignRecipient(t, db, campaign, ptrUUID(), nil, true)
addCampaignRecipient(t, db, campaign, nil, ptrUUID(), true)
addCampaignRecipient(t, db, campaign, ptrUUID(), nil, false)
var stmt string
traced := db.Session(&gorm.Session{Logger: planLogger{Interface: logger.Default.LogMode(logger.Silent), sql: &stmt}})
count, err := (&Program{DB: traced}).CountSentRows(ctx, programID)
if err != nil || count != 2 {
t.Fatalf("count %d %v, want 2", count, err)
}
var plan []struct {
ID, Parent, Notused int
Detail string
}
if err := db.Raw("EXPLAIN QUERY PLAN " + stmt).Scan(&plan).Error; err != nil {
t.Fatalf("plan: %v", err)
}
details := []string{}
for _, p := range plan {
details = append(details, p.Detail)
}
joined := strings.Join(details, " | ")
if !strings.Contains(joined, "campaign_recipients USING INDEX idx_campaign_recipients_campaign_sent_at") && !strings.Contains(joined, "campaign_recipients USING COVERING INDEX idx_campaign_recipients_campaign_sent_at") {
t.Fatalf("the count must read the partial index, plan: %s", joined)
}
}
// explainPlan returns the plan details of a statement joined in one line
func explainPlan(t *testing.T, db *gorm.DB, stmt string) string {
t.Helper()
testdb.SkipUnlessSQLite(t, "reads the sqlite query plan")
var plan []struct {
ID, Parent, Notused int
Detail string
}
if err := db.Raw("EXPLAIN QUERY PLAN " + stmt).Scan(&plan).Error; err != nil {
t.Fatalf("plan: %v", err)
}
details := []string{}
for _, p := range plan {
details = append(details, p.Detail)
}
return strings.Join(details, " | ")
}
// TestProgramResultReads checks the result reads stay inside one program, find
// the latest send by recipient or pseudonym and page the people table
func TestProgramResultReads(t *testing.T) {
db := newProgramTestDB(t)
if err := db.AutoMigrate(&database.Recipient{}); err != nil {
t.Fatalf("migrate recipients: %v", err)
}
ctx := context.Background()
repo := &Program{DB: db}
programID := createProgram(t, db, "p", nil)
otherID := createProgram(t, db, "other", nil)
c1, c2, other := ptrUUID(), ptrUUID(), ptrUUID()
createHiddenCampaign(t, db, c1, programID)
createHiddenCampaign(t, db, c2, programID)
createHiddenCampaign(t, db, other, otherID)
alice, bob := ptrUUID(), ptrUUID()
for i, r := range []struct {
id *uuid.UUID
email string
first string
}{{alice, "alice@example.com", "Alice"}, {bob, "bob@example.com", "Bob"}} {
email := r.email
row := &database.Recipient{ID: r.id, CreatedAt: ptrNow(), UpdatedAt: ptrNow(), Email: &email, FirstName: r.first}
if err := db.Create(row).Error; err != nil {
t.Fatalf("create recipient %d: %v", i, err)
}
due := time.Now().Add(time.Duration(i+1) * time.Hour)
e := &database.ProgramEnrollment{
ID: ptrUUID(), CreatedAt: ptrNow(), UpdatedAt: ptrNow(),
ProgramID: programID, RecipientID: r.id, Status: model.ProgramEnrollmentActive, NextDueAt: &due,
}
if err := db.Create(e).Error; err != nil {
t.Fatalf("create enrollment: %v", err)
}
}
pseudonym := ptrUUID()
first := addCampaignRecipient(t, db, c1, alice, nil, true)
second := addCampaignRecipient(t, db, c2, nil, pseudonym, true)
addCampaignRecipient(t, db, c1, bob, nil, false)
addCampaignRecipient(t, db, other, alice, nil, true)
old := time.Now().Add(-48 * time.Hour).UTC()
if err := db.Model(&database.CampaignRecipient{}).Where("id = ?", first).Update("sent_at", utils.RFC3339UTC(old)).Error; err != nil {
t.Fatalf("set sent_at: %v", err)
}
clickID := ptrUUID()
addEvent(t, db, c1, alice, nil, clickID)
addEvent(t, db, other, alice, nil, clickID)
sent, err := repo.GetSentRows(ctx, programID, nil)
if err != nil || len(sent) != 2 {
t.Fatalf("expected 2 sent rows of the program, got %d (%v)", len(sent), err)
}
sent, err = repo.GetSentRows(ctx, programID, []*uuid.UUID{alice})
if err != nil || len(sent) != 1 || sent[0].ID != *first {
t.Fatalf("expected alice's one sent row, got %v (%v)", sent, err)
}
events, err := repo.GetEventRows(ctx, programID, nil, []*uuid.UUID{clickID})
if err != nil || len(events) != 1 || events[0].CampaignID != *c1 {
t.Fatalf("expected one event of the program, got %v (%v)", events, err)
}
// latest send of the person matched by recipient id or pseudonym
latest, err := repo.GetLatestPhishingSend(ctx, programID, alice, pseudonym, nil)
if err != nil || latest.ID.MustGet() != *second {
t.Fatalf("expected the newest send, got %v", err)
}
before := time.Now().Add(-24 * time.Hour)
latest, err = repo.GetLatestPhishingSend(ctx, programID, alice, pseudonym, &before)
if err != nil || latest.ID.MustGet() != *first {
t.Fatalf("expected the send before the report time, got %v", err)
}
tooEarly := time.Now().Add(-72 * time.Hour)
if _, err := repo.GetLatestPhishingSend(ctx, programID, alice, nil, &tooEarly); err == nil {
t.Fatalf("expected no send before the first one")
}
// people page: search, sort and limit
rows, count, err := repo.GetEnrollmentPage(ctx, programID, &vo.QueryArgs{
OrderBy: ProgramEnrollmentSortColumns["email"], Desc: true, Limit: 1,
})
if err != nil || count != 2 || len(rows) != 1 || rows[0].Recipient == nil || *rows[0].Recipient.Email != "bob@example.com" {
t.Fatalf("expected bob first of 2, got %d rows count %d (%v)", len(rows), count, err)
}
rows, count, err = repo.GetEnrollmentPage(ctx, programID, &vo.QueryArgs{Search: "ali"})
if err != nil || count != 1 || len(rows) != 1 || *rows[0].RecipientID != *alice {
t.Fatalf("expected search to find alice, got %d (%v)", count, err)
}
// loop_count is a real column that is not sortable, so it stands in for a
// name outside the allowlist
if _, _, err := repo.GetEnrollmentPage(ctx, programID, &vo.QueryArgs{OrderBy: "loop_count"}); err == nil {
t.Fatalf("expected a column outside the allowlist to be rejected")
}
counts, err := repo.GetEnrollmentStatusCounts(ctx, programID)
if err != nil || len(counts) != 1 || counts[0].Count != 2 {
t.Fatalf("expected 2 active, got %v (%v)", counts, err)
}
enrollments, err := repo.GetEnrollmentsByRecipientID(ctx, alice)
if err != nil || len(enrollments) != 1 {
t.Fatalf("expected one enrollment for alice, got %d (%v)", len(enrollments), err)
}
}
// TestEventMarkLockTimeout checks a mark read that waits on an open event
// insert gives up after the lock timeout with the mark read before, that the
// reads which come meanwhile share one wait, and that the next read after the
// commit sees the event
func TestEventMarkLockTimeout(t *testing.T) {
testdb.SkipUnlessPostgres(t)
db := newProgramTestDB(t)
ctx := context.Background()
r := &Program{DB: db}
camp, eventID := ptrUUID(), ptrUUID()
addEvents(t, db, camp, eventID, 3)
before, err := r.LatestCampaignEventRowID(ctx)
if err != nil || before <= 0 {
t.Fatalf("first mark %d: %v", before, err)
}
tx := db.Begin()
committed := false
defer func() {
if !committed {
tx.Rollback()
}
}()
if err := tx.Create(&database.CampaignEvent{
ID: ptrUUID(), CreatedAt: ptrNow(), UpdatedAt: ptrNow(),
CampaignID: camp, RecipientID: ptrUUID(), EventID: eventID,
}).Error; err != nil {
t.Fatalf("open insert: %v", err)
}
const readers = 4
marks := make([]int64, readers)
errs := make([]error, readers)
var wg sync.WaitGroup
start := time.Now()
for i := 0; i < readers; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
marks[i], errs[i] = r.LatestCampaignEventRowID(ctx)
}(i)
}
waitForLockWaiters(t, db, 1)
time.Sleep(300 * time.Millisecond)
var waiting int
if err := db.Raw(`SELECT count(*) FROM pg_locks l JOIN pg_database d ON d.oid = l.database
WHERE d.datname = current_database() AND l.locktype = 'advisory' AND NOT l.granted`).Scan(&waiting).Error; err != nil {
t.Fatalf("advisory waiters: %v", err)
}
if waiting != 1 {
t.Fatalf("%d mark reads wait for the lock, want one shared read", waiting)
}
wg.Wait()
took := time.Since(start)
for i := 0; i < readers; i++ {
if errs[i] != nil {
t.Fatalf("read %d: %v", i, errs[i])
}
if marks[i] != before {
t.Fatalf("read %d gave %d, want the mark read before %d", i, marks[i], before)
}
}
if took > 6*time.Second {
t.Fatalf("the reads took %v, the lock timeout must end them", took)
}
// an event insert does not wait behind a read that gave up
if err := db.Create(&database.CampaignEvent{
ID: ptrUUID(), CreatedAt: ptrNow(), UpdatedAt: ptrNow(),
CampaignID: camp, RecipientID: ptrUUID(), EventID: eventID,
}).Error; err != nil {
t.Fatalf("insert after the timeout: %v", err)
}
if err := tx.Commit().Error; err != nil {
t.Fatalf("commit: %v", err)
}
committed = true
after, err := r.LatestCampaignEventRowID(ctx)
if err != nil {
t.Fatalf("mark after commit: %v", err)
}
var max int64
if err := db.Raw("SELECT MAX(seq) FROM campaign_events").Scan(&max).Error; err != nil {
t.Fatalf("max: %v", err)
}
if after != max {
t.Fatalf("mark after commit %d, want %d", after, max)
}
// a repository bound to a transaction may not read the mark
err = db.Transaction(func(tx *gorm.DB) error {
_, err := (&Program{DB: tx}).LatestCampaignEventRowID(ctx)
return err
})
if err == nil {
t.Fatal("a mark read inside a transaction must be refused")
}
}