Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

[server] clean up contacts on account deletion

Neeraj Gupta8fbce9096131
diff --git a/server/pkg/controller/user/user.go b/server/pkg/controller/user/user.go
index 02dddb7e86..366efc7fb7 100644
--- a/server/pkg/controller/user/user.go
+++ b/server/pkg/controller/user/user.go
@@ -21,6 +21,7 @@ import (
"github.com/ente-io/museum/pkg/controller"
"github.com/ente-io/museum/pkg/controller/family"
"github.com/ente-io/museum/pkg/repo"
+ contactrepo "github.com/ente-io/museum/pkg/repo/contact"
"github.com/ente-io/museum/pkg/repo/datacleanup"
"github.com/ente-io/museum/pkg/repo/passkey"
storageBonusRepo "github.com/ente-io/museum/pkg/repo/storagebonus"
@@ -53,6 +54,7 @@ type UserController struct {
DiscordController *discord.DiscordController
MailingListsController *controller.MailingListsController
PushController *controller.PushController
+ ContactRepo *contactrepo.Repository
HashingKey []byte
SecretEncryptionKey []byte
JwtSecret []byte
@@ -127,6 +129,7 @@ func NewUserController(
pushController *controller.PushController,
userCache *cache2.UserCache,
userCacheController *usercache.Controller,
+ contactRepo *contactrepo.Repository,
) *UserController {
srpLimiter := util.NewRateLimiter("100-H")
ottLimiter := util.NewRateLimiter("100-H")
@@ -153,6 +156,7 @@ func NewUserController(
DiscordController: discordController,
MailingListsController: mailingListsController,
PushController: pushController,
+ ContactRepo: contactRepo,
HardCodedOTT: ReadHardCodedOTTFromConfig(),
UserCache: userCache,
UserCacheController: userCacheController,
@@ -415,6 +419,7 @@ func (c *UserController) HandleAccountRecovery(ctx *gin.Context, req ente.Recove
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")
diff --git a/server/pkg/controller/user/user_recovery_test.go b/server/pkg/controller/user/user_recovery_test.go
new file mode 100644
index 0000000000..722f8b1e1c
--- /dev/null
+++ b/server/pkg/controller/user/user_recovery_test.go
@@ -0,0 +1,149 @@
+package user
+
+import (
+ "context"
+ "database/sql"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/ente-io/museum/ente"
+ contactmodel "github.com/ente-io/museum/ente/contact"
+ cleanupentity "github.com/ente-io/museum/ente/data_cleanup"
+ "github.com/ente-io/museum/internal/testutil"
+ "github.com/ente-io/museum/pkg/repo"
+ contactrepo "github.com/ente-io/museum/pkg/repo/contact"
+ cleanuprepo "github.com/ente-io/museum/pkg/repo/datacleanup"
+ "github.com/ente-io/museum/pkg/utils/config"
+ "github.com/gin-gonic/gin"
+ "github.com/spf13/viper"
+)
+
+func TestHandleAccountRecoveryTouchesContactsForResolvedEmailSync(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)
+ })
+
+ ownerID := testutil.InsertUser(t, db, testutil.UserFixture{
+ UserID: 1,
+ Email: "[email protected]",
+ CreationTime: 1,
+ })
+ contactUserID := testutil.InsertUser(t, db, testutil.UserFixture{
+ UserID: 82,
+ Email: "[email protected]",
+ CreationTime: 1,
+ })
+
+ insertKeyAttributes(t, db, contactUserID)
+ insertScheduledDelete(t, db, contactUserID)
+
+ objectCleanupRepo := &repo.ObjectCleanupRepository{DB: db}
+ contactsRepo := &contactrepo.Repository{
+ DB: db,
+ ObjectCleanupRepo: objectCleanupRepo,
+ SecretEncryptionKey: testutil.SecretEncryptionKey(),
+ }
+ contactID, err := contactsRepo.Create(context.Background(), ownerID, contactmodel.CreateRequest{
+ ContactUserID: contactUserID,
+ EncryptedKey: []byte("wrapped-key"),
+ EncryptedData: []byte("payload"),
+ })
+ if err != nil {
+ t.Fatalf("failed to create contact: %v", err)
+ }
+ created, err := contactsRepo.Get(context.Background(), ownerID, contactID)
+ if err != nil {
+ t.Fatalf("failed to fetch created contact: %v", err)
+ }
+ if created.Email == nil || *created.Email != "[email protected]" {
+ t.Fatalf("unexpected initial email: %v", created.Email)
+ }
+
+ userRepo := &repo.UserRepository{
+ DB: db,
+ SecretEncryptionKey: testutil.SecretEncryptionKey(),
+ HashingKey: testutil.HashingKey(),
+ }
+ if err := userRepo.Delete(contactUserID); err != nil {
+ t.Fatalf("failed to soft-delete contact user: %v", err)
+ }
+
+ gin.SetMode(gin.TestMode)
+ recorder := httptest.NewRecorder()
+ ctx, _ := gin.CreateTestContext(recorder)
+ ctx.Request = httptest.NewRequest("POST", "/", nil)
+ ctx.Set("req_id", "recovery-test")
+
+ controller := &UserController{
+ UserRepo: userRepo,
+ DataCleanupRepo: &cleanuprepo.Repository{DB: db},
+ ContactRepo: contactsRepo,
+ SecretEncryptionKey: testutil.SecretEncryptionKey(),
+ HashingKey: testutil.HashingKey(),
+ }
+
+ if err := controller.HandleAccountRecovery(ctx, ente.RecoverAccountRequest{
+ UserID: contactUserID,
+ EmailID: "[email protected]",
+ }); err != nil {
+ t.Fatalf("HandleAccountRecovery() error = %v", err)
+ }
+
+ diff, err := contactsRepo.GetDiff(context.Background(), ownerID, created.UpdatedAt, 10)
+ if err != nil {
+ t.Fatalf("GetDiff() error = %v", err)
+ }
+ if len(diff) != 1 {
+ t.Fatalf("diff length = %d, want 1", len(diff))
+ }
+ if diff[0].Email == nil || *diff[0].Email != "[email protected]" {
+ t.Fatalf("resolved email after recovery = %v, want updated email", diff[0].Email)
+ }
+}
+
+func insertKeyAttributes(t *testing.T, db *sql.DB, userID int64) {
+ t.Helper()
+ _, err := db.Exec(
+ `INSERT INTO key_attributes(
+ user_id, kek_salt, kek_hash_bytes, encrypted_key, key_decryption_nonce,
+ public_key, encrypted_secret_key, secret_key_decryption_nonce, mem_limit, ops_limit
+ ) VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`,
+ userID,
+ "kek-salt",
+ []byte("kek-hash"),
+ "encrypted-key",
+ "key-nonce",
+ "public-key",
+ "encrypted-secret-key",
+ "secret-key-nonce",
+ int64(67108864),
+ int64(2),
+ )
+ if err != nil {
+ t.Fatalf("failed to insert key_attributes for user %d: %v", userID, err)
+ }
+}
+
+func insertScheduledDelete(t *testing.T, db *sql.DB, userID int64) {
+ t.Helper()
+ _, err := db.Exec(
+ `INSERT INTO data_cleanup(user_id, stage, stage_schedule_time, stage_attempt_count)
+ VALUES($1, $2, $3, $4)`,
+ userID,
+ cleanupentity.Scheduled,
+ int64(1),
+ 0,
+ )
+ if err != nil {
+ t.Fatalf("failed to insert scheduled delete row for user %d: %v", userID, err)
+ }
+}
diff --git a/server/pkg/controller/user/userauth.go b/server/pkg/controller/user/userauth.go
index f7ecce9086..40a4508cbe 100644
--- a/server/pkg/controller/user/userauth.go
+++ b/server/pkg/controller/user/userauth.go
@@ -323,6 +323,7 @@ func (c *UserController) UpdateEmail(ctx *gin.Context, userID int64, email strin
if err != nil {
return stacktrace.Propagate(err, "")
}
+ c.touchContactsAfterEmailUpdate(ctx, userID)
_ = emailUtil.SendTemplatedEmail([]string{user.Email}, "ente", "[email protected]",
ente.EmailChangedSubject, ente.EmailChangedTemplate, map[string]interface{}{
"NewEmail": email,
@@ -361,6 +362,20 @@ func (c *UserController) UpdateEmail(ctx *gin.Context, userID int64, email strin
return nil
}
+func (c *UserController) touchContactsAfterEmailUpdate(ctx *gin.Context, userID int64) {
+ if c.ContactRepo == nil {
+ return
+ }
+ if touchErr := c.ContactRepo.TouchContactsForContactUser(ctx, userID); touchErr != nil {
+ log.WithError(touchErr).
+ WithFields(log.Fields{
+ "req_id": requestid.Get(ctx),
+ "user_id": userID,
+ }).
+ Error("failed to touch contacts after email update")
+ }
+}
+
// Logout removes the token from the cache and database.
// known issue: the token may be still cached in other instances till the expiry time (10min), JWTs might remain too
func (c *UserController) Logout(ctx *gin.Context) error {
diff --git a/server/pkg/repo/datacleanup/repository.go b/server/pkg/repo/datacleanup/repository.go
index 9f6e884215..7d080c2f0f 100644
--- a/server/pkg/repo/datacleanup/repository.go
+++ b/server/pkg/repo/datacleanup/repository.go
@@ -88,6 +88,14 @@ func (r *Repository) DeleteTableData(ctx context.Context, userID int64) error {
if err != nil {
return stacktrace.Propagate(err, "failed to delete entity data")
}
+ _, err = r.DB.ExecContext(ctx, `DELETE FROM user_attachments WHERE user_id = $1`, userID)
+ if err != nil {
+ return stacktrace.Propagate(err, "failed to delete contact attachment data")
+ }
+ _, err = r.DB.ExecContext(ctx, `DELETE FROM contact_entity WHERE user_id = $1`, userID)
+ if err != nil {
+ return stacktrace.Propagate(err, "failed to delete contact data")
+ }
// deleting casting data
_, err = r.DB.ExecContext(ctx, `DELETE FROM casting WHERE cast_user = $1`, userID)
if err != nil {
diff --git a/server/pkg/repo/datacleanup/repository_test.go b/server/pkg/repo/datacleanup/repository_test.go
new file mode 100644
index 0000000000..5d475bac04
--- /dev/null
+++ b/server/pkg/repo/datacleanup/repository_test.go
@@ -0,0 +1,95 @@
+package datacleanup
+
+import (
+ "context"
+ "database/sql"
+ "testing"
+
+ "github.com/ente-io/museum/internal/testutil"
+)
+
+func TestDeleteTableDataDeletesContactsAndAttachmentsForUser(t *testing.T) {
+ testutil.WithServerRoot(t)
+
+ db := testutil.RequireTestDB(t)
+ testutil.ResetTables(t, db)
+ t.Cleanup(func() {
+ testutil.ResetTables(t, db)
+ })
+
+ targetUserID := testutil.InsertUser(t, db, testutil.UserFixture{
+ UserID: 1,
+ Email: "[email protected]",
+ CreationTime: 1,
+ })
+ otherUserID := testutil.InsertUser(t, db, testutil.UserFixture{
+ UserID: 2,
+ Email: "[email protected]",
+ CreationTime: 1,
+ })
+
+ mustExecCleanupTest(t, db,
+ `INSERT INTO contact_entity(id, user_id, contact_user_id, encrypted_key, encrypted_data)
+ VALUES($1, $2, $3, $4, $5)`,
+ "ct_target",
+ targetUserID,
+ otherUserID,
+ []byte("wrapped-key-target"),
+ []byte("payload-target"),
+ )
+ mustExecCleanupTest(t, db,
+ `INSERT INTO contact_entity(id, user_id, contact_user_id, encrypted_key, encrypted_data)
+ VALUES($1, $2, $3, $4, $5)`,
+ "ct_other",
+ otherUserID,
+ targetUserID,
+ []byte("wrapped-key-other"),
+ []byte("payload-other"),
+ )
+ mustExecCleanupTest(t, db,
+ `INSERT INTO user_attachments(attachment_id, user_id, attachment_type, size, latest_bucket)
+ VALUES($1, $2, $3, $4, $5)`,
+ "ua_target",
+ targetUserID,
+ "profile_picture",
+ 128,
+ "b2-eu-cen",
+ )
+ mustExecCleanupTest(t, db,
+ `INSERT INTO user_attachments(attachment_id, user_id, attachment_type, size, latest_bucket)
+ VALUES($1, $2, $3, $4, $5)`,
+ "ua_other",
+ otherUserID,
+ "profile_picture",
+ 256,
+ "b2-eu-cen",
+ )
+
+ repo := &Repository{DB: db}
+ if err := repo.DeleteTableData(context.Background(), targetUserID); err != nil {
+ t.Fatalf("DeleteTableData() error = %v", err)
+ }
+
+ assertCleanupRowCount(t, db, `SELECT COUNT(*) FROM contact_entity WHERE user_id = $1`, targetUserID, 0)
+ assertCleanupRowCount(t, db, `SELECT COUNT(*) FROM user_attachments WHERE user_id = $1`, targetUserID, 0)
+ assertCleanupRowCount(t, db, `SELECT COUNT(*) FROM contact_entity WHERE user_id = $1`, otherUserID, 1)
+ assertCleanupRowCount(t, db, `SELECT COUNT(*) FROM user_attachments WHERE user_id = $1`, otherUserID, 1)
+}
+
+func mustExecCleanupTest(t *testing.T, db *sql.DB, query string, args ...any) {
+ t.Helper()
+ if _, err := db.Exec(query, args...); err != nil {
+ t.Fatalf("exec failed for %q: %v", query, err)
+ }
+}
+
+func assertCleanupRowCount(t *testing.T, db *sql.DB, query string, arg any, want int) {
+ t.Helper()
+ var got int
+ if err := db.QueryRow(query, arg).Scan(&got); err != nil {
+ t.Fatalf("query failed for %q: %v", query, err)
+ }
+ if got != want {
+ t.Fatalf("row count for %q = %d, want %d", query, got, want)
+ }
+}