V3 S6 : confiance (révocation, quota, appareils, conflits) + import + onboarding
Backend : token_version (000022, claim tv, 401 si révoqué, bump au password — fin limite V1), quota (000023 idempotente, colonne héritée de 000001, 413 QUOTA_EXCEEDED, GET /users/me/usage), devices (GET + DELETE révocation, EnforceDeviceExists en prod), renames concurrents transparents (baseUpdatedAt + conflicts[] non-fataux, tolérance 2 s). Tests service + handlers + migrations + auth. Mobile : pipeline conflits (DTO + SyncConflictStore + worker + dialogue), baseUpdatedAt prêt, liens 7j par défaut, écran Appareils (+ quota), import classeur unifié (scan/note/dossier), onboarding cercle Famille. Contrat docs/api-v1.md, V3.md (S6 livré).
This commit is contained in:
@@ -61,6 +61,9 @@ func main() {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
handlers.Auth = authManager
|
||||
// V3 S6 A1 : les tokens d'un device révoqué (ligne `devices` supprimée)
|
||||
// sont rejetés en 401 — révocation réelle, pas décorative.
|
||||
handlers.EnforceDeviceExists = true
|
||||
|
||||
repo := repository.NewRepository(conn)
|
||||
|
||||
|
||||
@@ -35,6 +35,10 @@ var expectedRoutes = []string{
|
||||
|
||||
"GET /api/v1/users/resolve",
|
||||
"PATCH /api/v1/users/me/password",
|
||||
"GET /api/v1/users/me/usage",
|
||||
|
||||
"GET /api/v1/devices",
|
||||
"DELETE /api/v1/devices/:id",
|
||||
|
||||
"POST /api/v1/groups",
|
||||
"GET /api/v1/groups",
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE users DROP COLUMN IF EXISTS token_version;
|
||||
@@ -0,0 +1,6 @@
|
||||
-- V3 S6 : révocation des tokens au changement de mot de passe.
|
||||
-- `token_version` est bumpé par PATCH /users/me/password ; le middleware
|
||||
-- rejette les tokens dont le claim `tv` diffère (401). Défaut 0 : les tokens
|
||||
-- pré-V3 (sans claim `tv`, lus comme 0) restent valides jusqu'au premier
|
||||
-- changement de mot de passe — montée en version sans coupure.
|
||||
ALTER TABLE users ADD COLUMN token_version INT NOT NULL DEFAULT 0;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- No-op : la colonne prédate cette migration (000001), on ne la supprime pas.
|
||||
SELECT 1;
|
||||
@@ -0,0 +1,6 @@
|
||||
-- V3 S6 (A2) : quota de stockage par compte (10 Go par défaut, V2.md §3.1).
|
||||
-- Garde-fou à l'upload (413 QUOTA_EXCEEDED) + affichage `GET /users/me/usage`.
|
||||
-- L'usage est calculé (somme `size_bytes` des fichiers vifs), jamais stocké.
|
||||
-- Note : la colonne existe depuis 000001 (modèle V2) — IF NOT EXISTS pour
|
||||
-- les bases créées avant/après, sans double ajout.
|
||||
ALTER TABLE users ADD COLUMN IF NOT EXISTS storage_quota_bytes BIGINT NOT NULL DEFAULT 10737418240;
|
||||
@@ -491,6 +491,30 @@ func TestMigrationsUpDown(t *testing.T) {
|
||||
t.Error("colonne resources.scan_session_id manquante après 000021")
|
||||
}
|
||||
|
||||
// --- 000022 : révocation tokens ------------------------------------------
|
||||
var tvCol int
|
||||
err = conn.QueryRow(`
|
||||
SELECT COUNT(*) FROM information_schema.columns
|
||||
WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'token_version'`).Scan(&tvCol)
|
||||
if err != nil {
|
||||
t.Fatalf("token_version column: %v", err)
|
||||
}
|
||||
if tvCol == 0 {
|
||||
t.Error("colonne users.token_version manquante après 000022")
|
||||
}
|
||||
|
||||
// --- 000023 : quota (colonne héritée de 000001, IF NOT EXISTS) ------------
|
||||
var quotaCol int
|
||||
err = conn.QueryRow(`
|
||||
SELECT COUNT(*) FROM information_schema.columns
|
||||
WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'storage_quota_bytes'`).Scan("aCol)
|
||||
if err != nil {
|
||||
t.Fatalf("storage_quota_bytes column: %v", err)
|
||||
}
|
||||
if quotaCol == 0 {
|
||||
t.Error("colonne users.storage_quota_bytes manquante après 000023")
|
||||
}
|
||||
|
||||
if err := MigrateDownDatabase(url); err != nil {
|
||||
t.Fatalf("migrate down: %v", err)
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -156,7 +157,7 @@ func AuthLogin(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
token, expiresAt, err := Auth.IssueWithExpiry(user.ID, req.DeviceID)
|
||||
token, expiresAt, err := Auth.IssueWithExpiry(user.ID, req.DeviceID, user.TokenVersion)
|
||||
if err != nil {
|
||||
api.Error(c, http.StatusInternalServerError, "INTERNAL", "could not issue token")
|
||||
return
|
||||
@@ -179,8 +180,9 @@ type changePasswordRequest struct {
|
||||
}
|
||||
|
||||
// ChangePassword met à jour le hash du compte connecté. Le mot de passe
|
||||
// courant est requis. Limite connue V1 : les tokens déjà émis restent valides
|
||||
// jusqu'à expiration (7 j, pas de révocation) — cf. docs/api-v1.md §7.
|
||||
// courant est requis. V3 S6 : le changement bumpe `token_version` — tous les
|
||||
// autres tokens (autres devices, sessions volées) sont révoqués aussitôt
|
||||
// (le token courant aussi : le client doit se reconnecter).
|
||||
func ChangePassword(c *gin.Context) {
|
||||
if Store == nil || Store.Repository == nil {
|
||||
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
|
||||
@@ -217,6 +219,11 @@ func ChangePassword(c *gin.Context) {
|
||||
api.Error(c, http.StatusInternalServerError, "INTERNAL", "could not update password")
|
||||
return
|
||||
}
|
||||
// Révocation (V3 S6) : bump best-effort — un échec ici ne doit pas faire
|
||||
// croire que le password n'a pas changé (il l'est, ligne ci-dessus).
|
||||
if err := Store.Repository.Users.BumpTokenVersion(userID); err != nil {
|
||||
log.Printf("auth: bump token_version(%s): %v", userID, err)
|
||||
}
|
||||
|
||||
api.OK(c, gin.H{"id": userID})
|
||||
}
|
||||
|
||||
@@ -105,3 +105,51 @@ func DevicesRegister(c *gin.Context) {
|
||||
api.OK(c, gin.H{"deviceId": req.DeviceID})
|
||||
|
||||
}
|
||||
|
||||
// DeviceDTO expose un device du compte (A1 — voir / révoquer).
|
||||
type DeviceDTO struct {
|
||||
DeviceID string `json:"deviceId"`
|
||||
LastSeenAt *int64 `json:"lastSeenAt"`
|
||||
}
|
||||
|
||||
// DevicesList renvoie les devices du compte connecté (`GET /devices`,
|
||||
// dernier login = ce compte, les plus récemment vus d'abord).
|
||||
func DevicesList(c *gin.Context) {
|
||||
if Store == nil || Store.Repository == nil {
|
||||
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
|
||||
return
|
||||
}
|
||||
userID := c.GetString(UserIDKey)
|
||||
rows, err := Store.Repository.Devices.ListByUser(userID)
|
||||
if err != nil {
|
||||
writeError(c, err)
|
||||
return
|
||||
}
|
||||
out := make([]DeviceDTO, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
out = append(out, DeviceDTO{DeviceID: row.DeviceID, LastSeenAt: row.LastSeenAt})
|
||||
}
|
||||
api.OK(c, out)
|
||||
}
|
||||
|
||||
// DeviceRevoke révoque un device du compte (`DELETE /devices/:id`, A1 —
|
||||
// téléphone perdu). Avec EnforceDeviceExists, ses tokens deviennent 401 et
|
||||
// son login est refusé (ré-enregistrement explicite requis). Ligne absente
|
||||
// ou d'un autre compte → 404 (pas d'énumération).
|
||||
func DeviceRevoke(c *gin.Context) {
|
||||
if Store == nil || Store.Repository == 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", "device not found")
|
||||
return
|
||||
}
|
||||
if err := Store.Repository.Devices.Revoke(userID, id); err != nil {
|
||||
writeError(c, err)
|
||||
return
|
||||
}
|
||||
api.OK(c, gin.H{"id": id})
|
||||
}
|
||||
|
||||
@@ -60,7 +60,7 @@ func RequireAuth(c *gin.Context) {
|
||||
// Le store peut être nil dans les tests middleware purs ; sinon on vérifie
|
||||
// que le compte existe toujours (supprimé → accès refusé).
|
||||
if Store != nil && Store.Repository != nil {
|
||||
_, err := Store.Repository.Users.GetByID(identity.UserID)
|
||||
user, err := Store.Repository.Users.GetByID(identity.UserID)
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
api.Error(c, http.StatusUnauthorized, "UNAUTHORIZED", "account no longer exists")
|
||||
c.Abort()
|
||||
@@ -71,6 +71,14 @@ func RequireAuth(c *gin.Context) {
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
// V3 S6 : révocation — un changement de mot de passe (bump de
|
||||
// token_version) invalide tous les tokens antérieurs, même non expirés.
|
||||
if identity.TokenVersion != user.TokenVersion {
|
||||
log.Printf("auth: token révoqué rejeté (user=%s tv=%d, attendu %d)", identity.UserID, identity.TokenVersion, user.TokenVersion)
|
||||
api.Error(c, http.StatusUnauthorized, "UNAUTHORIZED", "token revoked")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if EnforceDeviceExists && Store != nil && Store.Repository != nil {
|
||||
|
||||
@@ -51,6 +51,10 @@ func RegisterRoutes(r *gin.Engine) {
|
||||
|
||||
protected.GET("/users/resolve", ResolveUser)
|
||||
protected.PATCH("/users/me/password", ChangePassword)
|
||||
protected.GET("/users/me/usage", UsersUsage)
|
||||
|
||||
protected.GET("/devices", DevicesList)
|
||||
protected.DELETE("/devices/:id", DeviceRevoke)
|
||||
|
||||
protected.POST("/groups", GroupsCreate)
|
||||
protected.GET("/groups", GroupsList)
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
package handlers_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/kazier/backend/handlers"
|
||||
"github.com/kazier/backend/repository"
|
||||
)
|
||||
|
||||
// TestPasswordChangeRevokesTokens : le bump de token_version invalide tous
|
||||
// les tokens antérieurs (V3 S6) — l'ancien token devient 401, un nouveau
|
||||
// login fonctionne.
|
||||
func TestPasswordChangeRevokesTokens(t *testing.T) {
|
||||
r, _, repo := setup(t)
|
||||
device := repository.NewID()
|
||||
token, _ := registerAndLogin(t, r, repo, testUserUsername(device, "rv"), "revoke-test-password", device)
|
||||
|
||||
rec, _ := doRequest(t, r, http.MethodGet, "/api/v1/files", token, nil, "")
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("token initial rejeté: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
body := `{"current_password":"revoke-test-password","new_password":"revoke-test-password-2"}`
|
||||
rec, _ = doRequest(t, r, http.MethodPatch, "/api/v1/users/me/password", token, []byte(body), "application/json")
|
||||
expectOK(t, rec, "password-change")
|
||||
|
||||
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files", token, nil, "")
|
||||
expectError(t, rec, http.StatusUnauthorized, "UNAUTHORIZED", "revoked-token")
|
||||
|
||||
// Nouveau login (nouvelle version) : fonctionne.
|
||||
body = fmt.Sprintf(`{"username":%q,"password":"revoke-test-password-2","device_id":%q}`,
|
||||
testUserUsername(device, "rv"), device)
|
||||
rec, _ = doRequest(t, r, http.MethodPost, "/api/v1/auth/login", "", []byte(body), "application/json")
|
||||
expectOK(t, rec, "relogin")
|
||||
var login struct {
|
||||
Data struct {
|
||||
Token string `json:"token"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &login); err != nil || login.Data.Token == "" {
|
||||
t.Fatalf("relogin sans token: %s", rec.Body.String())
|
||||
}
|
||||
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files", login.Data.Token, nil, "")
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("nouveau token rejeté: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestDevicesListAndRevoke : liste les devices du compte, révoque (A1) —
|
||||
// avec EnforceDeviceExists, le token du device révoqué devient 401 et son
|
||||
// login est refusé (ré-enregistrement requis).
|
||||
func TestDevicesListAndRevoke(t *testing.T) {
|
||||
r, _, repo := setup(t)
|
||||
handlers.EnforceDeviceExists = true
|
||||
defer func() { handlers.EnforceDeviceExists = false }()
|
||||
device := repository.NewID()
|
||||
token, _ := registerAndLogin(t, r, repo, testUserUsername(device, "dv"), "devices-test-password", device)
|
||||
|
||||
rec, _ := doRequest(t, r, http.MethodGet, "/api/v1/devices", token, nil, "")
|
||||
env := expectOK(t, rec, "devices-list")
|
||||
var devices []struct {
|
||||
DeviceID string `json:"deviceId"`
|
||||
LastSeenAt *int64 `json:"lastSeenAt"`
|
||||
}
|
||||
if err := json.Unmarshal(env.Data, &devices); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
found := false
|
||||
for _, d := range devices {
|
||||
if d.DeviceID == device {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("device absent de la liste: %+v", devices)
|
||||
}
|
||||
|
||||
rec, _ = doRequest(t, r, http.MethodDelete, "/api/v1/devices/"+device, token, nil, "")
|
||||
expectOK(t, rec, "devices-revoke")
|
||||
|
||||
// Token existant → 401 (device inconnu).
|
||||
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files", token, nil, "")
|
||||
expectError(t, rec, http.StatusUnauthorized, "UNAUTHORIZED", "revoked-device-token")
|
||||
|
||||
// Login refusé (device inconnu, indistinguable — 401).
|
||||
body := fmt.Sprintf(`{"username":%q,"password":"devices-test-password","device_id":%q}`,
|
||||
testUserUsername(device, "dv"), device)
|
||||
rec, _ = doRequest(t, r, http.MethodPost, "/api/v1/auth/login", "", []byte(body), "application/json")
|
||||
expectError(t, rec, http.StatusUnauthorized, "UNAUTHORIZED", "revoked-device-login")
|
||||
|
||||
// Révoquer l'inexistant / malformé → 404 (avec un token encore valide).
|
||||
deviceB := repository.NewID()
|
||||
tokenB, _ := registerAndLogin(t, r, repo, testUserUsername(deviceB, "dv2"), "devices-test-password", deviceB)
|
||||
rec, _ = doRequest(t, r, http.MethodDelete, "/api/v1/devices/"+repository.NewID(), tokenB, nil, "")
|
||||
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "revoke-unknown")
|
||||
rec, _ = doRequest(t, r, http.MethodDelete, "/api/v1/devices/nope", tokenB, nil, "")
|
||||
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "revoke-malformed")
|
||||
}
|
||||
|
||||
// TestUsageAndQuota : GET /users/me/usage reflète l'état, et un upload
|
||||
// au-delà du quota est rejeté en 413 QUOTA_EXCEEDED (V3 S6 A2).
|
||||
func TestUsageAndQuota(t *testing.T) {
|
||||
r, store, repo := setup(t)
|
||||
_ = store
|
||||
device := repository.NewID()
|
||||
token, userID := registerAndLogin(t, r, repo, testUserUsername(device, "qu"), "quota-test-password", device)
|
||||
|
||||
rec, _ := doRequest(t, r, http.MethodGet, "/api/v1/users/me/usage", token, nil, "")
|
||||
env := expectOK(t, rec, "usage-empty")
|
||||
var usage struct {
|
||||
UsedBytes int64 `json:"usedBytes"`
|
||||
QuotaBytes int64 `json:"quotaBytes"`
|
||||
FileCount int `json:"fileCount"`
|
||||
TrashCount int `json:"trashCount"`
|
||||
TrashedBytes int64 `json:"trashedBytes"`
|
||||
}
|
||||
if err := json.Unmarshal(env.Data, &usage); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if usage.UsedBytes != 0 || usage.QuotaBytes != 10737418240 || usage.FileCount != 0 {
|
||||
t.Fatalf("usage initial inattendu: %+v", usage)
|
||||
}
|
||||
|
||||
// Quota miniature (10 octets) → l'upload passe sous le seuil puis casse.
|
||||
if _, err := repo.Users.DB.Exec(`UPDATE users SET storage_quota_bytes = 10 WHERE id = $1`, userID); err != nil {
|
||||
t.Fatalf("shrink quota: %v", err)
|
||||
}
|
||||
rec = uploadMultipart(t, r, token, "", "a.txt", []byte("12345"))
|
||||
expectOK(t, rec, "usage-under-quota")
|
||||
|
||||
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/users/me/usage", token, nil, "")
|
||||
env = expectOK(t, rec, "usage-after")
|
||||
usage = struct {
|
||||
UsedBytes int64 `json:"usedBytes"`
|
||||
QuotaBytes int64 `json:"quotaBytes"`
|
||||
FileCount int `json:"fileCount"`
|
||||
TrashCount int `json:"trashCount"`
|
||||
TrashedBytes int64 `json:"trashedBytes"`
|
||||
}{}
|
||||
if err := json.Unmarshal(env.Data, &usage); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if usage.UsedBytes != 5 || usage.FileCount != 1 {
|
||||
t.Fatalf("usage après upload: %+v", usage)
|
||||
}
|
||||
|
||||
rec = uploadMultipart(t, r, token, "", "b.txt", []byte("123456"))
|
||||
expectError(t, rec, http.StatusRequestEntityTooLarge, "QUOTA_EXCEEDED", "usage-over-quota")
|
||||
}
|
||||
@@ -30,6 +30,8 @@ func writeError(c *gin.Context, err error) {
|
||||
api.Error(c, 409, "NAME_CONFLICT", "a resource with this name already exists here")
|
||||
case errors.Is(err, service.ErrFileTooLarge):
|
||||
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")
|
||||
default:
|
||||
// Jamais de err.Error() brut au client (fuite SQL/FS/paths, cf.
|
||||
// FEEDBACK #8) : message générique, détail au log serveur.
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/kazier/backend/pkg/api"
|
||||
)
|
||||
|
||||
// UsersUsage expose l'empreinte du compte (V3 S6 A2) : `GET /users/me/usage`
|
||||
// `{ usedBytes, quotaBytes, fileCount, trashCount, trashedBytes }` —
|
||||
// calculé, jamais stocké. La corbeille est détaillée (octets récupérables).
|
||||
func UsersUsage(c *gin.Context) {
|
||||
if Store == nil || Store.Repository == nil {
|
||||
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
|
||||
return
|
||||
}
|
||||
userID := c.GetString(UserIDKey)
|
||||
usage, err := Store.Usage(userID)
|
||||
if err != nil {
|
||||
writeError(c, err)
|
||||
return
|
||||
}
|
||||
api.OK(c, usage)
|
||||
}
|
||||
+28
-12
@@ -4,6 +4,7 @@ import (
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"aidanwoods.dev/go-paseto"
|
||||
@@ -17,11 +18,14 @@ var ErrInvalidToken = errors.New("invalid token")
|
||||
|
||||
var hex32Pattern = regexp.MustCompile(`^[0-9a-f]{32}$`)
|
||||
|
||||
// Identity est le résultat de Verify : l'utilisateur (sujet du token, autorisant)
|
||||
// et le device (claim secondaire, porté mais NON autorisant seul).
|
||||
// Identity est le résultat de Verify : l'utilisateur (sujet du token, autorisant),
|
||||
// le device (claim secondaire, porté mais NON autorisant seul) et la version
|
||||
// de révocation (claim `tv`, V3 S6 — le middleware la compare à
|
||||
// users.token_version).
|
||||
type Identity struct {
|
||||
UserID string
|
||||
DeviceID string
|
||||
UserID string
|
||||
DeviceID string
|
||||
TokenVersion int
|
||||
}
|
||||
|
||||
// Manager issues and verifies paseto v4-local bearer tokens.
|
||||
@@ -40,16 +44,19 @@ func NewManager(secret string) (*Manager, error) {
|
||||
return &Manager{key: key}, nil
|
||||
}
|
||||
|
||||
// Issue émet un token lié à un utilisateur ET à un device.
|
||||
// Issue émet un token lié à un utilisateur ET à un device (version 0 —
|
||||
// compat pré-V3, cf. IssueWithExpiry).
|
||||
func (m *Manager) Issue(userID, deviceID string) (string, error) {
|
||||
token, _, err := m.IssueWithExpiry(userID, deviceID)
|
||||
token, _, err := m.IssueWithExpiry(userID, deviceID, 0)
|
||||
return token, err
|
||||
}
|
||||
|
||||
// IssueWithExpiry émet un token et retourne son expiration réelle (le `exp`
|
||||
// embarqué). Les appelants doivent exposer expiresAt, jamais le recalculer
|
||||
// via Now()+TTL (dérive d'horloge, cf. FEEDBACK A7).
|
||||
func (m *Manager) IssueWithExpiry(userID, deviceID string) (string, time.Time, error) {
|
||||
// via Now()+TTL (dérive d'horloge, cf. FEEDBACK A7). `tokenVersion` est le
|
||||
// compteur de révocation du compte (V3 S6) — bumpé à chaque changement de
|
||||
// mot de passe, vérifié par le middleware.
|
||||
func (m *Manager) IssueWithExpiry(userID, deviceID string, tokenVersion int) (string, time.Time, error) {
|
||||
now := time.Now()
|
||||
expiresAt := now.Add(TokenTTL)
|
||||
token := paseto.NewToken()
|
||||
@@ -59,12 +66,14 @@ func (m *Manager) IssueWithExpiry(userID, deviceID string) (string, time.Time, e
|
||||
token.SetSubject(userID)
|
||||
// v1.6.0 : SetString n'expose pas d'erreur (panic si non sérialisable).
|
||||
token.SetString("device_id", deviceID)
|
||||
token.SetString("tv", strconv.Itoa(tokenVersion))
|
||||
return token.V4Encrypt(m.key, nil), expiresAt, nil
|
||||
}
|
||||
|
||||
// Verify décode et contrôle le token, retourne l'identité (user + device).
|
||||
// Les deux identifiants doivent être 32-hex (cf. docs/api-v1.md) — rejet
|
||||
// sinon pour préserver les invariants UNIQUE(device_id,operation_id)/CHECK.
|
||||
// Verify décode et contrôle le token, retourne l'identité (user + device +
|
||||
// version). Les deux identifiants doivent être 32-hex (cf. docs/api-v1.md) —
|
||||
// rejet sinon pour préserver les invariants UNIQUE(device_id,operation_id)/CHECK.
|
||||
// `tv` absent (tokens pré-V3) → 0 ; non numérique → rejet.
|
||||
func (m *Manager) Verify(signed string) (Identity, error) {
|
||||
parsed, err := paseto.NewParserForValidNow().ParseV4Local(m.key, signed, nil)
|
||||
if err != nil {
|
||||
@@ -78,5 +87,12 @@ func (m *Manager) Verify(signed string) (Identity, error) {
|
||||
if err != nil || !hex32Pattern.MatchString(deviceID) {
|
||||
return Identity{}, ErrInvalidToken
|
||||
}
|
||||
return Identity{UserID: userID, DeviceID: deviceID}, nil
|
||||
tv := 0
|
||||
if raw, err := parsed.GetString("tv"); err == nil && raw != "" {
|
||||
tv, err = strconv.Atoi(raw)
|
||||
if err != nil || tv < 0 {
|
||||
return Identity{}, ErrInvalidToken
|
||||
}
|
||||
}
|
||||
return Identity{UserID: userID, DeviceID: deviceID, TokenVersion: tv}, nil
|
||||
}
|
||||
|
||||
@@ -159,7 +159,7 @@ func TestIssueSetsExpiration(t *testing.T) {
|
||||
|
||||
func TestIssueWithExpiryMatchesTokenExp(t *testing.T) {
|
||||
m, _ := NewManager("test-secret")
|
||||
signed, expiresAt, err := m.IssueWithExpiry(testUserID, testDeviceID)
|
||||
signed, expiresAt, err := m.IssueWithExpiry(testUserID, testDeviceID, 3)
|
||||
if err != nil {
|
||||
t.Fatalf("IssueWithExpiry: %v", err)
|
||||
}
|
||||
@@ -177,4 +177,28 @@ func TestIssueWithExpiryMatchesTokenExp(t *testing.T) {
|
||||
if exp.Unix() != expiresAt.Unix() {
|
||||
t.Errorf("expiresAt = %v, exp token = %v", expiresAt, exp)
|
||||
}
|
||||
id, err := m.Verify(signed)
|
||||
if err != nil {
|
||||
t.Fatalf("Verify: %v", err)
|
||||
}
|
||||
if id.TokenVersion != 3 {
|
||||
t.Errorf("tv = %d, attendu 3", id.TokenVersion)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyLegacyTokenWithoutTv(t *testing.T) {
|
||||
m, _ := NewManager("test-secret")
|
||||
// Tokens pré-V3 (Issue, tv=0) : Verify lit 0 — valides tant que le
|
||||
// compte n'a jamais bumpé (montée en version sans coupure).
|
||||
signed, err := m.Issue(testUserID, testDeviceID)
|
||||
if err != nil {
|
||||
t.Fatalf("Issue: %v", err)
|
||||
}
|
||||
id, err := m.Verify(signed)
|
||||
if err != nil {
|
||||
t.Fatalf("Verify legacy: %v", err)
|
||||
}
|
||||
if id.TokenVersion != 0 {
|
||||
t.Errorf("tv legacy = %d, attendu 0", id.TokenVersion)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,3 +52,61 @@ func (d *Devices) MarkUser(deviceID, userID string) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeviceRow is one registered device of an account (A1 — voir / révoquer).
|
||||
type DeviceRow struct {
|
||||
DeviceID string
|
||||
LastSeenAt *int64 // ms epoch, NULL si jamais vu depuis l'enregistrement
|
||||
}
|
||||
|
||||
// ListByUser returns the devices whose last login was this account
|
||||
// (devices.user_id informatif, jamais autorisant).
|
||||
func (d *Devices) ListByUser(userID string) ([]DeviceRow, error) {
|
||||
rows, err := d.DB.Query(
|
||||
`SELECT device_id, (EXTRACT(EPOCH FROM last_seen_at) * 1000)::bigint
|
||||
FROM devices WHERE user_id = $1 ORDER BY last_seen_at DESC NULLS LAST`,
|
||||
userID,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []DeviceRow{}
|
||||
for rows.Next() {
|
||||
var row DeviceRow
|
||||
if err := rows.Scan(&row.DeviceID, &row.LastSeenAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, row)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// Revoke deletes a device registration of this account (A1 — téléphone
|
||||
// perdu). Avec EnforceDeviceExists, les tokens du device deviennent 401 et
|
||||
// le login refuse le device (ré-enregistrement explicite requis).
|
||||
// Ligne absente ou d'un autre compte → ErrNotFound (pas d'énumération).
|
||||
// Les hints de présence (`storage_locations`) suivent.
|
||||
func (d *Devices) Revoke(userID, deviceID string) error {
|
||||
result, err := d.DB.Exec(
|
||||
`DELETE FROM devices WHERE device_id = $1 AND user_id = $2`,
|
||||
deviceID, userID,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
affected, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if affected == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
if _, err := d.DB.Exec(
|
||||
`DELETE FROM storage_locations WHERE device_id = $1 AND user_id = $2`,
|
||||
deviceID, userID,
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -124,6 +124,39 @@ func (r *Resources) ListMissingHashes(limit int) ([]MissingHash, error) {
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// StorageUsage aggregates a user's footprint (V3 S6 A2 — calculé, jamais
|
||||
// stocké). Les trashés sont exclus (octets récupérables à la purge).
|
||||
type StorageUsage struct {
|
||||
UsedBytes int64
|
||||
FileCount int
|
||||
TrashCount int
|
||||
TrashedBytes int64
|
||||
}
|
||||
|
||||
// StorageUsage sums live file bytes + counts (live + trashed) for a user.
|
||||
func (r *Resources) StorageUsage(ownerID string) (StorageUsage, error) {
|
||||
var u StorageUsage
|
||||
err := r.DB.QueryRow(
|
||||
`SELECT COALESCE(SUM(size_bytes), 0), COUNT(*)
|
||||
FROM resources
|
||||
WHERE user_id = $1 AND type = 'file' AND deleted_at IS NULL`,
|
||||
ownerID,
|
||||
).Scan(&u.UsedBytes, &u.FileCount)
|
||||
if err != nil {
|
||||
return StorageUsage{}, err
|
||||
}
|
||||
err = r.DB.QueryRow(
|
||||
`SELECT COUNT(*), COALESCE(SUM(size_bytes), 0)
|
||||
FROM resources
|
||||
WHERE user_id = $1 AND deleted_at IS NOT NULL`,
|
||||
ownerID,
|
||||
).Scan(&u.TrashCount, &u.TrashedBytes)
|
||||
if err != nil {
|
||||
return StorageUsage{}, err
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
type FileRow struct {
|
||||
ID string
|
||||
Name string
|
||||
@@ -700,6 +733,24 @@ func (r *Resources) TouchResource(resourceID string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// LiveNameAndUpdatedAt returns the current name and updated_at (ms epoch) of
|
||||
// a live resource, any type, unscoped — the caller (sync) has already
|
||||
// verified effective access. Absent/trashed → ErrNotFound. Sert à la
|
||||
// détection de conflits de rename (S6 A4 : baseUpdatedAt périmé).
|
||||
func (r *Resources) LiveNameAndUpdatedAt(resourceID string) (string, int64, error) {
|
||||
var name string
|
||||
var ms int64
|
||||
err := r.DB.QueryRow(
|
||||
`SELECT name, (EXTRACT(EPOCH FROM updated_at) * 1000)::bigint
|
||||
FROM resources WHERE resource_id = $1 AND deleted_at IS NULL`,
|
||||
resourceID,
|
||||
).Scan(&name, &ms)
|
||||
if err == sql.ErrNoRows {
|
||||
return "", 0, ErrNotFound
|
||||
}
|
||||
return name, ms, err
|
||||
}
|
||||
|
||||
// OwnedRow is a snapshot row: resource identity + freshness.
|
||||
type OwnedRow struct {
|
||||
ID string
|
||||
|
||||
@@ -13,6 +13,10 @@ type UserRow struct {
|
||||
PasswordHash string
|
||||
IsAdmin bool
|
||||
CreatedAt time.Time
|
||||
// V3 S6 : révocation des tokens (bump au changement de password) et
|
||||
// quota de stockage (garde-fou upload).
|
||||
TokenVersion int
|
||||
QuotaBytes int64
|
||||
}
|
||||
|
||||
// Users persiste les comptes utilisateurs (auth par login, cf. tranche identité).
|
||||
@@ -33,7 +37,8 @@ func (u *Users) Count() (int, error) {
|
||||
// (lowercase, unique). Absent → ErrNotFound.
|
||||
func (u *Users) GetByUsernameNormalized(normalized string) (*UserRow, error) {
|
||||
row := u.DB.QueryRow(
|
||||
`SELECT id, username, username_normalized, password_hash, is_admin, created_at
|
||||
`SELECT id, username, username_normalized, password_hash, is_admin, created_at,
|
||||
token_version, storage_quota_bytes
|
||||
FROM users
|
||||
WHERE username_normalized = $1 AND deleted_at IS NULL`,
|
||||
normalized,
|
||||
@@ -48,7 +53,8 @@ func (u *Users) GetByUsernameNormalized(normalized string) (*UserRow, error) {
|
||||
// GetByID charge un compte actif par id. Absent → ErrNotFound.
|
||||
func (u *Users) GetByID(id string) (*UserRow, error) {
|
||||
row := u.DB.QueryRow(
|
||||
`SELECT id, username, username_normalized, password_hash, is_admin, created_at
|
||||
`SELECT id, username, username_normalized, password_hash, is_admin, created_at,
|
||||
token_version, storage_quota_bytes
|
||||
FROM users
|
||||
WHERE id = $1 AND deleted_at IS NULL`,
|
||||
id,
|
||||
@@ -131,6 +137,27 @@ func (u *Users) MarkDeleted(id string) error {
|
||||
|
||||
func scanUser(scan func(...any) error) (*UserRow, error) {
|
||||
var user UserRow
|
||||
err := scan(&user.ID, &user.Username, &user.UsernameNormalized, &user.PasswordHash, &user.IsAdmin, &user.CreatedAt)
|
||||
err := scan(&user.ID, &user.Username, &user.UsernameNormalized, &user.PasswordHash, &user.IsAdmin, &user.CreatedAt, &user.TokenVersion, &user.QuotaBytes)
|
||||
return &user, err
|
||||
}
|
||||
|
||||
// BumpTokenVersion invalide tous les tokens émis (V3 S6) : le middleware
|
||||
// rejette les tokens dont le claim `tv` diffère. Compte absent → ErrNotFound.
|
||||
func (u *Users) BumpTokenVersion(id string) error {
|
||||
result, err := u.DB.Exec(
|
||||
`UPDATE users SET token_version = token_version + 1, updated_at = NOW()
|
||||
WHERE id = $1 AND deleted_at IS NULL`,
|
||||
id,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
affected, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if affected == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -18,6 +18,10 @@ import (
|
||||
// ErrFileTooLarge signals an upload above MaxFileSize.
|
||||
var ErrFileTooLarge = errors.New("file too large")
|
||||
|
||||
// ErrQuotaExceeded signals an upload that would overflow the account quota
|
||||
// (V3 S6 A2). Handlers map it to 413 QUOTA_EXCEEDED (never 500).
|
||||
var ErrQuotaExceeded = errors.New("storage quota exceeded")
|
||||
|
||||
// ErrInvalidUpload signals a rejected upload (display name or path component).
|
||||
// Handlers map it to 400 INVALID_REQUEST (never 500).
|
||||
var ErrInvalidUpload = errors.New("invalid upload name")
|
||||
@@ -343,6 +347,14 @@ func (s *Resources) Upload(ownerID string, file *multipart.FileHeader, folderID,
|
||||
if ferr != nil {
|
||||
return FileDTO{}, ferr
|
||||
}
|
||||
} else {
|
||||
// V3 S6 A2 : garde-fou quota sur les créations (les overwrites
|
||||
// ciblées remplacent des octets existants — gain net ~nul, pas de
|
||||
// check). Vérifié au header (rejet rapide) PUIS aux octets réels
|
||||
// (vérité, le header peut mentir, cf. A2).
|
||||
if err := s.checkQuotaFor(ownerID, file.Size); err != nil {
|
||||
return FileDTO{}, err
|
||||
}
|
||||
}
|
||||
|
||||
written, err := copyMultipartAtomic(file, destDir, destPath, s.MaxFileSize)
|
||||
@@ -352,6 +364,14 @@ func (s *Resources) Upload(ownerID string, file *multipart.FileHeader, folderID,
|
||||
}
|
||||
return FileDTO{}, err
|
||||
}
|
||||
if !targetExisting {
|
||||
// Vérité aux octets réels (le header `file.Size` peut mentir) :
|
||||
// dépassement → fichier supprimé + 413 (pas d'orphelin).
|
||||
if err := s.checkQuotaFor(ownerID, written); err != nil {
|
||||
_ = os.Remove(destPath)
|
||||
return FileDTO{}, err
|
||||
}
|
||||
}
|
||||
|
||||
mimeType := sanitizeMimeType(file.Header.Get("Content-Type"))
|
||||
var extPtr *string
|
||||
@@ -486,3 +506,48 @@ func toFileDTO(row repository.FileRow) FileDTO {
|
||||
UpdatedAt: row.UpdatedAt.UTC().Format(time.RFC3339),
|
||||
}
|
||||
}
|
||||
|
||||
// UsageDTO serializes GET /users/me/usage (V3 S6 A2) : quota + empreinte,
|
||||
// dont la corbeille (octets récupérables à la purge).
|
||||
type UsageDTO struct {
|
||||
UsedBytes int64 `json:"usedBytes"`
|
||||
QuotaBytes int64 `json:"quotaBytes"`
|
||||
FileCount int `json:"fileCount"`
|
||||
TrashCount int `json:"trashCount"`
|
||||
TrashedBytes int64 `json:"trashedBytes"`
|
||||
}
|
||||
|
||||
// Usage returns the account footprint (computed, never stored).
|
||||
func (s *Resources) Usage(ownerID string) (UsageDTO, error) {
|
||||
user, err := s.Repository.Users.GetByID(ownerID)
|
||||
if err != nil {
|
||||
return UsageDTO{}, err
|
||||
}
|
||||
usage, err := s.Repo.StorageUsage(ownerID)
|
||||
if err != nil {
|
||||
return UsageDTO{}, err
|
||||
}
|
||||
return UsageDTO{
|
||||
UsedBytes: usage.UsedBytes, QuotaBytes: user.QuotaBytes,
|
||||
FileCount: usage.FileCount, TrashCount: usage.TrashCount,
|
||||
TrashedBytes: usage.TrashedBytes,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// checkQuotaFor rejects a creation of incoming bytes that would overflow the
|
||||
// account quota (V3 S6 A2). Compte absent → l'erreur remonte (jamais de
|
||||
// défaut silencieux qui laisserait passer).
|
||||
func (s *Resources) checkQuotaFor(ownerID string, incoming int64) error {
|
||||
user, err := s.Repository.Users.GetByID(ownerID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
usage, err := s.Repo.StorageUsage(ownerID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if usage.UsedBytes+incoming > user.QuotaBytes {
|
||||
return ErrQuotaExceeded
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
+80
-13
@@ -53,10 +53,22 @@ type FailedOperation struct {
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// SyncResult is the outbox response: applied = index of the next op to send.
|
||||
// ConflictInfo reports a last-writer-wins rename applied over a concurrent
|
||||
// change (V3 S6 A4). Non-fatal : le batch continue, le client affiche
|
||||
// « renommé ailleurs » avec le nom serveur gagnant.
|
||||
type ConflictInfo struct {
|
||||
OperationID string `json:"operation_id"`
|
||||
ResourceID string `json:"resource_id"`
|
||||
ServerName string `json:"serverName"`
|
||||
ServerUpdatedAt int64 `json:"serverUpdatedAt"`
|
||||
}
|
||||
|
||||
// SyncResult is the outbox response: applied = index of the next op to send,
|
||||
// conflicts = renames concurrents appliqués quand même (non-fataux, S6 A4).
|
||||
type SyncResult struct {
|
||||
Applied int `json:"applied"`
|
||||
Failed *FailedOperation `json:"failed,omitempty"`
|
||||
Applied int `json:"applied"`
|
||||
Failed *FailedOperation `json:"failed,omitempty"`
|
||||
Conflicts []ConflictInfo `json:"conflicts,omitempty"`
|
||||
}
|
||||
|
||||
type createResourcePayload struct {
|
||||
@@ -71,6 +83,11 @@ type createResourcePayload struct {
|
||||
|
||||
type renamePayload struct {
|
||||
Name string `json:"name"`
|
||||
// V3 S6 A4 : `updated_at` (ms epoch) vu par le client au moment du
|
||||
// rename. Si la ressource a bougé depuis (concurrent), le rename
|
||||
// s'applique quand même (last-writer-wins) mais est signalé en
|
||||
// `conflicts` (transparence, pas de CRDT).
|
||||
BaseUpdatedAt *int64 `json:"baseUpdatedAt"`
|
||||
}
|
||||
|
||||
type movePayload struct {
|
||||
@@ -156,33 +173,39 @@ var errCycle = errors.New("cannot move a resource into its own subtree")
|
||||
// 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) {
|
||||
// Conflits de rename (S6 A4) : non-fataux, collectés tout au long du
|
||||
// batch et renvoyés avec le résultat (le batch continue).
|
||||
var conflicts []ConflictInfo
|
||||
fail := func(i int, op *SyncOperation, code, message string) (SyncResult, error) {
|
||||
return SyncResult{Applied: i, Failed: &FailedOperation{OperationID: op.OperationID, Code: code, Message: message}, Conflicts: conflicts}, nil
|
||||
}
|
||||
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
|
||||
return fail(i, op, "INVALID_REQUEST", err.Error())
|
||||
}
|
||||
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 {
|
||||
// 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
|
||||
return fail(i, op, "INVALID_REQUEST", "operation_id must be 32 lowercase hex chars")
|
||||
}
|
||||
if errors.Is(err, repository.ErrInvalidPayload) {
|
||||
return SyncResult{Applied: i, Failed: &FailedOperation{OperationID: op.OperationID, Code: "INVALID_REQUEST", Message: "invalid payload JSON"}}, nil
|
||||
return fail(i, op, "INVALID_REQUEST", "invalid payload JSON")
|
||||
}
|
||||
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
|
||||
return fail(i, op, "INTERNAL", "failed to persist operation state")
|
||||
}
|
||||
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
|
||||
return fail(i, op, "INTERNAL", "failed to read operation state")
|
||||
}
|
||||
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
|
||||
return fail(i, op, "INVALID_REQUEST", "operation replayed with different payload")
|
||||
}
|
||||
if stored.Status == repository.OpStatusApplied {
|
||||
continue // déjà appliquée à l'identique → skip idempotent
|
||||
@@ -190,16 +213,18 @@ func (s *Resources) ApplyBatch(userID, deviceID string, ops []SyncOperation) (Sy
|
||||
// Trace 'failed' à payload identique : la première tentative est
|
||||
// morte avant MarkApplied (crash) → on ré-applique (recovery).
|
||||
}
|
||||
if err := s.applySyncOp(userID, deviceID, op); err != nil {
|
||||
if conflict, err := s.applySyncOpWithConflict(userID, deviceID, op); err != nil {
|
||||
code, message := classifySyncError(err)
|
||||
return SyncResult{Applied: i, Failed: &FailedOperation{OperationID: op.OperationID, Code: code, Message: message}}, nil
|
||||
return fail(i, op, code, message)
|
||||
} else if conflict != nil {
|
||||
conflicts = append(conflicts, *conflict)
|
||||
}
|
||||
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 fail(i, op, "INTERNAL", "operation applied but trace update failed; safe to retry")
|
||||
}
|
||||
}
|
||||
return SyncResult{Applied: len(ops)}, nil
|
||||
return SyncResult{Applied: len(ops), Conflicts: conflicts}, nil
|
||||
}
|
||||
|
||||
func validateSyncOp(op *SyncOperation) error {
|
||||
@@ -226,6 +251,48 @@ func validateSyncOp(op *SyncOperation) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// conflictToleranceMs absorbe le skew d'horloge client/serveur ET la
|
||||
// troncation à la seconde des `updatedAt` RFC3339 lus par le client : un
|
||||
// écart ≤ 2 s n'est pas un conflit (ex. create suivi d'un rename immédiat
|
||||
// par le même device). Au-delà, quelqu'un d'autre a écrit entre-temps.
|
||||
const conflictToleranceMs = 2000
|
||||
|
||||
// applySyncOpWithConflict applique une op et détecte les renames concurrents
|
||||
// (S6 A4) : si `baseUpdatedAt` est fourni et que la ressource a bougé depuis
|
||||
// (au-delà de la tolérance), le rename s'applique quand même (LWW) mais est
|
||||
// signalé. Sans base (vieux clients) : aucun signalement, comportement V1.
|
||||
func (s *Resources) applySyncOpWithConflict(ownerID, deviceID string, op *SyncOperation) (*ConflictInfo, error) {
|
||||
var base *int64
|
||||
resID := derefString(op.ResourceID)
|
||||
if op.Operation == OpUpdateMetadata {
|
||||
var p renamePayload
|
||||
if err := json.Unmarshal(op.Payload, &p); err == nil && p.BaseUpdatedAt != nil {
|
||||
base = p.BaseUpdatedAt
|
||||
}
|
||||
}
|
||||
var preMs int64
|
||||
havePre := false
|
||||
if base != nil {
|
||||
if _, ms, err := s.Repo.LiveNameAndUpdatedAt(resID); err == nil {
|
||||
preMs, havePre = ms, true
|
||||
}
|
||||
}
|
||||
if err := s.applySyncOp(ownerID, deviceID, op); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if base != nil && havePre && preMs > *base+conflictToleranceMs {
|
||||
name, ms, err := s.Repo.LiveNameAndUpdatedAt(resID)
|
||||
if err != nil {
|
||||
return nil, nil // renommé puis supprimé dans le même batch : rien à signaler.
|
||||
}
|
||||
return &ConflictInfo{
|
||||
OperationID: op.OperationID, ResourceID: resID,
|
||||
ServerName: name, ServerUpdatedAt: ms,
|
||||
}, nil
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *Resources) applySyncOp(ownerID, deviceID string, op *SyncOperation) error {
|
||||
resourceID := derefString(op.ResourceID)
|
||||
switch op.Operation {
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/kazier/backend/repository"
|
||||
)
|
||||
|
||||
// TestRenameConflictReporting : un rename avec baseUpdatedAt périmée
|
||||
// s'applique quand même (LWW) mais est signalé en conflicts[] (S6 A4) ;
|
||||
// avec une base fraîche, aucun signalement.
|
||||
func TestRenameConflictReporting(t *testing.T) {
|
||||
s := newServiceStore(t)
|
||||
userID := mustCreateUser(t, s.Repository, "conflict-user")
|
||||
deviceA := mustRegisterDevice(t, s.Repository, "c0000000000000000000000000000001")
|
||||
fileID := repository.NewID()
|
||||
if err := s.Repository.Resources.InsertFile(userID, fileID, "origine.txt", "", 0, nil, nil); err != nil {
|
||||
t.Fatalf("insert: %v", err)
|
||||
}
|
||||
|
||||
// Base fraîche : pas de conflit.
|
||||
name, ms, err := s.Repository.Resources.LiveNameAndUpdatedAt(fileID)
|
||||
if err != nil || name != "origine.txt" {
|
||||
t.Fatalf("live: %q %d %v", name, ms, err)
|
||||
}
|
||||
res, err := s.ApplyBatch(userID, deviceA, []SyncOperation{
|
||||
syncOp(repository.NewID(), fileID, OpUpdateMetadata, "file", map[string]any{
|
||||
"name": "v2.txt", "baseUpdatedAt": ms,
|
||||
}),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("apply: %v", err)
|
||||
}
|
||||
if res.Applied != 1 || res.Failed != nil || len(res.Conflicts) != 0 {
|
||||
t.Fatalf("rename frais doit être silencieux: %+v", res)
|
||||
}
|
||||
|
||||
// Base périmée (concurrent théorique entre-temps) : appliqué + signalé.
|
||||
stale := ms - 60_000
|
||||
res, err = s.ApplyBatch(userID, deviceA, []SyncOperation{
|
||||
syncOp(repository.NewID(), fileID, OpUpdateMetadata, "file", map[string]any{
|
||||
"name": "v3.txt", "baseUpdatedAt": stale,
|
||||
}),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("apply: %v", err)
|
||||
}
|
||||
if res.Applied != 1 || res.Failed != nil {
|
||||
t.Fatalf("rename concurrent doit s'appliquer (LWW): %+v", res)
|
||||
}
|
||||
if len(res.Conflicts) != 1 {
|
||||
t.Fatalf("conflit manquant: %+v", res)
|
||||
}
|
||||
c := res.Conflicts[0]
|
||||
if c.ResourceID != fileID || c.ServerName != "v3.txt" || c.ServerUpdatedAt <= 0 {
|
||||
t.Fatalf("conflit inattendu: %+v", c)
|
||||
}
|
||||
|
||||
// Sans base (vieux client) : appliqué, jamais signalé.
|
||||
res, err = s.ApplyBatch(userID, deviceA, []SyncOperation{
|
||||
syncOp(repository.NewID(), fileID, OpUpdateMetadata, "file", map[string]any{"name": "v4.txt"}),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("apply: %v", err)
|
||||
}
|
||||
if res.Applied != 1 || res.Failed != nil || len(res.Conflicts) != 0 {
|
||||
t.Fatalf("sans base : silencieux: %+v", res)
|
||||
}
|
||||
|
||||
// Tolérance 2 s : un écart d'1 s (skew/troncation) n'est pas un conflit.
|
||||
_, nowMs, _ := s.Repository.Resources.LiveNameAndUpdatedAt(fileID)
|
||||
res, err = s.ApplyBatch(userID, deviceA, []SyncOperation{
|
||||
syncOp(repository.NewID(), fileID, OpUpdateMetadata, "file", map[string]any{
|
||||
"name": "v5.txt", "baseUpdatedAt": nowMs - 1000,
|
||||
}),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("apply: %v", err)
|
||||
}
|
||||
if len(res.Conflicts) != 0 {
|
||||
t.Fatalf("écart 1 s ne doit pas signaler: %+v", res)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user