Files
2026-12-04 23:34:19 +01:00

190 lines
7.5 KiB
Go

package service
import (
"archive/zip"
"bytes"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/oapi-codegen/nullable"
"github.com/phishingclub/phishingclub/data"
"github.com/phishingclub/phishingclub/model"
"github.com/phishingclub/phishingclub/vo"
"go.uber.org/zap/zapcore"
)
func TestImportAudit(t *testing.T) {
logger, buf := bufferLogger(zapcore.InfoLevel)
im := &Import{Common: Common{Logger: logger}}
g, _ := gin.CreateTestContext(httptest.NewRecorder())
g.Request = httptest.NewRequest("POST", "/", nil)
var zipBuf bytes.Buffer
if err := zip.NewWriter(&zipBuf).Close(); err != nil {
t.Fatal(err)
}
companyID := uuid.New()
denied := adminSession(uuid.New(), data.RoleCompanyUser)
if _, err := im.ImportFromBytes(g, denied, zipBuf.Bytes(), false, nil); err == nil {
t.Fatal("expected a role without permissions to be refused")
}
admin := adminSession(uuid.New(), data.RoleSuperAdministrator)
if _, err := im.ImportFromBytes(g, admin, zipBuf.Bytes(), true, &companyID); err != nil {
t.Fatalf("expected an empty archive to import: %v", err)
}
if _, err := im.ImportFromBytes(g, admin, []byte("not a zip"), false, nil); err == nil {
t.Fatal("expected a broken archive to fail")
}
ev := auditEventsNamed(t, buf.String(), "Import.Import")
if len(ev) != 3 {
t.Fatalf("expected 3 import events, got %d: %v", len(ev), ev)
}
results := []string{"denied", "success", "failed"}
for i, r := range results {
d, _ := ev[i]["details"].(map[string]any)
if ev[i]["result"] != r || d["source"] != "templates" {
t.Errorf("event %d: %v", i, ev[i])
}
}
d, _ := ev[1]["details"].(map[string]any)
if d["companyId"] != companyID.String() || d["created"] != float64(0) || d["errors"] != float64(0) {
t.Fatalf("success event should hold company and counts: %v", d)
}
}
func zipWith(t *testing.T, name, body string) *zip.File {
t.Helper()
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
w, err := zw.Create(name)
if err != nil {
t.Fatalf("zip create: %v", err)
}
if _, err := w.Write([]byte(body)); err != nil {
t.Fatalf("zip write: %v", err)
}
if err := zw.Close(); err != nil {
t.Fatalf("zip close: %v", err)
}
r, err := zip.NewReader(bytes.NewReader(buf.Bytes()), int64(buf.Len()))
if err != nil {
t.Fatalf("zip read: %v", err)
}
return r.File[0]
}
// TestZipImportAssetOverwrite checks that an unclean zip asset path is refused
// without touching the existing file, that a path owned by an asset row is
// skipped, and that a file on disk with no asset row is overwritten and gets
// a row so it shows in the asset list.
func TestZipImportAssetOverwrite(t *testing.T) {
h := newOwnershipFixture(t)
h.userAsset("a/logo.png", "user bytes")
im := &Import{Common: h.s.Common, File: h.s.File, Asset: h.s.Asset}
gin.SetMode(gin.TestMode)
g, _ := gin.CreateTestContext(httptest.NewRecorder())
g.Request = httptest.NewRequest("POST", "/", nil)
created, err := im.createAssetFromZipFile(g, h.session, zipWith(t, "assets/a//logo.png", "zip bytes"), "a//logo.png")
if err == nil || created {
t.Fatalf("unclean path accepted: created=%v err=%v", created, err)
}
if got := h.assetFile("a/logo.png"); got != "user bytes" {
t.Fatalf("existing file overwritten: %q", got)
}
// a path owned by a row is skipped and the file kept
created, err = im.createAssetFromZipFile(g, h.session, zipWith(t, "assets/a/logo.png", "zip bytes"), "a/logo.png")
if err != nil || created {
t.Fatalf("owned path should be skipped: created=%v err=%v", created, err)
}
if got := h.assetFile("a/logo.png"); got != "user bytes" {
t.Fatalf("owned file overwritten: %q", got)
}
// a file on disk without a row is overwritten and the new row kept
orphan := filepath.Join(h.assetRoot, data.ASSET_GLOBAL_FOLDER, "b", "logo.png")
if err := os.MkdirAll(filepath.Dir(orphan), 0o755); err != nil {
t.Fatalf("mkdir: %v", err)
}
if err := os.WriteFile(orphan, []byte("disk bytes"), 0o644); err != nil {
t.Fatalf("write: %v", err)
}
created, err = im.createAssetFromZipFile(g, h.session, zipWith(t, "assets/b/logo.png", "zip bytes"), "b/logo.png")
if err != nil || !created {
t.Fatalf("file without a row should be imported: created=%v err=%v", created, err)
}
if got := h.assetFile("b/logo.png"); got != "zip bytes" {
t.Fatalf("file not overwritten: %q", got)
}
if a, _ := h.s.Asset.AssetRepository.GetGlobalByPath(h.ctx, "b/logo.png"); a == nil {
t.Fatalf("no row kept for the imported file")
}
// a path into the asset folder of a company is refused and the file of
// the company is kept. The row of a company asset holds the path without
// the folder, so no row is found for the path in the zip.
companyName := vo.NewString64Must("Import Co")
companyID, err := h.s.Asset.CompanyRepository.Insert(h.ctx, &model.Company{Name: nullable.NewNullableWithValue(*companyName)})
if err != nil {
t.Fatalf("insert company: %v", err)
}
company, err := h.s.Asset.CompanyRepository.GetByID(h.ctx, companyID)
if err != nil {
t.Fatalf("get company: %v", err)
}
key := company.AssetsKey.MustGet().String()
companyFile := filepath.Join(h.assetRoot, data.ASSET_GLOBAL_FOLDER, key, "logo.png")
if err := os.MkdirAll(filepath.Dir(companyFile), 0o755); err != nil {
t.Fatalf("mkdir: %v", err)
}
if err := os.WriteFile(companyFile, []byte("company bytes"), 0o644); err != nil {
t.Fatalf("write: %v", err)
}
created, err = im.createAssetFromZipFile(g, h.session, zipWith(t, "assets/"+key+"/logo.png", "zip bytes"), key+"/logo.png")
if err == nil || created {
t.Fatalf("a path into the folder of a company was imported: created=%v err=%v", created, err)
}
if got := h.assetFile(key + "/logo.png"); got != "company bytes" {
t.Fatalf("the file of a company was overwritten: %q", got)
}
if a, _ := h.s.Asset.AssetRepository.GetGlobalByPath(h.ctx, key+"/logo.png"); a != nil {
t.Fatalf("a global row was made inside the folder of a company")
}
// a file named as the key of a company with no folder yet is refused
otherName := vo.NewString64Must("Import Co Two")
otherID, err := h.s.Asset.CompanyRepository.Insert(h.ctx, &model.Company{Name: nullable.NewNullableWithValue(*otherName)})
if err != nil {
t.Fatalf("insert company: %v", err)
}
other, err := h.s.Asset.CompanyRepository.GetByID(h.ctx, otherID)
if err != nil {
t.Fatalf("get company: %v", err)
}
otherKey := other.AssetsKey.MustGet().String()
if created, err = im.createAssetFromZipFile(g, h.session, zipWith(t, "assets/"+otherKey, "zip bytes"), otherKey); err == nil || created {
t.Fatalf("a file named as the key of a company was imported: created=%v err=%v", created, err)
}
// a file with no folder still imports
if created, err = im.createAssetFromZipFile(g, h.session, zipWith(t, "assets/top.png", "zip bytes"), "top.png"); err != nil || !created {
t.Fatalf("an asset with no folder was not imported: created=%v err=%v", created, err)
}
// other folders still import while a company exists
if created, err = im.createAssetFromZipFile(g, h.session, zipWith(t, "assets/img/icons/logo.png", "zip bytes"), "img/icons/logo.png"); err != nil || !created {
t.Fatalf("an asset in a folder of its own was not imported: created=%v err=%v", created, err)
}
if got := h.assetFile("img/icons/logo.png"); got != "zip bytes" {
t.Fatalf("the imported asset has the wrong content: %q", got)
}
// a new file in that folder is refused too
if created, err = im.createAssetFromZipFile(g, h.session, zipWith(t, "assets/"+key+"/new.png", "zip bytes"), key+"/new.png"); err == nil || created {
t.Fatalf("a new file in the folder of a company was imported: created=%v err=%v", created, err)
}
}