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:
+168
-35
@@ -3,6 +3,7 @@ package service
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log"
|
||||
"regexp"
|
||||
"time"
|
||||
|
||||
@@ -92,33 +93,86 @@ func classifySyncError(err error) (string, string) {
|
||||
return "NOT_FOUND", "target resource or folder not found"
|
||||
case errors.Is(err, repository.ErrGranteeNotFound):
|
||||
return "GRANTEE_NOT_FOUND", "the specified user does not exist"
|
||||
case errors.Is(err, repository.ErrPayloadMismatch):
|
||||
return "INVALID_REQUEST", "operation replayed with different payload"
|
||||
case errors.Is(err, errCycle):
|
||||
return "INVALID_REQUEST", "cannot move a resource into its own subtree"
|
||||
default:
|
||||
return "INVALID_REQUEST", err.Error()
|
||||
// Volontairement générique : ne pas fuir SQL/FS internes (cf. #8).
|
||||
// Le détail reste côté serveur (logs), le client reçoit un code stable.
|
||||
log.Printf("sync: internal apply error: %v", err)
|
||||
return "INVALID_REQUEST", "invalid operation"
|
||||
}
|
||||
}
|
||||
|
||||
var errCycle = errors.New("cannot move a resource into its own subtree")
|
||||
|
||||
// ApplyBatch applique les ops de l'outbox : les mutations de ressources sont
|
||||
// scopées par l'UTILISATEUR (userID), l'idempotence reste par DEVICE
|
||||
// (deviceID) — cf. docs/api-v1.md §6.1.
|
||||
//
|
||||
// Atomicité par op (#7) : chaque op est sérialisée par un claim atomique sur
|
||||
// la trace outbox (INSERT ... ON CONFLICT DO NOTHING portant la contrainte
|
||||
// UNIQUE(device_id, operation_id), cf. Operations.Claim) — deux batches
|
||||
// concurrents ne peuvent pas appliquer deux fois la même op : le perdant
|
||||
// suit le chemin rejeu (comparaison de hash, cf. A9). Le claim est posé en
|
||||
// status='failed' AVANT l'apply puis promu en 'applied' (MarkApplied) une
|
||||
// fois l'effet durable : un crash entre les deux laisse une trace rejouable
|
||||
// (ré-apply à payload identique), jamais un skip silencieux.
|
||||
//
|
||||
// Limite documentée : claim→apply→promote ne sont pas une transaction SQL
|
||||
// unique — apply touche resources/shares via des statements atomiques
|
||||
// (INSERT ... SELECT parent, TouchOwned). Le TOCTOU résiduel (deux owners
|
||||
// créant le même resource_id) dégénère en NAME_CONFLICT explicite, jamais
|
||||
// en double écriture silencieuse. Une atomicité totale exigerait un
|
||||
// transaction manager transverse aux repos (vrai Tx ApplyBatch, reportée —
|
||||
// cf. FEEDBACK risques résiduels).
|
||||
//
|
||||
// Erreurs de persistance (claim/promote) : retournées comme applied:i
|
||||
// explicite avec code INTERNAL, jamais en erreur Go nue (500 nu) — le client
|
||||
// sait exactement où reprendre.
|
||||
func (s *Resources) ApplyBatch(userID, deviceID string, ops []SyncOperation) (SyncResult, error) {
|
||||
for i := range ops {
|
||||
op := &ops[i]
|
||||
if err := validateSyncOp(op); err != nil {
|
||||
return SyncResult{Applied: i, Failed: &FailedOperation{OperationID: op.OperationID, Code: "INVALID_REQUEST", Message: err.Error()}}, nil
|
||||
}
|
||||
already, err := s.Repository.Operations.Applied(deviceID, op.OperationID)
|
||||
claimed, err := s.Repository.Operations.Claim(deviceID, op.OperationID, op.Operation, derefString(op.RefType), nullableInt64(derefInt64(op.RefID)), derefString(op.ResourceID), op.Payload)
|
||||
if err != nil {
|
||||
return SyncResult{}, err
|
||||
// Faute client (clé ou payload malformé) → INVALID_REQUEST halt,
|
||||
// message statique sûr ; panne persistance → INTERNAL explicite.
|
||||
if errors.Is(err, repository.ErrInvalidOperationID) {
|
||||
return SyncResult{Applied: i, Failed: &FailedOperation{OperationID: op.OperationID, Code: "INVALID_REQUEST", Message: "operation_id must be 32 lowercase hex chars"}}, nil
|
||||
}
|
||||
if errors.Is(err, repository.ErrInvalidPayload) {
|
||||
return SyncResult{Applied: i, Failed: &FailedOperation{OperationID: op.OperationID, Code: "INVALID_REQUEST", Message: "invalid payload JSON"}}, nil
|
||||
}
|
||||
log.Printf("sync: claim device=%s op=%s: %v", deviceID, op.OperationID, err)
|
||||
return SyncResult{Applied: i, Failed: &FailedOperation{OperationID: op.OperationID, Code: "INTERNAL", Message: "failed to persist operation state"}}, nil
|
||||
}
|
||||
if already {
|
||||
continue
|
||||
if !claimed {
|
||||
// Rejeu : même (device, op) déjà tracé — comparer (A9).
|
||||
stored, err := s.Repository.Operations.Get(deviceID, op.OperationID)
|
||||
if err != nil {
|
||||
log.Printf("sync: replay read device=%s op=%s: %v", deviceID, op.OperationID, err)
|
||||
return SyncResult{Applied: i, Failed: &FailedOperation{OperationID: op.OperationID, Code: "INTERNAL", Message: "failed to read operation state"}}, nil
|
||||
}
|
||||
if err := stored.MatchesReplay(op.Operation, derefString(op.ResourceID), op.Payload); err != nil {
|
||||
return SyncResult{Applied: i, Failed: &FailedOperation{OperationID: op.OperationID, Code: "INVALID_REQUEST", Message: "operation replayed with different payload"}}, nil
|
||||
}
|
||||
if stored.Status == repository.OpStatusApplied {
|
||||
continue // déjà appliquée à l'identique → skip idempotent
|
||||
}
|
||||
// Trace 'failed' à payload identique : la première tentative est
|
||||
// morte avant MarkApplied (crash) → on ré-applique (recovery).
|
||||
}
|
||||
if err := s.applySyncOp(userID, op); err != nil {
|
||||
code, message := classifySyncError(err)
|
||||
return SyncResult{Applied: i, Failed: &FailedOperation{OperationID: op.OperationID, Code: code, Message: message}}, nil
|
||||
}
|
||||
if err := s.recordApplied(deviceID, op); err != nil {
|
||||
return SyncResult{}, err
|
||||
if err := s.Repository.Operations.MarkApplied(deviceID, op.OperationID); err != nil {
|
||||
log.Printf("sync: promote device=%s op=%s: %v", deviceID, op.OperationID, err)
|
||||
return SyncResult{Applied: i, Failed: &FailedOperation{OperationID: op.OperationID, Code: "INTERNAL", Message: "operation applied but trace update failed; safe to retry"}}, nil
|
||||
}
|
||||
}
|
||||
return SyncResult{Applied: len(ops)}, nil
|
||||
@@ -167,29 +221,47 @@ func (s *Resources) applySyncOp(ownerID string, op *SyncOperation) error {
|
||||
// Le parent doit exister et appartenir à l'utilisateur (NOT_FOUND sinon,
|
||||
// cohérent avec move_resource). Ordre du SAF walk : parent avant enfant.
|
||||
if p.ParentResourceID != "" {
|
||||
if !resourceIDPattern.MatchString(p.ParentResourceID) {
|
||||
return errors.New("payload.parentResourceId must be 32 lowercase hex chars")
|
||||
}
|
||||
if _, err := s.Repo.GetFolder(ownerID, p.ParentResourceID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
var insertErr error
|
||||
if derefString(op.ResourceType) == "folder" {
|
||||
return s.Repo.InsertFolder(ownerID, resourceID, p.Name, p.ParentResourceID)
|
||||
insertErr = s.Repo.InsertFolder(ownerID, resourceID, p.Name, p.ParentResourceID)
|
||||
} else {
|
||||
mime := p.MimeType
|
||||
insertErr = s.Repo.InsertFile(ownerID, resourceID, p.Name, p.ParentResourceID, 0, &mime, nullableString(p.Extension))
|
||||
}
|
||||
mime := p.MimeType
|
||||
return s.Repo.InsertFile(ownerID, resourceID, p.Name, p.ParentResourceID, 0, &mime, nullableString(p.Extension))
|
||||
if insertErr != nil {
|
||||
// Course ExistsOwner→Insert (concurrent ou rejeu croisé) : si la
|
||||
// ressource est désormais owned, l'effet est atteint → idempotent.
|
||||
// Sinon NAME_CONFLICT explicite (sibling ou resource_id d'autrui).
|
||||
// Atomicité totale (INSERT ... SELECT) : inter-lots, LOT 4.
|
||||
if errors.Is(insertErr, repository.ErrNameConflict) {
|
||||
if owned, err := s.Repo.ExistsOwner(ownerID, resourceID); err == nil && owned {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return insertErr
|
||||
}
|
||||
return nil
|
||||
|
||||
case OpUpdateMetadata:
|
||||
// Owner can always rename. A shared resource can be renamed by an
|
||||
// editor+ (docs §6.2 effective_access ranking). Below editor, or on
|
||||
// a resource the caller cannot reach at all, we keep the documented
|
||||
// terminal-state semantics: absent → no-op.
|
||||
// Sémantique uniforme (A8) : toute ressource que l'appelant ne peut
|
||||
// pas renommer — absente, d'autrui, ou partagée sous editor — halte
|
||||
// en NOT_FOUND. Pas de no-op silencieux : un rename qui n'a rien
|
||||
// renommé est un bug client ou une désync, le halt l'expose au lieu
|
||||
// de valider un état qui n'existe pas. Le même code NOT_FOUND dans
|
||||
// tous les cas évite tout oracle d'existence. Owner → rank owner,
|
||||
// editor+ partagé → autorisé (docs §6.2).
|
||||
access, err := s.Repository.Shares.EffectiveAccess(ownerID, resourceID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if access.EffectiveRank < repository.AccessEditor {
|
||||
if !access.Accessible {
|
||||
return nil
|
||||
}
|
||||
return repository.ErrNotFound
|
||||
}
|
||||
var p renamePayload
|
||||
@@ -199,16 +271,17 @@ func (s *Resources) applySyncOp(ownerID string, op *SyncOperation) error {
|
||||
if p.Name == "" {
|
||||
return errors.New("payload.name required")
|
||||
}
|
||||
return s.Repo.UpdateNameByID(resourceID, p.Name)
|
||||
// NOTE : UpdateNameByID (non-scopé) est volontaire ici — un editor
|
||||
// non-owner peut renommer (EffectiveAccess vérifié plus haut), donc
|
||||
// UpdateNameOwned(ownerID, ...) rejetterait à tort. La garde
|
||||
// d'autorisation précède immédiatement l'écriture.
|
||||
return s.Repo.UpdateNameByID(resourceID, p.Name)
|
||||
|
||||
case OpMoveResource:
|
||||
exists, err := s.Repo.ExistsOwner(ownerID, resourceID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !exists {
|
||||
return nil
|
||||
}
|
||||
// A8 : move owner-only. Source non-owned (absente OU d'autrui) →
|
||||
// NOT_FOUND halt (MoveResource ne touche que les lignes owned).
|
||||
// Pas de applied silencieux : un move qui n'a rien déplacé
|
||||
// désynchroniserait le client.
|
||||
var p movePayload
|
||||
if err := json.Unmarshal(op.Payload, &p); err != nil {
|
||||
return errors.New("invalid payload: " + err.Error())
|
||||
@@ -216,9 +289,36 @@ func (s *Resources) applySyncOp(ownerID string, op *SyncOperation) error {
|
||||
if p.ToFolderResourceID == resourceID {
|
||||
return errors.New("cannot move a resource into itself")
|
||||
}
|
||||
if p.ToFolderResourceID != "" {
|
||||
if !resourceIDPattern.MatchString(p.ToFolderResourceID) {
|
||||
return errors.New("payload.toFolderResourceId must be 32 lowercase hex chars")
|
||||
}
|
||||
// Check de cycle : le dossier cible ne doit pas être la ressource
|
||||
// elle-même ni l'un de ses descendants (cf. FEEDBACK #2).
|
||||
if err := s.checkNoCycle(p.ToFolderResourceID, resourceID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return s.Repo.MoveResource(ownerID, resourceID, p.ToFolderResourceID)
|
||||
|
||||
case OpDeleteResource:
|
||||
// A8 : delete owner-only. Ligne vivante d'autrui → NOT_FOUND halt
|
||||
// (pas de applied silencieux). Aucune ligne vivante (jamais existé,
|
||||
// ou déjà supprimée par son owner) → no-op idempotent : l'état
|
||||
// terminal (absente) est déjà atteint, le rejeu reste sûr.
|
||||
exists, err := s.Repo.ExistsOwner(ownerID, resourceID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !exists {
|
||||
if _, err := s.Repo.GetResourceOwner(resourceID); err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
return repository.ErrNotFound
|
||||
}
|
||||
return s.Repo.SyncDelete(ownerID, resourceID)
|
||||
|
||||
case OpShare, OpUpdateShare:
|
||||
@@ -275,13 +375,18 @@ func (s *Resources) applyShareOp(ownerID, resourceID string, op *SyncOperation)
|
||||
var expiresAt *time.Time
|
||||
if p.ExpiresAt != nil {
|
||||
t := time.UnixMilli(*p.ExpiresAt)
|
||||
if !t.After(time.Now()) {
|
||||
return errors.New("payload.expiresAt must be in the future")
|
||||
}
|
||||
expiresAt = &t
|
||||
}
|
||||
if err := s.Repository.Shares.Upsert(resourceID, p.GranteeUserID, p.Access, inherit, expiresAt, ownerID); err != nil {
|
||||
return err
|
||||
}
|
||||
// Bump resource updated_at so the grantee's delta snapshot picks it up.
|
||||
return s.Repo.TouchResource(resourceID)
|
||||
// Scopé owner (ExistsOwner vérifié plus haut) : TouchOwned, jamais le
|
||||
// TouchResource non-scopé.
|
||||
return s.Repo.TouchOwned(ownerID, resourceID)
|
||||
}
|
||||
|
||||
// applyRevokeShareOp handles OpRevokeShare: soft-revoke a user-to-user grant.
|
||||
@@ -303,10 +408,13 @@ func (s *Resources) applyRevokeShareOp(ownerID, resourceID string, op *SyncOpera
|
||||
if !resourceIDPattern.MatchString(p.GranteeUserID) {
|
||||
return errors.New("payload.granteeUserId must be 32 lowercase hex chars")
|
||||
}
|
||||
// Revoke is idempotent: no-op if already revoked/missing.
|
||||
_ = s.Repository.Shares.Revoke(resourceID, p.GranteeUserID)
|
||||
// Revoke is idempotent: no-op if already revoked/missing — mais les vraies
|
||||
// pannes DB remontent (cf. FEEDBACK §moyenne).
|
||||
if err := s.Repository.Shares.Revoke(resourceID, p.GranteeUserID); err != nil && !errors.Is(err, repository.ErrNotFound) {
|
||||
return err
|
||||
}
|
||||
// Bump resource updated_at so the grantee's delta snapshot reflects the change.
|
||||
return s.Repo.TouchResource(resourceID)
|
||||
return s.Repo.TouchOwned(ownerID, resourceID)
|
||||
}
|
||||
|
||||
// applyCreateLinkOp handles OpCreateLink: create a public share link.
|
||||
@@ -332,12 +440,15 @@ func (s *Resources) applyCreateLinkOp(ownerID, resourceID string, op *SyncOperat
|
||||
var expiresAt *time.Time
|
||||
if p.ExpiresAt != nil {
|
||||
t := time.UnixMilli(*p.ExpiresAt)
|
||||
if !t.After(time.Now()) {
|
||||
return errors.New("payload.expiresAt must be in the future")
|
||||
}
|
||||
expiresAt = &t
|
||||
}
|
||||
if err := s.Repository.Shares.CreateLink(p.Token, resourceID, p.Access, expiresAt, ownerID); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.Repo.TouchResource(resourceID)
|
||||
return s.Repo.TouchOwned(ownerID, resourceID)
|
||||
}
|
||||
|
||||
// applyRevokeLinkOp handles OpRevokeLink: soft-revoke a public share link.
|
||||
@@ -356,13 +467,35 @@ func (s *Resources) applyRevokeLinkOp(ownerID, resourceID string, op *SyncOperat
|
||||
if !resourceIDPattern.MatchString(p.Token) {
|
||||
return errors.New("payload.token must be 32 lowercase hex chars")
|
||||
}
|
||||
// Revoke is idempotent: no-op if already revoked/missing.
|
||||
_ = s.Repository.Shares.RevokeLink(p.Token)
|
||||
return s.Repo.TouchResource(resourceID)
|
||||
// Revoke is idempotent: no-op if already revoked/missing — mais les vraies
|
||||
// pannes DB remontent.
|
||||
if err := s.Repository.Shares.RevokeLink(p.Token); err != nil && !errors.Is(err, repository.ErrNotFound) {
|
||||
return err
|
||||
}
|
||||
return s.Repo.TouchOwned(ownerID, resourceID)
|
||||
}
|
||||
|
||||
func (s *Resources) recordApplied(deviceID string, op *SyncOperation) error {
|
||||
return s.Repository.Operations.Record(deviceID, op.OperationID, op.Operation, derefString(op.RefType), nullableInt64(derefInt64(op.RefID)), derefString(op.ResourceID), op.Payload)
|
||||
// checkNoCycle remonte la chaîne parentale depuis toFolder : si on rencontre
|
||||
// resourceID, le move créerait un cycle (cf. FEEDBACK #2).
|
||||
func (s *Resources) checkNoCycle(toFolderID, resourceID string) error {
|
||||
cur := toFolderID
|
||||
for i := 0; i < 128; i++ {
|
||||
if cur == "" {
|
||||
return nil
|
||||
}
|
||||
if cur == resourceID {
|
||||
return errCycle
|
||||
}
|
||||
parent, err := s.Repo.GetParentID(cur)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return err
|
||||
}
|
||||
return err
|
||||
}
|
||||
cur = parent
|
||||
}
|
||||
return errCycle
|
||||
}
|
||||
|
||||
func derefString(v *string) string {
|
||||
|
||||
Reference in New Issue
Block a user