mirror of
https://github.com/phishingclub/phishingclub.git
synced 2026-12-06 10:03:46 +01:00
788 lines
29 KiB
Go
788 lines
29 KiB
Go
package repository
|
||
|
||
import (
|
||
"context"
|
||
"maps"
|
||
"path/filepath"
|
||
"reflect"
|
||
"regexp"
|
||
"slices"
|
||
"sort"
|
||
"strings"
|
||
"testing"
|
||
"time"
|
||
|
||
"github.com/google/uuid"
|
||
"github.com/phishingclub/phishingclub/database"
|
||
"github.com/phishingclub/phishingclub/testdb"
|
||
"github.com/phishingclub/phishingclub/vo"
|
||
"gorm.io/driver/sqlite"
|
||
"gorm.io/gorm"
|
||
"gorm.io/gorm/clause"
|
||
"gorm.io/gorm/logger"
|
||
)
|
||
|
||
// dialectRow is a row of the table the dialect tests read
|
||
type dialectRow struct {
|
||
ID int `gorm:"primaryKey;autoIncrement:false"`
|
||
SeenAt *time.Time
|
||
Name *string
|
||
Ref *string
|
||
}
|
||
|
||
func (dialectRow) TableName() string { return "dialect_rows" }
|
||
|
||
// dialectTimes are the stored times of the dialect rows, some close to a day,
|
||
// week and month edge. Rows 1 to 3 are written as time values by the driver,
|
||
// rows 4 to 6 as RFC3339 text, the two forms sqlite holds.
|
||
var dialectTimes = map[int]time.Time{
|
||
1: time.Date(2026, 11, 29, 23, 30, 0, 0, time.UTC), // a Sunday
|
||
2: time.Date(2026, 11, 30, 0, 15, 0, 123000000, time.UTC), // a Monday
|
||
3: time.Date(2026, 12, 31, 23, 59, 59, 999000000, time.UTC), // end of a year
|
||
4: time.Date(2026, 3, 1, 0, 30, 0, 0, time.UTC),
|
||
5: time.Date(2026, 2, 28, 22, 0, 0, 500000000, time.UTC),
|
||
6: time.Date(2027, 1, 4, 4, 0, 0, 0, time.UTC),
|
||
}
|
||
|
||
// dialectNames are the names of the rows, nil is null
|
||
var dialectNames = map[int]*string{
|
||
1: strPtr("beta"), 2: strPtr("Alpha"), 3: nil, 4: strPtr("alpha2"), 5: strPtr("Gamma"), 6: nil,
|
||
}
|
||
|
||
func strPtr(s string) *string { return &s }
|
||
|
||
// openBothEngines opens the test database, and on a postgres run also a
|
||
// sqlite database, so a test can read the same data through both engines.
|
||
// The sqlite one is opened without testdb so the engine of the process stays
|
||
// postgres. The expressions here pick their SQL and quoting from the
|
||
// statement.
|
||
func openBothEngines(t *testing.T) []*gorm.DB {
|
||
t.Helper()
|
||
db, err := testdb.Open(t, filepath.Join(t.TempDir(), "engine.db"))
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
dbs := []*gorm.DB{db}
|
||
if testdb.IsPostgres() {
|
||
other, err := gorm.Open(sqlite.Open(filepath.Join(t.TempDir(), "engine_sqlite.db")), &gorm.Config{
|
||
Logger: logger.Default.LogMode(logger.Silent),
|
||
})
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
dbs = append(dbs, other)
|
||
}
|
||
return dbs
|
||
}
|
||
|
||
// openDialectDBs opens the test database, and on a postgres run also a sqlite
|
||
// database, both filled with the same rows, so a test can read the same data
|
||
// through both engines
|
||
func openDialectDBs(t *testing.T) []*gorm.DB {
|
||
t.Helper()
|
||
dbs := openBothEngines(t)
|
||
for _, d := range dbs {
|
||
if err := d.AutoMigrate(&dialectRow{}); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
for id := 1; id <= 6; id++ {
|
||
at := dialectTimes[id]
|
||
if id <= 3 {
|
||
if err := d.Create(&dialectRow{ID: id, SeenAt: &at, Name: dialectNames[id]}).Error; err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
continue
|
||
}
|
||
if err := d.Exec("INSERT INTO dialect_rows (id, seen_at, name) VALUES (?, ?, ?)",
|
||
id, at.Format(time.RFC3339Nano), dialectNames[id]).Error; err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
}
|
||
if err := d.Exec("INSERT INTO dialect_rows (id, seen_at, name) VALUES (?, ?, ?)", 7, nil, "null time").Error; err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
}
|
||
return dbs
|
||
}
|
||
|
||
// TestDialectJulianDay checks the julian day of a time reads back as the
|
||
// stored time to the millisecond on each engine
|
||
func TestDialectJulianDay(t *testing.T) {
|
||
for _, db := range openDialectDBs(t) {
|
||
var rows []struct {
|
||
ID int
|
||
Julian *float64
|
||
}
|
||
err := db.Table("dialect_rows").
|
||
Select("id, ? AS julian", julianDay(clause.Column{Name: "seen_at"})).
|
||
Order("id").Scan(&rows).Error
|
||
if err != nil {
|
||
t.Fatalf("%s: %v", db.Dialector.Name(), err)
|
||
}
|
||
if len(rows) != 7 {
|
||
t.Fatalf("%s: rows %d", db.Dialector.Name(), len(rows))
|
||
}
|
||
for _, r := range rows {
|
||
want, ok := dialectTimes[r.ID]
|
||
if !ok {
|
||
if r.Julian != nil {
|
||
t.Fatalf("%s: null time gave %v", db.Dialector.Name(), *r.Julian)
|
||
}
|
||
continue
|
||
}
|
||
got := julianToTime(*r.Julian)
|
||
if d := got.Sub(want.Truncate(time.Millisecond)); d < -time.Millisecond || d > time.Millisecond {
|
||
t.Fatalf("%s row %d: julian time %v, want %v", db.Dialector.Name(), r.ID, got, want)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// TestDialectTimeBefore checks the time compare of two columns and of a
|
||
// column and a value on each engine
|
||
func TestDialectTimeBefore(t *testing.T) {
|
||
edge := time.Date(2026, 11, 30, 0, 15, 0, 123000000, time.UTC)
|
||
for _, db := range openDialectDBs(t) {
|
||
ids := []int{}
|
||
err := db.Table("dialect_rows").
|
||
Where(timeBefore(clause.Column{Name: "seen_at"}, edge)).
|
||
Order("id").Pluck("id", &ids).Error
|
||
if err != nil {
|
||
t.Fatalf("%s: %v", db.Dialector.Name(), err)
|
||
}
|
||
if want := []int{1, 4, 5}; !reflect.DeepEqual(ids, want) {
|
||
t.Fatalf("%s: before %v, want %v", db.Dialector.Name(), ids, want)
|
||
}
|
||
// queuedBefore and columnAfter bind the value in the layout of the
|
||
// engine
|
||
n := int64(0)
|
||
if err := db.Table("dialect_rows AS campaign_recipients").
|
||
Select("COUNT(*)").
|
||
Where(clause.Expr{SQL: "? IS NOT NULL", Vars: []any{clause.Column{Table: "campaign_recipients", Name: "seen_at"}}}).
|
||
Where(columnAfter("seen_at", edge.Add(-time.Second))).
|
||
Scan(&n).Error; err != nil {
|
||
t.Fatalf("%s: %v", db.Dialector.Name(), err)
|
||
}
|
||
if n != 3 {
|
||
t.Fatalf("%s: after count %d, want 3", db.Dialector.Name(), n)
|
||
}
|
||
}
|
||
}
|
||
|
||
// TestDialectMonthStart checks an update to the start of the month of a
|
||
// stored time on each engine
|
||
func TestDialectMonthStart(t *testing.T) {
|
||
for _, db := range openDialectDBs(t) {
|
||
if err := db.Table("dialect_rows").Where("id IN ?", []int{3, 5}).
|
||
Updates(map[string]any{"seen_at": monthStart(clause.Column{Name: "seen_at"})}).Error; err != nil {
|
||
t.Fatalf("%s: %v", db.Dialector.Name(), err)
|
||
}
|
||
var rows []dialectRow
|
||
if err := db.Where("id IN ?", []int{3, 5}).Order("id").Find(&rows).Error; err != nil {
|
||
t.Fatalf("%s: %v", db.Dialector.Name(), err)
|
||
}
|
||
want := []time.Time{
|
||
time.Date(2026, 12, 1, 0, 0, 0, 0, time.UTC),
|
||
time.Date(2026, 2, 1, 0, 0, 0, 0, time.UTC),
|
||
}
|
||
for i, r := range rows {
|
||
if r.SeenAt == nil || !r.SeenAt.Equal(want[i]) {
|
||
t.Fatalf("%s row %d: %v, want %v", db.Dialector.Name(), r.ID, r.SeenAt, want[i])
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// TestDialectNullSafeAndLike checks the null safe compares and the case
|
||
// insensitive LIKE on each engine
|
||
func TestDialectNullSafeAndLike(t *testing.T) {
|
||
for _, db := range openDialectDBs(t) {
|
||
name := clause.Column{Name: "name"}
|
||
pick := func(cond clause.Expression) []int {
|
||
ids := []int{}
|
||
if err := db.Table("dialect_rows").Where(cond).Order("id").Pluck("id", &ids).Error; err != nil {
|
||
t.Fatalf("%s: %v", db.Dialector.Name(), err)
|
||
}
|
||
return ids
|
||
}
|
||
if got, want := pick(nullSafeEqual(name, nil)), []int{3, 6}; !reflect.DeepEqual(got, want) {
|
||
t.Fatalf("%s: is null %v, want %v", db.Dialector.Name(), got, want)
|
||
}
|
||
if got, want := pick(nullSafeEqual(name, "beta")), []int{1}; !reflect.DeepEqual(got, want) {
|
||
t.Fatalf("%s: is beta %v, want %v", db.Dialector.Name(), got, want)
|
||
}
|
||
if got, want := pick(nullSafeNotEqual(name, "beta")), []int{2, 3, 4, 5, 6, 7}; !reflect.DeepEqual(got, want) {
|
||
t.Fatalf("%s: is not beta %v, want %v", db.Dialector.Name(), got, want)
|
||
}
|
||
if got, want := pick(nullSafeNotEqual(name, clause.Column{Name: "ref"})), []int{1, 2, 4, 5, 7}; !reflect.DeepEqual(got, want) {
|
||
t.Fatalf("%s: is not ref %v, want %v", db.Dialector.Name(), got, want)
|
||
}
|
||
if got, want := pick(like(name, "%ALPHA%")), []int{2, 4}; !reflect.DeepEqual(got, want) {
|
||
t.Fatalf("%s: like %v, want %v", db.Dialector.Name(), got, want)
|
||
}
|
||
// the underscore is escaped, alpha2 has no a_ in it
|
||
if got := pick(likeEscape(name, `%a\_%`, `\`)); len(got) != 0 {
|
||
t.Fatalf("%s: like escape %v, want none", db.Dialector.Name(), got)
|
||
}
|
||
if got, want := pick(likeEscape(name, `%h_2%`, `\`)), []int{4}; !reflect.DeepEqual(got, want) {
|
||
t.Fatalf("%s: like underscore %v, want %v", db.Dialector.Name(), got, want)
|
||
}
|
||
}
|
||
}
|
||
|
||
// TestDialectOrderBy checks a sort of the allowlist kind ignores letter case
|
||
// and puts nulls first ascending and last descending on each engine, and a
|
||
// search matches text and time columns without letter case
|
||
func TestDialectOrderBy(t *testing.T) {
|
||
name := col("dialect_rows", "name")
|
||
at := col("dialect_rows", "seen_at")
|
||
nameRef := ColumnRef("dialect_rows", "name")
|
||
atRef := ColumnRef("dialect_rows", "seen_at")
|
||
for _, db := range openDialectDBs(t) {
|
||
order := func(column string, desc bool) []int {
|
||
q, err := WithOrderBy(db.Table("dialect_rows"), column, desc, name, at)
|
||
if err != nil {
|
||
t.Fatalf("%s: %v", db.Dialector.Name(), err)
|
||
}
|
||
ids := []int{}
|
||
if err := q.Order("id").Pluck("id", &ids).Error; err != nil {
|
||
t.Fatalf("%s: %v", db.Dialector.Name(), err)
|
||
}
|
||
return ids
|
||
}
|
||
if got, want := order(nameRef, false), []int{3, 6, 2, 4, 1, 5, 7}; !reflect.DeepEqual(got, want) {
|
||
t.Fatalf("%s: name asc %v, want %v", db.Dialector.Name(), got, want)
|
||
}
|
||
if got, want := order(nameRef, true), []int{7, 5, 1, 4, 2, 3, 6}; !reflect.DeepEqual(got, want) {
|
||
t.Fatalf("%s: name desc %v, want %v", db.Dialector.Name(), got, want)
|
||
}
|
||
if got, want := order(atRef, false), []int{7, 5, 4, 1, 2, 3, 6}; !reflect.DeepEqual(got, want) {
|
||
t.Fatalf("%s: at asc %v, want %v", db.Dialector.Name(), got, want)
|
||
}
|
||
if got, want := order(atRef, true), []int{6, 3, 2, 1, 4, 5, 7}; !reflect.DeepEqual(got, want) {
|
||
t.Fatalf("%s: at desc %v, want %v", db.Dialector.Name(), got, want)
|
||
}
|
||
// a name is compared by its table and column, however it is quoted
|
||
for _, quoted := range []string{`"dialect_rows"."seen_at"`, "`dialect_rows`.`seen_at`"} {
|
||
if got, want := order(quoted, true), []int{6, 3, 2, 1, 4, 5, 7}; !reflect.DeepEqual(got, want) {
|
||
t.Fatalf("%s: quoted at desc %v, want %v", db.Dialector.Name(), got, want)
|
||
}
|
||
}
|
||
if _, err := WithOrderBy(db, ColumnRef("dialect_rows", "ref"), false, name, at); err == nil {
|
||
t.Fatalf("%s: a column off the allowlist must be refused", db.Dialector.Name())
|
||
}
|
||
search := func(text string) []int {
|
||
ids := []int{}
|
||
q := db.Table("dialect_rows").Where(searchCondition(dialectOf(db), []clause.Column{name}, "%"+text+"%"))
|
||
if err := q.Order("id").Pluck("id", &ids).Error; err != nil {
|
||
t.Fatalf("%s: %v", db.Dialector.Name(), err)
|
||
}
|
||
sort.Ints(ids)
|
||
return ids
|
||
}
|
||
if got, want := search("ALPHA"), []int{2, 4}; !reflect.DeepEqual(got, want) {
|
||
t.Fatalf("%s: search %v, want %v", db.Dialector.Name(), got, want)
|
||
}
|
||
ids := []int{}
|
||
q := db.Table("dialect_rows").Where(searchCondition(dialectOf(db), []clause.Column{at}, "%2026-12-31%"))
|
||
if err := q.Pluck("id", &ids).Error; err != nil {
|
||
t.Fatalf("%s: %v", db.Dialector.Name(), err)
|
||
}
|
||
if !reflect.DeepEqual(ids, []int{3}) {
|
||
t.Fatalf("%s: time search %v, want [3]", db.Dialector.Name(), ids)
|
||
}
|
||
}
|
||
}
|
||
|
||
// TestParseColumnToken checks the column forms the allowlists hold
|
||
func TestParseColumnToken(t *testing.T) {
|
||
cases := map[string]clause.Column{
|
||
"`campaigns`.`name`": {Table: "campaigns", Name: "name"},
|
||
`"campaigns"."name"`: {Table: "campaigns", Name: "name"},
|
||
"campaign_recipients.id": {Table: "campaign_recipients", Name: "id"},
|
||
"is_repeat_offender": {Name: "is_repeat_offender"},
|
||
"`before_landing_page`.x": {},
|
||
}
|
||
for in, want := range cases {
|
||
got, ok := parseColumnToken(in)
|
||
if want == (clause.Column{}) {
|
||
if ok {
|
||
t.Fatalf("%q: want refused, got %v", in, got)
|
||
}
|
||
continue
|
||
}
|
||
if !ok || got != want {
|
||
t.Fatalf("%q: got %v %v, want %v", in, got, ok, want)
|
||
}
|
||
}
|
||
for _, bad := range []string{"name; DROP TABLE x", "`a`.`b` DESC", "\"a\".`b`", "a.b.c", "LOWER(name)", ""} {
|
||
if _, ok := parseColumnToken(bad); ok {
|
||
t.Fatalf("%q must not parse", bad)
|
||
}
|
||
}
|
||
}
|
||
|
||
// TestSortColumnKinds checks the kind every allowlisted sort and search
|
||
// column has by its name, see kindOfColumn, against its postgres column type.
|
||
// postgres sorts text by LOWER and casts other columns to text for a search,
|
||
// so a wrong kind fails a query.
|
||
func TestSortColumnKinds(t *testing.T) {
|
||
testdb.SkipUnlessPostgres(t)
|
||
db, err := testdb.Open(t, filepath.Join(t.TempDir(), "kinds.db"))
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
models := map[string]any{
|
||
database.ALLOW_DENY_TABLE: &database.AllowDeny{},
|
||
database.ASSET_TABLE: &database.Asset{},
|
||
database.API_SENDER_TABLE: &database.APISender{},
|
||
database.ATTACHMENT_TABLE: &database.Attachment{},
|
||
database.CAMPAIGN_TEMPLATE_TABLE: &database.CampaignTemplate{},
|
||
database.CAMPAIGN_RECIPIENT_TABLE_NAME: &database.CampaignRecipient{},
|
||
database.DOMAIN_TABLE: &database.Domain{},
|
||
database.EMAIL_TABLE: &database.Email{},
|
||
database.OAUTH_PROVIDER_TABLE: &database.OAuthProvider{},
|
||
database.PAGE_TABLE: &database.Page{},
|
||
database.CAMPAIGN_TABLE: &database.Campaign{},
|
||
database.CAMPAIGN_EVENT_TABLE: &database.CampaignEvent{},
|
||
database.EVENT_TABLE: &database.Event{},
|
||
database.COMPANY_TABLE: &database.Company{},
|
||
database.IDENTIFIER_TABLE: &database.Identifier{},
|
||
database.PROXY_TABLE: &database.Proxy{},
|
||
database.RECIPIENT_GROUP_TABLE: &database.RecipientGroup{},
|
||
database.SMTP_CONFIGURATION_TABLE: &database.SMTPConfiguration{},
|
||
database.RECIPIENT_TABLE: &database.Recipient{},
|
||
database.REPORT_TEMPLATE_TABLE: &database.ReportTemplate{},
|
||
database.REMOTE_BROWSER_TABLE: &database.RemoteBrowser{},
|
||
database.PROGRAM_TABLE: &database.Program{},
|
||
database.PROGRAM_ENROLLMENT_TABLE: &database.ProgramEnrollment{},
|
||
database.SESSION_TABLE: &database.Session{},
|
||
database.USER_TABLE: &database.User{},
|
||
database.REPORT_SEND_LOG_TABLE: &database.ReportSendLog{},
|
||
database.WEBHOOK_TABLE: &database.Webhook{},
|
||
database.SCRIPT_TABLE: &database.Script{},
|
||
}
|
||
// the aliases the allowlists sort joined tables under
|
||
aliases := map[string]string{
|
||
"before_landing_page": database.PAGE_TABLE,
|
||
"landing_page": database.PAGE_TABLE,
|
||
"after_landing_page": database.PAGE_TABLE,
|
||
ProgramEnrollmentRecipientAlias: database.RECIPIENT_TABLE,
|
||
recipientProgramAlias: database.PROGRAM_TABLE,
|
||
}
|
||
allowlists := sortAndSearchAllowlists()
|
||
types := map[string]map[string]string{}
|
||
columnType := func(table, column string) (string, bool) {
|
||
if _, ok := types[table]; !ok {
|
||
model, ok := models[table]
|
||
if !ok {
|
||
t.Fatalf("no model for table %s, add it to the test", table)
|
||
}
|
||
if err := db.AutoMigrate(model); err != nil {
|
||
t.Fatalf("migrate %s: %v", table, err)
|
||
}
|
||
columns, err := db.Migrator().ColumnTypes(model)
|
||
if err != nil {
|
||
t.Fatalf("column types of %s: %v", table, err)
|
||
}
|
||
types[table] = map[string]string{}
|
||
for _, c := range columns {
|
||
types[table][c.Name()] = strings.ToUpper(c.DatabaseTypeName())
|
||
}
|
||
}
|
||
v, ok := types[table][column]
|
||
return v, ok
|
||
}
|
||
checked := 0
|
||
for list, columns := range allowlists {
|
||
for _, column := range columns {
|
||
if column.Table == "" {
|
||
// computed, such as is_repeat_offender, sorted on its own path
|
||
continue
|
||
}
|
||
table := column.Table
|
||
if real, ok := aliases[table]; ok {
|
||
table = real
|
||
}
|
||
dbType, ok := columnType(table, column.Name)
|
||
if !ok {
|
||
// a pre existing allowlist entry without a column fails the
|
||
// same way on sqlite, it is not a dialect matter
|
||
t.Logf("%s: %s.%s has no column", list, table, column.Name)
|
||
continue
|
||
}
|
||
want := columnOther
|
||
switch dbType {
|
||
case "TEXT", "VARCHAR", "BPCHAR", "CHARACTER VARYING":
|
||
want = columnText
|
||
case "TIMESTAMPTZ", "TIMESTAMP", "DATE":
|
||
want = columnTime
|
||
case "BOOL", "BOOLEAN":
|
||
want = columnBool
|
||
}
|
||
checked++
|
||
if got := kindOfColumn(column.Name); got != want {
|
||
t.Errorf("%s: %s.%s is %s, kind %d, want %d", list, table, column.Name, dbType, got, want)
|
||
}
|
||
}
|
||
}
|
||
if checked < 100 {
|
||
t.Fatalf("only %d columns checked", checked)
|
||
}
|
||
t.Logf("%d allowlisted columns checked", checked)
|
||
}
|
||
|
||
// sortAndSearchAllowlists are the allowlists of the sort and search columns
|
||
func sortAndSearchAllowlists() map[string][]clause.Column {
|
||
return map[string][]clause.Column{
|
||
"allowDeny": allowDenyAllowColumns,
|
||
"asset": assetAllowedColumns,
|
||
"apiSender": apiSenderAllowedColumns,
|
||
"attachment": attachmentAllowedColumns,
|
||
"campaignTemplate": allowdCampaignTemplatesColumns,
|
||
"campaignRecipient": allowedCampaignRecipientColumns,
|
||
"domain": domainAllowedColumns,
|
||
"email": allowedEmailOrderBy,
|
||
"oauthProvider": oauthProviderAllowedColumns,
|
||
"page": pageAllowedColumns,
|
||
"campaign": allowedCampaignColumns,
|
||
"campaignEvent": allowedCampaginEventColumns,
|
||
"campaignEventView": allowedCampaginEventViewColumns,
|
||
"company": companyAllowedColumns,
|
||
"identifier": identifierAllowedColumns,
|
||
"proxy": proxyAllowedColumns,
|
||
"recipientGroup": RecipientGroupAllowedColumns,
|
||
"smtp": allowedSMTPConfigurationsSortBy,
|
||
"recipient": allowdRecipientColumns,
|
||
"recipientCampaignEvent": allowdRecipientCampaignEventColumns,
|
||
"reportTemplate": reportTemplateAllowedColumns,
|
||
"remoteBrowser": remoteBrowserAllowedColumns,
|
||
"program": allowedProgramColumns,
|
||
"user": userAllowedColumns,
|
||
"reportSendLog": reportSendLogAllowedColumns,
|
||
"webhook": webhookAllowedColumns,
|
||
"userSession": allowedSessionColumns,
|
||
"script": scriptAllowedColumns,
|
||
"programEnrollment": allowedProgramEnrollmentColumns,
|
||
"programAudience": slices.Collect(maps.Values(programAudienceSortColumns)),
|
||
"programSearch": assignTableToColumns(database.PROGRAM_TABLE, append([]string{}, programSearchColumns...)),
|
||
"programPeopleRecipientRow": {col(recipientProgramAlias, "name")},
|
||
}
|
||
}
|
||
|
||
// TestAllowlistColumnsPlain checks that every allowlisted sort and search
|
||
// column is a plain column: a table and a name that are identifiers, no
|
||
// alias and no raw text, so gorm writes it quoted
|
||
func TestAllowlistColumnsPlain(t *testing.T) {
|
||
n := 0
|
||
for list, columns := range sortAndSearchAllowlists() {
|
||
for _, column := range columns {
|
||
n++
|
||
if column.Raw || column.Alias != "" || !identifierPattern.MatchString(column.Name) ||
|
||
(column.Table != "" && !identifierPattern.MatchString(column.Table)) {
|
||
t.Errorf("%s: %#v is no plain column", list, column)
|
||
}
|
||
}
|
||
}
|
||
if n < 100 {
|
||
t.Fatalf("only %d columns checked", n)
|
||
}
|
||
}
|
||
|
||
var identifierPattern = regexp.MustCompile(`^[A-Za-z0-9_]+$`)
|
||
|
||
// kelvin is U+212A KELVIN SIGN, which a postgres language collation lowers
|
||
// to k while sqlite LOWER keeps it
|
||
const kelvin = "K"
|
||
|
||
// parityRow is a row of the table the parity tests read on both engines
|
||
type parityRow struct {
|
||
ID int `gorm:"primaryKey;autoIncrement:false"`
|
||
Name string
|
||
// IsTest is a boolean of a name the kind map knows
|
||
IsTest bool
|
||
SeenAt *time.Time
|
||
}
|
||
|
||
func (parityRow) TableName() string { return "parity_rows" }
|
||
|
||
// parityNames are the names of the parity rows by id, chosen so that a
|
||
// language collation, a Unicode case fold or the postgres LIKE escape would
|
||
// give another result than sqlite
|
||
var parityNames = map[int]string{
|
||
1: `CORP\jdoe`,
|
||
2: "CORPjdoe",
|
||
3: "a b",
|
||
4: "ab",
|
||
5: "a-c",
|
||
6: "Ölund",
|
||
7: "ölund",
|
||
8: "B",
|
||
9: kelvin + "ate",
|
||
}
|
||
|
||
// parityTimes are the stored times, written as the RFC 3339 text the
|
||
// application writes to sqlite
|
||
var parityTimes = map[int]time.Time{
|
||
1: time.Date(2026, 11, 29, 10, 30, 50, 0, time.UTC),
|
||
2: time.Date(2026, 11, 29, 10, 30, 0, 500000000, time.UTC),
|
||
3: time.Date(2026, 11, 30, 0, 0, 0, 120300000, time.UTC),
|
||
}
|
||
|
||
// openParityDBs opens the test database, and on a postgres run also a sqlite
|
||
// database, both with the parity rows
|
||
func openParityDBs(t *testing.T) []*gorm.DB {
|
||
t.Helper()
|
||
dbs := openBothEngines(t)
|
||
for _, d := range dbs {
|
||
if err := d.AutoMigrate(&parityRow{}); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
for id := 1; id <= len(parityNames); id++ {
|
||
var seen any
|
||
if at, ok := parityTimes[id]; ok {
|
||
seen = at.Format(time.RFC3339Nano)
|
||
}
|
||
if err := d.Exec("INSERT INTO parity_rows (id, name, is_test, seen_at) VALUES (?, ?, ?, ?)",
|
||
id, parityNames[id], id%2 == 1, seen).Error; err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
}
|
||
}
|
||
return dbs
|
||
}
|
||
|
||
// TestDialectParitySearch checks that a search finds the same rows on both
|
||
// engines: a backslash is a plain character, a boolean reads as 1 or 0 and a
|
||
// time as the RFC 3339 text sqlite holds
|
||
func TestDialectParitySearch(t *testing.T) {
|
||
name := col("parity_rows", "name")
|
||
flag := col("parity_rows", "is_test")
|
||
at := col("parity_rows", "seen_at")
|
||
for _, db := range openParityDBs(t) {
|
||
engine := db.Dialector.Name()
|
||
search := func(column clause.Column, text string) []int {
|
||
ids := []int{}
|
||
q := db.Table("parity_rows").Where(searchCondition(dialectOf(db), []clause.Column{column}, "%"+text+"%"))
|
||
if err := q.Order("id").Pluck("id", &ids).Error; err != nil {
|
||
t.Fatalf("%s: %v", engine, err)
|
||
}
|
||
return ids
|
||
}
|
||
cases := []struct {
|
||
column clause.Column
|
||
text string
|
||
want []int
|
||
}{
|
||
{name, `CORP\jdoe`, []int{1}},
|
||
{name, `corp\j`, []int{1}},
|
||
{name, `\`, []int{1}},
|
||
{name, "corpj", []int{2}},
|
||
{flag, "1", []int{1, 3, 5, 7, 9}},
|
||
{flag, "0", []int{2, 4, 6, 8}},
|
||
{at, "2026-11-29T10:30:50Z", []int{1}},
|
||
{at, "T10:30:00.5Z", []int{2}},
|
||
{at, "2026-11-30T00:00:00.1203Z", []int{3}},
|
||
{at, "2026-11-29", []int{1, 2}},
|
||
}
|
||
for _, c := range cases {
|
||
if got := search(c.column, c.text); !reflect.DeepEqual(got, c.want) {
|
||
t.Errorf("%s: search %v for %q gave %v, want %v", engine, c.column, c.text, got, c.want)
|
||
}
|
||
}
|
||
// the audience search builds its own pattern through like
|
||
ids := []int{}
|
||
if err := db.Table("parity_rows").Where(like(clause.Column{Name: "name"}, `%P\j%`)).Pluck("id", &ids).Error; err != nil {
|
||
t.Fatalf("%s: %v", engine, err)
|
||
}
|
||
if !reflect.DeepEqual(ids, []int{1}) {
|
||
t.Errorf("%s: like with a backslash gave %v, want [1]", engine, ids)
|
||
}
|
||
}
|
||
}
|
||
|
||
// TestDialectParitySort checks that both engines sort text in the same
|
||
// order: the case insensitive sort as sqlite NOCASE, ASCII letters folded and
|
||
// then bytes, and the stored sort in byte order
|
||
func TestDialectParitySort(t *testing.T) {
|
||
name := col("parity_rows", "name")
|
||
for _, db := range openParityDBs(t) {
|
||
engine := db.Dialector.Name()
|
||
q, err := WithOrderBy(db.Table("parity_rows"), ColumnRef("parity_rows", "name"), false, name)
|
||
if err != nil {
|
||
t.Fatalf("%s: %v", engine, err)
|
||
}
|
||
ids := []int{}
|
||
if err := q.Order("id").Pluck("id", &ids).Error; err != nil {
|
||
t.Fatalf("%s: %v", engine, err)
|
||
}
|
||
if want := []int{3, 5, 4, 8, 1, 2, 6, 7, 9}; !reflect.DeepEqual(ids, want) {
|
||
t.Errorf("%s: case insensitive sort %v, want %v", engine, ids, want)
|
||
}
|
||
term := orderByColumnTerm(dialectOf(db), name, true)
|
||
ids = []int{}
|
||
if err := db.Raw("SELECT id FROM parity_rows ORDER BY ?", term).Scan(&ids).Error; err != nil {
|
||
t.Fatalf("%s: %v", engine, err)
|
||
}
|
||
if want := []int{9, 7, 6, 4, 5, 3, 2, 1, 8}; !reflect.DeepEqual(ids, want) {
|
||
t.Errorf("%s: stored sort desc %v, want %v", engine, ids, want)
|
||
}
|
||
if _, err := WithOrderBy(db, "LOWER(name)", false, name); err == nil {
|
||
t.Errorf("%s: a term that is no plain column must be refused", engine)
|
||
}
|
||
}
|
||
}
|
||
|
||
// TestDialectParityLowerASCII checks that the case insensitive compare used
|
||
// for addresses and names folds the ASCII letters only on both engines
|
||
func TestDialectParityLowerASCII(t *testing.T) {
|
||
for _, db := range openParityDBs(t) {
|
||
engine := db.Dialector.Name()
|
||
pick := func(value string) []int {
|
||
ids := []int{}
|
||
if err := db.Table("parity_rows").
|
||
Where(equalIgnoringASCIICase(clause.Column{Name: "name"}, value)).
|
||
Order("id").Pluck("id", &ids).Error; err != nil {
|
||
t.Fatalf("%s: %v", engine, err)
|
||
}
|
||
return ids
|
||
}
|
||
if got := pick("kate"); len(got) != 0 {
|
||
t.Errorf("%s: the Kelvin sign matched k: %v", engine, got)
|
||
}
|
||
if got := pick("ÖLUND"); !reflect.DeepEqual(got, []int{6}) {
|
||
t.Errorf("%s: only ASCII letters fold, got %v, want [6]", engine, got)
|
||
}
|
||
if got := pick("corp\\JDOE"); !reflect.DeepEqual(got, []int{1}) {
|
||
t.Errorf("%s: ASCII letters fold, got %v, want [1]", engine, got)
|
||
}
|
||
}
|
||
}
|
||
|
||
// TestIdentityMatchASCIIOnly checks the repository lookups that pick a user
|
||
// or a recipient by address: other casing of ASCII letters matches, a
|
||
// letter that only a Unicode case fold makes equal does not, on both engines
|
||
func TestIdentityMatchASCIIOnly(t *testing.T) {
|
||
db, err := testdb.Open(t, filepath.Join(t.TempDir(), "identity.db"))
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if err := db.AutoMigrate(&database.User{}, &database.Recipient{}, &database.Domain{}); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if err := (database.Recipient{}).Migrate(db); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
ctx := context.Background()
|
||
now := time.Now().UTC()
|
||
userID, roleID, recipientID, companyID := uuid.New(), uuid.New(), uuid.New(), uuid.New()
|
||
if err := db.Create(&database.User{
|
||
ID: &userID, CreatedAt: &now, UpdatedAt: &now, Name: "Kate", Username: "kate",
|
||
Email: "kate@corp.com", RoleID: &roleID,
|
||
}).Error; err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
email := "kate@corp.com"
|
||
if err := db.Create(&database.Recipient{
|
||
ID: &recipientID, CreatedAt: &now, UpdatedAt: &now, Email: &email, CompanyID: &companyID,
|
||
}).Error; err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
domainID := uuid.New()
|
||
if err := db.Create(&database.Domain{
|
||
ID: domainID, CreatedAt: &now, UpdatedAt: &now, Name: "kelvin.example", CompanyID: &companyID,
|
||
}).Error; err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
users := &User{DB: db}
|
||
recipients := &Recipient{DB: db}
|
||
companies := &Company{DB: db}
|
||
|
||
for _, c := range []struct {
|
||
address string
|
||
found bool
|
||
}{
|
||
{"KATE@Corp.COM", true},
|
||
{kelvin + "ate@corp.com", false},
|
||
} {
|
||
_, err := users.GetByEmail(ctx, vo.NewEmailMust(c.address), &UserOption{})
|
||
if got := err == nil; got != c.found {
|
||
t.Errorf("user %q found %v, want %v (%v)", c.address, got, c.found, err)
|
||
}
|
||
_, err = recipients.GetByEmailLowerInCompanyContext(ctx, vo.NewEmailMust(c.address), &companyID)
|
||
if got := err == nil; got != c.found {
|
||
t.Errorf("recipient %q found %v, want %v (%v)", c.address, got, c.found, err)
|
||
}
|
||
// a new recipient is stored with its email lowered by strings.ToLower,
|
||
// which makes the Kelvin sign a k, so that address is taken as well
|
||
taken, err := recipients.IsEmailTaken(ctx, vo.NewEmailMust(c.address), nil)
|
||
if err != nil || !taken {
|
||
t.Errorf("email %q taken %v, want true (%v)", c.address, taken, err)
|
||
}
|
||
_, err = recipients.GetByEmailLowerAndCompanyID(ctx, vo.NewEmailMust(c.address), &companyID)
|
||
if got := err == nil; got != c.found {
|
||
t.Errorf("company recipient %q found %v, want %v (%v)", c.address, got, c.found, err)
|
||
}
|
||
}
|
||
for _, c := range []struct {
|
||
name string
|
||
found bool
|
||
}{
|
||
{"KELVIN.example", true},
|
||
{kelvin + "elvin.example", false},
|
||
} {
|
||
found, err := companies.HasDomainNamed(ctx, &companyID, c.name)
|
||
if err != nil || found != c.found {
|
||
t.Errorf("domain %q found %v, want %v (%v)", c.name, found, c.found, err)
|
||
}
|
||
}
|
||
inbox := &ReportInbox{DB: db}
|
||
emails, err := inbox.SampleRecipientEmails(ctx, &companyID, "reports@CORP.com", 10)
|
||
if err != nil || !reflect.DeepEqual(emails, []string{"kate@corp.com"}) {
|
||
t.Errorf("sample %v %v", emails, err)
|
||
}
|
||
emails, err = inbox.SampleRecipientEmails(ctx, &companyID, "kate@corp.com", 10)
|
||
if err != nil || len(emails) != 0 {
|
||
t.Errorf("the mailbox itself must be left out: %v %v", emails, err)
|
||
}
|
||
|
||
if !testdb.IsPostgres() {
|
||
return
|
||
}
|
||
// the postgres lookup must use the index of its own expression, not
|
||
// read the whole table
|
||
sqlText := db.ToSQL(func(tx *gorm.DB) *gorm.DB {
|
||
return tx.Model(&database.Recipient{}).
|
||
Where(equalIgnoringASCIICase(clause.Column{Table: database.RECIPIENT_TABLE, Name: "email"}, "kate@corp.com")).
|
||
Find(&[]database.Recipient{})
|
||
})
|
||
var plan []string
|
||
conn, err := db.DB()
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
pinned, err := conn.Conn(ctx)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
defer pinned.Close()
|
||
if _, err := pinned.ExecContext(ctx, "SET enable_seqscan = off"); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
rows, err := pinned.QueryContext(ctx, "EXPLAIN "+sqlText)
|
||
if err != nil {
|
||
t.Fatalf("explain: %v", err)
|
||
}
|
||
defer rows.Close()
|
||
for rows.Next() {
|
||
var line string
|
||
if err := rows.Scan(&line); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
plan = append(plan, line)
|
||
}
|
||
if !strings.Contains(strings.Join(plan, "\n"), "idx_recipients_email_lower_ascii") {
|
||
t.Errorf("the lookup does not use idx_recipients_email_lower_ascii:\n%s", strings.Join(plan, "\n"))
|
||
}
|
||
}
|