Skip to content

armgit / ente

Public Imported from GitHub
0

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

[server] resolve contact email from users

Neeraj Gupta7e9c2c54ffb2
diff --git a/server/cmd/museum/main.go b/server/cmd/museum/main.go
index f653155644..be7bbb1f9f 100644
--- a/server/cmd/museum/main.go
+++ b/server/cmd/museum/main.go
@@ -178,7 +178,11 @@ func main() {
queueRepo := &repo.QueueRepository{DB: db}
objectRepo := &repo.ObjectRepository{DB: db, QueueRepo: queueRepo}
objectCleanupRepo := &repo.ObjectCleanupRepository{DB: db}
- contactRepository := &contactRepo.Repository{DB: db, ObjectCleanupRepo: objectCleanupRepo}
+ contactRepository := &contactRepo.Repository{
+ DB: db,
+ ObjectCleanupRepo: objectCleanupRepo,
+ SecretEncryptionKey: secretEncryptionKeyBytes,
+ }
objectCopiesRepo := &repo.ObjectCopiesRepository{DB: db}
usageRepo := &repo.UsageRepository{DB: db, UserRepo: userRepo}
fileRepo := &repo.FileRepository{DB: db, S3Config: s3Config, QueueRepo: queueRepo,
@@ -425,6 +429,7 @@ func main() {
pushController,
userCache,
userCacheCtrl,
+ contactRepository,
)
emailNotificationCtrl.UserAccessResetter = userController
inactiveUserOrchestrator := user.NewInactiveUserOrchestrator(
diff --git a/server/ente/contact/contact.go b/server/ente/contact/contact.go
index 6dcfe16bfe..df4fd9023a 100644
--- a/server/ente/contact/contact.go
+++ b/server/ente/contact/contact.go
@@ -23,6 +23,7 @@ type Entity struct {
ID string `json:"id" binding:"required"`
UserID int64 `json:"userID" binding:"required"`
ContactUserID int64 `json:"contactUserID" binding:"required"`
+ Email *string `json:"email"`
ProfilePictureAttachmentID *string `json:"profilePictureAttachmentID"`
EncryptedKey *[]byte `json:"encryptedKey"`
EncryptedData *[]byte `json:"encryptedData"`
diff --git a/server/pkg/controller/contact/controller.go b/server/pkg/controller/contact/controller.go
index e631b994af..a1734f879f 100644
--- a/server/pkg/controller/contact/controller.go
+++ b/server/pkg/controller/contact/controller.go
@@ -35,6 +35,16 @@ func (c *Controller) Create(ctx *gin.Context, req contactmodel.CreateRequest) (*
if err := req.Validate(); err != nil {
return nil, stacktrace.Propagate(err, "invalid create contact request")
}
+ exists, err := c.Repo.ContactUserExists(ctx, req.ContactUserID)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "failed to validate contact user")
+ }
+ if !exists {
+ return nil, stacktrace.Propagate(
+ ente.NewBadRequestWithMessage("contactUserID does not exist"),
+ "",
+ )
+ }
userID := auth.GetUserID(ctx.Request.Header)
canCreate, err := c.Repo.CanCreateContact(ctx, userID, req.ContactUserID)
if err != nil {
@@ -76,6 +86,16 @@ func (c *Controller) Update(ctx *gin.Context, contactID string, req contactmodel
if err := req.Validate(); err != nil {
return nil, stacktrace.Propagate(err, "invalid update contact request")
}
+ exists, err := c.Repo.ContactUserExists(ctx, req.ContactUserID)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "failed to validate contact user")
+ }
+ if !exists {
+ return nil, stacktrace.Propagate(
+ ente.NewBadRequestWithMessage("contactUserID does not exist"),
+ "",
+ )
+ }
userID := auth.GetUserID(ctx.Request.Header)
if err := c.Repo.Update(ctx, userID, contactID, req); err != nil {
return nil, stacktrace.Propagate(err, "")
diff --git a/server/pkg/controller/contact/controller_test.go b/server/pkg/controller/contact/controller_test.go
index 46518053b4..c114056b7c 100644
--- a/server/pkg/controller/contact/controller_test.go
+++ b/server/pkg/controller/contact/controller_test.go
@@ -15,6 +15,7 @@ import (
repo "github.com/ente-io/museum/pkg/repo"
contactrepo "github.com/ente-io/museum/pkg/repo/contact"
"github.com/ente-io/museum/pkg/utils/config"
+ "github.com/ente-io/museum/pkg/utils/crypto"
"github.com/ente-io/museum/pkg/utils/s3config"
"github.com/gin-gonic/gin"
"github.com/spf13/viper"
@@ -46,8 +47,9 @@ func setupContactControllerTest(t *testing.T) (*Controller, *sql.DB, *gin.Contex
objectCleanupRepo := &repo.ObjectCleanupRepository{DB: db}
objectCleanupCtrl := &basecontroller.ObjectCleanupController{Repo: objectCleanupRepo}
contactRepository := &contactrepo.Repository{
- DB: db,
- ObjectCleanupRepo: objectCleanupRepo,
+ DB: db,
+ ObjectCleanupRepo: objectCleanupRepo,
+ SecretEncryptionKey: testutil.SecretEncryptionKey(),
}
ctrl := New(contactRepository, objectCleanupCtrl, s3Cfg)
return ctrl, db, ctx, s3Cfg
@@ -237,6 +239,10 @@ func TestContactCRUDAndDiff(t *testing.T) {
if created.ContactUserID != 11 {
t.Fatalf("contactUserID = %d, want 11", created.ContactUserID)
}
+ expectedCreateEmail := "[email protected]"
+ if created.Email == nil || *created.Email != expectedCreateEmail {
+ t.Fatalf("email = %v, want %q", created.Email, expectedCreateEmail)
+ }
if created.EncryptedKey == nil || string(*created.EncryptedKey) != "wrapped-key-1" {
t.Fatalf("unexpected encrypted key: %v", created.EncryptedKey)
}
@@ -248,6 +254,12 @@ func TestContactCRUDAndDiff(t *testing.T) {
if got.ID != created.ID {
t.Fatalf("Get().ID = %q, want %q", got.ID, created.ID)
}
+ if got.Email == nil || *got.Email != expectedCreateEmail {
+ t.Fatalf("Get().Email = %v, want %q", got.Email, expectedCreateEmail)
+ }
+
+ mustInsertTestUser(t, db, 12)
+ mustInsertEmergencyContact(t, db, 1, 12, ente.UserInvitedContact)
updated, err := ctrl.Update(ctx, created.ID, contactmodel.UpdateRequest{
ContactUserID: 12,
@@ -259,6 +271,10 @@ func TestContactCRUDAndDiff(t *testing.T) {
if updated.ContactUserID != 12 {
t.Fatalf("updated contactUserID = %d, want 12", updated.ContactUserID)
}
+ expectedUpdatedEmail := "[email protected]"
+ if updated.Email == nil || *updated.Email != expectedUpdatedEmail {
+ t.Fatalf("updated email = %v, want %q", updated.Email, expectedUpdatedEmail)
+ }
if updated.EncryptedData == nil || string(*updated.EncryptedData) != "payload-2" {
t.Fatalf("updated encrypted data = %v", updated.EncryptedData)
}
@@ -276,6 +292,9 @@ func TestContactCRUDAndDiff(t *testing.T) {
if diff[0].ID != created.ID || diff[0].ContactUserID != 12 {
t.Fatalf("unexpected diff row: %+v", diff[0])
}
+ if diff[0].Email == nil || *diff[0].Email != expectedUpdatedEmail {
+ t.Fatalf("unexpected diff email: %v", diff[0].Email)
+ }
if err := ctrl.Delete(ctx, created.ID); err != nil {
t.Fatalf("Delete() error = %v", err)
@@ -290,6 +309,9 @@ func TestContactCRUDAndDiff(t *testing.T) {
if deleted.EncryptedKey != nil || deleted.EncryptedData != nil || deleted.ProfilePictureAttachmentID != nil {
t.Fatalf("deleted contact leaked encrypted fields or attachment ref: %+v", deleted)
}
+ if deleted.Email != nil {
+ t.Fatalf("deleted contact leaked email: %+v", deleted)
+ }
}
func TestCreateContactRejectsDuplicateContactUserID(t *testing.T) {
@@ -325,6 +347,29 @@ func TestCreateContactRequiresEligibleRelationship(t *testing.T) {
}
}
+func TestCreateAndUpdateRejectUnknownContactUserID(t *testing.T) {
+ ctrl, db, ctx, _ := setupContactControllerTest(t)
+ mustInsertTestUser(t, db, 1)
+
+ _, err := ctrl.Create(ctx, contactmodel.CreateRequest{
+ ContactUserID: 9999,
+ EncryptedKey: []byte("wrapped-key"),
+ EncryptedData: []byte("payload"),
+ })
+ if err == nil || !strings.Contains(err.Error(), "contactUserID does not exist") {
+ t.Fatalf("expected unknown contact user create to fail, got %v", err)
+ }
+
+ created := createContactForTest(t, db, ctrl, ctx, 21, "wrapped-key-1", "payload-1")
+ _, err = ctrl.Update(ctx, created.ID, contactmodel.UpdateRequest{
+ ContactUserID: 9999,
+ EncryptedData: []byte("payload-2"),
+ })
+ if err == nil || !strings.Contains(err.Error(), "contactUserID does not exist") {
+ t.Fatalf("expected unknown contact user update to fail, got %v", err)
+ }
+}
+
func TestCreateContactAllowedForEmergencyRelationshipInEitherDirection(t *testing.T) {
tests := []struct {
name string
@@ -470,6 +515,47 @@ func TestCreateContactAllowedForSharedCollectionAccess(t *testing.T) {
}
}
+func TestTouchContactsForContactUserRefreshesResolvedEmailInDiff(t *testing.T) {
+ ctrl, db, ctx, _ := setupContactControllerTest(t)
+ mustInsertTestUser(t, db, 1)
+
+ created := createContactForTest(t, db, ctrl, ctx, 82, "wrapped-key-1", "payload-1")
+
+ userRepo := &repo.UserRepository{
+ DB: db,
+ SecretEncryptionKey: testutil.SecretEncryptionKey(),
+ HashingKey: testutil.HashingKey(),
+ }
+ encryptedEmail, err := crypto.Encrypt("[email protected]", testutil.SecretEncryptionKey())
+ if err != nil {
+ t.Fatalf("failed to encrypt email: %v", err)
+ }
+ emailHash, err := crypto.GetHash("[email protected]", testutil.HashingKey())
+ if err != nil {
+ t.Fatalf("failed to hash email: %v", err)
+ }
+ if err := userRepo.UpdateEmail(82, encryptedEmail, emailHash); err != nil {
+ t.Fatalf("failed to update user email: %v", err)
+ }
+ if err := ctrl.Repo.TouchContactsForContactUser(ctx, 82); err != nil {
+ t.Fatalf("failed to touch contacts for updated email: %v", err)
+ }
+
+ diff, err := ctrl.GetDiff(ctx, contactmodel.DiffRequest{
+ SinceTime: ptrInt64(created.UpdatedAt),
+ Limit: 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 = %v, want updated email", diff[0].Email)
+ }
+}
+
func TestContactEntityEncryptedKeyIsImmutable(t *testing.T) {
ctrl, db, ctx, _ := setupContactControllerTest(t)
mustInsertTestUser(t, db, 1)
diff --git a/server/pkg/repo/contact/contact.go b/server/pkg/repo/contact/contact.go
index 169abc2337..630a6a0cb4 100644
--- a/server/pkg/repo/contact/contact.go
+++ b/server/pkg/repo/contact/contact.go
@@ -7,6 +7,7 @@ import (
"github.com/ente-io/museum/ente"
contactmodel "github.com/ente-io/museum/ente/contact"
+ "github.com/ente-io/museum/pkg/utils/crypto"
"github.com/ente-io/stacktrace"
"github.com/lib/pq"
)
@@ -61,6 +62,24 @@ func (r *Repository) Create(ctx context.Context, userID int64, req contactmodel.
return id, nil
}
+func (r *Repository) ContactUserExists(ctx context.Context, contactUserID int64) (bool, error) {
+ var exists bool
+ err := r.DB.QueryRowContext(
+ ctx,
+ `SELECT EXISTS(
+ SELECT 1
+ FROM users
+ WHERE user_id = $1
+ AND encrypted_email IS NOT NULL
+ )`,
+ contactUserID,
+ ).Scan(&exists)
+ if err != nil {
+ return false, stacktrace.Propagate(err, "failed to check contact user existence")
+ }
+ return exists, nil
+}
+
func (r *Repository) hasActiveEmergencyRelationship(ctx context.Context, actorUserID int64, contactUserID int64) (bool, error) {
var exists bool
err := r.DB.QueryRowContext(
@@ -138,14 +157,16 @@ func (r *Repository) hasCommonSharedCollection(ctx context.Context, actorUserID
func (r *Repository) Get(ctx context.Context, userID int64, id string) (*contactmodel.Entity, error) {
row := r.DB.QueryRowContext(
ctx,
- `SELECT id, user_id, contact_user_id, profile_picture_attachment_id, encrypted_key, encrypted_data,
- is_deleted, created_at, updated_at
- FROM contact_entity
- WHERE id = $1 AND user_id = $2`,
+ `SELECT c.id, c.user_id, c.contact_user_id, c.profile_picture_attachment_id, c.encrypted_key, c.encrypted_data,
+ c.is_deleted, c.created_at, c.updated_at, u.encrypted_email, u.email_decryption_nonce
+ FROM contact_entity c
+ LEFT JOIN users u
+ ON u.user_id = c.contact_user_id
+ WHERE c.id = $1 AND c.user_id = $2`,
id,
userID,
)
- entity, err := scanEntity(row)
+ entity, err := r.scanEntityWithEmail(row)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, &ente.ErrNotFoundError
@@ -231,11 +252,13 @@ func (r *Repository) Delete(ctx context.Context, userID int64, id string) error
func (r *Repository) GetDiff(ctx context.Context, userID int64, sinceTime int64, limit int16) ([]contactmodel.Entity, error) {
rows, err := r.DB.QueryContext(
ctx,
- `SELECT id, user_id, contact_user_id, profile_picture_attachment_id, encrypted_key, encrypted_data,
- is_deleted, created_at, updated_at
- FROM contact_entity
- WHERE user_id = $1 AND updated_at > $2
- ORDER BY updated_at
+ `SELECT c.id, c.user_id, c.contact_user_id, c.profile_picture_attachment_id, c.encrypted_key, c.encrypted_data,
+ c.is_deleted, c.created_at, c.updated_at, u.encrypted_email, u.email_decryption_nonce
+ FROM contact_entity c
+ LEFT JOIN users u
+ ON u.user_id = c.contact_user_id
+ WHERE c.user_id = $1 AND c.updated_at > $2
+ ORDER BY c.updated_at
LIMIT $3`,
userID,
sinceTime,
@@ -248,7 +271,7 @@ func (r *Repository) GetDiff(ctx context.Context, userID int64, sinceTime int64,
entities := make([]contactmodel.Entity, 0)
for rows.Next() {
- entity, scanErr := scanEntity(rows)
+ entity, scanErr := r.scanEntityWithEmail(rows)
if scanErr != nil {
return nil, stacktrace.Propagate(scanErr, "failed to scan contact diff row")
}
@@ -257,6 +280,18 @@ func (r *Repository) GetDiff(ctx context.Context, userID int64, sinceTime int64,
return entities, nil
}
+func (r *Repository) TouchContactsForContactUser(ctx context.Context, contactUserID int64) error {
+ _, err := r.DB.ExecContext(
+ ctx,
+ `UPDATE contact_entity
+ SET contact_user_id = contact_user_id
+ WHERE contact_user_id = $1
+ AND is_deleted = FALSE`,
+ contactUserID,
+ )
+ return stacktrace.Propagate(err, "failed to touch contacts for contact user")
+}
+
func (r *Repository) AttachProfilePicture(ctx context.Context, userID int64, contactID string, attachmentID string, size int64) (*contactmodel.Entity, error) {
tx, err := r.DB.BeginTx(ctx, nil)
if err != nil {
@@ -470,6 +505,67 @@ func scanEntity(scanner rowScanner) (*contactmodel.Entity, error) {
return &entity, nil
}
+func (r *Repository) scanEntityWithEmail(scanner rowScanner) (*contactmodel.Entity, error) {
+ entity, encryptedEmail, nonce, err := scanEntityWithEncryptedEmail(scanner)
+ if err != nil {
+ return nil, err
+ }
+ if entity.IsDeleted || encryptedEmail == nil || nonce == nil {
+ entity.Email = nil
+ return entity, nil
+ }
+ email, err := crypto.Decrypt(*encryptedEmail, r.SecretEncryptionKey, *nonce)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "failed to decrypt contact email")
+ }
+ entity.Email = &email
+ return entity, nil
+}
+
+func scanEntityWithEncryptedEmail(scanner rowScanner) (*contactmodel.Entity, *[]byte, *[]byte, error) {
+ var (
+ entity contactmodel.Entity
+ pictureID sql.NullString
+ encryptedKey []byte
+ encryptedData []byte
+ contactEmail []byte
+ contactEmailNonce []byte
+ )
+ if err := scanner.Scan(
+ &entity.ID,
+ &entity.UserID,
+ &entity.ContactUserID,
+ &pictureID,
+ &encryptedKey,
+ &encryptedData,
+ &entity.IsDeleted,
+ &entity.CreatedAt,
+ &entity.UpdatedAt,
+ &contactEmail,
+ &contactEmailNonce,
+ ); err != nil {
+ return nil, nil, nil, err
+ }
+ if pictureID.Valid {
+ entity.ProfilePictureAttachmentID = &pictureID.String
+ }
+ if entity.IsDeleted {
+ entity.ProfilePictureAttachmentID = nil
+ entity.EncryptedKey = nil
+ entity.EncryptedData = nil
+ return &entity, nil, nil, nil
+ }
+ entity.EncryptedKey = &encryptedKey
+ entity.EncryptedData = &encryptedData
+ var emailPtr *[]byte
+ var noncePtr *[]byte
+ if len(contactEmail) > 0 && len(contactEmailNonce) > 0 {
+ emailPtr = &contactEmail
+ noncePtr = &contactEmailNonce
+ }
+ return &entity, emailPtr, noncePtr, nil
+}
+
func scanAttachment(scanner rowScanner) (*contactmodel.Attachment, error) {
var attachment contactmodel.Attachment
if err := scanner.Scan(
diff --git a/server/pkg/repo/contact/repository.go b/server/pkg/repo/contact/repository.go
index df0b1063f9..3f4cebec57 100644
--- a/server/pkg/repo/contact/repository.go
+++ b/server/pkg/repo/contact/repository.go
@@ -7,6 +7,7 @@ import (
)
type Repository struct {
- DB *sql.DB
- ObjectCleanupRepo *repo.ObjectCleanupRepository
+ DB *sql.DB
+ ObjectCleanupRepo *repo.ObjectCleanupRepository
+ SecretEncryptionKey []byte
}