V3 S7 : preview cloud + export chiffré + release 1.2.0
Release / release-apk (push) Successful in 8m58s
Release / release-docker (push) Successful in 3m47s
CI / docker (push) Successful in 7s
CI / lint-backend (push) Successful in 1m44s
CI / lint-mobile (push) Failing after 18m59s
CI / test-backend (push) Successful in 2m12s
CI / test-mobile (push) Successful in 8m50s
CI / build-backend (push) Successful in 45s
Release / release-apk (push) Successful in 8m58s
Release / release-docker (push) Successful in 3m47s
CI / docker (push) Successful in 7s
CI / lint-backend (push) Successful in 1m44s
CI / lint-mobile (push) Failing after 18m59s
CI / test-backend (push) Successful in 2m12s
CI / test-mobile (push) Successful in 8m50s
CI / build-backend (push) Successful in 45s
Backend : resource_previews (000024), GET /files/:id/preview (JPEG
512, images pur Go, PDF page 1 via pdftoppm + poppler au Dockerfile,
cache régénéré sur changement, 404 NO_PREVIEW sinon), POST /export
{password 8+} -> zip AES-256 streamé (fichiers vifs possédés +
manifest.json avec faits, metadata-only sans octets). Deps :
alexmullins/zip, x/image directs. Tests service + handlers + migrations.
Mobile : vignettes distantes (une requête/session puis cache WebP
versionné, garde tried, icône sinon), FileThumbnail cloud-only,
export (mot de passe jamais persisté, cache + partage FileProvider),
bouton Partager ACTION_SEND. Impression papier reportée V4. FR/EN.
Contrat docs/api-v1.md, V3.md (S7 livré, V3 close), AGENTS.md,
VERSION 1.2.0 + CHANGELOG.
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/kazier/backend/pkg/api"
|
||||
)
|
||||
|
||||
type exportRequest struct {
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
// ExportFull streame un zip AES-256 du compte (V3 S7 C3) :
|
||||
// `POST /export { password }` (mot de passe en corps JSON, jamais en query
|
||||
// — pas de fuite dans les logs). Chaque entrée (fichiers + manifest.json)
|
||||
// est chiffrée. Scope : fichiers vifs possédés uniquement.
|
||||
// Le mot de passe exige 8+ caractères (400 sinon) ; le zip peut être long
|
||||
// (pas de cap S7 — donnée de l'utilisateur, self-hosté).
|
||||
func ExportFull(c *gin.Context) {
|
||||
if Store == nil || Store.Repository == nil {
|
||||
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
|
||||
return
|
||||
}
|
||||
userID := c.GetString(UserIDKey)
|
||||
var req exportRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "invalid JSON body (expected { password })")
|
||||
return
|
||||
}
|
||||
if len(req.Password) < 8 {
|
||||
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "password must be at least 8 characters")
|
||||
return
|
||||
}
|
||||
filename := fmt.Sprintf("kazier-export-%s.zip", time.Now().UTC().Format("20060102-150405"))
|
||||
c.Header("Content-Type", "application/zip")
|
||||
c.Header("Content-Disposition", "attachment; filename=\""+filename+"\"")
|
||||
// Erreur mid-stream : headers déjà partis — log + abort (zip tronqué,
|
||||
// documenté ; le manifest chiffré en fin d'archive manque alors).
|
||||
if err := Store.Export(c.Writer, userID, req.Password); err != nil {
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package handlers_test
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/kazier/backend/repository"
|
||||
)
|
||||
|
||||
// TestExportEndpoint : POST /export exige un mot de passe 8+ (400 sinon) et
|
||||
// streame un zip (200 + application/zip).
|
||||
func TestExportEndpoint(t *testing.T) {
|
||||
r, _, repo := setup(t)
|
||||
device := repository.NewID()
|
||||
token, _ := registerAndLogin(t, r, repo, testUserUsername(device, "ex"), "export-test-password", device)
|
||||
|
||||
for _, body := range []string{`{}`, `{"password":"court"}`, `not-json`} {
|
||||
rec, _ := doRequest(t, r, http.MethodPost, "/api/v1/export", token, []byte(body), "application/json")
|
||||
expectError(t, rec, http.StatusBadRequest, "INVALID_REQUEST", "export-400:"+body)
|
||||
}
|
||||
|
||||
rec, _ := doRequest(t, r, http.MethodPost, "/api/v1/export", token, []byte(`{"password":"motdepasse-8"}`), "application/json")
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("export: attendu 200, got %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if ct := rec.Header().Get("Content-Type"); ct != "application/zip" {
|
||||
t.Fatalf("content-type = %q", ct)
|
||||
}
|
||||
if cd := rec.Header().Get("Content-Disposition"); cd == "" {
|
||||
t.Fatal("content-disposition manquant")
|
||||
}
|
||||
if rec.Body.Len() == 0 {
|
||||
t.Fatal("zip vide")
|
||||
}
|
||||
if rec.Body.Bytes()[0] != 'P' || rec.Body.Bytes()[1] != 'K' {
|
||||
t.Fatal("pas une archive zip (signature PK manquante)")
|
||||
}
|
||||
}
|
||||
@@ -299,6 +299,34 @@ func FilesContent(c *gin.Context) {
|
||||
c.File(info.Path)
|
||||
}
|
||||
|
||||
// FilesPreview sert la vignette JPEG d'un fichier visible (V3 S7) :
|
||||
// `GET /files/:id/preview` (binaire brut, hors enveloppe, `inline`).
|
||||
// Générée à la demande (images pur Go, PDF page 1 via `pdftoppm`) et cachée
|
||||
// jusqu'au prochain changement (taille/`updated_at`). 404 NOT_FOUND si
|
||||
// invisible/metadata-only (indistinguables, pas d'énumération), 404
|
||||
// NO_PREVIEW si le type ne se prévisualise pas (l'UI montre l'icône).
|
||||
func FilesPreview(c *gin.Context) {
|
||||
if Store == nil {
|
||||
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
|
||||
return
|
||||
}
|
||||
userID := c.GetString(UserIDKey)
|
||||
id := c.Param("id")
|
||||
if !deviceIDPattern.MatchString(id) {
|
||||
api.Error(c, http.StatusNotFound, "NOT_FOUND", "file not found")
|
||||
return
|
||||
}
|
||||
path, err := Store.OpenPreview(userID, id)
|
||||
if err != nil {
|
||||
writeError(c, err)
|
||||
return
|
||||
}
|
||||
c.Header("Content-Type", "image/jpeg")
|
||||
c.Header("Content-Disposition", "inline; filename=\""+id+".jpg\"")
|
||||
c.Header("Cache-Control", "private, max-age=3600")
|
||||
c.File(path)
|
||||
}
|
||||
|
||||
func FilesDelete(c *gin.Context) {
|
||||
if Store == nil {
|
||||
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
package handlers_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/jpeg"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/kazier/backend/repository"
|
||||
)
|
||||
|
||||
// previewImageBytes génère un JPEG 640x480 uni (décodable sans fixture).
|
||||
func previewImageBytes(t *testing.T) []byte {
|
||||
t.Helper()
|
||||
img := image.NewRGBA(image.Rect(0, 0, 640, 480))
|
||||
for y := 0; y < 480; y++ {
|
||||
for x := 0; x < 640; x++ {
|
||||
img.Set(x, y, color.RGBA{uint8(x % 256), 128, 64, 255})
|
||||
}
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if err := jpeg.Encode(&buf, img, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
// TestFilesPreview : JPEG 200 + image/jpeg pour une image, NO_PREVIEW pour
|
||||
// un txt, NOT_FOUND si trashé/étranger. L'upload HTTP de test est capé à
|
||||
// 10 o : le physique est écrit directement (même layout UPLOAD_DIR).
|
||||
func TestFilesPreview(t *testing.T) {
|
||||
r, store, repo := setup(t)
|
||||
device := repository.NewID()
|
||||
token, userID := registerAndLogin(t, r, repo, testUserUsername(device, "pv"), "preview-test-password", device)
|
||||
|
||||
createdID := seedPhysical(t, store.UploadDir, repo, userID, "photo.jpg", previewImageBytes(t))
|
||||
|
||||
rec, _ := doRequest(t, r, http.MethodGet, "/api/v1/files/"+createdID+"/preview", token, nil, "")
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("preview: attendu 200, got %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if ct := rec.Header().Get("Content-Type"); ct != "image/jpeg" {
|
||||
t.Fatalf("content-type = %q, attendu image/jpeg", ct)
|
||||
}
|
||||
if _, err := jpeg.Decode(bytes.NewReader(rec.Body.Bytes())); err != nil {
|
||||
t.Fatalf("corps non-JPEG: %v", err)
|
||||
}
|
||||
|
||||
// Txt → NO_PREVIEW (404 typé, l'UI montre l'icône).
|
||||
txtID := seedPhysical(t, store.UploadDir, repo, userID, "notes.txt", []byte("hello"))
|
||||
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+txtID+"/preview", token, nil, "")
|
||||
expectError(t, rec, http.StatusNotFound, "NO_PREVIEW", "preview-txt")
|
||||
|
||||
// Trashé → NOT_FOUND (invisible d'abord, pas NO_PREVIEW).
|
||||
if err := repo.Resources.TrashResource(userID, createdID); err != nil {
|
||||
t.Fatalf("trash: %v", err)
|
||||
}
|
||||
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+createdID+"/preview", token, nil, "")
|
||||
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "preview-trashed")
|
||||
|
||||
// Étranger → NOT_FOUND.
|
||||
deviceB := repository.NewID()
|
||||
tokenB, _ := registerAndLogin(t, r, repo, testUserUsername(deviceB, "pb"), "preview-test-password", deviceB)
|
||||
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+txtID+"/preview", tokenB, nil, "")
|
||||
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "preview-foreign")
|
||||
}
|
||||
|
||||
// seedPhysical insère la métadonnée + écrit les octets (même layout que
|
||||
// l'upload, sans passer par le multipart capé des tests).
|
||||
func seedPhysical(t *testing.T, uploadDir string, repo *repository.Repository, userID, name string, content []byte) string {
|
||||
t.Helper()
|
||||
id := repository.NewID()
|
||||
ext := ""
|
||||
if i := strings.LastIndex(name, "."); i >= 0 {
|
||||
ext = name[i+1:]
|
||||
}
|
||||
var extPtr *string
|
||||
if ext != "" {
|
||||
extPtr = &ext
|
||||
}
|
||||
mime := "application/octet-stream"
|
||||
if ext == "jpg" {
|
||||
mime = "image/jpeg"
|
||||
}
|
||||
if err := repo.Resources.InsertFile(userID, id, name, "", int64(len(content)), &mime, extPtr); err != nil {
|
||||
t.Fatalf("insert: %v", err)
|
||||
}
|
||||
dir := filepath.Join(uploadDir, userID)
|
||||
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||
t.Fatalf("mkdir: %v", err)
|
||||
}
|
||||
dest := id
|
||||
if ext != "" {
|
||||
dest = id + "." + ext
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, dest), content, 0o600); err != nil {
|
||||
t.Fatalf("write: %v", err)
|
||||
}
|
||||
if err := repo.Resources.SetHasContent(userID, id, true); err != nil {
|
||||
t.Fatalf("has_content: %v", err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
@@ -36,6 +36,7 @@ func RegisterRoutes(r *gin.Engine) {
|
||||
protected.GET("/files/:id/facts", FilesGetFacts)
|
||||
protected.PATCH("/files/:id/facts", FilesCorrectFacts)
|
||||
protected.GET("/files/:id/content", FilesContent)
|
||||
protected.GET("/files/:id/preview", FilesPreview)
|
||||
protected.GET("/files/:id/shares", SharesList)
|
||||
protected.GET("/files/:id/links", LinksList)
|
||||
protected.GET("/files/:id/placements", PlacementsList)
|
||||
@@ -43,6 +44,7 @@ func RegisterRoutes(r *gin.Engine) {
|
||||
protected.GET("/files/:id/relations", RelationsList)
|
||||
protected.POST("/files/:id/relations/verdict", RelationVerdict)
|
||||
protected.GET("/duplicates", DuplicatesList)
|
||||
protected.POST("/export", ExportFull)
|
||||
protected.POST("/files/:id/restore", FilesRestore)
|
||||
protected.POST("/files/:id/versions/:n/restore", VersionRestore)
|
||||
protected.GET("/trash", TrashList)
|
||||
|
||||
@@ -32,6 +32,8 @@ func writeError(c *gin.Context, err error) {
|
||||
api.Error(c, 413, "FILE_TOO_LARGE", "file exceeds the maximum allowed size")
|
||||
case errors.Is(err, service.ErrQuotaExceeded):
|
||||
api.Error(c, 413, "QUOTA_EXCEEDED", "storage quota exceeded")
|
||||
case errors.Is(err, service.ErrNoPreview):
|
||||
api.Error(c, 404, "NO_PREVIEW", "no preview available for this file")
|
||||
default:
|
||||
// Jamais de err.Error() brut au client (fuite SQL/FS/paths, cf.
|
||||
// FEEDBACK #8) : message générique, détail au log serveur.
|
||||
|
||||
Reference in New Issue
Block a user