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:
@@ -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)
|
||||
}
|
||||
Reference in New Issue
Block a user