mirror of
https://github.com/phishingclub/phishingclub.git
synced 2026-12-06 01:53:42 +01:00
292 lines
9.9 KiB
Go
292 lines
9.9 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"net/url"
|
|
"strings"
|
|
"testing"
|
|
"text/template"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/oapi-codegen/nullable"
|
|
"github.com/phishingclub/phishingclub/data"
|
|
"github.com/phishingclub/phishingclub/model"
|
|
"github.com/phishingclub/phishingclub/utils"
|
|
"github.com/phishingclub/phishingclub/vo"
|
|
)
|
|
|
|
const randomRecipientContent = `{{.RandomRecipient.FirstName}} {{.RandomRecipient.LastName}} {{.RandomRecipient.Email}}`
|
|
|
|
// The template service has no recipient repository here, so any attempt to
|
|
// read a real recipient panics and fails the test.
|
|
|
|
func TestReportPageRenderUsesFakeRandomRecipient(t *testing.T) {
|
|
ts := &Template{}
|
|
page := &model.Page{
|
|
Content: nullable.NewNullableWithValue(*vo.NewOptionalString1MBMust(randomRecipientContent)),
|
|
}
|
|
buf, err := ts.CreatePageMockForReport(context.Background(), page, nil, "example.test", "/")
|
|
if err != nil {
|
|
t.Fatalf("render page: %v", err)
|
|
}
|
|
if got := buf.String(); got != "John Smith john.smith@example.test" {
|
|
t.Fatalf("unexpected page output %q", got)
|
|
}
|
|
}
|
|
|
|
func TestReportEmailRenderUsesFakeRandomRecipient(t *testing.T) {
|
|
ts := &Template{}
|
|
email := model.NewEmailExample()
|
|
email.Content = nullable.NewNullableWithValue(*vo.NewOptionalString1MBMust(randomRecipientContent))
|
|
out, err := ts.CreateMailBodyForReport(email, "example.test", "/")
|
|
if err != nil {
|
|
t.Fatalf("render email: %v", err)
|
|
}
|
|
if !strings.Contains(out, "John Smith john.smith@example.test") {
|
|
t.Fatalf("unexpected email output %q", out)
|
|
}
|
|
}
|
|
|
|
func TestReportRendersUsePlainRecipientEmail(t *testing.T) {
|
|
ts := &Template{}
|
|
content := `{{.Email}}`
|
|
page := &model.Page{Content: nullable.NewNullableWithValue(*vo.NewOptionalString1MBMust(content))}
|
|
buf, err := ts.CreatePageMockForReport(context.Background(), page, nil, "example.test", "/")
|
|
if err != nil || buf.String() != "rick@company.test" {
|
|
t.Fatalf("page: got %q %v", buf.String(), err)
|
|
}
|
|
email := model.NewEmailExample()
|
|
email.Content = nullable.NewNullableWithValue(*vo.NewOptionalString1MBMust(content))
|
|
out, err := ts.CreateMailBodyForReport(email, "example.test", "/")
|
|
if err != nil || out != "rick@company.test" {
|
|
t.Fatalf("email: got %q %v", out, err)
|
|
}
|
|
}
|
|
|
|
func TestReportEmailSubjectRender(t *testing.T) {
|
|
ts := &Template{}
|
|
email := model.NewEmailExample()
|
|
email.MailHeaderSubject = nullable.NewNullableWithValue(*vo.NewOptionalString255Must(`Hi {{.FirstName}}, {{.RandomRecipient.FirstName}} shared a file`))
|
|
out, err := ts.CreateMailSubjectForReport(email, "example.test", "/")
|
|
if err != nil {
|
|
t.Fatalf("render subject: %v", err)
|
|
}
|
|
want := "Hi " + reportExampleRecipient().FirstName.MustGet().String() + ", John shared a file"
|
|
if out != want {
|
|
t.Fatalf("got subject %q, want %q", out, want)
|
|
}
|
|
}
|
|
|
|
// Checking a template on save uses the fixed mock for {{.RandomRecipient}}, so
|
|
// no real recipient is read.
|
|
|
|
func TestValidatePageTemplateUsesFakeRandomRecipient(t *testing.T) {
|
|
ts := &Template{}
|
|
if err := ts.ValidatePageTemplate(randomRecipientContent); err != nil {
|
|
t.Fatalf("validate page: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestValidateEmailTemplateUsesFakeRandomRecipient(t *testing.T) {
|
|
ts := &Template{}
|
|
if err := ts.ValidateEmailTemplate(randomRecipientContent); err != nil {
|
|
t.Fatalf("validate email: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestFormatDate(t *testing.T) {
|
|
// 5 Jan 2026 07:08:09 in the morning, so leading zeros and am show up
|
|
morning := time.Date(2026, time.January, 5, 7, 8, 9, 0, time.UTC)
|
|
// 25 Dec 2026 19:30:45 in the evening
|
|
evening := time.Date(2026, time.December, 25, 19, 30, 45, 0, time.UTC)
|
|
|
|
cases := []struct {
|
|
name string
|
|
t time.Time
|
|
format string
|
|
want string
|
|
}{
|
|
{"full date", morning, "Y-m-d H:i:s", "2026-01-05 07:08:09"},
|
|
{"short year", morning, "y/n/j", "26/1/5"},
|
|
{"short month name", morning, "M", "Jan"},
|
|
{"full month name", morning, "F", "January"},
|
|
{"month names in a sentence", evening, "d F Y", "25 December 2026"},
|
|
{"short month with am", morning, "M j, g:i a", "Jan 5, 7:08 am"},
|
|
{"24 hour without leading zero", morning, "G", "7"},
|
|
{"24 hour without leading zero evening", evening, "G:i", "19:30"},
|
|
{"12 hour", evening, "h:i A", "07:30 PM"},
|
|
{"12 hour no zero", evening, "g a", "7 pm"},
|
|
{"punctuation kept", morning, "(Y) [m]", "(2026) [01]"},
|
|
{"go layout digits are literal", morning, "1 2 3", "1 2 3"},
|
|
{"empty", morning, "", ""},
|
|
}
|
|
for _, c := range cases {
|
|
t.Run(c.name, func(t *testing.T) {
|
|
got := formatDate(c.t, c.format)
|
|
if got != c.want {
|
|
t.Fatalf("formatDate(%q) = %q, want %q", c.format, got, c.want)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// decryptState pulls the state parameter out of a built flow url and decrypts it back to
|
|
// the page type it encodes, so the test can assert the url points at the right stage.
|
|
func decryptState(t *testing.T, rawURL string, stateKey string, secret string) string {
|
|
t.Helper()
|
|
parsed, err := url.Parse(rawURL)
|
|
if err != nil {
|
|
t.Fatalf("failed to parse url %q: %v", rawURL, err)
|
|
}
|
|
state := parsed.Query().Get(stateKey)
|
|
if state == "" {
|
|
t.Fatalf("url %q has no %q state param", rawURL, stateKey)
|
|
}
|
|
page, err := utils.Decrypt(state, secret)
|
|
if err != nil {
|
|
t.Fatalf("failed to decrypt state %q: %v", state, err)
|
|
}
|
|
return page
|
|
}
|
|
|
|
func TestBuildFlowPageURLs(t *testing.T) {
|
|
campaignID := uuid.New()
|
|
secret := utils.UUIDToSecret(&campaignID)
|
|
crid := uuid.New().String()
|
|
|
|
base := FlowPageURLParams{
|
|
BaseURL: "https://example.test",
|
|
URLPath: "/login",
|
|
URLIdentifier: "id",
|
|
StateIdentifier: "state",
|
|
CampaignRecipientID: crid,
|
|
CampaignID: campaignID,
|
|
}
|
|
|
|
t.Run("all stages present", func(t *testing.T) {
|
|
p := base
|
|
p.HasBeforePage = true
|
|
p.HasAfterPage = true
|
|
before, landing, after := BuildFlowPageURLs(p)
|
|
|
|
for name, u := range map[string]string{"before": before, "landing": landing, "after": after} {
|
|
if u == "" {
|
|
t.Fatalf("%s url is empty, expected a value", name)
|
|
}
|
|
parsed, err := url.Parse(u)
|
|
if err != nil {
|
|
t.Fatalf("%s url %q did not parse: %v", name, u, err)
|
|
}
|
|
if got := parsed.Query().Get("id"); got != crid {
|
|
t.Errorf("%s url id param = %q, want %q", name, got, crid)
|
|
}
|
|
if parsed.Path != "/login" {
|
|
t.Errorf("%s url path = %q, want /login", name, parsed.Path)
|
|
}
|
|
}
|
|
|
|
if got := decryptState(t, before, "state", secret); got != data.PAGE_TYPE_BEFORE {
|
|
t.Errorf("before state = %q, want %q", got, data.PAGE_TYPE_BEFORE)
|
|
}
|
|
if got := decryptState(t, landing, "state", secret); got != data.PAGE_TYPE_LANDING {
|
|
t.Errorf("landing state = %q, want %q", got, data.PAGE_TYPE_LANDING)
|
|
}
|
|
if got := decryptState(t, after, "state", secret); got != data.PAGE_TYPE_AFTER {
|
|
t.Errorf("after state = %q, want %q", got, data.PAGE_TYPE_AFTER)
|
|
}
|
|
})
|
|
|
|
t.Run("no before or after stage renders empty", func(t *testing.T) {
|
|
before, landing, after := BuildFlowPageURLs(base)
|
|
if before != "" {
|
|
t.Errorf("before url = %q, want empty when stage absent", before)
|
|
}
|
|
if after != "" {
|
|
t.Errorf("after url = %q, want empty when stage absent", after)
|
|
}
|
|
if landing == "" {
|
|
t.Fatal("landing url is empty, want a value since landing is always present")
|
|
}
|
|
if got := decryptState(t, landing, "state", secret); got != data.PAGE_TYPE_LANDING {
|
|
t.Errorf("landing state = %q, want %q", got, data.PAGE_TYPE_LANDING)
|
|
}
|
|
})
|
|
}
|
|
|
|
func TestTemplateMathFunctions(t *testing.T) {
|
|
render := func(text string, data any) (string, error) {
|
|
tmpl, err := template.New("").Funcs(TemplateFuncs()).Parse(text)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
var b strings.Builder
|
|
err = tmpl.Execute(&b, data)
|
|
return b.String(), err
|
|
}
|
|
data := map[string]any{"Rate": 26.7, "Count": int64(32), "Total": 120, "Pct": "27", "Rows": []string{"a", "b", "c"}}
|
|
cases := map[string]string{
|
|
`{{mul .Rate 2}}`: "53.4",
|
|
`{{mul .Count 2}}`: "64",
|
|
`{{mul .Pct 2}}`: "54",
|
|
`{{add .Count 0.5}}`: "32.5",
|
|
`{{sub .Total .Count}}`: "88",
|
|
`{{printf "%.2f" (div .Count .Total)}}`: "0.27",
|
|
`{{div .Count 0}}`: "0",
|
|
`{{range $i, $r := .Rows}}{{mul $i 40}} {{end}}`: "0 40 80 ",
|
|
`{{printf "%.3f" (add (mul .Rate 3.1416) (sub 100 .Pct))}}`: "156.881",
|
|
}
|
|
for text, want := range cases {
|
|
if got, err := render(text, data); err != nil || got != want {
|
|
t.Errorf("%s = %q %v, want %q", text, got, err, want)
|
|
}
|
|
}
|
|
for _, bad := range []string{`{{mul "abc" 2}}`, `{{add .Rows 1}}`, `{{mul "NaN" 1}}`, `{{add "Inf" 1}}`, `{{mul 1e308 1e308}}`} {
|
|
if _, err := render(bad, data); err == nil {
|
|
t.Errorf("%s must fail", bad)
|
|
}
|
|
}
|
|
}
|
|
|
|
// GenerateQRCode backs the qr template function. The table must keep its
|
|
// grid size and orientation so QR codes in emails stay the same size and scan.
|
|
func TestGenerateQRCode(t *testing.T) {
|
|
out, err := GenerateQRCode("https://a.io", 3)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if !strings.HasPrefix(out, "<table") || !strings.HasSuffix(out, "</table>") {
|
|
t.Fatalf("not a table: %.60s", out)
|
|
}
|
|
rows := strings.Split(strings.TrimSuffix(out, "</tr></table>"), "</tr>")
|
|
// a 12 character URL at level Q is a version 2 code, 25 by 25 modules
|
|
if len(rows) != 25 {
|
|
t.Fatalf("expected 25 rows, got %d", len(rows))
|
|
}
|
|
for i, row := range rows {
|
|
if n := strings.Count(row, "<td "); n != 25 {
|
|
t.Fatalf("row %d: expected 25 cells, got %d", i, n)
|
|
}
|
|
}
|
|
// the top left finder pattern starts with 7 dark modules and a light separator
|
|
cells := strings.Split(rows[0], "<td ")[1:]
|
|
for x := 0; x < 7; x++ {
|
|
if !strings.Contains(cells[x], `bgcolor="#000000"`) {
|
|
t.Fatalf("finder cell %d is not dark", x)
|
|
}
|
|
}
|
|
if !strings.Contains(cells[7], `bgcolor="#FFFFFF"`) {
|
|
t.Fatal("finder separator is not light")
|
|
}
|
|
if !strings.Contains(cells[0], `width="3"`) {
|
|
t.Fatal("dot size argument not used")
|
|
}
|
|
|
|
if _, err := GenerateQRCode(); err == nil {
|
|
t.Fatal("expected error without a URL")
|
|
}
|
|
if _, err := GenerateQRCode(42); err == nil {
|
|
t.Fatal("expected error for a non string URL")
|
|
}
|
|
}
|