fix backend audit findings (auth, upload, sync, data, ocr, contract)
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
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
This commit is contained in:
+80
-12
@@ -3,8 +3,11 @@ package service
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -41,7 +44,29 @@ type Ocr struct {
|
||||
}
|
||||
|
||||
func NewOcr(repo *repository.Repository, uploadDir, lang string, engine ocr.Engine) *Ocr {
|
||||
return &Ocr{Repository: repo, UploadDir: uploadDir, Lang: lang, Engine: engine, StaleAfter: StaleClaimTimeout}
|
||||
return &Ocr{Repository: repo, UploadDir: uploadDir, Lang: normalizeOcrLang(lang), Engine: engine, StaleAfter: StaleClaimTimeout}
|
||||
}
|
||||
|
||||
var (
|
||||
// ocrLangPattern : whitelist OCR_LANG (A12) — lettres Tesseract + `+`
|
||||
// uniquement (ex. `fra`, `eng`, `fra+eng`). Tout le reste (espaces,
|
||||
// `;`, `-`, options `--...`) est une tentative d'injection `-l`.
|
||||
ocrLangPattern = regexp.MustCompile(`^[a-z+]{2,20}$`)
|
||||
// hexIDPattern : identifiants 32-hex (anti `..` dans physicalPath).
|
||||
hexIDPattern = regexp.MustCompile(`^[0-9a-f]{32}$`)
|
||||
)
|
||||
|
||||
// DefaultOcrLang est la langue Tesseract de repli (OCR_LANG, défaut fra+eng).
|
||||
const DefaultOcrLang = "fra+eng"
|
||||
|
||||
// normalizeOcrLang applique la whitelist OCR_LANG : valeur invalide → repli
|
||||
// sur le défaut avec log (jamais d'injection vers `tesseract -l`).
|
||||
func normalizeOcrLang(lang string) string {
|
||||
if ocrLangPattern.MatchString(lang) {
|
||||
return lang
|
||||
}
|
||||
log.Printf("ocr: OCR_LANG %q invalide (whitelist ^[a-z+]{2,20}$), repli sur %q", lang, DefaultOcrLang)
|
||||
return DefaultOcrLang
|
||||
}
|
||||
|
||||
// Create valide la ressource (ownership par user) et l'enfile uniquement
|
||||
@@ -110,44 +135,87 @@ func (o *Ocr) workerLoop(ctx context.Context) {
|
||||
}
|
||||
|
||||
// process exécute l'extraction pour un job déjà réclamé (`processing`).
|
||||
// Ordre A13 : l'écriture `UpdateOcrText` est vérifiée AVANT le `Complete` —
|
||||
// hôte supprimé entre-temps (0 ligne, ErrNotFound) → le job `Fail` au lieu
|
||||
// de rester `done` avec un texte fantôme. Les erreurs `Fail`/`Complete`
|
||||
// (conflit d'état : job requeue et repris par un autre worker) sont loggées,
|
||||
// jamais silencieuses.
|
||||
func (o *Ocr) process(ctx context.Context, row repository.OcrJobRow) {
|
||||
fail := func(message string) {
|
||||
if err := o.Repository.OcrJobs.Fail(row.DeviceID, row.ID, message); err != nil {
|
||||
log.Printf("ocr: fail job %s: %v", row.ID, err)
|
||||
}
|
||||
}
|
||||
complete := func(text string) {
|
||||
if err := o.Repository.OcrJobs.Complete(row.DeviceID, row.ID, text); err != nil {
|
||||
log.Printf("ocr: complete job %s: %v", row.ID, err)
|
||||
}
|
||||
}
|
||||
userID, err := o.Repository.Resources.GetResourceOwner(row.FileID)
|
||||
if err != nil {
|
||||
_ = o.Repository.OcrJobs.Fail(row.DeviceID, row.ID, "file not readable")
|
||||
fail("file not readable")
|
||||
return
|
||||
}
|
||||
path, err := o.physicalPath(userID, row.FileID)
|
||||
if err != nil {
|
||||
_ = o.Repository.OcrJobs.Fail(row.DeviceID, row.ID, "file not readable")
|
||||
fail("file not readable")
|
||||
return
|
||||
}
|
||||
text, err := o.Engine.ExtractText(ctx, path, o.Lang)
|
||||
if err != nil {
|
||||
_ = o.Repository.OcrJobs.Fail(row.DeviceID, row.ID, err.Error())
|
||||
fail(err.Error())
|
||||
return
|
||||
}
|
||||
_ = o.Repository.OcrJobs.Complete(row.DeviceID, row.ID, text)
|
||||
// Le texte atterrit sur la ressource (updated_at bumpé) : consultable par
|
||||
// tous les devices du user et les grantees via GET /files/:id/ocr. SILENCIEUX
|
||||
// (hôte déjà supprimé ou lock d'écriture) : le job reste source d'historique.
|
||||
// tous les devices du user et les grantees via GET /files/:id/ocr.
|
||||
if trimmed := strings.TrimSpace(text); trimmed != "" {
|
||||
if err := o.Repository.Resources.UpdateOcrText(userID, row.FileID, trimmed); err != nil {
|
||||
log.Printf("ocr: persiste ocr_text de %s: %v", row.FileID, err)
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
fail("file not readable")
|
||||
} else {
|
||||
fail(err.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
complete(text)
|
||||
}
|
||||
|
||||
// physicalPath résout UPLOAD_DIR/<user_id>/<resource_id>.<ext> — l'ext est
|
||||
// choisi à l'upload, le fichier réel est retrouvé par préfixe.
|
||||
// choisi à l'upload, le fichier réel est retrouvé par préfixe. Durci (A12) :
|
||||
// identifiants 32-hex uniquement (anti `..`), `Lstat` + fichier régulier
|
||||
// (ni dossier, ni symlink brut), `EvalSymlinks` contenu dans UPLOAD_DIR
|
||||
// (anti évasion par lien symbolique). Candidat rejeté → candidat suivant ;
|
||||
// aucun candidat → ErrNotFound.
|
||||
func (o *Ocr) physicalPath(userID, fileID string) (string, error) {
|
||||
if !hexIDPattern.MatchString(userID) || !hexIDPattern.MatchString(fileID) {
|
||||
return "", fmt.Errorf("physicalPath: identifiant non 32-hex")
|
||||
}
|
||||
base, err := filepath.EvalSymlinks(o.UploadDir)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("physicalPath: upload dir illisible: %w", err)
|
||||
}
|
||||
matches, err := filepath.Glob(filepath.Join(o.UploadDir, userID, fileID+".*"))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
for _, m := range matches {
|
||||
if strings.HasPrefix(filepath.Base(m), fileID+".") {
|
||||
return m, nil
|
||||
if !strings.HasPrefix(filepath.Base(m), fileID+".") {
|
||||
continue
|
||||
}
|
||||
fi, err := os.Lstat(m)
|
||||
if err != nil || !fi.Mode().IsRegular() {
|
||||
continue
|
||||
}
|
||||
resolved, err := filepath.EvalSymlinks(m)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
rel, err := filepath.Rel(base, resolved)
|
||||
if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) {
|
||||
continue
|
||||
}
|
||||
return resolved, nil
|
||||
}
|
||||
return "", repository.ErrNotFound
|
||||
}
|
||||
@@ -161,4 +229,4 @@ func toOcrJobDTO(row repository.OcrJobRow) OcrJobDTO {
|
||||
dto.Error = *row.Error
|
||||
}
|
||||
return dto
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user