mirror of
https://github.com/phishingclub/phishingclub.git
synced 2026-12-06 01:53:42 +01:00
804 lines
30 KiB
Go
804 lines
30 KiB
Go
package repository
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"fmt"
|
|
"path/filepath"
|
|
"reflect"
|
|
"regexp"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/phishingclub/phishingclub/database"
|
|
"github.com/phishingclub/phishingclub/testdb"
|
|
"github.com/phishingclub/phishingclub/vo"
|
|
"gorm.io/gorm"
|
|
"gorm.io/gorm/clause"
|
|
)
|
|
|
|
// TestLeftJoinOnWithAlias checks the join helpers build a join gorm quotes
|
|
// for the engine of the statement and that it runs on both engines
|
|
func TestLeftJoinOnWithAlias(t *testing.T) {
|
|
for _, db := range openParityDBs(t) {
|
|
engine := db.Dialector.Name()
|
|
q := func(tx *gorm.DB) *gorm.DB {
|
|
return tx.Table("parity_rows").
|
|
Joins(LeftJoinOnWithAlias("parity_rows", "id", "parity_rows", "id", "other")).
|
|
Joins(LeftJoinOn("parity_rows", "id", "dialect_none", "id")).
|
|
Select("? AS name", clause.Column{Table: "other", Name: "name"}).
|
|
Where(clause.Eq{Column: clause.Column{Table: "parity_rows", Name: "id"}, Value: 1})
|
|
}
|
|
text := db.ToSQL(func(tx *gorm.DB) *gorm.DB { return q(tx).Scan(&[]struct{ Name string }{}) })
|
|
want := "LEFT JOIN `parity_rows` `other` on `parity_rows`.`id` = `other`.`id` LEFT JOIN `dialect_none` on `parity_rows`.`id` = `dialect_none`.`id`"
|
|
if engine == "postgres" {
|
|
want = `LEFT JOIN "parity_rows" "other" on "parity_rows"."id" = "other"."id" LEFT JOIN "dialect_none" on "parity_rows"."id" = "dialect_none"."id"`
|
|
}
|
|
if !strings.Contains(text, want) {
|
|
t.Fatalf("%s: join %s, want %s", engine, text, want)
|
|
}
|
|
if err := db.Exec("CREATE TABLE dialect_none (id INTEGER)").Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
var names []string
|
|
if err := q(db).Pluck("other.name", &names).Error; err != nil {
|
|
t.Fatalf("%s: %v", engine, err)
|
|
}
|
|
if !reflect.DeepEqual(names, []string{`CORP\jdoe`}) {
|
|
t.Fatalf("%s: joined %v", engine, names)
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestPagingPeek checks that a list read with one extra row gives the right
|
|
// page and the right next page flag on a real database
|
|
func TestPagingPeek(t *testing.T) {
|
|
dsn := filepath.Join(t.TempDir(), "peek.db") + "?_foreign_keys=OFF&_busy_timeout=5000"
|
|
db, err := testdb.Open(t, dsn)
|
|
if err != nil {
|
|
t.Fatalf("open sqlite: %v", err)
|
|
}
|
|
if err := db.AutoMigrate(&database.Company{}); err != nil {
|
|
t.Fatalf("migrate: %v", err)
|
|
}
|
|
const total = 7
|
|
now := time.Now().UTC()
|
|
for i := 0; i < total; i++ {
|
|
row := database.Company{
|
|
ID: uuid.New(),
|
|
CreatedAt: &now,
|
|
UpdatedAt: &now,
|
|
Name: fmt.Sprintf("company-%02d", i),
|
|
AssetsKey: uuid.NewString(),
|
|
}
|
|
if err := db.Create(&row).Error; err != nil {
|
|
t.Fatalf("seed: %v", err)
|
|
}
|
|
}
|
|
repo := &Company{DB: db}
|
|
|
|
cases := []struct {
|
|
offset, limit int
|
|
wantRows int
|
|
wantNext bool
|
|
wantFirst string
|
|
}{
|
|
{offset: 0, limit: 3, wantRows: 3, wantNext: true, wantFirst: "company-00"},
|
|
{offset: 3, limit: 3, wantRows: 3, wantNext: true, wantFirst: "company-03"},
|
|
// the page ends exactly at the last row
|
|
{offset: total - 3, limit: 3, wantRows: 3, wantNext: false, wantFirst: "company-04"},
|
|
{offset: total - 1, limit: 3, wantRows: 1, wantNext: false, wantFirst: "company-06"},
|
|
{offset: total, limit: 3, wantRows: 0, wantNext: false},
|
|
{offset: total + 5, limit: 3, wantRows: 0, wantNext: false},
|
|
// a page that holds everything
|
|
{offset: 0, limit: total, wantRows: total, wantNext: false, wantFirst: "company-00"},
|
|
{offset: 0, limit: total - 1, wantRows: total - 1, wantNext: true, wantFirst: "company-00"},
|
|
// no limit reads all rows
|
|
{offset: 0, limit: 0, wantRows: total, wantNext: false, wantFirst: "company-00"},
|
|
}
|
|
for _, c := range cases {
|
|
t.Run(fmt.Sprintf("offset%d_limit%d", c.offset, c.limit), func(t *testing.T) {
|
|
q := &vo.QueryArgs{Offset: c.offset, Limit: c.limit, OrderBy: "name"}
|
|
res, err := repo.GetAll(context.Background(), q)
|
|
if err != nil {
|
|
t.Fatalf("get all: %v", err)
|
|
}
|
|
if len(res.Rows) != c.wantRows {
|
|
t.Fatalf("rows = %d, want %d", len(res.Rows), c.wantRows)
|
|
}
|
|
if res.HasNextPage != c.wantNext {
|
|
t.Fatalf("has next page = %v, want %v", res.HasNextPage, c.wantNext)
|
|
}
|
|
if c.wantFirst != "" {
|
|
got := res.Rows[0].Name.MustGet().String()
|
|
if got != c.wantFirst {
|
|
t.Fatalf("first row = %s, want %s", got, c.wantFirst)
|
|
}
|
|
}
|
|
})
|
|
}
|
|
|
|
// nil query args reads everything with no next page
|
|
res, err := repo.GetAll(context.Background(), nil)
|
|
if err != nil {
|
|
t.Fatalf("get all nil: %v", err)
|
|
}
|
|
if len(res.Rows) != total || res.HasNextPage {
|
|
t.Fatalf("nil args: rows = %d next = %v", len(res.Rows), res.HasNextPage)
|
|
}
|
|
}
|
|
|
|
// relationColumnsOf returns the part of a select that gorm writes for the
|
|
// relation join Company: from the first Company column to FROM
|
|
func relationColumnsOf(t *testing.T, sql string) string {
|
|
t.Helper()
|
|
start := strings.Index(sql, "Company`.") - 1
|
|
if testdb.IsPostgres() {
|
|
start = strings.Index(sql, `Company".`) - 1
|
|
}
|
|
end := strings.Index(sql, " FROM ")
|
|
if start < 0 || end < start {
|
|
t.Fatalf("no relation columns in %s", sql)
|
|
}
|
|
return sql[start:end]
|
|
}
|
|
|
|
// TestSelectListRelationJoin checks that a page and a proxy list with Fields
|
|
// and WithCompany select the company columns as gorm does for its own
|
|
// select, so the company is read, on both engines
|
|
func TestSelectListRelationJoin(t *testing.T) {
|
|
db, captured := newBuilderDB(t, &database.Company{}, &database.Page{}, &database.Proxy{})
|
|
ctx := context.Background()
|
|
now := time.Now().UTC()
|
|
companyID := uuid.New()
|
|
if err := db.Create(&database.Company{ID: companyID, CreatedAt: &now, UpdatedAt: &now, Name: "acme"}).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
pageID, proxyID := uuid.New(), uuid.New()
|
|
if err := db.Create(&database.Page{ID: &pageID, CreatedAt: &now, UpdatedAt: &now, CompanyID: &companyID, Name: "p1", Content: "c"}).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := db.Create(&database.Proxy{ID: &proxyID, CreatedAt: &now, UpdatedAt: &now, CompanyID: &companyID, Name: "x1", StartURL: "https://a.test", ProxyConfig: "c"}).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
// the relation columns gorm writes when it builds the select itself
|
|
var full []database.Page
|
|
stmt := db.Session(&gorm.Session{DryRun: true}).Joins("Company").Find(&full).Statement
|
|
want := relationColumnsOf(t, stmt.SQL.String())
|
|
|
|
fields := []string{"id", "name", "company_id"}
|
|
// a proxy row needs its start url and config to become a model
|
|
proxyFields := []string{"id", "name", "company_id", "start_url", "proxy_config"}
|
|
pageRepo := &Page{DB: db}
|
|
for name, list := range map[string]func() error{
|
|
"page all": func() error {
|
|
_, err := pageRepo.GetAll(ctx, &companyID, &PageOption{Fields: fields, WithCompany: true, QueryArgs: &vo.QueryArgs{}})
|
|
return err
|
|
},
|
|
"page by company": func() error {
|
|
_, err := pageRepo.GetAllByCompanyID(ctx, &companyID, &PageOption{Fields: fields, WithCompany: true, QueryArgs: &vo.QueryArgs{}})
|
|
return err
|
|
},
|
|
"proxy all": func() error {
|
|
_, err := (&Proxy{DB: db}).GetAll(ctx, &companyID, &ProxyOption{Fields: proxyFields, WithCompany: true, QueryArgs: &vo.QueryArgs{}})
|
|
return err
|
|
},
|
|
"proxy by company": func() error {
|
|
_, err := (&Proxy{DB: db}).GetAllByCompanyID(ctx, &companyID, &ProxyOption{Fields: proxyFields, WithCompany: true, QueryArgs: &vo.QueryArgs{}})
|
|
return err
|
|
},
|
|
} {
|
|
if err := list(); err != nil {
|
|
t.Fatalf("%s: %v", name, err)
|
|
}
|
|
sql := lastQuery(t, captured).sql
|
|
if got := relationColumnsOf(t, sql); got != want {
|
|
t.Fatalf("%s: relation columns\n%s\nwant\n%s", name, got, want)
|
|
}
|
|
if !containsSQL(sql, "SELECT `") || !containsSQL(sql, "`.`id`,") {
|
|
t.Fatalf("%s: select %s", name, sql)
|
|
}
|
|
}
|
|
|
|
// the rows read the company through the same chain the lists build
|
|
var pages []database.Page
|
|
err := selectTableColumns(pageRepo.load(&PageOption{WithCompany: true}, db), database.PAGE_TABLE, fields).Find(&pages).Error
|
|
if err != nil || len(pages) != 1 || pages[0].Company == nil || pages[0].Company.Name != "acme" || pages[0].Content != "" {
|
|
t.Fatalf("page rows %+v, %v", pages, err)
|
|
}
|
|
var proxies []database.Proxy
|
|
err = selectTableColumns((&Proxy{DB: db}).load(&ProxyOption{WithCompany: true}, db), database.PROXY_TABLE, proxyFields).Find(&proxies).Error
|
|
if err != nil || len(proxies) != 1 || proxies[0].Company == nil || proxies[0].Company.ID != companyID {
|
|
t.Fatalf("proxy rows %+v, %v", proxies, err)
|
|
}
|
|
|
|
// a join by SQL text adds no columns
|
|
var plain []database.Page
|
|
stmt = selectColumns(db.Session(&gorm.Session{DryRun: true}).
|
|
Joins(LeftJoinOn(database.PAGE_TABLE, "company_id", database.COMPANY_TABLE, "id")),
|
|
selectCol(database.PAGE_TABLE, "id")).Find(&plain).Statement
|
|
if !containsSQL(stmt.SQL.String(), "SELECT `pages`.`id` FROM `pages` LEFT JOIN") {
|
|
t.Fatalf("raw join select %s", stmt.SQL.String())
|
|
}
|
|
}
|
|
|
|
// TestSelectColumnNames checks that the select helpers refuse an item not
|
|
// made by the constructors and a name that is no plain identifier, with an
|
|
// error of the query and without harm to the connection
|
|
func TestSelectColumnNames(t *testing.T) {
|
|
db, _ := newBuilderDB(t, &database.Page{})
|
|
var rows []database.Page
|
|
if err := selectColumns(db, SelectColumn{}).Find(&rows).Error; err == nil {
|
|
t.Fatal("an empty select item must fail the query")
|
|
}
|
|
for _, bad := range [][2]string{
|
|
{database.PAGE_TABLE, "id, content"},
|
|
{database.PAGE_TABLE, "name`"},
|
|
{database.PAGE_TABLE, `name"`},
|
|
{database.PAGE_TABLE, "(SELECT 1)"},
|
|
{database.PAGE_TABLE, ""},
|
|
{"pages p", "id"},
|
|
{"", "id"},
|
|
} {
|
|
if err := selectTableColumns(db, bad[0], []string{bad[1]}).Find(&rows).Error; err == nil {
|
|
t.Errorf("%q.%q must be refused", bad[0], bad[1])
|
|
}
|
|
}
|
|
// the refusal is an error of that query only
|
|
if err := selectTableColumns(db, database.PAGE_TABLE, []string{"id", "name"}).Find(&rows).Error; err != nil {
|
|
t.Fatalf("plain names: %v", err)
|
|
}
|
|
if err := db.Find(&rows).Error; err != nil {
|
|
t.Fatalf("the connection keeps an error: %v", err)
|
|
}
|
|
if _, err := pluckUUIDs(db.Model(&database.Page{}), "COUNT(id)"); err == nil {
|
|
t.Fatal("pluck of a column with SQL must be refused")
|
|
}
|
|
}
|
|
|
|
// TestColumnHelpersRefuseNames checks that the column, select and join
|
|
// helpers panic on a name that is no plain identifier
|
|
func TestColumnHelpersRefuseNames(t *testing.T) {
|
|
panics := func(name string, fn func()) {
|
|
t.Helper()
|
|
defer func() {
|
|
if recover() == nil {
|
|
t.Errorf("%s must panic", name)
|
|
}
|
|
}()
|
|
fn()
|
|
}
|
|
for _, bad := range []string{"", "a b", "a.b", "a`b", `a"b`, "a;--", "a)", "é", "a\n"} {
|
|
panics("col name "+bad, func() { col("t", bad) })
|
|
if bad != "" {
|
|
panics("col table "+bad, func() { col(bad, "c") })
|
|
}
|
|
panics("selectAll "+bad, func() { selectAll(bad) })
|
|
panics("selectColAs "+bad, func() { selectColAs("t", "c", bad) })
|
|
panics("LeftJoinOn "+bad, func() { LeftJoinOn("t", "c", bad, "id") })
|
|
panics("LeftJoinOnWithAlias "+bad, func() { LeftJoinOnWithAlias("t", "c", "u", "id", bad) })
|
|
if bad != "" {
|
|
panics("companyColumn "+bad, func() { companyColumn(bad) })
|
|
}
|
|
}
|
|
if c := col("", "name"); c != (clause.Column{Name: "name"}) {
|
|
t.Fatalf("a column without a table: %+v", c)
|
|
}
|
|
}
|
|
|
|
// TestOrderTermKeepsOtherOrders checks that an order term keeps the orders
|
|
// of Order calls before and after it, in place, and that the SQL is the
|
|
// order list gorm writes for columns with the term's expression at its
|
|
// place; an order expression of gorm still replaces the list
|
|
func TestOrderTermKeepsOtherOrders(t *testing.T) {
|
|
for _, db := range openDialectDBs(t) {
|
|
engine := db.Dialector.Name()
|
|
name := col("dialect_rows", "name")
|
|
ref := col("dialect_rows", "ref")
|
|
id := col("dialect_rows", "id")
|
|
build := func(q *gorm.DB) string {
|
|
t.Helper()
|
|
stmt := q.Session(&gorm.Session{DryRun: true}).Find(&[]dialectRow{}).Statement
|
|
if stmt.Error != nil {
|
|
t.Fatalf("%s: %v", engine, stmt.Error)
|
|
}
|
|
sql := stmt.SQL.String()
|
|
return sql[strings.Index(sql, "ORDER BY"):]
|
|
}
|
|
// the text of an expression and a quoted column in this engine
|
|
text := func(v any) string {
|
|
stmt := &gorm.Statement{DB: db}
|
|
stmt.AddVar(stmt, v)
|
|
return stmt.SQL.String()
|
|
}
|
|
d := dialectOf(db)
|
|
nameDesc := text(clause.Expr{SQL: d.orderBySQL(columnText, true), Vars: []any{name}})
|
|
idAsc := text(clause.Expr{SQL: d.orderBySQL(columnOther, false), Vars: []any{id}})
|
|
|
|
// a session, so each chain below starts from its own copy
|
|
base := db.Table("dialect_rows").Session(&gorm.Session{})
|
|
q := base.Order(clause.OrderByColumn{Column: ref}).
|
|
Clauses(orderByTerm(name, true)).
|
|
Order(clause.OrderByColumn{Column: id, Desc: true}).
|
|
Session(&gorm.Session{})
|
|
want := "ORDER BY " + text(ref) + "," + nameDesc + "," + text(id) + " DESC"
|
|
if got := build(q); got != want {
|
|
t.Fatalf("%s: %s\nwant %s", engine, got, want)
|
|
}
|
|
// two terms, and a copy of the statement that takes another term
|
|
// does not change the first
|
|
two := base.Clauses(orderByTerm(name, true)).Session(&gorm.Session{})
|
|
other := two.Clauses(orderByTerm(id, false))
|
|
third := two.Order(clause.OrderByColumn{Column: ref})
|
|
if got, want := build(other), "ORDER BY "+nameDesc+","+idAsc; got != want {
|
|
t.Fatalf("%s: %s\nwant %s", engine, got, want)
|
|
}
|
|
if got, want := build(third), "ORDER BY "+nameDesc+","+text(ref); got != want {
|
|
t.Fatalf("%s: %s\nwant %s", engine, got, want)
|
|
}
|
|
if got, want := build(two), "ORDER BY "+nameDesc; got != want {
|
|
t.Fatalf("%s: %s\nwant %s", engine, got, want)
|
|
}
|
|
// an order expression of gorm is written alone, as gorm does
|
|
replaced := q.Order(clause.OrderBy{Expression: clause.Expr{SQL: "?", Vars: []any{ref}}})
|
|
if got, want := build(replaced), "ORDER BY "+text(ref); got != want {
|
|
t.Fatalf("%s: %s\nwant %s", engine, got, want)
|
|
}
|
|
// the query runs, sorts and counts
|
|
ids := []int{}
|
|
if err := q.Pluck("id", &ids).Error; err != nil || len(ids) != 7 {
|
|
t.Fatalf("%s: %v %v", engine, ids, err)
|
|
}
|
|
var n int64
|
|
if err := q.Count(&n).Error; err != nil || n != 7 {
|
|
t.Fatalf("%s: count %d %v", engine, n, err)
|
|
}
|
|
// nulls first on both engines
|
|
var refs []sql.NullString
|
|
if err := base.Clauses(nullsFirst(ref)).Pluck("ref", &refs).Error; err != nil || len(refs) == 0 {
|
|
t.Fatalf("%s: %v", engine, err)
|
|
}
|
|
for i := 1; i < len(refs); i++ {
|
|
if !refs[i].Valid && refs[i-1].Valid {
|
|
t.Fatalf("%s: a null after a value", engine)
|
|
}
|
|
}
|
|
// a stand in written without the builder fails the query
|
|
bare := base.Clauses(setClause{clause.Clause{
|
|
Name: orderByClause,
|
|
Expression: clause.OrderBy{Columns: []clause.OrderByColumn{{
|
|
Column: clause.Column{Table: orderTermTable, Name: "0"},
|
|
}}},
|
|
BeforeExpression: orderTerms{clause.Expr{SQL: "?", Vars: []any{ref}}},
|
|
}})
|
|
if err := bare.Pluck("id", &ids).Error; err == nil {
|
|
t.Fatalf("%s: order terms without their builder must fail", engine)
|
|
}
|
|
}
|
|
}
|
|
|
|
// setClause puts a clause into a statement as it is
|
|
type setClause struct{ c clause.Clause }
|
|
|
|
func (s setClause) ModifyStatement(stmt *gorm.Statement) { stmt.Clauses[s.c.Name] = s.c }
|
|
|
|
func (s setClause) Build(clause.Builder) {}
|
|
|
|
// TestSortNameAllowlist checks that a sort name reaches the SQL only through
|
|
// an allowlist on each engine: a listed column sorts however its name is
|
|
// quoted, and the column gorm writes is the allowlist entry; any other name
|
|
// is refused before a query is built
|
|
func TestSortNameAllowlist(t *testing.T) {
|
|
allowed := assignTableToColumns("dialect_rows", []string{"name"})
|
|
for _, db := range openDialectDBs(t) {
|
|
engine := db.Dialector.Name()
|
|
for _, name := range []string{"name", "dialect_rows.name", "`dialect_rows`.`name`", `"dialect_rows"."name"`} {
|
|
q, err := useQuery(db.Table("dialect_rows"), "dialect_rows", &vo.QueryArgs{OrderBy: name}, allowed...)
|
|
if err != nil {
|
|
t.Fatalf("%s: %q: %v", engine, name, err)
|
|
}
|
|
ids := []int{}
|
|
if err := q.Pluck("id", &ids).Error; err != nil || len(ids) != 7 {
|
|
t.Fatalf("%s: %q: %v %v", engine, name, ids, err)
|
|
}
|
|
stmt := q.Session(&gorm.Session{DryRun: true}).Find(&[]dialectRow{}).Statement
|
|
var quoted strings.Builder
|
|
stmt.QuoteTo("ed, clause.Column{Table: "dialect_rows", Name: "name"})
|
|
if sql := stmt.SQL.String(); !strings.Contains(sql, "ORDER BY "+quoted.String()) &&
|
|
!strings.Contains(sql, "ORDER BY LOWER("+quoted.String()) {
|
|
t.Fatalf("%s: %q sorts by %s", engine, name, sql)
|
|
}
|
|
}
|
|
refused := []string{
|
|
"ref",
|
|
"dialect_rows.ref",
|
|
"other.name",
|
|
"`other`.`name`",
|
|
"name DESC",
|
|
"name; DROP TABLE dialect_rows",
|
|
"LOWER(name)",
|
|
"1",
|
|
"(SELECT 1)",
|
|
"`dialect_rows`.`name` --",
|
|
"dialect_rows.name.x",
|
|
"\"dialect_rows\".`name`",
|
|
"*",
|
|
"dialect_rows.*",
|
|
" name",
|
|
}
|
|
for _, name := range refused {
|
|
if _, err := useQuery(db.Table("dialect_rows"), "dialect_rows", &vo.QueryArgs{OrderBy: name}, allowed...); err == nil {
|
|
t.Errorf("%s: %q must be refused", engine, name)
|
|
}
|
|
if _, err := WithOrderBy(db.Table("dialect_rows"), name, false, allowed...); err == nil {
|
|
t.Errorf("%s: %q must be refused by WithOrderBy", engine, name)
|
|
}
|
|
}
|
|
// a bare name needs the table of the list, WithOrderBy has none
|
|
if _, err := WithOrderBy(db.Table("dialect_rows"), "name", false, allowed...); err == nil {
|
|
t.Errorf("%s: a bare name without a table must be refused", engine)
|
|
}
|
|
// a list without an allowlist sorts by nothing
|
|
if _, err := useQuery(db.Table("dialect_rows"), "dialect_rows", &vo.QueryArgs{OrderBy: "name"}); err == nil {
|
|
t.Errorf("%s: a sort without an allowlist must be refused", engine)
|
|
}
|
|
// the grouped stats group on an allowlisted column only
|
|
id := uuid.New()
|
|
for _, group := range []string{"email", "position; DROP TABLE campaigns", "cr.position", "`position`"} {
|
|
if _, err := (&Campaign{DB: db}).GetGroupedResultStats(context.Background(), &id, group); err == nil {
|
|
t.Errorf("%s: group %q must be refused", engine, group)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestAllowedColumnTable checks the column a sort name refers to is the
|
|
// allowlist entry with its table, never a column made from the name
|
|
func TestAllowedColumnTable(t *testing.T) {
|
|
allowed := []clause.Column{
|
|
{Table: "recipients", Name: "email"},
|
|
{Table: "Recipient", Name: "first_name"},
|
|
}
|
|
cases := map[string]clause.Column{
|
|
"email": {Table: "recipients", Name: "email"},
|
|
"recipients.email": {Table: "recipients", Name: "email"},
|
|
"`recipients`.`email`": {Table: "recipients", Name: "email"},
|
|
"Recipient.first_name": {Table: "Recipient", Name: "first_name"},
|
|
`"Recipient"."first_name"`: {Table: "Recipient", Name: "first_name"},
|
|
}
|
|
for name, want := range cases {
|
|
got, ok := allowedColumn(allowed, "recipients", name)
|
|
if !ok || got != want {
|
|
t.Errorf("%q: got %v %v, want %v", name, got, ok, want)
|
|
}
|
|
}
|
|
for _, name := range []string{"first_name", "recipient.first_name", "RECIPIENTS.email", "recipients.Email", "campaigns.email"} {
|
|
if got, ok := allowedColumn(allowed, "recipients", name); ok {
|
|
t.Errorf("%q: must be refused, got %v", name, got)
|
|
}
|
|
}
|
|
}
|
|
|
|
type capturedQuery struct {
|
|
sql string
|
|
vars []interface{}
|
|
}
|
|
|
|
// newBuilderDB opens a temp SQLite db and records the SQL and vars of every query
|
|
func newBuilderDB(t *testing.T, models ...interface{}) (*gorm.DB, *[]capturedQuery) {
|
|
t.Helper()
|
|
dsn := filepath.Join(t.TempDir(), "builder.db")
|
|
db, err := testdb.Open(t, dsn)
|
|
if err != nil {
|
|
t.Fatalf("open sqlite: %v", err)
|
|
}
|
|
if err := db.AutoMigrate(models...); err != nil {
|
|
t.Fatalf("migrate: %v", err)
|
|
}
|
|
captured := &[]capturedQuery{}
|
|
err = db.Callback().Query().After("gorm:query").Register("test:capture", func(tx *gorm.DB) {
|
|
*captured = append(*captured, capturedQuery{
|
|
sql: tx.Statement.SQL.String(),
|
|
vars: append([]interface{}{}, tx.Statement.Vars...),
|
|
})
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("register callback: %v", err)
|
|
}
|
|
return db, captured
|
|
}
|
|
|
|
func lastQuery(t *testing.T, captured *[]capturedQuery) capturedQuery {
|
|
t.Helper()
|
|
if len(*captured) == 0 {
|
|
t.Fatal("no query captured")
|
|
}
|
|
return (*captured)[len(*captured)-1]
|
|
}
|
|
|
|
// pgPlaceholder is a numbered postgres placeholder
|
|
var pgPlaceholder = regexp.MustCompile(`\$[0-9]+`)
|
|
|
|
// checkPlaceholders fails when the number of placeholders, ? on sqlite and
|
|
// $n on postgres, differs from the bound vars
|
|
func checkPlaceholders(t *testing.T, q capturedQuery) {
|
|
t.Helper()
|
|
n := strings.Count(q.sql, "?")
|
|
if testdb.IsPostgres() {
|
|
n = len(pgPlaceholder.FindAllString(q.sql, -1))
|
|
}
|
|
if n != len(q.vars) {
|
|
t.Fatalf("placeholders %d != vars %d in %q (%v)", n, len(q.vars), q.sql, q.vars)
|
|
}
|
|
}
|
|
|
|
// containsSQL reports whether sql holds want, which is written in the sqlite
|
|
// form. On postgres the backticks of want are read as double quotes and each
|
|
// ? as a numbered placeholder.
|
|
func containsSQL(sql, want string) bool {
|
|
if !testdb.IsPostgres() {
|
|
return strings.Contains(sql, want)
|
|
}
|
|
pattern := regexp.QuoteMeta(strings.ReplaceAll(want, "`", `"`))
|
|
pattern = strings.ReplaceAll(pattern, `\?`, `\$[0-9]+`)
|
|
return regexp.MustCompile(pattern).MatchString(sql)
|
|
}
|
|
|
|
func insertScript(t *testing.T, db *gorm.DB, name, body string, companyID *uuid.UUID) {
|
|
t.Helper()
|
|
id := uuid.New()
|
|
now := time.Now()
|
|
row := database.Script{ID: &id, CreatedAt: &now, UpdatedAt: &now, CompanyID: companyID, Name: name, Script: body}
|
|
if err := db.Create(&row).Error; err != nil {
|
|
t.Fatalf("insert script %s: %v", name, err)
|
|
}
|
|
}
|
|
|
|
// TestCompanyHelpersSQL checks the SQL shape of the company scope helpers
|
|
func TestCompanyHelpersSQL(t *testing.T) {
|
|
db, _ := newBuilderDB(t, &database.Script{})
|
|
companyID := uuid.New()
|
|
dry := db.Session(&gorm.Session{DryRun: true})
|
|
build := func(fn func(*gorm.DB) *gorm.DB) capturedQuery {
|
|
var rows []database.Script
|
|
stmt := fn(dry.Model(&database.Script{})).Find(&rows).Statement
|
|
return capturedQuery{sql: stmt.SQL.String(), vars: stmt.Vars}
|
|
}
|
|
cases := []struct {
|
|
name string
|
|
fn func(*gorm.DB) *gorm.DB
|
|
want string
|
|
}{
|
|
{"including null with company", func(d *gorm.DB) *gorm.DB {
|
|
return withCompanyIncludingNullContext(d, &companyID, database.SCRIPT_TABLE)
|
|
}, "WHERE (`scripts`.`company_id` = ? OR `scripts`.`company_id` IS NULL)"},
|
|
{"including null without company", func(d *gorm.DB) *gorm.DB {
|
|
return withCompanyIncludingNullContext(d, nil, database.SCRIPT_TABLE)
|
|
}, "WHERE `scripts`.`company_id` IS NULL"},
|
|
{"where company", func(d *gorm.DB) *gorm.DB {
|
|
return whereCompany(d, database.SCRIPT_TABLE, &companyID)
|
|
}, "WHERE `scripts`.`company_id` = ?"},
|
|
{"where company nil", func(d *gorm.DB) *gorm.DB {
|
|
return whereCompany(d, database.SCRIPT_TABLE, nil)
|
|
}, "WHERE `scripts`.`company_id` IS NULL"},
|
|
{"where company is null", func(d *gorm.DB) *gorm.DB {
|
|
return whereCompanyIsNull(d, database.SCRIPT_TABLE)
|
|
}, "WHERE `scripts`.`company_id` IS NULL"},
|
|
{"including null joined with and", func(d *gorm.DB) *gorm.DB {
|
|
return withCompanyIncludingNullContext(d.Where("1 = 1"), &companyID, database.SCRIPT_TABLE)
|
|
}, "WHERE 1 = 1 AND (`scripts`.`company_id` = ? OR `scripts`.`company_id` IS NULL)"},
|
|
}
|
|
for _, c := range cases {
|
|
q := build(c.fn)
|
|
if !containsSQL(q.sql, c.want) {
|
|
t.Fatalf("%s: want %q in %q", c.name, c.want, q.sql)
|
|
}
|
|
checkPlaceholders(t, q)
|
|
}
|
|
}
|
|
|
|
// TestCompanyHelpersRows checks the company helpers return a company's rows plus
|
|
// the global rows, only the global rows for no company, and only the rows with
|
|
// no company for the is null helper
|
|
func TestCompanyHelpersRows(t *testing.T) {
|
|
db, _ := newBuilderDB(t, &database.Script{})
|
|
a, b := uuid.New(), uuid.New()
|
|
insertScript(t, db, "global", "g", nil)
|
|
insertScript(t, db, "a1", "a", &a)
|
|
insertScript(t, db, "b1", "b", &b)
|
|
|
|
count := func(d *gorm.DB) int64 {
|
|
var n int64
|
|
if err := d.Model(&database.Script{}).Count(&n).Error; err != nil {
|
|
t.Fatalf("count: %v", err)
|
|
}
|
|
return n
|
|
}
|
|
if n := count(withCompanyIncludingNullContext(db, &a, database.SCRIPT_TABLE)); n != 2 {
|
|
t.Fatalf("company a plus global: want 2, got %d", n)
|
|
}
|
|
if n := count(withCompanyIncludingNullContext(db, nil, database.SCRIPT_TABLE)); n != 1 {
|
|
t.Fatalf("global only: want 1, got %d", n)
|
|
}
|
|
if n := count(whereCompany(db, database.SCRIPT_TABLE, &b)); n != 1 {
|
|
t.Fatalf("company b: want 1, got %d", n)
|
|
}
|
|
if n := count(whereCompany(db, database.SCRIPT_TABLE, nil)); n != 1 {
|
|
t.Fatalf("company nil: want 1, got %d", n)
|
|
}
|
|
if n := count(whereCompanyIsNull(db, database.SCRIPT_TABLE)); n != 1 {
|
|
t.Fatalf("company is null: want 1, got %d", n)
|
|
}
|
|
}
|
|
|
|
// TestNameLookupPlaceholders checks every name lookup binds one var per placeholder
|
|
// and is scoped to the right company, with and without a company id
|
|
func TestNameLookupPlaceholders(t *testing.T) {
|
|
db, captured := newBuilderDB(t,
|
|
&database.SMTPConfiguration{},
|
|
&database.RecipientGroup{},
|
|
&database.Email{},
|
|
&database.Page{},
|
|
&database.Proxy{},
|
|
&database.APISender{},
|
|
&database.RemoteBrowser{},
|
|
&database.Domain{},
|
|
&database.Identifier{},
|
|
&database.Webhook{},
|
|
)
|
|
ctx := context.Background()
|
|
companyID := uuid.New()
|
|
n64 := vo.NewString64Must("missing")
|
|
n127 := vo.NewString127Must("missing")
|
|
n255 := vo.NewString255Must("missing")
|
|
|
|
type lookup struct {
|
|
name string
|
|
run func(c *uuid.UUID) error
|
|
scoped bool
|
|
wantWith string
|
|
wantNil string
|
|
}
|
|
lookups := []lookup{
|
|
{"smtp", func(c *uuid.UUID) error {
|
|
_, err := (&SMTPConfiguration{DB: db}).GetByNameAndCompanyID(ctx, n127, c, &SMTPConfigurationOption{})
|
|
return err
|
|
}, true, "`smtp_configurations`.`company_id` = ?", "`smtp_configurations`.`company_id` IS NULL"},
|
|
{"recipient group", func(c *uuid.UUID) error {
|
|
_, err := (&RecipientGroup{DB: db}).GetByNameAndCompanyID(ctx, "missing", c, &RecipientGroupOption{})
|
|
return err
|
|
}, true, "`recipient_groups`.`company_id` = ?", "`recipient_groups`.`company_id` IS NULL"},
|
|
{"email", func(c *uuid.UUID) error {
|
|
_, err := (&Email{DB: db}).GetByNameAndCompanyID(ctx, n64, c, &EmailOption{})
|
|
return err
|
|
}, true, "`emails`.`company_id` = ?", "`emails`.`company_id` IS NULL"},
|
|
{"page", func(c *uuid.UUID) error {
|
|
_, err := (&Page{DB: db}).GetByNameAndCompanyID(ctx, n64, c, &PageOption{})
|
|
return err
|
|
}, true, "(`pages`.`company_id` = ? OR `pages`.`company_id` IS NULL)", "`pages`.`company_id` IS NULL"},
|
|
{"proxy", func(c *uuid.UUID) error {
|
|
_, err := (&Proxy{DB: db}).GetByNameAndCompanyID(ctx, n64, c, &ProxyOption{})
|
|
return err
|
|
}, true, "(`proxies`.`company_id` = ? OR `proxies`.`company_id` IS NULL)", "`proxies`.`company_id` IS NULL"},
|
|
{"api sender", func(c *uuid.UUID) error {
|
|
_, err := (&APISender{DB: db}).GetByName(ctx, n64, c, &APISenderOption{})
|
|
return err
|
|
}, true,
|
|
"(`api_senders`.`company_id` = ? OR `api_senders`.`company_id` IS NULL)",
|
|
"`api_senders`.`company_id` IS NULL",
|
|
},
|
|
{"remote browser", func(c *uuid.UUID) error {
|
|
_, err := (&RemoteBrowser{DB: db}).GetByNameAndCompanyID(ctx, n64, c, &RemoteBrowserOption{})
|
|
return err
|
|
}, true,
|
|
"(`remote_browsers`.`company_id` = ? OR `remote_browsers`.`company_id` IS NULL)",
|
|
"`remote_browsers`.`company_id` IS NULL",
|
|
},
|
|
{"domain", func(c *uuid.UUID) error {
|
|
_, err := (&Domain{DB: db}).GetByName(ctx, n255, &DomainOption{})
|
|
return err
|
|
}, false, "`domains`.`name` = ?", "`domains`.`name` = ?"},
|
|
{"identifier", func(c *uuid.UUID) error {
|
|
_, err := (&Identifier{DB: db}).GetByName(ctx, "missing")
|
|
return err
|
|
}, false, "`identifiers`.`name` = ?", "`identifiers`.`name` = ?"},
|
|
{"webhook", func(c *uuid.UUID) error {
|
|
_, err := (&Webhook{DB: db}).GetByName(ctx, n127)
|
|
return err
|
|
}, false, "`webhooks`.`name` = ?", "`webhooks`.`name` = ?"},
|
|
}
|
|
for _, l := range lookups {
|
|
for _, c := range []*uuid.UUID{&companyID, nil} {
|
|
if err := l.run(c); err != gorm.ErrRecordNotFound {
|
|
t.Fatalf("%s: want record not found, got %v", l.name, err)
|
|
}
|
|
q := lastQuery(t, captured)
|
|
checkPlaceholders(t, q)
|
|
want := l.wantWith
|
|
if c == nil {
|
|
want = l.wantNil
|
|
}
|
|
if !containsSQL(q.sql, want) {
|
|
t.Fatalf("%s: want %q in %q", l.name, want, q.sql)
|
|
}
|
|
if !containsSQL(q.sql, ".`name` = ?") {
|
|
t.Fatalf("%s: missing name filter in %q", l.name, q.sql)
|
|
}
|
|
if !l.scoped {
|
|
break
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestCheckColumnIsUnique checks the unique check sees global and company rows
|
|
func TestCheckColumnIsUnique(t *testing.T) {
|
|
db, captured := newBuilderDB(t, &database.Script{})
|
|
a, b := uuid.New(), uuid.New()
|
|
insertScript(t, db, "global", "g", nil)
|
|
insertScript(t, db, "a1", "a", &a)
|
|
ctx := context.Background()
|
|
|
|
cases := []struct {
|
|
name string
|
|
companyID *uuid.UUID
|
|
want bool
|
|
}{
|
|
{"global", &b, false},
|
|
{"a1", &a, false},
|
|
{"a1", &b, true},
|
|
{"a1", nil, false},
|
|
{"fresh", &a, true},
|
|
{"fresh", nil, true},
|
|
}
|
|
for _, c := range cases {
|
|
ok, err := CheckNameIsUnique(ctx, db, database.SCRIPT_TABLE, c.name, c.companyID, nil)
|
|
if err != nil {
|
|
t.Fatalf("%s: %v", c.name, err)
|
|
}
|
|
if ok != c.want {
|
|
t.Fatalf("%s company %v: want unique %v, got %v", c.name, c.companyID, c.want, ok)
|
|
}
|
|
checkPlaceholders(t, lastQuery(t, captured))
|
|
}
|
|
var row database.Script
|
|
if err := db.Where("name = ?", "a1").First(&row).Error; err != nil {
|
|
t.Fatalf("load a1: %v", err)
|
|
}
|
|
ok, err := CheckNameIsUnique(ctx, db, database.SCRIPT_TABLE, "a1", &a, row.ID)
|
|
if err != nil || !ok {
|
|
t.Fatalf("own row must not clash: ok %v err %v", ok, err)
|
|
}
|
|
}
|
|
|
|
// TestUseQuerySearchOnRootHandle checks that a search is kept when useQuery
|
|
// gets the root handle with no paging and no sort. A Where on the root handle
|
|
// starts a new statement, so the search is only kept when the returned handle
|
|
// is used.
|
|
func TestUseQuerySearchOnRootHandle(t *testing.T) {
|
|
for _, db := range openParityDBs(t) {
|
|
engine := db.Dialector.Name()
|
|
q, err := useQuery(db, "parity_rows", &vo.QueryArgs{Search: "lund"}, col("parity_rows", "name"))
|
|
if err != nil {
|
|
t.Fatalf("%s: %v", engine, err)
|
|
}
|
|
ids := []int{}
|
|
if err := q.Table("parity_rows").Order("id").Pluck("id", &ids).Error; err != nil {
|
|
t.Fatalf("%s: %v", engine, err)
|
|
}
|
|
if !reflect.DeepEqual(ids, []int{6, 7}) {
|
|
t.Fatalf("%s: search on the root handle found %v, want [6 7]", engine, ids)
|
|
}
|
|
// the root handle itself is left as it was
|
|
all := []int{}
|
|
if err := db.Table("parity_rows").Pluck("id", &all).Error; err != nil {
|
|
t.Fatalf("%s: %v", engine, err)
|
|
}
|
|
if len(all) != len(parityNames) {
|
|
t.Fatalf("%s: root handle reads %d rows, want %d", engine, len(all), len(parityNames))
|
|
}
|
|
}
|
|
}
|