CI / lint-backend (push) Failing after 1m39s
CI / lint-mobile (push) Canceled after 11m8s
CI / test-backend (push) Canceled after 0s
CI / test-mobile (push) Canceled after 0s
CI / build-backend (push) Canceled after 0s
CI / docker (push) Canceled after 0s
367 lines
13 KiB
Go
367 lines
13 KiB
Go
package service
|
|
|
|
import (
|
|
"bytes"
|
|
"errors"
|
|
"mime/multipart"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/kazier/backend/repository"
|
|
)
|
|
|
|
func multipartFileHeader(t *testing.T, filename string, content []byte) *multipart.FileHeader {
|
|
t.Helper()
|
|
var body bytes.Buffer
|
|
writer := multipart.NewWriter(&body)
|
|
part, err := writer.CreateFormFile("file", filename)
|
|
if err != nil {
|
|
t.Fatalf("create form: %v", err)
|
|
}
|
|
if _, err := part.Write(content); err != nil {
|
|
t.Fatalf("write: %v", err)
|
|
}
|
|
if err := writer.Close(); err != nil {
|
|
t.Fatalf("close: %v", err)
|
|
}
|
|
|
|
reader := multipart.NewReader(&body, writer.Boundary())
|
|
form, err := reader.ReadForm(1 << 20)
|
|
if err != nil {
|
|
t.Fatalf("read form: %v", err)
|
|
}
|
|
files := form.File["file"]
|
|
if len(files) == 0 {
|
|
t.Fatal("aucun fichier dans la forme")
|
|
}
|
|
return files[0]
|
|
}
|
|
|
|
func TestUploadPersistsPhysicalFile(t *testing.T) {
|
|
s := newServiceStore(t)
|
|
userID := mustCreateUser(t, s.Repository, "upload-happy")
|
|
|
|
dto, err := s.Upload(userID, multipartFileHeader(t, "docs.txt", []byte("hello")), "", "")
|
|
if err != nil {
|
|
t.Fatalf("upload: %v", err)
|
|
}
|
|
if dto.ID == "" || dto.Name != "docs.txt" {
|
|
t.Errorf("dto inattendu: %+v", dto)
|
|
}
|
|
|
|
// Le fichier physique existe sous UploadDir/<user>/<id>.<ext>.
|
|
path := filepath.Join(s.UploadDir, userID, dto.ID+".txt")
|
|
info, err := os.Stat(path)
|
|
if err != nil {
|
|
t.Fatalf("fichier physique absent: %v", err)
|
|
}
|
|
if info.Size() != 5 {
|
|
t.Errorf("taille physique = %d, attendu 5", info.Size())
|
|
}
|
|
}
|
|
|
|
func TestUploadRemovesPhysicalFileOnNameConflict(t *testing.T) {
|
|
s := newServiceStore(t)
|
|
userID := mustCreateUser(t, s.Repository, "upload-conflict")
|
|
folderID := repository.NewID()
|
|
if err := s.Repository.Resources.InsertFolder(userID, folderID, "Docs", ""); err != nil {
|
|
t.Fatalf("insert folder: %v", err)
|
|
}
|
|
|
|
target := multipartFileHeader(t, "dupe.txt", []byte("hello"))
|
|
first, err := s.Upload(userID, target, folderID, "")
|
|
if err != nil {
|
|
t.Fatalf("premier upload: %v", err)
|
|
}
|
|
if first.ID == "" {
|
|
t.Fatal("aucun id au premier upload")
|
|
}
|
|
|
|
// Même nom, même dossier → NAME_CONFLICT et pas de second fichier physique.
|
|
if _, err := s.Upload(userID, target, folderID, ""); !errors.Is(err, repository.ErrNameConflict) {
|
|
t.Fatalf("second upload : attendu ErrNameConflict, got %v", err)
|
|
}
|
|
|
|
entries, err := os.ReadDir(filepath.Join(s.UploadDir, userID))
|
|
if err != nil {
|
|
t.Fatalf("readdir: %v", err)
|
|
}
|
|
if len(entries) != 1 {
|
|
t.Errorf("fichier orphelin laissé après NAME_CONFLICT : %d fichiers", len(entries))
|
|
}
|
|
}
|
|
|
|
func TestUploadTargetsExistingResource(t *testing.T) {
|
|
s := newServiceStore(t)
|
|
userID := mustCreateUser(t, s.Repository, "upload-target")
|
|
|
|
// Fiche metadata-only créée par l'outbox côté client.
|
|
resourceID := repository.NewID()
|
|
ext := "png"
|
|
if err := s.Repository.Resources.InsertFile(userID, resourceID, "scan.png", "", 0, nil, &ext); err != nil {
|
|
t.Fatalf("insert metadata-only file: %v", err)
|
|
}
|
|
|
|
// Re-upload ciblé : mêmes octets, même resource_id, pas de doublon.
|
|
dto, err := s.Upload(userID, multipartFileHeader(t, "scan.png", []byte("PNGDATA")), "", resourceID)
|
|
if err != nil {
|
|
t.Fatalf("targeted upload: %v", err)
|
|
}
|
|
if dto.ID != resourceID {
|
|
t.Errorf("id attendu %s, got %s", resourceID, dto.ID)
|
|
}
|
|
if dto.Size != 7 {
|
|
t.Errorf("taille = %d, attendu 7 (rafraîchie)", dto.Size)
|
|
}
|
|
|
|
path := filepath.Join(s.UploadDir, userID, resourceID+".png")
|
|
info, err := os.Stat(path)
|
|
if err != nil {
|
|
t.Fatalf("fichier physique absent: %v", err)
|
|
}
|
|
if info.Size() != 7 {
|
|
t.Errorf("taille physique = %d, attendu 7", info.Size())
|
|
}
|
|
|
|
// Une seule ligne serveur (pas de doublon créé par le re-upload).
|
|
rows, total, err := s.Repo.ListFiles(userID, "", 50, 0, "", "")
|
|
if err != nil {
|
|
t.Fatalf("list: %v", err)
|
|
}
|
|
if total != 1 || len(rows) != 1 || rows[0].ID != resourceID {
|
|
t.Errorf("liste après re-upload: total=%d rows=%+v", total, rows)
|
|
}
|
|
}
|
|
|
|
func TestUploadTargetsOwnedResourceOnly(t *testing.T) {
|
|
s := newServiceStore(t)
|
|
userID := mustCreateUser(t, s.Repository, "upload-owner")
|
|
otherUser := mustCreateUser(t, s.Repository, "upload-owner-other")
|
|
|
|
resourceID := repository.NewID()
|
|
if err := s.Repository.Resources.InsertFile(otherUser, resourceID, "mine.png", "", 0, nil, nil); err != nil {
|
|
t.Fatalf("insert other's file: %v", err)
|
|
}
|
|
|
|
// Un resource_id d'un autre user → ErrNotFound, aucun octet écrit.
|
|
if _, err := s.Upload(userID, multipartFileHeader(t, "mine.png", []byte("DATA")), "", resourceID); !errors.Is(err, repository.ErrNotFound) {
|
|
t.Fatalf("upload cross-user : attendu ErrNotFound, got %v", err)
|
|
}
|
|
// Le dossier upload du user ne doit pas avoir été créé (échec avant écriture).
|
|
if _, err := os.Stat(filepath.Join(s.UploadDir, userID)); !os.IsNotExist(err) {
|
|
t.Errorf("dossier upload créé à tort ou erreur inattendue: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestUploadTargetUnknownIsNotFound(t *testing.T) {
|
|
s := newServiceStore(t)
|
|
userID := mustCreateUser(t, s.Repository, "upload-unknown")
|
|
|
|
if _, err := s.Upload(userID, multipartFileHeader(t, "ghost.png", []byte("DATA")), "", repository.NewID()); !errors.Is(err, repository.ErrNotFound) {
|
|
t.Fatalf("upload inconnu : attendu ErrNotFound, got %v", err)
|
|
}
|
|
}
|
|
|
|
// A2 : le header multipart Size est déclaratif — seul le comptage réel des
|
|
// octets (LimitReader MaxFileSize+1) fait foi.
|
|
func TestUploadEnforcesActualSizeDespiteLyingHeader(t *testing.T) {
|
|
s := newServiceStore(t) // MaxFileSize = 100
|
|
userID := mustCreateUser(t, s.Repository, "upload-lying")
|
|
|
|
fh := multipartFileHeader(t, "big.txt", bytes.Repeat([]byte("x"), 150))
|
|
fh.Size = 10 // header menteur : annonce 10 alors que 150 arrivent
|
|
if _, err := s.Upload(userID, fh, "", ""); !errors.Is(err, ErrFileTooLarge) {
|
|
t.Fatalf("header menteur : attendu ErrFileTooLarge, got %v", err)
|
|
}
|
|
// Aucun résidu physique (ni fichier final, ni .tmp-* orphelin).
|
|
if entries, err := os.ReadDir(filepath.Join(s.UploadDir, userID)); err == nil && len(entries) != 0 {
|
|
names := make([]string, 0, len(entries))
|
|
for _, e := range entries {
|
|
names = append(names, e.Name())
|
|
}
|
|
t.Errorf("résidu physique après refus : %v", names)
|
|
}
|
|
}
|
|
|
|
// #5 : extension sanitizée (lowercase [a-z0-9]{1,10}), pas de "id." si vide.
|
|
func TestUploadSanitizesExtension(t *testing.T) {
|
|
s := newServiceStore(t)
|
|
userID := mustCreateUser(t, s.Repository, "upload-ext")
|
|
|
|
// Uppercase → lowercase.
|
|
dto, err := s.Upload(userID, multipartFileHeader(t, "PHOTO.JPG", []byte("data")), "", "")
|
|
if err != nil {
|
|
t.Fatalf("upload uppercase ext: %v", err)
|
|
}
|
|
if _, err := os.Stat(filepath.Join(s.UploadDir, userID, dto.ID+".jpg")); err != nil {
|
|
t.Errorf("fichier .jpg (lowercase) attendu: %v", err)
|
|
}
|
|
|
|
// Pas d'extension → fichier nu, sans trailing dot.
|
|
dto2, err := s.Upload(userID, multipartFileHeader(t, "README", []byte("data")), "", "")
|
|
if err != nil {
|
|
t.Fatalf("upload sans ext: %v", err)
|
|
}
|
|
if _, err := os.Stat(filepath.Join(s.UploadDir, userID, dto2.ID)); err != nil {
|
|
t.Errorf("fichier sans extension attendu: %v", err)
|
|
}
|
|
if _, err := os.Stat(filepath.Join(s.UploadDir, userID, dto2.ID+".")); !os.IsNotExist(err) {
|
|
t.Errorf("trailing dot interdit (id.) : err=%v", err)
|
|
}
|
|
|
|
// Extension trop longue / non alnum → "" (fichier nu).
|
|
dto3, err := s.Upload(userID, multipartFileHeader(t, "run.verylongextensiontoolong", []byte("data")), "", "")
|
|
if err != nil {
|
|
t.Fatalf("upload ext invalide: %v", err)
|
|
}
|
|
if _, err := os.Stat(filepath.Join(s.UploadDir, userID, dto3.ID)); err != nil {
|
|
t.Errorf("ext invalide → fichier nu attendu: %v", err)
|
|
}
|
|
|
|
// Backslash survit au round-trip multipart stdlib → rejet prouvé de bout
|
|
// en bout (les autres cas slash/NUL/retour-ligne sont couverts en
|
|
// unitaire sur sanitizeFileName, la stdlib Go les neutralisant déjà).
|
|
if _, err := s.Upload(userID, multipartFileHeader(t, `a\b.txt`, []byte("data")), "", ""); !errors.Is(err, ErrInvalidUpload) {
|
|
t.Errorf(`nom %q : attendu ErrInvalidUpload, got %v`, `a\b.txt`, err)
|
|
}
|
|
}
|
|
|
|
// #5/A16 : sanitizeurs unitaires — un client non-Go peut envoyer un filename
|
|
// brut (slash, .., NUL, retour-ligne) que la stdlib Go ne neutraliserait pas
|
|
// côté lecture serveur.
|
|
func TestSanitizeFileName(t *testing.T) {
|
|
for _, bad := range []string{"", " ", "../evil.txt", "a/b.txt", "a\x00b.txt", "bad\nname.txt", "bad\rname.txt", strings.Repeat("a", 256)} {
|
|
if _, err := sanitizeFileName(bad); !errors.Is(err, ErrInvalidUpload) {
|
|
t.Errorf("sanitizeFileName(%q) : attendu ErrInvalidUpload, got %v", bad, err)
|
|
}
|
|
}
|
|
for _, good := range []string{"docs.txt", " pad.txt ", "vacances-août.jpg", "a b c.pdf"} {
|
|
got, err := sanitizeFileName(good)
|
|
if err != nil {
|
|
t.Errorf("sanitizeFileName(%q) : rejet inattendu: %v", good, err)
|
|
} else if got != strings.TrimSpace(good) {
|
|
t.Errorf("sanitizeFileName(%q) = %q, attendu trim", good, got)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestSanitizeExtension(t *testing.T) {
|
|
cases := map[string]string{
|
|
"photo.JPG": "jpg",
|
|
"archive.tar.gz": "gz",
|
|
"README": "",
|
|
"run.verylongextensiontoolong": "",
|
|
"evil.php/../../x": "",
|
|
"a.b/c": "",
|
|
"weird.HTM\nL": "",
|
|
"dot.": "",
|
|
}
|
|
for in, want := range cases {
|
|
if got := sanitizeExtension(in); got != want {
|
|
t.Errorf("sanitizeExtension(%q) = %q, attendu %q", in, got, want)
|
|
}
|
|
}
|
|
}
|
|
|
|
// #6 : un re-upload ciblé avec une nouvelle extension ne laisse qu'un seul
|
|
// fichier physique (l'ancien suffixe est supprimé).
|
|
func TestUploadReuploadNewExtensionRemovesStaleFile(t *testing.T) {
|
|
s := newServiceStore(t)
|
|
userID := mustCreateUser(t, s.Repository, "upload-reext")
|
|
|
|
resourceID := repository.NewID()
|
|
png := "png"
|
|
if err := s.Repository.Resources.InsertFile(userID, resourceID, "scan.png", "", 0, nil, &png); err != nil {
|
|
t.Fatalf("insert metadata-only: %v", err)
|
|
}
|
|
if _, err := s.Upload(userID, multipartFileHeader(t, "scan.png", []byte("PNGDATA")), "", resourceID); err != nil {
|
|
t.Fatalf("premier upload ciblé: %v", err)
|
|
}
|
|
|
|
dto, err := s.Upload(userID, multipartFileHeader(t, "scan.jpg", []byte("JPGDATA!")), "", resourceID)
|
|
if err != nil {
|
|
t.Fatalf("re-upload nouvelle ext: %v", err)
|
|
}
|
|
if dto.ID != resourceID {
|
|
t.Fatalf("id attendu %s, got %s", resourceID, dto.ID)
|
|
}
|
|
entries, err := os.ReadDir(filepath.Join(s.UploadDir, userID))
|
|
if err != nil {
|
|
t.Fatalf("readdir: %v", err)
|
|
}
|
|
if len(entries) != 1 || entries[0].Name() != resourceID+".jpg" {
|
|
names := make([]string, 0, len(entries))
|
|
for _, e := range entries {
|
|
names = append(names, e.Name())
|
|
}
|
|
t.Errorf("un seul physique attendu (%s.jpg), got %v", resourceID, names)
|
|
}
|
|
content, err := os.ReadFile(filepath.Join(s.UploadDir, userID, resourceID+".jpg"))
|
|
if err != nil || string(content) != "JPGDATA!" {
|
|
t.Errorf("contenu = %q, err=%v (attendu JPGDATA!)", content, err)
|
|
}
|
|
}
|
|
|
|
// A4 : répertoire 0700, fichier 0600 (enforcés malgré umask).
|
|
func TestUploadFileAndDirPermissions(t *testing.T) {
|
|
s := newServiceStore(t)
|
|
userID := mustCreateUser(t, s.Repository, "upload-perms")
|
|
|
|
dto, err := s.Upload(userID, multipartFileHeader(t, "secret.txt", []byte("data")), "", "")
|
|
if err != nil {
|
|
t.Fatalf("upload: %v", err)
|
|
}
|
|
dirInfo, err := os.Stat(filepath.Join(s.UploadDir, userID))
|
|
if err != nil {
|
|
t.Fatalf("stat dir: %v", err)
|
|
}
|
|
if perm := dirInfo.Mode().Perm(); perm != 0o700 {
|
|
t.Errorf("perms dossier = %04o, attendu 0700", perm)
|
|
}
|
|
fileInfo, err := os.Stat(filepath.Join(s.UploadDir, userID, dto.ID+".txt"))
|
|
if err != nil {
|
|
t.Fatalf("stat file: %v", err)
|
|
}
|
|
if perm := fileInfo.Mode().Perm(); perm != 0o600 {
|
|
t.Errorf("perms fichier = %04o, attendu 0600", perm)
|
|
}
|
|
}
|
|
|
|
// A16 : Content-Type hors whitelist → fallback application/octet-stream.
|
|
func TestUploadMimeTypeWhitelistFallback(t *testing.T) {
|
|
s := newServiceStore(t)
|
|
userID := mustCreateUser(t, s.Repository, "upload-mime")
|
|
|
|
evil := multipartFileHeader(t, "evil.bin", []byte("data"))
|
|
evil.Header.Set("Content-Type", "application/x-evil-tool")
|
|
dto, err := s.Upload(userID, evil, "", "")
|
|
if err != nil {
|
|
t.Fatalf("upload evil mime: %v", err)
|
|
}
|
|
if dto.MimeType != "application/octet-stream" {
|
|
t.Errorf("mime inattendu = %q, attendu fallback application/octet-stream", dto.MimeType)
|
|
}
|
|
|
|
withParams := multipartFileHeader(t, "page.bin", []byte("data"))
|
|
withParams.Header.Set("Content-Type", "text/html; charset=utf-8")
|
|
dto, err = s.Upload(userID, withParams, "", "")
|
|
if err != nil {
|
|
t.Fatalf("upload html mime: %v", err)
|
|
}
|
|
if dto.MimeType != "application/octet-stream" {
|
|
t.Errorf("text/html non whitelisté, fallback attendu, got %q", dto.MimeType)
|
|
}
|
|
|
|
allowed := multipartFileHeader(t, "img.bin", []byte("data"))
|
|
allowed.Header.Set("Content-Type", "image/png")
|
|
dto, err = s.Upload(userID, allowed, "", "")
|
|
if err != nil {
|
|
t.Fatalf("upload png mime: %v", err)
|
|
}
|
|
if dto.MimeType != "image/png" {
|
|
t.Errorf("mime whitelisté perdu, got %q", dto.MimeType)
|
|
}
|
|
}
|