mirror of
https://github.com/phishingclub/phishingclub.git
synced 2026-12-06 10:03:46 +01:00
327 lines
12 KiB
Go
327 lines
12 KiB
Go
package repository
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/oapi-codegen/nullable"
|
|
"github.com/phishingclub/phishingclub/database"
|
|
"github.com/phishingclub/phishingclub/database/dbengine"
|
|
"github.com/phishingclub/phishingclub/model"
|
|
"github.com/phishingclub/phishingclub/testdb"
|
|
"github.com/phishingclub/phishingclub/vo"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// dirtyAgent is a user agent with a NUL and bytes that are not UTF-8, as a
|
|
// client can send in a header
|
|
const dirtyAgent = "Mozilla\x00/5.0 \xff\xfe"
|
|
|
|
// dirtyData is a submitted JSON body with a NUL escape turned into a raw NUL
|
|
// and a Latin-1 byte
|
|
const dirtyData = "{\"user\":\"a\x00b\",\"note\":\"caf\xe9\"}"
|
|
|
|
// stored is what the engine keeps of s: postgres the cleaned text, sqlite
|
|
// every byte
|
|
func stored(s string) string {
|
|
if testdb.IsPostgres() {
|
|
return dbengine.CleanText(s)
|
|
}
|
|
return s
|
|
}
|
|
|
|
// TestEventTextRoundTrip saves events with a NUL and invalid UTF-8 in the
|
|
// user agent and the data through both event writes and reads them back:
|
|
// postgres keeps the cleaned text, sqlite every byte. A user agent cut at
|
|
// its 255 byte limit inside a rune and data at its 1 MB limit full of NULs
|
|
// still read back into the vo types, so the cleaning never makes a value
|
|
// longer than the limit it was checked against.
|
|
func TestEventTextRoundTrip(t *testing.T) {
|
|
db := newProgramTestDB(t)
|
|
ctx := context.Background()
|
|
repo := &Campaign{DB: db}
|
|
camp := ptrUUID()
|
|
createHiddenCampaign(t, db, camp, nil)
|
|
|
|
cutAgent := strings.Repeat("a", 253) + "\xe2\x82"
|
|
fullData := strings.Repeat("x\x00", 500000)
|
|
cases := []struct {
|
|
name string
|
|
agent, data string
|
|
save func(context.Context, *model.CampaignEvent) error
|
|
}{
|
|
{"save", dirtyAgent, dirtyData, repo.SaveEvent},
|
|
{"save if open", dirtyAgent, dirtyData, repo.SaveEventIfOpen},
|
|
{"limits", cutAgent, fullData, repo.SaveEvent},
|
|
}
|
|
for _, c := range cases {
|
|
id := uuid.New()
|
|
ev := &model.CampaignEvent{
|
|
ID: &id, CampaignID: camp, RecipientID: ptrUUID(), EventID: ptrUUID(),
|
|
IP: vo.NewOptionalString64Must("198.51.100.7"),
|
|
UserAgent: vo.NewOptionalString255Must(c.agent),
|
|
Data: vo.NewOptionalString1MBMust(c.data),
|
|
Metadata: vo.NewEmptyOptionalString1MB(),
|
|
}
|
|
if err := c.save(ctx, ev); err != nil {
|
|
t.Fatalf("%s: %v", c.name, err)
|
|
}
|
|
if ev.UserAgent.String() != c.agent || ev.Data.String() != c.data {
|
|
t.Fatalf("%s: the event of the caller changed", c.name)
|
|
}
|
|
row, err := repo.GetEventByID(ctx, &id)
|
|
if err != nil {
|
|
t.Fatalf("%s: read: %v", c.name, err)
|
|
}
|
|
if row.UserAgent != stored(c.agent) {
|
|
t.Errorf("%s: user agent %q, want %q", c.name, row.UserAgent, stored(c.agent))
|
|
}
|
|
if row.Data != stored(c.data) {
|
|
t.Errorf("%s: data %q, want %q", c.name, row.Data, stored(c.data))
|
|
}
|
|
if _, err := ToCampaignEvent(row); err != nil {
|
|
t.Errorf("%s: to model: %v", c.name, err)
|
|
}
|
|
}
|
|
result, err := repo.GetEventsByCampaignID(ctx, camp, &CampaignEventOption{QueryArgs: &vo.QueryArgs{}}, nil)
|
|
if err != nil {
|
|
t.Fatalf("list: %v", err)
|
|
}
|
|
if len(result.Rows) != len(cases) {
|
|
t.Fatalf("listed %d events, want %d", len(result.Rows), len(cases))
|
|
}
|
|
}
|
|
|
|
// textCleanRow is a table for the bound value forms of gorm
|
|
type textCleanRow struct {
|
|
ID uuid.UUID `gorm:"primaryKey;type:uuid"`
|
|
Body string
|
|
Note *string
|
|
}
|
|
|
|
// TestBoundTextForms writes and finds text with a NUL and invalid UTF-8 in
|
|
// every way gorm binds a value: create, map updates, raw exec, batches, IN
|
|
// lists, a nested transaction. postgres stores and matches the cleaned text,
|
|
// sqlite every byte, and a lookup by the dirty value finds its row on both.
|
|
func TestBoundTextForms(t *testing.T) {
|
|
dsn := filepath.Join(t.TempDir(), "text.db")
|
|
db, err := testdb.OpenMigrated(t, dsn, testdb.Migration{Steps: []testdb.Step{testdb.AutoMigrate(&textCleanRow{})}})
|
|
if err != nil {
|
|
t.Fatalf("open: %v", err)
|
|
}
|
|
body := func(id uuid.UUID) string {
|
|
t.Helper()
|
|
var got []string
|
|
if err := db.Model(&textCleanRow{}).Where("id = ?", id).Pluck("body", &got).Error; err != nil || len(got) != 1 {
|
|
t.Fatalf("read %s: %v %v", id, got, err)
|
|
}
|
|
return got[0]
|
|
}
|
|
findBy := func(value string) []uuid.UUID {
|
|
t.Helper()
|
|
var ids []uuid.UUID
|
|
if err := db.Model(&textCleanRow{}).Where("body = ?", value).Order("id").Pluck("id", &ids).Error; err != nil {
|
|
t.Fatalf("find: %v", err)
|
|
}
|
|
return ids
|
|
}
|
|
|
|
note := dirtyAgent
|
|
created := textCleanRow{ID: uuid.New(), Body: dirtyData, Note: ¬e}
|
|
if err := db.Create(&created).Error; err != nil {
|
|
t.Fatalf("create: %v", err)
|
|
}
|
|
if created.Body != dirtyData || note != dirtyAgent {
|
|
t.Fatal("create changed the row of the caller")
|
|
}
|
|
if got := body(created.ID); got != stored(dirtyData) {
|
|
t.Errorf("create: %q", got)
|
|
}
|
|
if ids := findBy(dirtyData); len(ids) != 1 || ids[0] != created.ID {
|
|
t.Errorf("lookup by the dirty value: %v", ids)
|
|
}
|
|
|
|
// map updates
|
|
if err := db.Model(&textCleanRow{}).Where("id = ?", created.ID).
|
|
Updates(map[string]any{"body": "upd\x00\xc3("}).Error; err != nil {
|
|
t.Fatalf("updates: %v", err)
|
|
}
|
|
if got := body(created.ID); got != stored("upd\x00\xc3(") {
|
|
t.Errorf("updates: %q", got)
|
|
}
|
|
|
|
// raw exec with ? values
|
|
if err := db.Exec("UPDATE text_clean_rows SET body = ? WHERE body = ?", "exec\xff", "upd\x00\xc3(").Error; err != nil {
|
|
t.Fatalf("exec: %v", err)
|
|
}
|
|
if got := body(created.ID); got != stored("exec\xff") {
|
|
t.Errorf("exec: %q", got)
|
|
}
|
|
|
|
// batches, then an IN list of more than one value, which is one array
|
|
// parameter on postgres
|
|
batch := []textCleanRow{
|
|
{ID: uuid.New(), Body: "batch one \x00"},
|
|
{ID: uuid.New(), Body: "batch two \xfe"},
|
|
{ID: uuid.New(), Body: "batch three"},
|
|
}
|
|
if err := db.CreateInBatches(&batch, 2).Error; err != nil {
|
|
t.Fatalf("batches: %v", err)
|
|
}
|
|
for _, b := range batch {
|
|
if got := body(b.ID); got != stored(b.Body) {
|
|
t.Errorf("batch: %q", got)
|
|
}
|
|
}
|
|
var inIDs []uuid.UUID
|
|
if err := db.Model(&textCleanRow{}).Where("body IN ?", []string{"batch one \x00", "batch two \xfe"}).
|
|
Pluck("id", &inIDs).Error; err != nil {
|
|
t.Fatalf("in list: %v", err)
|
|
}
|
|
if len(inIDs) != 2 {
|
|
t.Errorf("in list found %d rows, want 2", len(inIDs))
|
|
}
|
|
|
|
// a nested transaction, a savepoint, rolled back and committed
|
|
err = db.Transaction(func(tx *gorm.DB) error {
|
|
if err := tx.Transaction(func(inner *gorm.DB) error {
|
|
if err := inner.Model(&textCleanRow{}).Where("id = ?", created.ID).Update("body", "rolled\x00back").Error; err != nil {
|
|
return err
|
|
}
|
|
return errors.New("roll back the savepoint")
|
|
}); err == nil {
|
|
return errors.New("the inner transaction did not fail")
|
|
}
|
|
return tx.Transaction(func(inner *gorm.DB) error {
|
|
return inner.Model(&textCleanRow{}).Where("id = ?", created.ID).Update("body", "saved\x00\xff").Error
|
|
})
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("nested transaction: %v", err)
|
|
}
|
|
if got := body(created.ID); got != stored("saved\x00\xff") {
|
|
t.Errorf("nested transaction: %q", got)
|
|
}
|
|
}
|
|
|
|
// TestDirtyLookupsMiss looks up values with a NUL or invalid UTF-8 that match
|
|
// no row: every engine answers with a plain miss, never a database error, so
|
|
// a scanner probing the phishing server sees the same on both
|
|
func TestDirtyLookupsMiss(t *testing.T) {
|
|
db := newProgramTestDB(t)
|
|
ctx := context.Background()
|
|
camp := ptrUUID()
|
|
createHiddenCampaign(t, db, camp, nil)
|
|
cr := addCampaignRecipient(t, db, camp, ptrUUID(), nil, true)
|
|
if err := db.Model(&database.CampaignRecipient{}).Where("id = ?", cr).
|
|
Updates(map[string]any{"message_id": "ab@send.example", "lure_code": "AB12CD"}).Error; err != nil {
|
|
t.Fatalf("recipient: %v", err)
|
|
}
|
|
recipients := &CampaignRecipient{DB: db}
|
|
|
|
for _, id := range []string{"a\x00b", "ab@send.example\xff", "ab\x00@send.example"} {
|
|
if _, err := recipients.GetByMessageID(ctx, id); !errors.Is(err, gorm.ErrRecordNotFound) {
|
|
t.Errorf("message id %q: %v, want not found", id, err)
|
|
}
|
|
used, err := (&ReportInbox{DB: db}).MessageIDUsed(ctx, id)
|
|
if err != nil || used {
|
|
t.Errorf("message id used %q: %v %v", id, used, err)
|
|
}
|
|
}
|
|
domainID := uuid.New()
|
|
for _, code := range []string{"\xc3(", "AB12CD\x00", "AB\xff12CD"} {
|
|
if _, err := recipients.GetByLureCodeOnDomain(ctx, code, &database.Domain{ID: domainID}); !errors.Is(err, gorm.ErrRecordNotFound) {
|
|
t.Errorf("lure code %q: %v, want not found", code, err)
|
|
}
|
|
}
|
|
campaigns := &Campaign{DB: db}
|
|
for _, term := range []string{"zz\x00zz", "zz\xffzz"} {
|
|
result, err := campaigns.GetAll(ctx, nil, &CampaignOption{QueryArgs: &vo.QueryArgs{Search: term}, WithCampaignTemplate: true})
|
|
if err != nil {
|
|
t.Errorf("search %q: %v", term, err)
|
|
continue
|
|
}
|
|
if len(result.Rows) != 0 {
|
|
t.Errorf("search %q found %d campaigns", term, len(result.Rows))
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestLongProviderTokens stores provider tokens longer than the old
|
|
// varchar(4096) column and a tenant domain longer than the old varchar(255)
|
|
// column, the lengths an Entra token with group claims and a long tenant
|
|
// domain reach. Both engines keep every character.
|
|
func TestLongProviderTokens(t *testing.T) {
|
|
dsn := filepath.Join(t.TempDir(), "oauth.db")
|
|
db, err := testdb.OpenMigrated(t, dsn, testdb.Migration{ForeignKeysOff: true, Steps: []testdb.Step{
|
|
testdb.AutoMigrate(&database.Company{}, &database.OAuthProvider{}, &database.ReportInbox{}),
|
|
}})
|
|
if err != nil {
|
|
t.Fatalf("open: %v", err)
|
|
}
|
|
ctx := context.Background()
|
|
providers := &OAuthProvider{DB: db}
|
|
access, refresh := strings.Repeat("A", 6000), strings.Repeat("R", 6000)
|
|
|
|
// the insert the token import makes
|
|
id, err := providers.Insert(ctx, &model.OAuthProvider{
|
|
Name: nullable.NewNullableWithValue(*vo.NewString127Must("imported")),
|
|
AuthURL: nullable.NewNullableWithValue(*vo.NewString512Must("n/a")),
|
|
TokenURL: nullable.NewNullableWithValue(*vo.NewString512Must("https://login.example.com/token")),
|
|
Scopes: nullable.NewNullableWithValue(*vo.NewString2048Must("offline_access")),
|
|
ClientID: nullable.NewNullableWithValue(*vo.NewString255Must("client")),
|
|
ClientSecret: nullable.NewNullableWithValue(*vo.NewOptionalString255Must("n/a")),
|
|
AccessToken: nullable.NewNullableWithValue(*vo.NewOptionalString1MBMust(access)),
|
|
RefreshToken: nullable.NewNullableWithValue(*vo.NewOptionalString1MBMust(refresh)),
|
|
AuthorizedEmail: nullable.NewNullableWithValue(*vo.NewOptionalString255Must("ops@example.com")),
|
|
IsAuthorized: nullable.NewNullableWithValue(true),
|
|
IsImported: nullable.NewNullableWithValue(true),
|
|
CompanyID: nullable.NewNullNullable[uuid.UUID](),
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("insert: %v", err)
|
|
}
|
|
got, err := providers.GetByID(ctx, *id)
|
|
if err != nil {
|
|
t.Fatalf("read: %v", err)
|
|
}
|
|
if got.AccessToken.MustGet().String() != access || got.RefreshToken.MustGet().String() != refresh {
|
|
t.Fatal("imported tokens not kept in full")
|
|
}
|
|
|
|
// the refresh write
|
|
access, refresh = strings.Repeat("B", 6100), strings.Repeat("S", 6100)
|
|
if err := providers.UpdateTokens(ctx, *id, access, refresh, time.Now().Add(time.Hour)); err != nil {
|
|
t.Fatalf("update tokens: %v", err)
|
|
}
|
|
got, err = providers.GetByID(ctx, *id)
|
|
if err != nil {
|
|
t.Fatalf("read: %v", err)
|
|
}
|
|
if got.AccessToken.MustGet().String() != access || got.RefreshToken.MustGet().String() != refresh {
|
|
t.Fatal("refreshed tokens not kept in full")
|
|
}
|
|
|
|
tenant := strings.Repeat("sub.", 73) + "example.com"
|
|
inboxes := &ReportInbox{DB: db}
|
|
inboxID, err := inboxes.Insert(ctx, &model.ReportInbox{
|
|
AuthMode: "app", Mailbox: "report@example.com", TenantID: tenant,
|
|
ClientID: uuid.NewString(), ClientSecret: "secret",
|
|
}, nil)
|
|
if err != nil {
|
|
t.Fatalf("inbox insert: %v", err)
|
|
}
|
|
inbox, err := inboxes.GetByID(ctx, inboxID)
|
|
if err != nil {
|
|
t.Fatalf("inbox read: %v", err)
|
|
}
|
|
if len(tenant) < 300 || inbox.TenantID != tenant {
|
|
t.Fatalf("tenant domain of %d characters not kept: %d", len(tenant), len(inbox.TenantID))
|
|
}
|
|
}
|