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:
@@ -33,10 +33,22 @@ func (d *Devices) Exists(deviceID string) (bool, error) {
|
||||
|
||||
// MarkUser mémorise le dernier utilisateur connecté sur ce device (INFORMATIF,
|
||||
// jamais autorisant) et rafraîchit last_seen_at. Appelé au login.
|
||||
// Device absent → ErrNotFound (le handler distingue la course
|
||||
// Exists→MarkUser au lieu d'émettre un token pour un device fantôme).
|
||||
func (d *Devices) MarkUser(deviceID, userID string) error {
|
||||
_, err := d.DB.Exec(
|
||||
result, err := d.DB.Exec(
|
||||
`UPDATE devices SET user_id = $2, last_seen_at = NOW() WHERE device_id = $1`,
|
||||
deviceID, userID,
|
||||
)
|
||||
return err
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
affected, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if affected == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/kazier/backend/dbtest"
|
||||
@@ -71,3 +72,12 @@ func TestDevicesMarkUser(t *testing.T) {
|
||||
t.Errorf("user_id mémorisé = %q, attendu %q", storedUser, userID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDevicesMarkUserUnknownDevice(t *testing.T) {
|
||||
d := newTestDevices(t)
|
||||
// Device jamais enregistré → ErrNotFound (pas de UPDATE silencieux à
|
||||
// 0 ligne) : le login mappe ce cas en 401 au lieu d'émettre un token.
|
||||
if err := d.MarkUser(NewID(), NewID()); !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("MarkUser device inconnu: attendu ErrNotFound, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,6 +22,12 @@ var ErrJobNotFound = errors.New("ocr job not found")
|
||||
// ErrNoQueuedJobs marks an OCR queue drained (no job to claim).
|
||||
var ErrNoQueuedJobs = errors.New("no queued ocr jobs")
|
||||
|
||||
// ErrJobStateConflict marks a guarded transition attempted from an
|
||||
// unexpected state (double Complete, Fail of a non-processing job,
|
||||
// TouchProcessing of a non-queued job). Terminal states are sticky:
|
||||
// a second transition never overwrites the first.
|
||||
var ErrJobStateConflict = errors.New("ocr job state conflict")
|
||||
|
||||
type OcrJobs struct{ DB *sql.DB }
|
||||
|
||||
func (o *OcrJobs) Create(jobID, deviceID, fileID string) error {
|
||||
@@ -58,12 +64,22 @@ func (o *OcrJobs) Get(deviceID, jobID string) (OcrJobRow, error) {
|
||||
}
|
||||
|
||||
func (o *OcrJobs) TouchProcessing(deviceID, jobID string) error {
|
||||
_, err := o.DB.Exec(
|
||||
res, err := o.DB.Exec(
|
||||
`UPDATE ocr_jobs SET status = 'processing', started_at = NOW()
|
||||
WHERE job_id = $1 AND device_id = $2 AND status = 'queued'`,
|
||||
jobID, deviceID,
|
||||
)
|
||||
return err
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
affected, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if affected == 0 {
|
||||
return ErrJobStateConflict
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ClaimNext atomically picks the oldest queued job (FIFO) and moves it to
|
||||
@@ -96,12 +112,15 @@ func (o *OcrJobs) ClaimNext() (OcrJobRow, error) {
|
||||
|
||||
// ResetStaleProcessing requeues jobs stuck in `processing` (worker crash /
|
||||
// processus redémarré) et plus vieux que `olderThan`. Retourne le nb de jobs
|
||||
// requeued.
|
||||
// requeued. La comparaison utilise l'horloge DB (NOW(), pas time.Now() du
|
||||
// process) pour rester correcte même si les horloges divergent. Les jobs sans
|
||||
// `started_at` (claim sans timestamp, anomalie) sont aussi requeued.
|
||||
func (o *OcrJobs) ResetStaleProcessing(olderThan time.Duration) (int64, error) {
|
||||
res, err := o.DB.Exec(
|
||||
`UPDATE ocr_jobs SET status = 'queued', started_at = NULL
|
||||
WHERE status = 'processing' AND started_at < $1`,
|
||||
time.Now().Add(-olderThan),
|
||||
WHERE status = 'processing'
|
||||
AND (started_at IS NULL OR started_at < NOW() - ($1::bigint * INTERVAL '1 millisecond'))`,
|
||||
olderThan.Milliseconds(),
|
||||
)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
@@ -110,19 +129,39 @@ func (o *OcrJobs) ResetStaleProcessing(olderThan time.Duration) (int64, error) {
|
||||
}
|
||||
|
||||
func (o *OcrJobs) Complete(deviceID, jobID, text string) error {
|
||||
_, err := o.DB.Exec(
|
||||
res, err := o.DB.Exec(
|
||||
`UPDATE ocr_jobs SET status = 'done', text = NULLIF($3, ''), started_at = COALESCE(started_at, NOW()), completed_at = NOW()
|
||||
WHERE job_id = $1 AND device_id = $2`,
|
||||
WHERE job_id = $1 AND device_id = $2 AND status = 'processing'`,
|
||||
jobID, deviceID, text,
|
||||
)
|
||||
return err
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
affected, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if affected == 0 {
|
||||
return ErrJobStateConflict
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (o *OcrJobs) Fail(deviceID, jobID, message string) error {
|
||||
_, err := o.DB.Exec(
|
||||
res, err := o.DB.Exec(
|
||||
`UPDATE ocr_jobs SET status = 'failed', error = NULLIF($3, ''), started_at = COALESCE(started_at, NOW()), completed_at = NOW()
|
||||
WHERE job_id = $1 AND device_id = $2`,
|
||||
WHERE job_id = $1 AND device_id = $2 AND status = 'processing'`,
|
||||
jobID, deviceID, message,
|
||||
)
|
||||
return err
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
affected, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if affected == 0 {
|
||||
return ErrJobStateConflict
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -67,6 +67,10 @@ func TestOcrJobsFail(t *testing.T) {
|
||||
if err := repo.OcrJobs.Create(jobID, deviceID, fileID); err != nil {
|
||||
t.Fatalf("create: %v", err)
|
||||
}
|
||||
// Fail n'est valide que depuis `processing` (transition gardée).
|
||||
if err := repo.OcrJobs.TouchProcessing(deviceID, jobID); err != nil {
|
||||
t.Fatalf("touch processing: %v", err)
|
||||
}
|
||||
if err := repo.OcrJobs.Fail(deviceID, jobID, "tesseract exploded"); err != nil {
|
||||
t.Fatalf("fail: %v", err)
|
||||
}
|
||||
@@ -76,6 +80,71 @@ func TestOcrJobsFail(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestOcrJobsGuardedTransitions(t *testing.T) {
|
||||
repo, _, deviceID, fileID := seedOcrJobFixture(t)
|
||||
newJob := func(t *testing.T) string {
|
||||
t.Helper()
|
||||
jobID := NewID()
|
||||
if err := repo.OcrJobs.Create(jobID, deviceID, fileID); err != nil {
|
||||
t.Fatalf("create: %v", err)
|
||||
}
|
||||
return jobID
|
||||
}
|
||||
|
||||
// Fail depuis `queued` → conflit, le job reste queued.
|
||||
queued := newJob(t)
|
||||
if err := repo.OcrJobs.Fail(deviceID, queued, "boom"); !errors.Is(err, ErrJobStateConflict) {
|
||||
t.Errorf("fail depuis queued : attendu ErrJobStateConflict, got %v", err)
|
||||
}
|
||||
if row, _ := repo.OcrJobs.Get(deviceID, queued); row.Status != "queued" {
|
||||
t.Errorf("fail depuis queued : status = %q, attendu queued", row.Status)
|
||||
}
|
||||
|
||||
// Complete depuis `queued` → conflit.
|
||||
if err := repo.OcrJobs.Complete(deviceID, queued, "x"); !errors.Is(err, ErrJobStateConflict) {
|
||||
t.Errorf("complete depuis queued : attendu ErrJobStateConflict, got %v", err)
|
||||
}
|
||||
|
||||
// Double TouchProcessing → conflit.
|
||||
if err := repo.OcrJobs.TouchProcessing(deviceID, queued); err != nil {
|
||||
t.Fatalf("touch processing: %v", err)
|
||||
}
|
||||
if err := repo.OcrJobs.TouchProcessing(deviceID, queued); !errors.Is(err, ErrJobStateConflict) {
|
||||
t.Errorf("double touch : attendu ErrJobStateConflict, got %v", err)
|
||||
}
|
||||
|
||||
// Double Complete → le premier gagne, le second est un conflit.
|
||||
if err := repo.OcrJobs.Complete(deviceID, queued, "FIRST"); err != nil {
|
||||
t.Fatalf("complete: %v", err)
|
||||
}
|
||||
if err := repo.OcrJobs.Complete(deviceID, queued, "SECOND"); !errors.Is(err, ErrJobStateConflict) {
|
||||
t.Errorf("double complete : attendu ErrJobStateConflict, got %v", err)
|
||||
}
|
||||
if row, _ := repo.OcrJobs.Get(deviceID, queued); row.Text == nil || *row.Text != "FIRST" {
|
||||
t.Errorf("double complete : texte = %+v, attendu FIRST", row.Text)
|
||||
}
|
||||
|
||||
// Fail après Complete → conflit, le statut `done` est collant.
|
||||
if err := repo.OcrJobs.Fail(deviceID, queued, "late"); !errors.Is(err, ErrJobStateConflict) {
|
||||
t.Errorf("fail après done : attendu ErrJobStateConflict, got %v", err)
|
||||
}
|
||||
if row, _ := repo.OcrJobs.Get(deviceID, queued); row.Status != "done" {
|
||||
t.Errorf("fail après done : status = %q, attendu done", row.Status)
|
||||
}
|
||||
|
||||
// Complete après Fail → conflit.
|
||||
failed := newJob(t)
|
||||
if err := repo.OcrJobs.TouchProcessing(deviceID, failed); err != nil {
|
||||
t.Fatalf("touch processing: %v", err)
|
||||
}
|
||||
if err := repo.OcrJobs.Fail(deviceID, failed, "boom"); err != nil {
|
||||
t.Fatalf("fail: %v", err)
|
||||
}
|
||||
if err := repo.OcrJobs.Complete(deviceID, failed, "late"); !errors.Is(err, ErrJobStateConflict) {
|
||||
t.Errorf("complete après failed : attendu ErrJobStateConflict, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOcrJobsGetScopedByDevice(t *testing.T) {
|
||||
repo, _, deviceID, fileID := seedOcrJobFixture(t)
|
||||
jobID := NewID()
|
||||
@@ -179,3 +248,24 @@ func TestOcrJobsResetStaleProcessing(t *testing.T) {
|
||||
t.Errorf("status après reset = %q, attendu queued", row.Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOcrJobsResetStaleProcessingNullStartedAt(t *testing.T) {
|
||||
repo, _, deviceID, fileID := seedOcrJobFixture(t)
|
||||
jobID := NewID()
|
||||
if err := repo.OcrJobs.Create(jobID, deviceID, fileID); err != nil {
|
||||
t.Fatalf("create: %v", err)
|
||||
}
|
||||
// Job passé en `processing` sans `started_at` (anomalie de claim) → stale.
|
||||
if _, err := repo.OcrJobs.DB.Exec(
|
||||
`UPDATE ocr_jobs SET status = 'processing', started_at = NULL WHERE job_id = $1`, jobID); err != nil {
|
||||
t.Fatalf("forcer processing sans started_at: %v", err)
|
||||
}
|
||||
if n, err := repo.OcrJobs.ResetStaleProcessing(time.Minute); err != nil {
|
||||
t.Fatalf("reset: %v", err)
|
||||
} else if n != 1 {
|
||||
t.Errorf("reset started_at NULL : attendu 1, got %d", n)
|
||||
}
|
||||
if row, _ := repo.OcrJobs.Get(deviceID, jobID); row.Status != "queued" {
|
||||
t.Errorf("status après reset = %q, attendu queued", row.Status)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"regexp"
|
||||
@@ -16,9 +18,26 @@ type Operations struct {
|
||||
DB *sql.DB
|
||||
}
|
||||
|
||||
// Statuts de la trace outbox (CHECK status IN ('applied','failed'), 000004).
|
||||
// 'failed' = brouillon claimé pas encore confirmé (ou apply en échec) ;
|
||||
// 'applied' = effet durable confirmé.
|
||||
const (
|
||||
OpStatusApplied = "applied"
|
||||
OpStatusFailed = "failed"
|
||||
)
|
||||
|
||||
// ErrInvalidOperationID is returned when operation_id is not 32 lowercase hex.
|
||||
var ErrInvalidOperationID = errors.New("operation_id must be 32 lowercase hex chars")
|
||||
|
||||
// ErrInvalidPayload is returned when the trace payload is not valid JSON.
|
||||
// Le service le mappe en INVALID_REQUEST (faute client, message statique sûr).
|
||||
var ErrInvalidPayload = errors.New("invalid payload JSON")
|
||||
|
||||
// ErrPayloadMismatch is returned when an operation is replayed under the same
|
||||
// (device_id, operation_id) with a different payload (cf. A9). The replay
|
||||
// must halt in INVALID_REQUEST, never skip silently.
|
||||
var ErrPayloadMismatch = errors.New("operation replayed with different payload")
|
||||
|
||||
// Applied reports whether the operation was already processed for this device.
|
||||
func (o *Operations) Applied(deviceID, operationID string) (bool, error) {
|
||||
var exists int
|
||||
@@ -32,20 +51,157 @@ func (o *Operations) Applied(deviceID, operationID string) (bool, error) {
|
||||
return err == nil, err
|
||||
}
|
||||
|
||||
// StoredOp is the persisted trace of an applied operation (replay compare).
|
||||
type StoredOp struct {
|
||||
OpType string
|
||||
ResourceID string
|
||||
Payload []byte
|
||||
Status string
|
||||
PayloadHash string // "" = trace héritée pré-000013 (hash recalculé depuis Payload)
|
||||
}
|
||||
|
||||
// Get returns the stored trace for (device, operation), or sql.ErrNoRows.
|
||||
func (o *Operations) Get(deviceID, operationID string) (StoredOp, error) {
|
||||
var op StoredOp
|
||||
var resourceID sql.NullString
|
||||
var payloadHash sql.NullString
|
||||
var payload []byte
|
||||
err := o.DB.QueryRow(
|
||||
`SELECT op_type, resource_id, COALESCE(payload::text, '{}'), status, payload_hash
|
||||
FROM operations WHERE device_id = $1 AND operation_id = $2`,
|
||||
deviceID, operationID,
|
||||
).Scan(&op.OpType, &resourceID, &payload, &op.Status, &payloadHash)
|
||||
if err != nil {
|
||||
return StoredOp{}, err
|
||||
}
|
||||
if resourceID.Valid {
|
||||
op.ResourceID = resourceID.String
|
||||
}
|
||||
if payloadHash.Valid {
|
||||
op.PayloadHash = payloadHash.String
|
||||
}
|
||||
op.Payload = payload
|
||||
return op, nil
|
||||
}
|
||||
|
||||
// Claim atomically takes ownership of an operation slot for this device
|
||||
// (#7 : sérialisation des batches concurrents sur la contrainte
|
||||
// UNIQUE(device_id, operation_id)). Premier appelant → claimed=true, la ligne
|
||||
// est insérée en status='failed' (brouillon) avec le hash du payload ; le
|
||||
// perdant du conflit (claimed=false) suit le chemin rejeu (comparer via Get).
|
||||
// Après apply réussi, l'appelant promeut la ligne via MarkApplied ; en cas
|
||||
// d'échec d'apply, la ligne reste 'failed' (rejouable à payload identique).
|
||||
func (o *Operations) Claim(deviceID, operationID string, opType, refType string, refID *int64, resourceID string, payload []byte) (bool, error) {
|
||||
if !operationIDPattern.MatchString(operationID) {
|
||||
return false, ErrInvalidOperationID
|
||||
}
|
||||
if len(payload) != 0 && string(payload) != "null" && !json.Valid(payload) {
|
||||
return false, ErrInvalidPayload
|
||||
}
|
||||
var refTypeValue any
|
||||
if refType != "" {
|
||||
refTypeValue = refType
|
||||
}
|
||||
res, err := o.DB.Exec(
|
||||
`INSERT INTO operations (device_id, operation_id, op_type, ref_type, ref_id, resource_id, payload, payload_hash, status)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'failed')
|
||||
ON CONFLICT (device_id, operation_id) DO NOTHING`,
|
||||
deviceID, operationID, opType, refTypeValue, refID, nullable(resourceID), jsonBytes(payload), CanonicalPayloadHash(payload),
|
||||
)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
affected, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return affected == 1, nil
|
||||
}
|
||||
|
||||
// MarkApplied promotes a claimed ('failed') trace row to 'applied' once the
|
||||
// operation effect is durable. Best-effort : l'échec est remonté pour que le
|
||||
// batch retourne applied:i explicite (rejouable, pas 500 nu).
|
||||
func (o *Operations) MarkApplied(deviceID, operationID string) error {
|
||||
res, err := o.DB.Exec(
|
||||
`UPDATE operations SET status = 'applied'
|
||||
WHERE device_id = $1 AND operation_id = $2 AND status = 'failed'`,
|
||||
deviceID, operationID,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
affected, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if affected == 0 {
|
||||
// Déjà promue (rejeu concurrent) ou ligne absente : pas d'erreur,
|
||||
// l'idempotence est portée par la contrainte d'unicité.
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// MatchesReplay reports whether an incoming operation matches the stored
|
||||
// trace: same op type, same resource, same canonical payload hash. Legacy
|
||||
// rows (payload_hash NULL, pré-000013) comparent le hash recalculé depuis le
|
||||
// payload stocké. Mismatch → ErrPayloadMismatch (wrappable via errors.Is).
|
||||
func (op StoredOp) MatchesReplay(opType, resourceID string, payload []byte) error {
|
||||
if op.OpType != opType || op.ResourceID != resourceID {
|
||||
return ErrPayloadMismatch
|
||||
}
|
||||
want := CanonicalPayloadHash(payload)
|
||||
got := op.PayloadHash
|
||||
if got == "" {
|
||||
got = CanonicalPayloadHash(op.Payload)
|
||||
}
|
||||
if got != want {
|
||||
return ErrPayloadMismatch
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CanonicalPayloadHash is sha256-hex of the canonical payload form: empty /
|
||||
// "null" → {}, sinon round-trip JSON (clés triées, espaces neutralisés) pour
|
||||
// que deux sérialisations du même objet donnent le même hash.
|
||||
func CanonicalPayloadHash(payload []byte) string {
|
||||
sum := sha256.Sum256(canonicalPayloadBytes(payload))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func canonicalPayloadBytes(payload []byte) []byte {
|
||||
if len(payload) == 0 || string(payload) == "null" {
|
||||
return []byte(`{}`)
|
||||
}
|
||||
var v any
|
||||
if err := json.Unmarshal(payload, &v); err != nil {
|
||||
return []byte(`{}`)
|
||||
}
|
||||
out, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
return []byte(`{}`)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Record stores an applied operation trace (idempotent on replay).
|
||||
// Le hash canonique du payload est persisté (000013, cf. A9) ; status='applied'.
|
||||
func (o *Operations) Record(deviceID, operationID string, opType, refType string, refID *int64, resourceID string, payload []byte) error {
|
||||
if !operationIDPattern.MatchString(operationID) {
|
||||
return ErrInvalidOperationID
|
||||
}
|
||||
if len(payload) != 0 && string(payload) != "null" && !json.Valid(payload) {
|
||||
return ErrInvalidPayload
|
||||
}
|
||||
var refTypeValue any
|
||||
if refType != "" {
|
||||
refTypeValue = refType
|
||||
}
|
||||
_, err := o.DB.Exec(
|
||||
`INSERT INTO operations (device_id, operation_id, op_type, ref_type, ref_id, resource_id, payload)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||
`INSERT INTO operations (device_id, operation_id, op_type, ref_type, ref_id, resource_id, payload, payload_hash, status)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'applied')
|
||||
ON CONFLICT (device_id, operation_id) DO NOTHING`,
|
||||
deviceID, operationID, opType, refTypeValue, refID, nullable(resourceID), jsonBytes(payload),
|
||||
deviceID, operationID, opType, refTypeValue, refID, nullable(resourceID), jsonBytes(payload), CanonicalPayloadHash(payload),
|
||||
)
|
||||
return err
|
||||
}
|
||||
@@ -62,7 +218,9 @@ func jsonBytes(payload []byte) any {
|
||||
return []byte(`{}`)
|
||||
}
|
||||
if !json.Valid(payload) {
|
||||
return []byte(`{}`)
|
||||
// Trace infidèle refusée (cf. A15) : l'appelant doit rejeter en amont ;
|
||||
// ici on ne normalise plus silencieusement vers {}.
|
||||
return nil
|
||||
}
|
||||
return payload
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
@@ -66,7 +65,7 @@ func TestOperationsRecordRejectsInvalidOperationID(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestOperationsRecordNormalizesInvalidPayload(t *testing.T) {
|
||||
func TestOperationsRecordRejectsInvalidPayload(t *testing.T) {
|
||||
o, devices := newTestOperations(t)
|
||||
deviceID := NewID()
|
||||
if err := devices.Upsert(deviceID); err != nil {
|
||||
@@ -74,20 +73,128 @@ func TestOperationsRecordNormalizesInvalidPayload(t *testing.T) {
|
||||
}
|
||||
|
||||
opID := NewID()
|
||||
// Un payload non-JSON ne doit pas faire échouer la trace (jsonBytes → {}).
|
||||
if err := o.Record(deviceID, opID, "create_resource", "resource", nil, NewID(), []byte(`not-json`)); err != nil {
|
||||
t.Fatalf("record: %v", err)
|
||||
// Un payload non-JSON est refusé (pas de normalisation silencieuse vers {}) :
|
||||
// l'appelant (service) doit rejeter en amont en INVALID_REQUEST.
|
||||
if err := o.Record(deviceID, opID, "create_resource", "resource", nil, NewID(), []byte(`not-json`)); err == nil {
|
||||
t.Error("payload non-JSON : erreur attendue, got nil")
|
||||
}
|
||||
if applied, _ := o.Applied(deviceID, opID); applied {
|
||||
t.Error("record refusé : l'op ne doit pas être tracée")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOperationsRecordStoresPayloadHash(t *testing.T) {
|
||||
o, devices := newTestOperations(t)
|
||||
deviceID := NewID()
|
||||
if err := devices.Upsert(deviceID); err != nil {
|
||||
t.Fatalf("register device: %v", err)
|
||||
}
|
||||
|
||||
opID := NewID()
|
||||
payload := []byte(`{"name":"x"}`)
|
||||
if err := o.Record(deviceID, opID, "create_resource", "resource", nil, NewID(), payload); err != nil {
|
||||
t.Fatalf("record: %v", err)
|
||||
}
|
||||
stored, err := o.Get(deviceID, opID)
|
||||
if err != nil {
|
||||
t.Fatalf("get: %v", err)
|
||||
}
|
||||
if stored.Status != OpStatusApplied {
|
||||
t.Errorf("status = %q, attendu %q", stored.Status, OpStatusApplied)
|
||||
}
|
||||
want := CanonicalPayloadHash(payload)
|
||||
if stored.PayloadHash != want {
|
||||
t.Errorf("payload_hash = %q, attendu %q", stored.PayloadHash, want)
|
||||
}
|
||||
if len(stored.PayloadHash) != 64 {
|
||||
t.Errorf("payload_hash attendu 64-hex, got %q", stored.PayloadHash)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOperationsClaimAndMarkApplied(t *testing.T) {
|
||||
o, devices := newTestOperations(t)
|
||||
deviceID := NewID()
|
||||
if err := devices.Upsert(deviceID); err != nil {
|
||||
t.Fatalf("register device: %v", err)
|
||||
}
|
||||
|
||||
var stored string
|
||||
if err := o.DB.QueryRow(`SELECT payload::text FROM operations WHERE device_id = $1 AND operation_id = $2`, deviceID, opID).Scan(&stored); err != nil {
|
||||
t.Fatalf("read payload: %v", err)
|
||||
opID := NewID()
|
||||
payload := []byte(`{"name":"x"}`)
|
||||
// Premier claim → pris.
|
||||
claimed, err := o.Claim(deviceID, opID, "create_resource", "resource", nil, NewID(), payload)
|
||||
if err != nil || !claimed {
|
||||
t.Fatalf("claim 1: claimed=%v err=%v", claimed, err)
|
||||
}
|
||||
// La trace brouillon est en status failed (pas encore confirmée).
|
||||
stored, err := o.Get(deviceID, opID)
|
||||
if err != nil {
|
||||
t.Fatalf("get: %v", err)
|
||||
}
|
||||
if stored.Status != OpStatusFailed {
|
||||
t.Errorf("status après claim = %q, attendu %q", stored.Status, OpStatusFailed)
|
||||
}
|
||||
// Second claim (batch concurrent) → perdu, chemin rejeu.
|
||||
claimed, err = o.Claim(deviceID, opID, "create_resource", "resource", nil, NewID(), payload)
|
||||
if err != nil || claimed {
|
||||
t.Fatalf("claim 2: claimed=%v err=%v", claimed, err)
|
||||
}
|
||||
// Promotion après apply réussi.
|
||||
if err := o.MarkApplied(deviceID, opID); err != nil {
|
||||
t.Fatalf("mark applied: %v", err)
|
||||
}
|
||||
stored, err = o.Get(deviceID, opID)
|
||||
if err != nil {
|
||||
t.Fatalf("get 2: %v", err)
|
||||
}
|
||||
if stored.Status != OpStatusApplied {
|
||||
t.Errorf("status après promote = %q, attendu %q", stored.Status, OpStatusApplied)
|
||||
}
|
||||
// MarkApplied idempotent (re-promote sans effet).
|
||||
if err := o.MarkApplied(deviceID, opID); err != nil {
|
||||
t.Errorf("re-promote: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStoredOpMatchesReplay(t *testing.T) {
|
||||
o, devices := newTestOperations(t)
|
||||
deviceID := NewID()
|
||||
if err := devices.Upsert(deviceID); err != nil {
|
||||
t.Fatalf("register device: %v", err)
|
||||
}
|
||||
|
||||
opID := NewID()
|
||||
resID := NewID()
|
||||
payload := []byte(`{"name":"x"}`)
|
||||
if err := o.Record(deviceID, opID, "create_resource", "resource", nil, resID, payload); err != nil {
|
||||
t.Fatalf("record: %v", err)
|
||||
}
|
||||
stored, err := o.Get(deviceID, opID)
|
||||
if err != nil {
|
||||
t.Fatalf("get: %v", err)
|
||||
}
|
||||
// Identique (espaces neutres via hash canonique) → match.
|
||||
if err := stored.MatchesReplay("create_resource", resID, []byte("{ \"name\" : \"x\" }")); err != nil {
|
||||
t.Errorf("rejeu identique: %v", err)
|
||||
}
|
||||
// Payload muté → ErrPayloadMismatch.
|
||||
if err := stored.MatchesReplay("create_resource", resID, []byte(`{"name":"y"}`)); !errors.Is(err, ErrPayloadMismatch) {
|
||||
t.Errorf("payload muté : attendu ErrPayloadMismatch, got %v", err)
|
||||
}
|
||||
// Type muté → ErrPayloadMismatch.
|
||||
if err := stored.MatchesReplay("delete_resource", resID, payload); !errors.Is(err, ErrPayloadMismatch) {
|
||||
t.Errorf("type muté : attendu ErrPayloadMismatch, got %v", err)
|
||||
}
|
||||
// Ressource mutée → ErrPayloadMismatch.
|
||||
if err := stored.MatchesReplay("create_resource", NewID(), payload); !errors.Is(err, ErrPayloadMismatch) {
|
||||
t.Errorf("ressource mutée : attendu ErrPayloadMismatch, got %v", err)
|
||||
}
|
||||
var parsed any
|
||||
if err := json.Unmarshal([]byte(stored), &parsed); err != nil {
|
||||
t.Fatalf("payload stocké invalide: %q", stored)
|
||||
// Ligne héritée sans payload_hash (pré-000013) : hash recalculé depuis
|
||||
// le payload stocké → match quand identique.
|
||||
stored.PayloadHash = ""
|
||||
if err := stored.MatchesReplay("create_resource", resID, payload); err != nil {
|
||||
t.Errorf("ligne héritée identique: %v", err)
|
||||
}
|
||||
if stored != "{}" {
|
||||
t.Errorf("payload normalisé attendu {}, got %q", stored)
|
||||
if err := stored.MatchesReplay("create_resource", resID, []byte(`{"name":"z"}`)); !errors.Is(err, ErrPayloadMismatch) {
|
||||
t.Errorf("ligne héritée mutée : attendu ErrPayloadMismatch, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
+122
-48
@@ -20,12 +20,22 @@ var ErrNameConflict = errors.New("name conflict")
|
||||
|
||||
// NewID returns an opaque lowercase 32-hex identifier (charset ^[0-9a-f]{32}$),
|
||||
// mirroring the mobile's lower(hex(randomblob(16))). Never a UUID.
|
||||
// Panics on entropy failure (legacy) — prefer NewIDErr for new code.
|
||||
func NewID() string {
|
||||
buf := make([]byte, 16)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
id, err := NewIDErr()
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("crypto/rand failed: %v", err))
|
||||
}
|
||||
return hex.EncodeToString(buf)
|
||||
return id
|
||||
}
|
||||
|
||||
// NewIDErr is the non-panicking variant (cf. FEEDBACK A5).
|
||||
func NewIDErr() (string, error) {
|
||||
buf := make([]byte, 16)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
return "", fmt.Errorf("crypto/rand failed: %w", err)
|
||||
}
|
||||
return hex.EncodeToString(buf), nil
|
||||
}
|
||||
|
||||
func isUniqueViolation(err error) bool {
|
||||
@@ -33,6 +43,14 @@ func isUniqueViolation(err error) bool {
|
||||
return errors.As(err, &pqErr) && pqErr.Code == "23505"
|
||||
}
|
||||
|
||||
// isForeignKeyViolation reports a Postgres FK violation (23503). Une
|
||||
// violation de FK parent (dossier cible disparu en course) est mappée vers
|
||||
// ErrNotFound — cible inexistante — plutôt que de fuir en 500.
|
||||
func isForeignKeyViolation(err error) bool {
|
||||
var pqErr *pq.Error
|
||||
return errors.As(err, &pqErr) && pqErr.Code == "23503"
|
||||
}
|
||||
|
||||
type FileRow struct {
|
||||
ID string
|
||||
Name string
|
||||
@@ -108,42 +126,39 @@ const grantedCTE = `
|
||||
AND r.deleted_at IS NULL AND g.depth < 100
|
||||
)`
|
||||
|
||||
func (r *Resources) folderExists(ownerID, folderID string) (bool, error) {
|
||||
var exists int
|
||||
err := r.DB.QueryRow(
|
||||
`SELECT 1 FROM resources
|
||||
WHERE resource_id = $1 AND user_id = $2 AND type = 'folder' AND deleted_at IS NULL`,
|
||||
folderID, ownerID,
|
||||
).Scan(&exists)
|
||||
if err == sql.ErrNoRows {
|
||||
return false, nil
|
||||
}
|
||||
return err == nil, err
|
||||
}
|
||||
|
||||
// insert persiste une ligne file/folder avec parent-check ATOMIQUE
|
||||
// (single-statement INSERT...SELECT) : le dossier parent (quand non vide)
|
||||
// doit exister, appartenir au même owner, être un folder non supprimé —
|
||||
// sinon ErrNotFound. L'ancien SELECT-then-INSERT (TOCTOU : parent supprimé
|
||||
// entre check et insert → FK 500) est remplacé ; une violation FK résiduelle
|
||||
// (course) est mappée vers ErrNotFound, jamais 500.
|
||||
func (r *Resources) insert(ownerID, id, name, parentResourceID, resourceType string, size int64, mimeType, extension *string) error {
|
||||
if parentResourceID != "" {
|
||||
ok, err := r.folderExists(ownerID, parentResourceID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
return fmt.Errorf("folder %s: %w", parentResourceID, ErrNotFound)
|
||||
}
|
||||
}
|
||||
var parentID any
|
||||
if parentResourceID != "" {
|
||||
parentID = parentResourceID
|
||||
}
|
||||
_, err := r.DB.Exec(
|
||||
result, err := r.DB.Exec(
|
||||
`INSERT INTO resources (resource_id, type, name, parent_id, user_id, size_bytes, mime_type, extension)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
|
||||
id, resourceType, name, parentID, ownerID, size, mimeType, extension,
|
||||
SELECT $1, $2, $3, NULLIF($4, ''), $5, $6, $7, $8
|
||||
WHERE $4 = '' OR EXISTS (
|
||||
SELECT 1 FROM resources
|
||||
WHERE resource_id = $4 AND user_id = $5 AND type = 'folder' AND deleted_at IS NULL
|
||||
)`,
|
||||
id, resourceType, name, parentResourceID, ownerID, size, mimeType, extension,
|
||||
)
|
||||
if isUniqueViolation(err) {
|
||||
return ErrNameConflict
|
||||
}
|
||||
return err
|
||||
if isForeignKeyViolation(err) {
|
||||
return fmt.Errorf("folder %s: %w", parentResourceID, ErrNotFound)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
affected, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if affected == 0 {
|
||||
return fmt.Errorf("folder %s: %w", parentResourceID, ErrNotFound)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// InsertFile persists a file metadata row for the owner device. The parent
|
||||
@@ -270,6 +285,26 @@ func (r *Resources) GetResourceOwner(resourceID string) (string, error) {
|
||||
return ownerID, err
|
||||
}
|
||||
|
||||
// GetParentID returns the parent_id ('""' si racine) d'une ressource non
|
||||
// supprimée. No-rows → ErrNotFound. Sert au check de cycle des moves.
|
||||
func (r *Resources) GetParentID(resourceID string) (string, error) {
|
||||
var parent sql.NullString
|
||||
err := r.DB.QueryRow(
|
||||
`SELECT parent_id FROM resources WHERE resource_id = $1 AND deleted_at IS NULL`,
|
||||
resourceID,
|
||||
).Scan(&parent)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return "", ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !parent.Valid {
|
||||
return "", nil
|
||||
}
|
||||
return parent.String, nil
|
||||
}
|
||||
|
||||
// DeleteFile soft-deletes the file (deleted_at), returning its id.
|
||||
func (r *Resources) DeleteFile(ownerID, resourceID string) (string, error) {
|
||||
result, err := r.DB.Exec(
|
||||
@@ -369,26 +404,28 @@ func (r *Resources) GetFolder(ownerID, resourceID string) (FolderRow, error) {
|
||||
return row, err
|
||||
}
|
||||
|
||||
// MoveResource sets parent_id (root when parentResourceID empty). The target
|
||||
// folder must exist and belong to the owner. Absent source is a no-op.
|
||||
// MoveResource sets parent_id (root when parentResourceID empty) avec
|
||||
// parent-check ATOMIQUE (single-statement) : la cible doit exister,
|
||||
// appartenir au même owner, être un folder non supprimé. Source absente /
|
||||
// non-owned OU cible absente → ErrNotFound (même code : le choix A8
|
||||
// move-non-owned → NOT_FOUND est appliqué ici, cf. LOT 3 pour la doc
|
||||
// sync). Violation FK résiduelle (course) → ErrNotFound, jamais 500.
|
||||
func (r *Resources) MoveResource(ownerID, resourceID, parentResourceID string) error {
|
||||
if parentResourceID != "" {
|
||||
if _, err := r.GetFolder(ownerID, parentResourceID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
var parentID any
|
||||
if parentResourceID != "" {
|
||||
parentID = parentResourceID
|
||||
}
|
||||
result, err := r.DB.Exec(
|
||||
`UPDATE resources SET parent_id = $3, updated_at = NOW()
|
||||
WHERE resource_id = $1 AND user_id = $2 AND deleted_at IS NULL`,
|
||||
resourceID, ownerID, parentID,
|
||||
`UPDATE resources SET parent_id = NULLIF($3, ''), updated_at = NOW()
|
||||
WHERE resource_id = $1 AND user_id = $2 AND deleted_at IS NULL
|
||||
AND ($3 = '' OR EXISTS (
|
||||
SELECT 1 FROM resources
|
||||
WHERE resource_id = $3 AND user_id = $2 AND type = 'folder' AND deleted_at IS NULL
|
||||
))`,
|
||||
resourceID, ownerID, parentResourceID,
|
||||
)
|
||||
if err != nil && isUniqueViolation(err) {
|
||||
return ErrNameConflict
|
||||
}
|
||||
if err != nil && isForeignKeyViolation(err) {
|
||||
return fmt.Errorf("folder %s: %w", parentResourceID, ErrNotFound)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -402,7 +439,7 @@ func (r *Resources) MoveResource(ownerID, resourceID, parentResourceID string) e
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateName renames a resource. Absent source is a no-op.
|
||||
// UpdateName renames a resource. Absent / not owned → ErrNotFound.
|
||||
func (r *Resources) UpdateName(ownerID, resourceID, name string) error {
|
||||
result, err := r.DB.Exec(
|
||||
`UPDATE resources SET name = $3, updated_at = NOW()
|
||||
@@ -425,8 +462,18 @@ func (r *Resources) UpdateName(ownerID, resourceID, name string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateNameOwned renames a resource OWNED by ownerID. Absent / not owned →
|
||||
// ErrNotFound, sibling homonyme → ErrNameConflict. Variante scopée
|
||||
// canonique (sémantique identique à UpdateName, nom aligné sur TouchOwned
|
||||
// pour LOT 3).
|
||||
func (r *Resources) UpdateNameOwned(ownerID, resourceID, name string) error {
|
||||
return r.UpdateName(ownerID, resourceID, name)
|
||||
}
|
||||
|
||||
// UpdateNameByID renames a resource without owner scoping — the caller
|
||||
// (service) has already verified the user's effective access (editor+).
|
||||
// Conservée volontairement pour update_metadata : un editor non-owner peut
|
||||
// renommer, UpdateNameOwned rejetterait à tort.
|
||||
func (r *Resources) UpdateNameByID(resourceID, name string) error {
|
||||
result, err := r.DB.Exec(
|
||||
`UPDATE resources SET name = $2, updated_at = NOW()
|
||||
@@ -519,8 +566,35 @@ func (r *Resources) ExistsOwner(ownerID, resourceID string) (bool, error) {
|
||||
return err == nil, err
|
||||
}
|
||||
|
||||
// TouchOwned bumps updated_at on a non-deleted resource OWNED by ownerID so
|
||||
// that the grantee's delta snapshot picks it up after a share is created.
|
||||
// Absent / not owned → ErrNotFound. C'est la variante scopée à utiliser
|
||||
// (LOT 3 : migrer les appelants sync vers TouchOwned).
|
||||
func (r *Resources) TouchOwned(ownerID, resourceID string) error {
|
||||
result, err := r.DB.Exec(
|
||||
`UPDATE resources SET updated_at = NOW()
|
||||
WHERE resource_id = $1 AND user_id = $2 AND deleted_at IS NULL`,
|
||||
resourceID, ownerID,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
affected, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if affected == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// TouchResource bumps updated_at on a non-deleted resource so that the
|
||||
// grantee's delta snapshot picks it up after a share is created.
|
||||
//
|
||||
// Deprecated: non scopée (touche n'importe quel owner) — préférer TouchOwned.
|
||||
// Plus aucun appelant sync (migrés vers TouchOwned) ; conservée pour
|
||||
// compatibilité des appelants externes éventuels.
|
||||
func (r *Resources) TouchResource(resourceID string) error {
|
||||
_, err := r.DB.Exec(
|
||||
`UPDATE resources SET updated_at = NOW() WHERE resource_id = $1 AND deleted_at IS NULL`,
|
||||
|
||||
@@ -233,6 +233,156 @@ func TestListOwnedDelta(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestInsertParentCrossOwnerNotFound(t *testing.T) {
|
||||
repo := newTestResources(t)
|
||||
owner := NewID()
|
||||
other := NewID()
|
||||
mustInsertUser(t, repo, owner)
|
||||
mustInsertUser(t, repo, other)
|
||||
|
||||
ownerFolder := NewID()
|
||||
if err := repo.InsertFolder(owner, ownerFolder, "Docs", ""); err != nil {
|
||||
t.Fatalf("insert folder: %v", err)
|
||||
}
|
||||
|
||||
// Dossier d'un autre owner comme parent → NOT_FOUND (pas de fuite 500).
|
||||
if err := repo.InsertFile(other, NewID(), "x.txt", ownerFolder, 1, nil, nil); !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("parent autre owner : attendu ErrNotFound, got %v", err)
|
||||
}
|
||||
if err := repo.InsertFolder(other, NewID(), "Sub", ownerFolder); !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("parent dossier autre owner : attendu ErrNotFound, got %v", err)
|
||||
}
|
||||
|
||||
// Un fichier comme parent → NOT_FOUND (pas un folder).
|
||||
fileID := NewID()
|
||||
if err := repo.InsertFile(owner, fileID, "note.txt", "", 1, nil, nil); err != nil {
|
||||
t.Fatalf("insert file: %v", err)
|
||||
}
|
||||
if err := repo.InsertFile(owner, NewID(), "y.txt", fileID, 1, nil, nil); !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("parent fichier : attendu ErrNotFound, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMoveResourceAtomic(t *testing.T) {
|
||||
repo := newTestResources(t)
|
||||
owner := NewID()
|
||||
other := NewID()
|
||||
mustInsertUser(t, repo, owner)
|
||||
mustInsertUser(t, repo, other)
|
||||
|
||||
folderA := NewID()
|
||||
folderB := NewID()
|
||||
if err := repo.InsertFolder(owner, folderA, "A", ""); err != nil {
|
||||
t.Fatalf("insert A: %v", err)
|
||||
}
|
||||
if err := repo.InsertFolder(owner, folderB, "B", ""); err != nil {
|
||||
t.Fatalf("insert B: %v", err)
|
||||
}
|
||||
otherFolder := NewID()
|
||||
if err := repo.InsertFolder(other, otherFolder, "Other", ""); err != nil {
|
||||
t.Fatalf("insert other: %v", err)
|
||||
}
|
||||
fileID := NewID()
|
||||
if err := repo.InsertFile(owner, fileID, "note.txt", folderA, 1, nil, nil); err != nil {
|
||||
t.Fatalf("insert file: %v", err)
|
||||
}
|
||||
|
||||
// Move OK vers dossier owned.
|
||||
if err := repo.MoveResource(owner, fileID, folderB); err != nil {
|
||||
t.Fatalf("move: %v", err)
|
||||
}
|
||||
got, err := repo.GetFile(owner, fileID)
|
||||
if err != nil || got.FolderID != folderB {
|
||||
t.Errorf("après move : folder=%q err=%v", got.FolderID, err)
|
||||
}
|
||||
|
||||
// Cible d'un autre owner → NOT_FOUND, la source ne bouge pas.
|
||||
if err := repo.MoveResource(owner, fileID, otherFolder); !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("cible autre owner : attendu ErrNotFound, got %v", err)
|
||||
}
|
||||
got, _ = repo.GetFile(owner, fileID)
|
||||
if got.FolderID != folderB {
|
||||
t.Errorf("move refusé ne doit rien changer, folder=%q", got.FolderID)
|
||||
}
|
||||
|
||||
// Cible inexistante → NOT_FOUND.
|
||||
if err := repo.MoveResource(owner, fileID, NewID()); !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("cible inconnue : attendu ErrNotFound, got %v", err)
|
||||
}
|
||||
|
||||
// Source inconnue → NOT_FOUND.
|
||||
if err := repo.MoveResource(owner, NewID(), folderB); !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("source inconnue : attendu ErrNotFound, got %v", err)
|
||||
}
|
||||
|
||||
// Retour à la racine.
|
||||
if err := repo.MoveResource(owner, fileID, ""); err != nil {
|
||||
t.Fatalf("move racine: %v", err)
|
||||
}
|
||||
got, _ = repo.GetFile(owner, fileID)
|
||||
if got.FolderID != "" {
|
||||
t.Errorf("racine attendue, folder=%q", got.FolderID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTouchOwnedAndUpdateNameOwned(t *testing.T) {
|
||||
repo := newTestResources(t)
|
||||
owner := NewID()
|
||||
other := NewID()
|
||||
mustInsertUser(t, repo, owner)
|
||||
mustInsertUser(t, repo, other)
|
||||
|
||||
fileID := NewID()
|
||||
if err := repo.InsertFile(owner, fileID, "note.txt", "", 1, nil, nil); err != nil {
|
||||
t.Fatalf("insert: %v", err)
|
||||
}
|
||||
|
||||
before, err := repo.GetFile(owner, fileID)
|
||||
if err != nil {
|
||||
t.Fatalf("get: %v", err)
|
||||
}
|
||||
if err := repo.TouchOwned(owner, fileID); err != nil {
|
||||
t.Fatalf("touch owned: %v", err)
|
||||
}
|
||||
after, err := repo.GetFile(owner, fileID)
|
||||
if err != nil {
|
||||
t.Fatalf("get après touch: %v", err)
|
||||
}
|
||||
if !after.UpdatedAt.After(before.UpdatedAt) && !after.UpdatedAt.Equal(before.UpdatedAt) {
|
||||
t.Errorf("touch doit bumperc updated_at : %v → %v", before.UpdatedAt, after.UpdatedAt)
|
||||
}
|
||||
|
||||
// Non-owned / inconnu → ErrNotFound.
|
||||
if err := repo.TouchOwned(other, fileID); !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("touch autre owner : attendu ErrNotFound, got %v", err)
|
||||
}
|
||||
if err := repo.TouchOwned(owner, NewID()); !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("touch inconnu : attendu ErrNotFound, got %v", err)
|
||||
}
|
||||
|
||||
if err := repo.UpdateNameOwned(owner, fileID, "renamed.txt"); err != nil {
|
||||
t.Fatalf("rename owned: %v", err)
|
||||
}
|
||||
renamed, err := repo.GetFile(owner, fileID)
|
||||
if err != nil || renamed.Name != "renamed.txt" {
|
||||
t.Errorf("rename : %+v err=%v", renamed, err)
|
||||
}
|
||||
if err := repo.UpdateNameOwned(other, fileID, "volé.txt"); !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("rename autre owner : attendu ErrNotFound, got %v", err)
|
||||
}
|
||||
if err := repo.UpdateNameOwned(owner, NewID(), "x.txt"); !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("rename inconnu : attendu ErrNotFound, got %v", err)
|
||||
}
|
||||
|
||||
// Anciennes variantes (deprecated, compat LOT 3) : toujours fonctionnelles.
|
||||
if err := repo.TouchResource(fileID); err != nil {
|
||||
t.Errorf("touch legacy: %v", err)
|
||||
}
|
||||
if err := repo.UpdateNameByID(fileID, "legacy.txt"); err != nil {
|
||||
t.Errorf("rename legacy: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateOcrTextAndReadBack(t *testing.T) {
|
||||
repo := newTestResources(t)
|
||||
owner := NewID()
|
||||
|
||||
@@ -327,17 +327,44 @@ func (s *Shares) ResourceExists(resourceID string) (bool, error) {
|
||||
}
|
||||
|
||||
// CreateLink stores a share link (token = id, client-generated 32-hex).
|
||||
// Idempotent sur rejeu même (token) : ON CONFLICT DO NOTHING puis vérifie
|
||||
// que le lien existant vise la même ressource ET le même owner (created_by) —
|
||||
// sinon ErrNameConflict (réutilisation de token, cf. FEEDBACK #3). Un lien
|
||||
// révoqué identique reste révoqué (pas de résurrection par rejeu : revoke gagne).
|
||||
func (s *Shares) CreateLink(token, resourceID, access string, expiresAt *time.Time, createdBy string) error {
|
||||
var expires any
|
||||
if expiresAt != nil {
|
||||
expires = *expiresAt
|
||||
}
|
||||
_, err := s.DB.Exec(
|
||||
res, err := s.DB.Exec(
|
||||
`INSERT INTO share_links (id, resource_id, access, created_by, expires_at)
|
||||
VALUES ($1, $2, $3, $4, $5)`,
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (id) DO NOTHING`,
|
||||
token, resourceID, access, createdBy, expires,
|
||||
)
|
||||
return err
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
affected, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if affected == 1 {
|
||||
return nil
|
||||
}
|
||||
// Conflit : le token existe déjà — idempotent si même (ressource, owner),
|
||||
// sinon conflit (le token est une clé d'idempotence client).
|
||||
var existing struct {
|
||||
resourceID string
|
||||
createdBy string
|
||||
}
|
||||
if err := s.DB.QueryRow(`SELECT resource_id, created_by FROM share_links WHERE id = $1`, token).Scan(&existing.resourceID, &existing.createdBy); err != nil {
|
||||
return err
|
||||
}
|
||||
if existing.resourceID != resourceID || existing.createdBy != createdBy {
|
||||
return ErrNameConflict
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RevokeLink soft-revokes a link by token. Returns ErrNotFound if the link
|
||||
|
||||
+42
-15
@@ -20,11 +20,12 @@ type Users struct {
|
||||
DB *sql.DB
|
||||
}
|
||||
|
||||
// Count retourne le nombre d'utilisateurs (y compris supprimés) — sert au
|
||||
// bootstrap admin au démarrage.
|
||||
// Count retourne le nombre d'utilisateurs ACTIFS (deleted_at IS NULL) — sert
|
||||
// au bootstrap admin au démarrage. Une base dont tous les comptes sont
|
||||
// soft-deleted est vue comme vide : EnsureAdmin recréera un admin (#9+A10).
|
||||
func (u *Users) Count() (int, error) {
|
||||
var n int
|
||||
err := u.DB.QueryRow(`SELECT COUNT(*) FROM users`).Scan(&n)
|
||||
err := u.DB.QueryRow(`SELECT COUNT(*) FROM users WHERE deleted_at IS NULL`).Scan(&n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
@@ -67,8 +68,11 @@ func (u *Users) ResolveExact(normalized string) (*UserRow, error) {
|
||||
|
||||
// Create insère un compte avec un id 32-hex généré. Retourne l'id.
|
||||
func (u *Users) Create(username, usernameNormalized, passwordHash string, isAdmin bool) (string, error) {
|
||||
id := NewID()
|
||||
_, err := u.DB.Exec(
|
||||
id, err := NewIDErr()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
_, err = u.DB.Exec(
|
||||
`INSERT INTO users (id, username, username_normalized, password_hash, is_admin, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5, NOW())`,
|
||||
id, username, usernameNormalized, passwordHash, isAdmin,
|
||||
@@ -82,24 +86,47 @@ func (u *Users) Create(username, usernameNormalized, passwordHash string, isAdmi
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// UpdatePassword remplace le hash du compte. Les tokens déjà émis restent
|
||||
// valides 7 jours : limite assumée V1 (pas de liste de révocation).
|
||||
// UpdatePassword remplace le hash du compte actif. Compte absent ou
|
||||
// soft-deleted → ErrNotFound. Les tokens déjà émis restent valides 7 jours :
|
||||
// limite assumée V1 (pas de liste de révocation).
|
||||
func (u *Users) UpdatePassword(id, newHash string) error {
|
||||
_, err := u.DB.Exec(
|
||||
`UPDATE users SET password_hash = $2, updated_at = NOW() WHERE id = $1`,
|
||||
result, err := u.DB.Exec(
|
||||
`UPDATE users SET password_hash = $2, updated_at = NOW() WHERE id = $1 AND deleted_at IS NULL`,
|
||||
id, newHash,
|
||||
)
|
||||
return err
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
affected, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if affected == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarkDeleted soft-delete un compte : les tokens issus sont rejetés par le
|
||||
// middleware (GetByID filtre deleted_at).
|
||||
// MarkDeleted soft-delete un compte actif : les tokens issus sont rejetés par
|
||||
// le middleware (GetByID filtre deleted_at). Compte absent ou déjà supprimé →
|
||||
// ErrNotFound (pas d'idempotence silencieuse : le second delete signale que
|
||||
// la cible n'est plus active).
|
||||
func (u *Users) MarkDeleted(id string) error {
|
||||
_, err := u.DB.Exec(
|
||||
`UPDATE users SET deleted_at = NOW(), updated_at = NOW() WHERE id = $1`,
|
||||
result, err := u.DB.Exec(
|
||||
`UPDATE users SET deleted_at = NOW(), updated_at = NOW() WHERE id = $1 AND deleted_at IS NULL`,
|
||||
id,
|
||||
)
|
||||
return err
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
affected, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if affected == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func scanUser(scan func(...any) error) (*UserRow, error) {
|
||||
|
||||
@@ -64,6 +64,11 @@ func TestUsersUpdatePassword(t *testing.T) {
|
||||
if err != nil || row.PasswordHash != "hash-2" {
|
||||
t.Errorf("hash après update = %q (err=%v)", row.PasswordHash, err)
|
||||
}
|
||||
|
||||
// Compte inconnu → ErrNotFound (#9+A10).
|
||||
if err := u.UpdatePassword(NewID(), "hash-x"); !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("update password inconnu : attendu ErrNotFound, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUsersMarkDeletedHidesAccount(t *testing.T) {
|
||||
@@ -82,7 +87,22 @@ func TestUsersMarkDeletedHidesAccount(t *testing.T) {
|
||||
if _, err := u.GetByUsernameNormalized("carol"); !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("get par username après suppression : attendu ErrNotFound, got %v", err)
|
||||
}
|
||||
if n, _ := u.Count(); n != 1 {
|
||||
t.Errorf("count doit compter aussi les supprimés (bootstrap), got %d", n)
|
||||
// Count ne compte que les ACTIFS : carol soft-deleted → 0 (#9+A10). Une
|
||||
// base 100% soft-deleted est vue comme vide par le bootstrap.
|
||||
if n, _ := u.Count(); n != 0 {
|
||||
t.Errorf("count doit exclure les supprimés, got %d", n)
|
||||
}
|
||||
|
||||
// UpdatePassword sur compte supprimé → ErrNotFound.
|
||||
if err := u.UpdatePassword(id, "hash-2"); !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("update password après suppression : attendu ErrNotFound, got %v", err)
|
||||
}
|
||||
// Second MarkDeleted → ErrNotFound (plus de cible active).
|
||||
if err := u.MarkDeleted(id); !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("second mark deleted : attendu ErrNotFound, got %v", err)
|
||||
}
|
||||
// MarkDeleted sur inconnu → ErrNotFound.
|
||||
if err := u.MarkDeleted(NewID()); !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("mark deleted inconnu : attendu ErrNotFound, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user