π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Improve account deletion recovery
Neeraj Guptabd539340bad5
diff --git a/server/cmd/museum/main.go b/server/cmd/museum/main.goindex 21b91d97d4..7eefa40399 100644--- a/server/cmd/museum/main.go+++ b/server/cmd/museum/main.go@@ -717,6 +717,8 @@ func main() {privateAPI.GET("/users/delete-challenge", userHandler.GetDeleteChallenge)privateAPI.DELETE("/users/delete", userHandler.DeleteUser)publicAPI.GET("/users/recover-account", userHandler.SelfAccountRecovery)+ publicAPI.POST("/users/recover-account/validate", userHandler.ValidateSelfAccountRecovery)+ publicAPI.POST("/users/recover-account", userHandler.RecoverSelfAccount)accountsJwtAuthAPI := server.Group("/")accountsJwtAuthAPI.Use(rateLimiter.GlobalRateLimiter(), authMiddleware.TokenAuthMiddleware(jwt.ACCOUNTS.Ptr()), rateLimiter.APIRateLimitForUserMiddleware(urlSanitizer))diff --git a/server/ente/jwt/jwt.go b/server/ente/jwt/jwt.goindex fc53a84bcd..adbae41472 100644--- a/server/ente/jwt/jwt.go+++ b/server/ente/jwt/jwt.go@@ -2,9 +2,12 @@ package jwtimport ("errors"+"github.com/ente/museum/pkg/utils/time")+var ErrTokenExpired = errors.New("token expired")+type ClaimScope stringconst (@@ -35,7 +38,7 @@ func (w *WebCommonJWTClaim) GetScope() ClaimScope {func (w WebCommonJWTClaim) Valid() error {if w.ExpiryTime < time.Microseconds() {- return errors.New("token expired")+ return ErrTokenExpired}return nil}@@ -48,7 +51,7 @@ type LinkPasswordClaim struct {func (c LinkPasswordClaim) Valid() error {if c.ExpiryTime < time.Microseconds() {- return errors.New("token expired")+ return ErrTokenExpired}return nil}@@ -62,7 +65,7 @@ type PasteGuardClaim struct {func (c PasteGuardClaim) Valid() error {if c.ExpiryTime < time.Microseconds() {- return errors.New("token expired")+ return ErrTokenExpired}return nil}diff --git a/server/ente/user.go b/server/ente/user.goindex 4b5178aec0..91cabfaa8e 100644--- a/server/ente/user.go+++ b/server/ente/user.go@@ -179,6 +179,21 @@ type DeleteAccountResponse struct {UserID int64 `json:"userID"`}+type AccountRecoveryRequest struct {+ Token string `json:"token" binding:"required"`+}++type AccountRecoveryStatus string++const (+ AccountRecoveryReady AccountRecoveryStatus = "ready"+ AccountRecoveryRecovered AccountRecoveryStatus = "recovered"+)++type AccountRecoveryResponse struct {+ Status AccountRecoveryStatus `json:"status"`+}+// TwoFactorSecret represents the two factor secret generator value, user enters in his authenticator apptype TwoFactorSecret struct {SecretCode string `json:"secretCode"`diff --git a/server/pkg/api/user.go b/server/pkg/api/user.goindex 14b0355654..c8609c7587 100644--- a/server/pkg/api/user.go+++ b/server/pkg/api/user.go@@ -584,6 +584,34 @@ func (h *UserHandler) SelfAccountRecovery(c *gin.Context) {c.HTML(http.StatusOK, "account_recovered.html", gin.H{})}+func (h *UserHandler) ValidateSelfAccountRecovery(c *gin.Context) {+ var request ente.AccountRecoveryRequest+ if err := handler.BindJSON(c, &request); err != nil {+ handler.Error(c, stacktrace.Propagate(err, "Could not bind request params"))+ return+ }+ response, err := h.UserController.ValidateSelfAccountRecovery(request.Token)+ if err != nil {+ handler.Error(c, err)+ return+ }+ c.JSON(http.StatusOK, response)+}++func (h *UserHandler) RecoverSelfAccount(c *gin.Context) {+ var request ente.AccountRecoveryRequest+ if err := handler.BindJSON(c, &request); err != nil {+ handler.Error(c, stacktrace.Propagate(err, "Could not bind request params"))+ return+ }+ response, err := h.UserController.RecoverSelfAccount(c, request.Token)+ if err != nil {+ handler.Error(c, err)+ return+ }+ c.JSON(http.StatusOK, response)+}+// GetSRPAttributes returns the SRP attributes for a userfunc (h *UserHandler) GetSRPAttributes(c *gin.Context) {var request ente.GetSRPAttributesRequestdiff --git a/server/pkg/controller/user/account_recovery.go b/server/pkg/controller/user/account_recovery.gonew file mode 100644index 0000000000..37d0c768be--- /dev/null+++ b/server/pkg/controller/user/account_recovery.go@@ -0,0 +1,199 @@+package user++import (+ "database/sql"+ "errors"+ "fmt"+ "net/http"+ "net/url"+ "strings"++ "github.com/ente/museum/ente"+ enteJWT "github.com/ente/museum/ente/jwt"+ "github.com/ente/museum/pkg/utils/crypto"+ "github.com/ente/museum/pkg/utils/email"+ "github.com/ente/museum/pkg/utils/time"+ "github.com/ente/stacktrace"+ "github.com/gin-gonic/gin"+ "github.com/lib/pq"+ "github.com/sirupsen/logrus"+ "github.com/spf13/viper"+)++const (+ accountRecoveryLinkValidityDays = 7+ accountRecoveryInvalidLinkCode ente.ErrorCode = "ACCOUNT_RECOVERY_INVALID_LINK"+ accountRecoveryLinkExpiredCode ente.ErrorCode = "ACCOUNT_RECOVERY_LINK_EXPIRED"+ accountRecoveryEmailInUseCode ente.ErrorCode = "ACCOUNT_RECOVERY_EMAIL_IN_USE"+ accountRecoveryUnavailableCode ente.ErrorCode = "ACCOUNT_RECOVERY_UNAVAILABLE"+)++var (+ ErrAccountRecoveryInvalidLink = &ente.ApiError{+ Code: accountRecoveryInvalidLinkCode,+ Message: "invalid account recovery link",+ HttpStatusCode: http.StatusBadRequest,+ }+ ErrAccountRecoveryLinkExpired = &ente.ApiError{+ Code: accountRecoveryLinkExpiredCode,+ Message: "expired account recovery link",+ HttpStatusCode: http.StatusGone,+ }+ ErrAccountRecoveryEmailInUse = &ente.ApiError{+ Code: accountRecoveryEmailInUseCode,+ Message: "account recovery email already in use",+ HttpStatusCode: http.StatusConflict,+ }+ ErrAccountRecoveryUnavailable = &ente.ApiError{+ Code: accountRecoveryUnavailableCode,+ Message: "account can no longer be recovered",+ HttpStatusCode: http.StatusGone,+ }+)++func (c *UserController) getAccountRecoveryLink(userID int64, userEmail string) (string, error) {+ recoverToken, err := c.GetJWTTokenForClaim(&enteJWT.WebCommonJWTClaim{+ UserID: userID,+ ExpiryTime: time.MicrosecondsAfterDays(accountRecoveryLinkValidityDays),+ ClaimScope: enteJWT.RestoreAccount.Ptr(),+ Email: userEmail,+ })+ if err != nil {+ return "", err+ }+ accountsURL := strings.TrimRight(viper.GetString("apps.accounts"), "/")+ return fmt.Sprintf("%s/recover-account#recoveryToken=%s", accountsURL, url.QueryEscape(recoverToken)), nil+}++func (c *UserController) ValidateSelfAccountRecovery(token string) (ente.AccountRecoveryResponse, error) {+ req, err := c.accountRecoveryRequest(token)+ if err != nil {+ return ente.AccountRecoveryResponse{}, err+ }+ status, err := c.accountRecoveryStatus(req, true)+ if err != nil {+ return ente.AccountRecoveryResponse{}, err+ }+ return ente.AccountRecoveryResponse{Status: status}, nil+}++func (c *UserController) RecoverSelfAccount(ctx *gin.Context, token string) (ente.AccountRecoveryResponse, error) {+ req, err := c.accountRecoveryRequest(token)+ if err != nil {+ return ente.AccountRecoveryResponse{}, err+ }+ status, err := c.recoverAccount(ctx, req, true)+ if err != nil {+ return ente.AccountRecoveryResponse{}, err+ }+ return ente.AccountRecoveryResponse{Status: status}, nil+}++// HandleSelfAccountRecovery keeps the legacy recovery link behavior until all+// previously issued links have expired.+func (c *UserController) HandleSelfAccountRecovery(ctx *gin.Context, token string) error {+ _, err := c.RecoverSelfAccount(ctx, token)+ return err+}++func (c *UserController) accountRecoveryRequest(token string) (ente.RecoverAccountRequest, error) {+ jwtToken, err := c.ValidateJWTToken(token, enteJWT.RestoreAccount)+ if err != nil {+ if errors.Is(err, errJWTExpired) {+ return ente.RecoverAccountRequest{}, stacktrace.Propagate(ErrAccountRecoveryLinkExpired, "failed to validate jwt token")+ }+ return ente.RecoverAccountRequest{}, stacktrace.Propagate(ErrAccountRecoveryInvalidLink, "failed to validate jwt token: %s", err.Error())+ }+ if jwtToken.UserID == 0 || jwtToken.Email == "" {+ return ente.RecoverAccountRequest{}, stacktrace.Propagate(ErrAccountRecoveryInvalidLink, "userID or email is empty")+ }+ return ente.RecoverAccountRequest{UserID: jwtToken.UserID, EmailID: jwtToken.Email}, nil+}++func (c *UserController) accountRecoveryStatus(req ente.RecoverAccountRequest, allowAlreadyRecovered bool) (ente.AccountRecoveryStatus, error) {+ user, err := c.UserRepo.Get(req.UserID)+ if err == nil {+ if allowAlreadyRecovered && strings.EqualFold(email.NormalizeEmail(user.Email), email.NormalizeEmail(req.EmailID)) {+ return ente.AccountRecoveryRecovered, nil+ }+ if !allowAlreadyRecovered {+ return "", stacktrace.Propagate(ente.NewBadRequestError(&ente.ApiErrorParams{+ Message: "account is already recovered or userID is linked to another active account",+ }), "")+ }+ return "", stacktrace.Propagate(ErrAccountRecoveryUnavailable, "userID is linked to another active account")+ }+ if errors.Is(err, sql.ErrNoRows) {+ return "", stacktrace.Propagate(ErrAccountRecoveryUnavailable, "user no longer exists")+ }+ if !errors.Is(err, ente.ErrUserDeleted) {+ return "", stacktrace.Propagate(err, "error while getting the user")+ }++ if _, err := c.UserRepo.GetKeyAttributes(req.UserID); err != nil {+ if errors.Is(err, sql.ErrNoRows) {+ return "", stacktrace.Propagate(ErrAccountRecoveryUnavailable, "key attributes have been deleted")+ }+ return "", stacktrace.Propagate(err, "failed to get key attributes")+ }++ recoveryEmail := email.NormalizeEmail(req.EmailID)+ if userID, err := c.UserRepo.GetUserIDWithEmailUnrestricted(recoveryEmail); err == nil {+ if userID != req.UserID {+ return "", stacktrace.Propagate(ErrAccountRecoveryEmailInUse, "email is already used by user %d", userID)+ }+ } else if !errors.Is(err, sql.ErrNoRows) {+ return "", stacktrace.Propagate(err, "failed to look up the recovery email")+ }+ return ente.AccountRecoveryReady, nil+}++func (c *UserController) HandleAccountRecovery(ctx *gin.Context, req ente.RecoverAccountRequest) error {+ _, err := c.recoverAccount(ctx, req, false)+ return err+}++func (c *UserController) recoverAccount(ctx *gin.Context, req ente.RecoverAccountRequest, allowAlreadyRecovered bool) (ente.AccountRecoveryStatus, error) {+ logger := logrus.WithFields(logrus.Fields{+ "req_id": ctx.GetString("req_id"),+ "req_ctx": "account_recovery",+ "email": req.EmailID,+ "userID": req.UserID,+ })+ logger.Info("initiating account recovery")++ status, err := c.accountRecoveryStatus(req, allowAlreadyRecovered)+ if err != nil {+ return "", err+ }+ if status == ente.AccountRecoveryRecovered {+ return status, nil+ }++ recoveryEmail := email.NormalizeEmail(req.EmailID)+ encryptedEmail, err := crypto.Encrypt(recoveryEmail, c.SecretEncryptionKey)+ if err != nil {+ return "", stacktrace.Propagate(err, "")+ }+ emailHash, err := crypto.GetHash(recoveryEmail, c.HashingKey)+ if err != nil {+ return "", stacktrace.Propagate(err, "")+ }+ if err := c.UserRepo.UpdateEmail(req.UserID, encryptedEmail, emailHash); err != nil {+ if isEmailHashUniqueConstraint(err) {+ return "", stacktrace.Propagate(ErrAccountRecoveryEmailInUse, "email was claimed while recovering the account")+ }+ return "", stacktrace.Propagate(err, "failed to update email")+ }+ c.touchContactsAfterEmailUpdate(ctx, req.UserID)+ if err := c.DataCleanupRepo.RemoveScheduledDelete(ctx, req.UserID); err != nil {+ logger.WithError(err).Error("failed to remove scheduled delete")+ return "", stacktrace.Propagate(err, "")+ }+ return ente.AccountRecoveryRecovered, nil+}++func isEmailHashUniqueConstraint(err error) bool {+ var pqErr *pq.Error+ return errors.As(err, &pqErr) && pqErr.Code == "23505"+}diff --git a/server/pkg/controller/user/jwt.go b/server/pkg/controller/user/jwt.goindex 0a50bc36f0..8a7df40c73 100644--- a/server/pkg/controller/user/jwt.go+++ b/server/pkg/controller/user/jwt.go@@ -1,7 +1,10 @@package userimport (+ "errors""fmt"+ "net/http"+"github.com/ente/museum/ente"enteJWT "github.com/ente/museum/ente/jwt""github.com/ente/museum/pkg/utils/time"@@ -12,6 +15,12 @@ import (// jwt token validity = 1 dayconst ValidForDays = 1+var errJWTExpired = &ente.ApiError{+ Code: ente.BadRequest,+ Message: "token expired",+ HttpStatusCode: http.StatusBadRequest,+}+func (c *UserController) GetJWTToken(userID int64, scope enteJWT.ClaimScope) (string, error) {tokenExpiry := time.NDaysFromNow(1)if scope == enteJWT.ACCOUNTS {@@ -46,8 +55,8 @@ func (c *UserController) ValidateJWTToken(jwtToken string, scope enteJWT.ClaimScreturn c.JwtSecret, nil})if err != nil {- if ve, ok := err.(*jwt.ValidationError); ok && ve.Error() == "token expired" {- return nil, stacktrace.Propagate(ente.NewBadRequestWithMessage("token expired"), "")+ if errors.Is(err, enteJWT.ErrTokenExpired) {+ return nil, stacktrace.Propagate(errJWTExpired, "")}return nil, stacktrace.Propagate(err, "JWT parsed failed")}diff --git a/server/pkg/controller/user/user.go b/server/pkg/controller/user/user.goindex d0bd63c851..5d11775f3a 100644--- a/server/pkg/controller/user/user.go+++ b/server/pkg/controller/user/user.go@@ -2,16 +2,12 @@ package userimport ("context"- "database/sql""errors""fmt"- enteJWT "github.com/ente/museum/ente/jwt""github.com/ente/museum/pkg/controller/collections""github.com/ente/museum/pkg/repo/two_factor_recovery"util "github.com/ente/museum/pkg/utils"- "github.com/ente/museum/pkg/utils/time""github.com/ulule/limiter/v3"- "strings"cache2 "github.com/ente/museum/ente/cache""github.com/ente/museum/pkg/controller/discord"@@ -116,8 +112,6 @@ const (AccountDeletedEmailTemplate = "account_deleted.html"AccountDeletedWithActiveSubscriptionEmailTemplate = "account_deleted_active_sub.html"AccountDeletedEmailSubject = "Your Ente account has been deleted"- accountRecoveryLinkHost = "https://api.ente.com"- accountRecoveryLinkValidityDays = 7)func NewUserController(@@ -397,93 +391,6 @@ func (c *UserController) NotifyAccountDeletion(userID int64, userEmail string, i}}-func (c *UserController) getAccountRecoveryLink(userID int64, userEmail string) (string, error) {- recoverToken, err := c.GetJWTTokenForClaim(&enteJWT.WebCommonJWTClaim{- UserID: userID,- ExpiryTime: time.MicrosecondsAfterDays(accountRecoveryLinkValidityDays),- ClaimScope: enteJWT.RestoreAccount.Ptr(),- Email: userEmail,- })- if err != nil {- return "", err- }- return fmt.Sprintf("%s/users/recover-account?token=%s", accountRecoveryLinkHost, recoverToken), nil-}--func (c *UserController) HandleSelfAccountRecovery(ctx *gin.Context, token string) error {- jwtToken, err := c.ValidateJWTToken(token, enteJWT.RestoreAccount)- if err != nil {- return stacktrace.Propagate(ente.NewPermissionDeniedError("invalid token"), "failed to validate jwt token: %s", err.Error())- }- if jwtToken.UserID == 0 || jwtToken.Email == "" {- return stacktrace.Propagate(ente.NewBadRequestError(&ente.ApiErrorParams{- Message: "Invalid token",- }), "userID or email is empty")- }- if jwtToken.ExpiryTime < time.Microseconds() {- return stacktrace.Propagate(ente.NewBadRequestError(&ente.ApiErrorParams{- Message: "Token expired",- }), "")- }- // check if account is already recovered- if user, userErr := c.UserRepo.Get(jwtToken.UserID); userErr == nil {- if strings.EqualFold(user.Email, jwtToken.Email) {- logrus.WithField("userID", jwtToken.UserID).Error("account is already recovered")- return nil- }- }- return c.HandleAccountRecovery(ctx, ente.RecoverAccountRequest{- UserID: jwtToken.UserID,- EmailID: jwtToken.Email,- })-}--func (c *UserController) HandleAccountRecovery(ctx *gin.Context, req ente.RecoverAccountRequest) error {- logger := logrus.WithFields(logrus.Fields{- "req_id": ctx.GetString("req_id"),- "req_ctx": "account_recovery",- "email": req.EmailID,- "userID": req.UserID,- })- logger.Info("initiating account recovery")- _, err := c.UserRepo.Get(req.UserID)- if err == nil {- return stacktrace.Propagate(ente.NewBadRequestError(&ente.ApiErrorParams{- Message: "account is already recovered or userID is linked to another active account",- }), "")- }- if !errors.Is(err, ente.ErrUserDeleted) {- return stacktrace.Propagate(err, "error while getting the user")- }- // check if the user keyAttributes are still available- if _, keyErr := c.UserRepo.GetKeyAttributes(req.UserID); keyErr != nil {- if errors.Is(keyErr, sql.ErrNoRows) {- return stacktrace.Propagate(ente.NewBadRequestWithMessage("account can not be recovered now"), "")- }- return stacktrace.Propagate(keyErr, "keyAttributes missing? Account can not be recovered")- }- email := email.NormalizeEmail(req.EmailID)- encryptedEmail, err := crypto.Encrypt(email, c.SecretEncryptionKey)- if err != nil {- return stacktrace.Propagate(err, "")- }- emailHash, err := crypto.GetHash(email, c.HashingKey)- if err != nil {- return stacktrace.Propagate(err, "")- }- err = c.UserRepo.UpdateEmail(req.UserID, encryptedEmail, emailHash)- if err != nil {- return stacktrace.Propagate(err, "failed to update email")- }- c.touchContactsAfterEmailUpdate(ctx, req.UserID)- err = c.DataCleanupRepo.RemoveScheduledDelete(ctx, req.UserID)- if err != nil {- logrus.WithError(err).Error("failed to remove scheduled delete")- return stacktrace.Propagate(err, "")- }- return stacktrace.Propagate(err, "")-}-func (c *UserController) attachFreeSubscription(userID int64) (ente.Subscription, error) {subscription := billing.GetFreeSubscription(userID)generatedID, err := c.BillingRepo.AddSubscription(subscription)diff --git a/server/pkg/controller/user/user_recovery_test.go b/server/pkg/controller/user/user_recovery_test.goindex 742b61f6e9..9fa93e681f 100644--- a/server/pkg/controller/user/user_recovery_test.go+++ b/server/pkg/controller/user/user_recovery_test.go@@ -2,21 +2,261 @@ package userimport ("database/sql"+ "errors"+ "net/http""net/http/httptest"+ "net/url""testing""github.com/ente/museum/ente"contactmodel "github.com/ente/museum/ente/contact"cleanupentity "github.com/ente/museum/ente/data_cleanup"+ enteJWT "github.com/ente/museum/ente/jwt""github.com/ente/museum/internal/testutil""github.com/ente/museum/pkg/repo"contactrepo "github.com/ente/museum/pkg/repo/contact"cleanuprepo "github.com/ente/museum/pkg/repo/datacleanup""github.com/ente/museum/pkg/utils/config"+ "github.com/ente/museum/pkg/utils/time""github.com/gin-gonic/gin""github.com/spf13/viper")+func TestGetAccountRecoveryLinkExpiresAfterSevenDays(t *testing.T) {+ viper.Reset()+ viper.Set("apps.accounts", "https://accounts.example.com/")+ t.Cleanup(viper.Reset)++ controller := &UserController{JwtSecret: []byte("test-jwt-secret")}++ before := time.Microseconds()+ recoveryLink, err := controller.getAccountRecoveryLink(42, "[email protected]")+ if err != nil {+ t.Fatalf("getAccountRecoveryLink() error = %v", err)+ }+ after := time.Microseconds()++ parsedLink, err := url.Parse(recoveryLink)+ if err != nil {+ t.Fatalf("failed to parse recovery link: %v", err)+ }+ if parsedLink.Scheme != "https" || parsedLink.Host != "accounts.example.com" || parsedLink.Path != "/recover-account" {+ t.Fatalf("recovery link = %q, want configured accounts recovery page", recoveryLink)+ }+ if parsedLink.RawQuery != "" {+ t.Fatalf("recovery link query = %q, want token only in fragment", parsedLink.RawQuery)+ }+ fragment, err := url.ParseQuery(parsedLink.Fragment)+ if err != nil {+ t.Fatalf("failed to parse recovery link fragment: %v", err)+ }+ claim, err := controller.ValidateJWTToken(fragment.Get("recoveryToken"), enteJWT.RestoreAccount)+ if err != nil {+ t.Fatalf("ValidateJWTToken() error = %v", err)+ }++ const sevenDays = int64(7*24) * time.MicroSecondsInOneHour+ if claim.ExpiryTime < before+sevenDays || claim.ExpiryTime > after+sevenDays {+ t.Fatalf("token expiry = %d, want approximately 7 days after issuance", claim.ExpiryTime)+ }+ if claim.UserID != 42 || claim.Email != "[email protected]" {+ t.Fatalf("recovery token claim = %+v, want user 42 and [email protected]", claim)+ }+}++func TestValidateSelfAccountRecoveryClassifiesTokenErrors(t *testing.T) {+ controller := &UserController{JwtSecret: []byte("test-jwt-secret")}+ expiredToken := accountRecoveryToken(t, controller, &enteJWT.WebCommonJWTClaim{+ UserID: 42,+ Email: "[email protected]",+ ExpiryTime: time.Microseconds() - 1,+ ClaimScope: enteJWT.RestoreAccount.Ptr(),+ })+ wrongScopeToken := accountRecoveryToken(t, controller, &enteJWT.WebCommonJWTClaim{+ UserID: 42,+ Email: "[email protected]",+ ExpiryTime: time.MicrosecondsAfterDays(1),+ ClaimScope: enteJWT.DELETE_ACCOUNT.Ptr(),+ })++ tests := []struct {+ name string+ token string+ wantError *ente.ApiError+ wantCode ente.ErrorCode+ wantStatus int+ }{+ {+ name: "malformed",+ token: "not-a-jwt",+ wantError: ErrAccountRecoveryInvalidLink,+ wantCode: accountRecoveryInvalidLinkCode,+ wantStatus: http.StatusBadRequest,+ },+ {+ name: "wrong scope",+ token: wrongScopeToken,+ wantError: ErrAccountRecoveryInvalidLink,+ wantCode: accountRecoveryInvalidLinkCode,+ wantStatus: http.StatusBadRequest,+ },+ {+ name: "expired",+ token: expiredToken,+ wantError: ErrAccountRecoveryLinkExpired,+ wantCode: accountRecoveryLinkExpiredCode,+ wantStatus: http.StatusGone,+ },+ }++ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ _, err := controller.ValidateSelfAccountRecovery(test.token)+ if !errors.Is(err, test.wantError) {+ t.Fatalf("ValidateSelfAccountRecovery() error = %v, want %v", err, test.wantError)+ }+ var apiErr *ente.ApiError+ if !errors.As(err, &apiErr) {+ t.Fatalf("ValidateSelfAccountRecovery() error = %v, want ApiError", err)+ }+ if apiErr.Code != test.wantCode || apiErr.HttpStatusCode != test.wantStatus {+ t.Fatalf("ApiError = %+v, want code %s and status %d", apiErr, test.wantCode, test.wantStatus)+ }+ })+ }+}++func TestSelfAccountRecoveryStatusAndRecovery(t *testing.T) {+ testutil.WithServerRoot(t)+ db := testutil.RequireTestDB(t)+ testutil.ResetTables(t, db)+ t.Cleanup(func() { testutil.ResetTables(t, db) })++ userID := testutil.InsertUser(t, db, testutil.UserFixture{+ UserID: 82,+ Email: "[email protected]",+ CreationTime: 1,+ })+ insertKeyAttributes(t, db, userID)+ insertScheduledDelete(t, db, userID)++ userRepo := &repo.UserRepository{+ DB: db,+ SecretEncryptionKey: testutil.SecretEncryptionKey(),+ HashingKey: testutil.HashingKey(),+ }+ if err := userRepo.Delete(userID); err != nil {+ t.Fatalf("failed to delete user: %v", err)+ }+ controller := &UserController{+ UserRepo: userRepo,+ DataCleanupRepo: &cleanuprepo.Repository{DB: db},+ SecretEncryptionKey: testutil.SecretEncryptionKey(),+ HashingKey: testutil.HashingKey(),+ JwtSecret: []byte("test-jwt-secret"),+ }+ token := accountRecoveryToken(t, controller, &enteJWT.WebCommonJWTClaim{+ UserID: userID,+ Email: "[email protected]",+ ExpiryTime: time.MicrosecondsAfterDays(1),+ ClaimScope: enteJWT.RestoreAccount.Ptr(),+ })++ response, err := controller.ValidateSelfAccountRecovery(token)+ if err != nil {+ t.Fatalf("ValidateSelfAccountRecovery() error = %v", err)+ }+ if response.Status != ente.AccountRecoveryReady {+ t.Fatalf("validation status = %q, want %q", response.Status, ente.AccountRecoveryReady)+ }++ gin.SetMode(gin.TestMode)+ ctx, _ := gin.CreateTestContext(httptest.NewRecorder())+ response, err = controller.RecoverSelfAccount(ctx, token)+ if err != nil {+ t.Fatalf("RecoverSelfAccount() error = %v", err)+ }+ if response.Status != ente.AccountRecoveryRecovered {+ t.Fatalf("recovery status = %q, want %q", response.Status, ente.AccountRecoveryRecovered)+ }+ if _, err := userRepo.Get(userID); err != nil {+ t.Fatalf("recovered user is not active: %v", err)+ }+ var cleanupRows int+ if err := db.QueryRow(`SELECT COUNT(*) FROM data_cleanup WHERE user_id = $1`, userID).Scan(&cleanupRows); err != nil {+ t.Fatalf("failed to count cleanup rows: %v", err)+ }+ if cleanupRows != 0 {+ t.Fatalf("cleanup row count = %d, want 0", cleanupRows)+ }++ response, err = controller.ValidateSelfAccountRecovery(token)+ if err != nil {+ t.Fatalf("ValidateSelfAccountRecovery() after recovery error = %v", err)+ }+ if response.Status != ente.AccountRecoveryRecovered {+ t.Fatalf("validation status after recovery = %q, want %q", response.Status, ente.AccountRecoveryRecovered)+ }++ err = controller.HandleAccountRecovery(ctx, ente.RecoverAccountRequest{+ UserID: userID,+ EmailID: "[email protected]",+ })+ var apiErr *ente.ApiError+ if !errors.As(err, &apiErr) || apiErr.Code != ente.BadRequest || apiErr.HttpStatusCode != http.StatusBadRequest {+ t.Fatalf("HandleAccountRecovery() for active account error = %v, want bad request", err)+ }+}++func TestValidateSelfAccountRecoveryReportsUnavailableAfterKeyCleanup(t *testing.T) {+ testutil.WithServerRoot(t)+ db := testutil.RequireTestDB(t)+ testutil.ResetTables(t, db)+ t.Cleanup(func() { testutil.ResetTables(t, db) })++ userID := testutil.InsertUser(t, db, testutil.UserFixture{+ UserID: 82,+ Email: "[email protected]",+ CreationTime: 1,+ })+ userRepo := &repo.UserRepository{+ DB: db,+ SecretEncryptionKey: testutil.SecretEncryptionKey(),+ HashingKey: testutil.HashingKey(),+ }+ if err := userRepo.Delete(userID); err != nil {+ t.Fatalf("failed to delete user: %v", err)+ }+ controller := &UserController{+ UserRepo: userRepo,+ JwtSecret: []byte("test-jwt-secret"),+ }+ token := accountRecoveryToken(t, controller, &enteJWT.WebCommonJWTClaim{+ UserID: userID,+ Email: "[email protected]",+ ExpiryTime: time.MicrosecondsAfterDays(1),+ ClaimScope: enteJWT.RestoreAccount.Ptr(),+ })++ _, err := controller.ValidateSelfAccountRecovery(token)+ if !errors.Is(err, ErrAccountRecoveryUnavailable) {+ t.Fatalf("ValidateSelfAccountRecovery() error = %v, want ErrAccountRecoveryUnavailable", err)+ }+ var apiErr *ente.ApiError+ if !errors.As(err, &apiErr) || apiErr.Code != accountRecoveryUnavailableCode || apiErr.HttpStatusCode != http.StatusGone {+ t.Fatalf("ValidateSelfAccountRecovery() error = %v, want unavailable ApiError", err)+ }+}++func accountRecoveryToken(t *testing.T, controller *UserController, claim *enteJWT.WebCommonJWTClaim) string {+ t.Helper()+ token, err := controller.GetJWTTokenForClaim(claim)+ if err != nil {+ t.Fatalf("failed to create account recovery token: %v", err)+ }+ return token+}+func TestHandleAccountRecoveryTouchesContactsForResolvedEmailSync(t *testing.T) {testutil.WithServerRoot(t)viper.Reset()@@ -109,6 +349,64 @@ func TestHandleAccountRecoveryTouchesContactsForResolvedEmailSync(t *testing.T)}}+func TestHandleAccountRecoveryReportsEmailInUse(t *testing.T) {+ testutil.WithServerRoot(t)+ viper.Reset()+ if err := config.ConfigureViper("local"); err != nil {+ t.Fatalf("failed to configure viper: %v", err)+ }+ t.Cleanup(viper.Reset)++ db := testutil.RequireTestDB(t)+ testutil.ResetTables(t, db)+ t.Cleanup(func() {+ testutil.ResetTables(t, db)+ })++ deletedUserID := testutil.InsertUser(t, db, testutil.UserFixture{+ UserID: 82,+ Email: "[email protected]",+ CreationTime: 1,+ })+ insertKeyAttributes(t, db, deletedUserID)+ insertScheduledDelete(t, db, deletedUserID)++ userRepo := &repo.UserRepository{+ DB: db,+ SecretEncryptionKey: testutil.SecretEncryptionKey(),+ HashingKey: testutil.HashingKey(),+ }+ if err := userRepo.Delete(deletedUserID); err != nil {+ t.Fatalf("failed to delete user: %v", err)+ }+ testutil.InsertUser(t, db, testutil.UserFixture{+ UserID: 83,+ Email: "[email protected]",+ CreationTime: 1,+ })++ gin.SetMode(gin.TestMode)+ ctx, _ := gin.CreateTestContext(httptest.NewRecorder())+ controller := &UserController{+ UserRepo: userRepo,+ DataCleanupRepo: &cleanuprepo.Repository{DB: db},+ SecretEncryptionKey: testutil.SecretEncryptionKey(),+ HashingKey: testutil.HashingKey(),+ }++ err := controller.HandleAccountRecovery(ctx, ente.RecoverAccountRequest{+ UserID: deletedUserID,+ EmailID: "[email protected]",+ })+ if !errors.Is(err, ErrAccountRecoveryEmailInUse) {+ t.Fatalf("HandleAccountRecovery() error = %v, want ErrAccountRecoveryEmailInUse", err)+ }+ var apiErr *ente.ApiError+ if !errors.As(err, &apiErr) || apiErr.Code != accountRecoveryEmailInUseCode || apiErr.HttpStatusCode != http.StatusConflict {+ t.Fatalf("HandleAccountRecovery() error = %v, want email-in-use ApiError", err)+ }+}+func insertKeyAttributes(t *testing.T, db *sql.DB, userID int64) {t.Helper()_, err := db.Exec(diff --git a/server/pkg/middleware/event_test.go b/server/pkg/middleware/event_test.goindex 88c70eb5d5..3b1d7290b6 100644--- a/server/pkg/middleware/event_test.go+++ b/server/pkg/middleware/event_test.go@@ -28,6 +28,12 @@ func TestShouldSkipBodyLogForSpaceKeyRoutes(t *testing.T) {require.False(t, shouldSkipBodyLog(http.MethodGet, "/user-entity/key"))}+func TestAccountRecoveryTokensAreNotLogged(t *testing.T) {+ require.True(t, shouldSkipBodyLog(http.MethodPost, "/users/recover-account/validate"))+ require.True(t, shouldSkipBodyLog(http.MethodPost, "/users/recover-account"))+ require.False(t, shouldSkipBodyLog(http.MethodGet, "/users/recover-account"))+}+func TestEventsUse120PerHourGlobalRateLimit(t *testing.T) {limit := util.NewRateLimiter("120-H")rateLimiter := &RateLimitMiddleware{limit120ReqPerHour: limit}@@ -69,6 +75,15 @@ func TestSpaceRoutesUseRouteSpecificRateLimits(t *testing.T) {require.Nil(t, rateLimiter.getLimiter("/account/space", http.MethodGet))}+func TestAccountRecoveryRoutesUsePublicSensitiveRateLimit(t *testing.T) {+ limit := util.NewRateLimiter("10-M")+ rateLimiter := &RateLimitMiddleware{limit10ReqPerMin: limit}++ require.Same(t, limit, rateLimiter.getLimiter("/users/recover-account/validate", http.MethodPost))+ require.Same(t, limit, rateLimiter.getLimiter("/users/recover-account", http.MethodPost))+ require.Nil(t, rateLimiter.getLimiter("/users/recover-account", http.MethodGet))+}+func TestEventsShareGlobalRateLimitAcrossPublicAndAuthenticatedRoutes(t *testing.T) {gin.SetMode(gin.TestMode)rateLimiter := &RateLimitMiddleware{diff --git a/server/pkg/middleware/rate_limit.go b/server/pkg/middleware/rate_limit.goindex 8289934277..34266d911f 100644--- a/server/pkg/middleware/rate_limit.go+++ b/server/pkg/middleware/rate_limit.go@@ -268,6 +268,8 @@ func (r *RateLimitMiddleware) getLimiter(reqPath string, reqMethod string) *limireqPath == "/public-collection/verify-password" ||reqPath == "/file-link/verify-password" ||reqPath == "/family/accept-invite" ||+ reqPath == "/users/recover-account/validate" ||+ (reqPath == "/users/recover-account" && reqMethod == http.MethodPost) ||reqPath == "/users/srp/attributes" ||(reqPath == "/cast/device-info" && reqMethod == "POST") ||(reqPath == "/cast/device-info/" && reqMethod == "POST") ||diff --git a/server/pkg/middleware/request_logger.go b/server/pkg/middleware/request_logger.goindex b2dd1a0982..de3bc1b5be 100644--- a/server/pkg/middleware/request_logger.go+++ b/server/pkg/middleware/request_logger.go@@ -58,6 +58,9 @@ func shouldSkipBodyLog(method string, path string) bool {if method == http.MethodPost && (path == "/paste/create" || path == "/paste/guard" || path == "/paste/consume") {return true}+ if method == http.MethodPost && (path == "/users/recover-account" || path == "/users/recover-account/validate") {+ return true+ }if !isReadOnly && (strings.HasPrefix(path, "/space") || strings.HasPrefix(path, "/account/space")) {return true}diff --git a/server/pkg/utils/email/storage_warning_template_test.go b/server/pkg/utils/email/storage_warning_template_test.goindex 561ea346d6..6747f45c7f 100644--- a/server/pkg/utils/email/storage_warning_template_test.go+++ b/server/pkg/utils/email/storage_warning_template_test.go@@ -35,7 +35,7 @@ func TestStorageWarningTemplatesIncludeAccountEmail(t *testing.T) {func TestInactiveUserDeletionFinalTemplateIncludesRecoveryLink(t *testing.T) {testutil.WithServerRoot(t)- recoveryLink := "https://api.ente.com/users/recover-account?token=test-token"+ recoveryLink := "https://accounts.ente.com/recover-account#recoveryToken=test-token"body, err := getMailBodyWithBase("ente_base.html", "inactive-user-deletion/confirm_13m.html", map[string]interface{}{"Email": "[email protected]","DeletionDate": "01 Apr 2026",diff --git a/web/apps/accounts/src/pages/family.tsx b/web/apps/accounts/src/pages/family.tsxindex 7764b48a7e..1172f2baee 100644--- a/web/apps/accounts/src/pages/family.tsx+++ b/web/apps/accounts/src/pages/family.tsx@@ -32,7 +32,6 @@ const Page: React.FC = () => {setPhase("loading");try {setInvite(await getFamilyInviteInfo(token));- window.history.replaceState(null, "", window.location.pathname);setPhase("ready");} catch (e) {const invalid =@@ -61,6 +60,7 @@ const Page: React.FC = () => {setPhase("accepting");try {setInvite(await acceptFamilyInvite(token!));+ window.history.replaceState(null, "", window.location.pathname);setPhase("accepted");} catch (e) {const invalid =diff --git a/web/apps/accounts/src/pages/recover-account.tsx b/web/apps/accounts/src/pages/recover-account.tsxnew file mode 100644index 0000000000..54503289cd--- /dev/null+++ b/web/apps/accounts/src/pages/recover-account.tsx@@ -0,0 +1,228 @@+import {+ accountRecoveryErrorCode,+ recoverAccount,+ validateAccountRecovery,+ type AccountRecoveryErrorCode,+} from "@/services/account-recovery";+import InfoOutlinedIcon from "@mui/icons-material/InfoOutlined";+import { Box, Stack, Typography } from "@mui/material";+import { AccountsPageContents } from "ente-accounts/components/layouts/centered-paper";+import { ActivityIndicator } from "ente-base/components/mui/ActivityIndicator";+import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";+import { LoadingButton } from "ente-base/components/mui/LoadingButton";+import { useBaseContext } from "ente-base/context";+import { t } from "i18next";+import React, { useCallback, useEffect, useState } from "react";++type Phase =+ | "loading"+ | "ready"+ | "recovering"+ | "recovered"+ | AccountRecoveryErrorPhase+ | "failed";++type AccountRecoveryErrorPhase =+ | "invalid"+ | "expired"+ | "emailInUse"+ | "unavailable";++const accountRecoveryErrorPhases: Record<+ AccountRecoveryErrorCode,+ AccountRecoveryErrorPhase+> = {+ ACCOUNT_RECOVERY_INVALID_LINK: "invalid",+ ACCOUNT_RECOVERY_LINK_EXPIRED: "expired",+ ACCOUNT_RECOVERY_EMAIL_IN_USE: "emailInUse",+ ACCOUNT_RECOVERY_UNAVAILABLE: "unavailable",+};++const Page: React.FC = () => {+ const { onGenericError } = useBaseContext();+ const [phase, setPhase] = useState<Phase>("loading");+ const [token, setToken] = useState<string>();++ const handleError = useCallback(+ async (error: unknown) => {+ const code = await accountRecoveryErrorCode(error);+ if (code) {+ setPhase(accountRecoveryErrorPhases[code]);+ } else {+ setPhase("failed");+ onGenericError(error);+ }+ },+ [onGenericError],+ );++ const validate = useCallback(+ async (token: string) => {+ setPhase("loading");+ try {+ const response = await validateAccountRecovery(token);+ const recovered = response.status == "recovered";+ if (recovered) {+ window.history.replaceState(+ null,+ "",+ window.location.pathname,+ );+ }+ setPhase(recovered ? "recovered" : "ready");+ } catch (error) {+ await handleError(error);+ }+ },+ [handleError],+ );++ useEffect(() => {+ const reloadForNewToken = () => window.location.reload();+ window.addEventListener("hashchange", reloadForNewToken);++ const token = new URLSearchParams(window.location.hash.slice(1)).get(+ "recoveryToken",+ );+ if (!token) {+ setPhase("invalid");+ } else {+ setToken(token);+ void validate(token);+ }++ return () =>+ window.removeEventListener("hashchange", reloadForNewToken);+ }, [validate]);++ const recover = async () => {+ setPhase("recovering");+ try {+ await recoverAccount(token!);+ window.history.replaceState(null, "", window.location.pathname);+ setPhase("recovered");+ } catch (error) {+ await handleError(error);+ }+ };++ return (+ <AccountsPageContents>+ {phase == "loading" ? (+ <Stack+ sx={{+ flex: 1,+ placeContent: "center",+ alignItems: "center",+ }}+ >+ <ActivityIndicator />+ </Stack>+ ) : phase == "failed" ? (+ <RecoveryContents>+ <Typography variant="h3">+ {t("generic_error_retry")}+ </Typography>+ <FocusVisibleButton onClick={() => void validate(token!)}>+ {t("retry")}+ </FocusVisibleButton>+ </RecoveryContents>+ ) : phase == "recovered" ? (+ <RecoveryContents>+ <RecoveryIcon />+ <RecoveryMessage+ title={t("account_recovery_success")}+ description={t("account_recovery_success_description")}+ />+ <FocusVisibleButton color="accent" href="https://ente.com">+ {t("open_ente")}+ </FocusVisibleButton>+ </RecoveryContents>+ ) : phase == "invalid" ? (+ <RecoveryContents>+ <RecoveryMessage+ title={t("account_recovery_invalid_title")}+ description={t("account_recovery_invalid_description")}+ />+ </RecoveryContents>+ ) : phase == "expired" ? (+ <RecoveryContents>+ <RecoveryMessage+ title={t("account_recovery_expired_title")}+ description={t("account_recovery_expired_description")}+ />+ </RecoveryContents>+ ) : phase == "emailInUse" ? (+ <RecoveryContents>+ <InfoOutlinedIcon color="secondary" sx={{ fontSize: 48 }} />+ <RecoveryMessage+ title={t("account_recovery_email_in_use")}+ description={t(+ "account_recovery_email_in_use_description",+ )}+ />+ </RecoveryContents>+ ) : phase == "unavailable" ? (+ <RecoveryContents>+ <RecoveryMessage+ title={t("account_recovery_unavailable_title")}+ description={t(+ "account_recovery_unavailable_description",+ )}+ />+ </RecoveryContents>+ ) : (+ <RecoveryContents>+ <RecoveryIcon />+ <RecoveryMessage+ title={t("account_recovery_title")}+ description={t("account_recovery_description")}+ />+ <LoadingButton+ fullWidth+ color="accent"+ loading={phase == "recovering"}+ onClick={() => void recover()}+ >+ {t("recover_account")}+ </LoadingButton>+ </RecoveryContents>+ )}+ </AccountsPageContents>+ );+};++const RecoveryIcon = () => (+ <Box+ component="img"+ alt=""+ src="/images/ente-circular.png"+ sx={{ width: 96, height: 96 }}+ />+);++const RecoveryMessage: React.FC<{ title: string; description: string }> = ({+ title,+ description,+}) => (+ <Stack sx={{ gap: 1.5 }}>+ <Typography variant="h3">{title}</Typography>+ <Typography sx={{ color: "text.muted" }}>{description}</Typography>+ </Stack>+);++const RecoveryContents: React.FC<React.PropsWithChildren> = ({ children }) => (+ <Stack+ sx={{+ flex: 1,+ placeContent: "center",+ alignItems: "center",+ textAlign: "center",+ gap: 3,+ }}+ >+ {children}+ </Stack>+);++export default Page;diff --git a/web/apps/accounts/src/services/account-recovery.ts b/web/apps/accounts/src/services/account-recovery.tsnew file mode 100644index 0000000000..fc5a294e33--- /dev/null+++ b/web/apps/accounts/src/services/account-recovery.ts@@ -0,0 +1,50 @@+import { ensureOk, HTTPError, publicRequestHeaders } from "ente-base/http";+import { apiURL } from "ente-base/origins";+import { z } from "zod";++const AccountRecoveryResponse = z.object({+ status: z.enum(["ready", "recovered"]),+});++export type AccountRecoveryResponse = z.infer<typeof AccountRecoveryResponse>;++const AccountRecoveryErrorCode = z.enum([+ "ACCOUNT_RECOVERY_INVALID_LINK",+ "ACCOUNT_RECOVERY_LINK_EXPIRED",+ "ACCOUNT_RECOVERY_EMAIL_IN_USE",+ "ACCOUNT_RECOVERY_UNAVAILABLE",+]);++export type AccountRecoveryErrorCode = z.infer<typeof AccountRecoveryErrorCode>;++const postAccountRecoveryToken = async (path: string, token: string) => {+ const res = await fetch(await apiURL(path), {+ method: "POST",+ headers: {+ ...publicRequestHeaders(),+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ token }),+ });+ ensureOk(res);+ return AccountRecoveryResponse.parse(await res.json());+};++export const validateAccountRecovery = (token: string) =>+ postAccountRecoveryToken("/users/recover-account/validate", token);++export const recoverAccount = (token: string) =>+ postAccountRecoveryToken("/users/recover-account", token);++export const accountRecoveryErrorCode = async (error: unknown) => {+ if (!(error instanceof HTTPError)) return undefined;++ try {+ const payload = z+ .object({ code: AccountRecoveryErrorCode })+ .parse(await error.res.clone().json());+ return payload.code;+ } catch {+ return undefined;+ }+};diff --git a/web/packages/base/locales/en-US/translation.json b/web/packages/base/locales/en-US/translation.jsonindex 1b3a68b2e9..af98cb8a71 100644--- a/web/packages/base/locales/en-US/translation.json+++ b/web/packages/base/locales/en-US/translation.json@@ -257,6 +257,18 @@"family_invite_accepted_description": "You are now sharing {{email}}'s plan.","family_invite_invalid": "This invite is invalid or no longer available.","open_ente": "Open Ente",+ "account_recovery_title": "Recover your Ente account",+ "account_recovery_description": "Restore your account and cancel its scheduled deletion.",+ "account_recovery_success": "Your account has been recovered",+ "account_recovery_success_description": "You can now sign in to Ente again.",+ "account_recovery_invalid_title": "Invalid recovery link",+ "account_recovery_invalid_description": "This recovery link is invalid.",+ "account_recovery_expired_title": "Recovery link expired",+ "account_recovery_expired_description": "This recovery link has expired.",+ "account_recovery_unavailable_title": "Account recovery unavailable",+ "account_recovery_unavailable_description": "This account can no longer be recovered.",+ "account_recovery_email_in_use": "This email is already in use",+ "account_recovery_email_in_use_description": "To recover your deleted account, first sign in to the account using this email and delete it. Then reopen this recovery link before it expires.","invite": "Invite","enter_valid_email": "Enter a valid email address","family_user_not_found": "No Ente account was found for this email address.",