Skip to content

armgit / ente

Public Imported from GitHub
0

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

[server] add contacts backend

Neeraj Gupta4b3665a8e78c
diff --git a/server/cmd/museum/main.go b/server/cmd/museum/main.go
index f501e3ddc1..f653155644 100644
--- a/server/cmd/museum/main.go
+++ b/server/cmd/museum/main.go
@@ -29,6 +29,7 @@ import (
"github.com/ente-io/museum/pkg/controller/cast"
"github.com/ente-io/museum/pkg/controller/commonbilling"
+ contactCtrl "github.com/ente-io/museum/pkg/controller/contact"
cache2 "github.com/ente-io/museum/ente/cache"
"github.com/ente-io/museum/pkg/controller/discord"
@@ -57,6 +58,7 @@ import (
"github.com/ente-io/museum/pkg/repo"
authenticatorRepo "github.com/ente-io/museum/pkg/repo/authenticator"
castRepo "github.com/ente-io/museum/pkg/repo/cast"
+ contactRepo "github.com/ente-io/museum/pkg/repo/contact"
"github.com/ente-io/museum/pkg/repo/datacleanup"
discountCouponRepo "github.com/ente-io/museum/pkg/repo/discountcoupon"
"github.com/ente-io/museum/pkg/repo/embedding"
@@ -176,6 +178,7 @@ 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}
objectCopiesRepo := &repo.ObjectCopiesRepository{DB: db}
usageRepo := &repo.UsageRepository{DB: db, UserRepo: userRepo}
fileRepo := &repo.FileRepository{DB: db, S3Config: s3Config, QueueRepo: queueRepo,
@@ -935,6 +938,19 @@ func main() {
privateAPI.DELETE("/user-entity/entity", userEntityHandler.DeleteEntity)
privateAPI.GET("/user-entity/entity/diff", userEntityHandler.GetDiff)
+ contactController := contactCtrl.New(contactRepository, objectCleanupController, s3Config)
+ contactHandler := &api.ContactHandler{Controller: contactController}
+
+ privateAPI.POST("/contacts", contactHandler.Create)
+ privateAPI.GET("/contacts/:id", contactHandler.Get)
+ privateAPI.GET("/contacts/diff", contactHandler.GetDiff)
+ privateAPI.PUT("/contacts/:id", contactHandler.Update)
+ privateAPI.DELETE("/contacts/:id", contactHandler.Delete)
+ privateAPI.POST("/contacts/:id/profile-picture/upload-url", contactHandler.GetProfilePictureUploadURL)
+ privateAPI.PUT("/contacts/:id/profile-picture", contactHandler.AttachProfilePicture)
+ privateAPI.GET("/contacts/:id/profile-picture", contactHandler.GetProfilePicture)
+ privateAPI.DELETE("/contacts/:id/profile-picture", contactHandler.DeleteProfilePicture)
+
authenticatorController := &authenticatorCtrl.Controller{Repo: authRepo, UserRepo: userRepo}
authenticatorHandler := &api.AuthenticatorHandler{Controller: authenticatorController}
diff --git a/server/configurations/local.yaml b/server/configurations/local.yaml
index 01f8e2c739..c4d714b235 100644
--- a/server/configurations/local.yaml
+++ b/server/configurations/local.yaml
@@ -228,6 +228,10 @@ s3:
# img_preview:
# primaryBucket:
# replicaBuckets: []
+ # attachment-config:
+ # profile_picture:
+ # primaryBucket:
+ # replicaBuckets: []
# Key used for encrypting customer emails before storing them in DB
#
diff --git a/server/ente/contact/contact.go b/server/ente/contact/contact.go
new file mode 100644
index 0000000000..6dcfe16bfe
--- /dev/null
+++ b/server/ente/contact/contact.go
@@ -0,0 +1,164 @@
+package contact
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/ente-io/museum/ente"
+ "github.com/ente-io/museum/ente/base"
+)
+
+type AttachmentType string
+
+const (
+ ProfilePicture AttachmentType = "profile_picture"
+
+ contactIDPrefix = "ct"
+ attachmentIDPrefix = "ua"
+
+ MaxProfilePictureEncryptedSize int64 = 512 * 1024
+)
+
+type Entity struct {
+ ID string `json:"id" binding:"required"`
+ UserID int64 `json:"userID" binding:"required"`
+ ContactUserID int64 `json:"contactUserID" binding:"required"`
+ ProfilePictureAttachmentID *string `json:"profilePictureAttachmentID"`
+ EncryptedKey *[]byte `json:"encryptedKey"`
+ EncryptedData *[]byte `json:"encryptedData"`
+ IsDeleted bool `json:"isDeleted" binding:"required"`
+ CreatedAt int64 `json:"createdAt" binding:"required"`
+ UpdatedAt int64 `json:"updatedAt" binding:"required"`
+}
+
+type CreateRequest struct {
+ ContactUserID int64 `json:"contactUserID" binding:"required"`
+ EncryptedKey []byte `json:"encryptedKey" binding:"required"`
+ EncryptedData []byte `json:"encryptedData" binding:"required"`
+}
+
+func (r CreateRequest) Validate() error {
+ if r.ContactUserID <= 0 {
+ return ente.NewBadRequestWithMessage("contactUserID must be greater than 0")
+ }
+ if len(r.EncryptedKey) == 0 {
+ return ente.NewBadRequestWithMessage("encryptedKey is required")
+ }
+ if len(r.EncryptedData) == 0 {
+ return ente.NewBadRequestWithMessage("encryptedData is required")
+ }
+ return nil
+}
+
+type UpdateRequest struct {
+ ContactUserID int64 `json:"contactUserID" binding:"required"`
+ EncryptedData []byte `json:"encryptedData" binding:"required"`
+}
+
+func (r UpdateRequest) Validate() error {
+ if r.ContactUserID <= 0 {
+ return ente.NewBadRequestWithMessage("contactUserID must be greater than 0")
+ }
+ if len(r.EncryptedData) == 0 {
+ return ente.NewBadRequestWithMessage("encryptedData is required")
+ }
+ return nil
+}
+
+type DiffRequest struct {
+ SinceTime *int64 `form:"sinceTime" binding:"required"`
+ Limit int16 `form:"limit" binding:"required"`
+}
+
+type ProfilePictureUploadURLRequest struct {
+ ContentLength int64 `json:"contentLength" binding:"required"`
+ ContentMD5 string `json:"contentMD5" binding:"required"`
+}
+
+func (r ProfilePictureUploadURLRequest) Validate() error {
+ if r.ContentLength <= 0 {
+ return ente.NewBadRequestWithMessage("contentLength must be greater than 0")
+ }
+ if r.ContentLength > MaxProfilePictureEncryptedSize {
+ return ente.NewBadRequestWithMessage(
+ fmt.Sprintf("profile picture must be <= %d bytes", MaxProfilePictureEncryptedSize),
+ )
+ }
+ if strings.TrimSpace(r.ContentMD5) == "" {
+ return ente.NewBadRequestWithMessage("contentMD5 is required")
+ }
+ return nil
+}
+
+type ProfilePictureUploadURL struct {
+ AttachmentID string `json:"attachmentID" binding:"required"`
+ URL string `json:"url" binding:"required"`
+}
+
+type CommitProfilePictureRequest struct {
+ AttachmentID string `json:"attachmentID" binding:"required"`
+ Size int64 `json:"size" binding:"required"`
+}
+
+func (r CommitProfilePictureRequest) Validate() error {
+ if !IsValidAttachmentID(r.AttachmentID) {
+ return ente.NewBadRequestWithMessage("invalid attachmentID")
+ }
+ if r.Size <= 0 {
+ return ente.NewBadRequestWithMessage("size must be greater than 0")
+ }
+ if r.Size > MaxProfilePictureEncryptedSize {
+ return ente.NewBadRequestWithMessage(
+ fmt.Sprintf("profile picture must be <= %d bytes", MaxProfilePictureEncryptedSize),
+ )
+ }
+ return nil
+}
+
+type SignedURLResponse struct {
+ URL string `json:"url" binding:"required"`
+}
+
+type Attachment struct {
+ AttachmentID string `json:"attachmentID" binding:"required"`
+ UserID int64 `json:"userID" binding:"required"`
+ AttachmentType AttachmentType `json:"attachmentType" binding:"required"`
+ Size int64 `json:"size" binding:"required"`
+ LatestBucket string `json:"latestBucket" binding:"required"`
+ ReplicatedBuckets []string `json:"replicatedBuckets" binding:"required"`
+ DeleteFromBuckets []string `json:"deleteFromBuckets" binding:"required"`
+ InflightRepBuckets []string `json:"inflightRepBuckets" binding:"required"`
+ PendingSync bool `json:"pendingSync" binding:"required"`
+ IsDeleted bool `json:"isDeleted" binding:"required"`
+ SyncLockedTill int64 `json:"syncLockedTill" binding:"required"`
+ CreatedAt int64 `json:"createdAt" binding:"required"`
+ UpdatedAt int64 `json:"updatedAt" binding:"required"`
+}
+
+func (at AttachmentType) IsValid() error {
+ switch at {
+ case ProfilePicture:
+ return nil
+ }
+ return ente.NewBadRequestWithMessage(fmt.Sprintf("invalid attachment type: %s", at))
+}
+
+func NewContactID() string {
+ return base.MustNewID(contactIDPrefix)
+}
+
+func NewAttachmentID() string {
+ return base.MustNewID(attachmentIDPrefix)
+}
+
+func AttachmentObjectKey(userID int64, attachmentType AttachmentType, attachmentID string) string {
+ return fmt.Sprintf("%d/user-attachments/%s/%s", userID, attachmentType, attachmentID)
+}
+
+func IsValidContactID(id string) bool {
+ return strings.HasPrefix(id, contactIDPrefix+"_") && len(id) > len(contactIDPrefix)+1
+}
+
+func IsValidAttachmentID(id string) bool {
+ return strings.HasPrefix(id, attachmentIDPrefix+"_") && len(id) > len(attachmentIDPrefix)+1
+}
diff --git a/server/ente/userentity/entity.go b/server/ente/userentity/entity.go
index dbfd7d6ad0..d456e65fa3 100644
--- a/server/ente/userentity/entity.go
+++ b/server/ente/userentity/entity.go
@@ -20,11 +20,13 @@ const (
SmartAlbum EntityType = "smart_album"
// Memory is the entity type for memory share encryption keys
Memory EntityType = "memory"
+ // Contact is the entity type for the shared contact root key.
+ Contact EntityType = "contact"
)
func (et EntityType) IsValid() error {
switch et {
- case Location, Person, CGroup, SmartAlbum, Memory:
+ case Location, Person, CGroup, SmartAlbum, Memory, Contact:
return nil
}
return ente.NewBadRequestWithMessage(fmt.Sprintf("Invalid EntityType: %s", et))
diff --git a/server/internal/testutil/testutil.go b/server/internal/testutil/testutil.go
index 858cd1b859..4571f4b6fa 100644
--- a/server/internal/testutil/testutil.go
+++ b/server/internal/testutil/testutil.go
@@ -123,6 +123,11 @@ func ResetTables(t *testing.T, db *sql.DB) {
usage,
families,
tokens,
+ temp_objects,
+ user_attachments,
+ contact_entity,
+ entity_data,
+ entity_key,
authenticator_entity,
collections,
users
diff --git a/server/migrations/120_contacts.down.sql b/server/migrations/120_contacts.down.sql
new file mode 100644
index 0000000000..59ad72976d
--- /dev/null
+++ b/server/migrations/120_contacts.down.sql
@@ -0,0 +1,9 @@
+DROP TRIGGER IF EXISTS update_user_attachments_updated_at ON user_attachments;
+DROP TRIGGER IF EXISTS check_no_common_attachment_buckets ON user_attachments;
+DROP FUNCTION IF EXISTS ensure_no_common_attachment_buckets();
+DROP TABLE IF EXISTS user_attachments;
+
+DROP TRIGGER IF EXISTS update_contact_entity_updated_at ON contact_entity;
+DROP TRIGGER IF EXISTS trigger_reject_contact_key_update ON contact_entity;
+DROP FUNCTION IF EXISTS fn_reject_contact_key_update();
+DROP TABLE IF EXISTS contact_entity;
diff --git a/server/migrations/120_contacts.up.sql b/server/migrations/120_contacts.up.sql
new file mode 100644
index 0000000000..e2da27661e
--- /dev/null
+++ b/server/migrations/120_contacts.up.sql
@@ -0,0 +1,109 @@
+CREATE TABLE IF NOT EXISTS contact_entity
+(
+ id TEXT PRIMARY KEY NOT NULL,
+ user_id BIGINT NOT NULL,
+ contact_user_id BIGINT NOT NULL,
+ profile_picture_attachment_id TEXT,
+ encrypted_key BYTEA NOT NULL,
+ encrypted_data BYTEA,
+ is_deleted BOOLEAN NOT NULL DEFAULT FALSE,
+ created_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),
+ updated_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),
+ CONSTRAINT fk_contact_entity_user_id FOREIGN KEY (user_id) REFERENCES users (user_id) ON DELETE CASCADE,
+ CONSTRAINT contact_entity_state_constraint CHECK (
+ (is_deleted = FALSE AND encrypted_data IS NOT NULL) OR
+ (is_deleted = TRUE AND encrypted_data IS NULL AND profile_picture_attachment_id IS NULL)
+ )
+);
+
+CREATE INDEX IF NOT EXISTS idx_contact_entity_user_updated_at
+ ON contact_entity (user_id, updated_at);
+
+CREATE UNIQUE INDEX IF NOT EXISTS idx_contact_entity_user_contact_user_id
+ ON contact_entity (user_id, contact_user_id);
+
+CREATE OR REPLACE FUNCTION fn_reject_contact_key_update()
+RETURNS TRIGGER AS
+$$
+BEGIN
+ IF NEW.encrypted_key IS DISTINCT FROM OLD.encrypted_key THEN
+ RAISE EXCEPTION 'contact_entity.encrypted_key is immutable';
+ END IF;
+ RETURN NEW;
+END;
+$$ LANGUAGE plpgsql;
+
+CREATE TRIGGER trigger_reject_contact_key_update
+ BEFORE UPDATE
+ ON contact_entity
+ FOR EACH ROW
+EXECUTE FUNCTION fn_reject_contact_key_update();
+
+CREATE TRIGGER update_contact_entity_updated_at
+ BEFORE UPDATE
+ ON contact_entity
+ FOR EACH ROW
+EXECUTE PROCEDURE trigger_updated_at_microseconds_column();
+
+CREATE TABLE IF NOT EXISTS user_attachments
+(
+ attachment_id TEXT PRIMARY KEY NOT NULL,
+ user_id BIGINT NOT NULL,
+ attachment_type TEXT NOT NULL,
+ size BIGINT NOT NULL,
+ latest_bucket s3region NOT NULL,
+ replicated_buckets s3region[] NOT NULL DEFAULT '{}',
+ delete_from_buckets s3region[] NOT NULL DEFAULT '{}',
+ inflight_rep_buckets s3region[] NOT NULL DEFAULT '{}',
+ is_deleted BOOLEAN NOT NULL DEFAULT FALSE,
+ pending_sync BOOLEAN NOT NULL DEFAULT TRUE,
+ sync_locked_till BIGINT NOT NULL DEFAULT 0,
+ created_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),
+ updated_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),
+ CONSTRAINT fk_user_attachments_user_id FOREIGN KEY (user_id) REFERENCES users (user_id) ON DELETE CASCADE
+);
+
+CREATE INDEX IF NOT EXISTS idx_user_attachments_pending_sync_locked_till
+ ON user_attachments (is_deleted, sync_locked_till)
+ WHERE pending_sync = TRUE;
+
+CREATE INDEX IF NOT EXISTS idx_user_attachments_lookup
+ ON user_attachments (user_id, attachment_type, is_deleted);
+
+CREATE OR REPLACE FUNCTION ensure_no_common_attachment_buckets()
+RETURNS TRIGGER AS
+$$
+DECLARE
+ all_buckets s3region[];
+ duplicate_buckets s3region[];
+BEGIN
+ all_buckets := ARRAY [NEW.latest_bucket]
+ || NEW.replicated_buckets
+ || NEW.delete_from_buckets
+ || NEW.inflight_rep_buckets;
+
+ SELECT ARRAY_AGG(DISTINCT bucket)
+ INTO duplicate_buckets
+ FROM unnest(all_buckets) bucket
+ GROUP BY bucket
+ HAVING COUNT(*) > 1;
+
+ IF ARRAY_LENGTH(duplicate_buckets, 1) > 0 THEN
+ RAISE EXCEPTION 'Duplicate bucket IDs found in attachment row: %', duplicate_buckets;
+ END IF;
+
+ RETURN NEW;
+END;
+$$ LANGUAGE plpgsql;
+
+CREATE TRIGGER check_no_common_attachment_buckets
+ BEFORE INSERT OR UPDATE
+ ON user_attachments
+ FOR EACH ROW
+EXECUTE FUNCTION ensure_no_common_attachment_buckets();
+
+CREATE TRIGGER update_user_attachments_updated_at
+ BEFORE UPDATE
+ ON user_attachments
+ FOR EACH ROW
+EXECUTE PROCEDURE trigger_updated_at_microseconds_column();
diff --git a/server/pkg/api/contact.go b/server/pkg/api/contact.go
new file mode 100644
index 0000000000..4ef9662f2c
--- /dev/null
+++ b/server/pkg/api/contact.go
@@ -0,0 +1,122 @@
+package api
+
+import (
+ "fmt"
+ "net/http"
+
+ "github.com/ente-io/museum/ente"
+ contactmodel "github.com/ente-io/museum/ente/contact"
+ contactcontroller "github.com/ente-io/museum/pkg/controller/contact"
+ "github.com/ente-io/museum/pkg/utils/handler"
+ "github.com/ente-io/stacktrace"
+ "github.com/gin-gonic/gin"
+)
+
+type ContactHandler struct {
+ Controller *contactcontroller.Controller
+}
+
+func (h *ContactHandler) Create(c *gin.Context) {
+ var request contactmodel.CreateRequest
+ if err := c.ShouldBindJSON(&request); err != nil {
+ handler.Error(c, stacktrace.Propagate(ente.ErrBadRequest, fmt.Sprintf("request binding failed %s", err)))
+ return
+ }
+ resp, err := h.Controller.Create(c, request)
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, "failed to create contact"))
+ return
+ }
+ c.JSON(http.StatusOK, resp)
+}
+
+func (h *ContactHandler) Get(c *gin.Context) {
+ resp, err := h.Controller.Get(c, c.Param("id"))
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, "failed to fetch contact"))
+ return
+ }
+ c.JSON(http.StatusOK, resp)
+}
+
+func (h *ContactHandler) GetDiff(c *gin.Context) {
+ var request contactmodel.DiffRequest
+ if err := c.ShouldBindQuery(&request); err != nil {
+ handler.Error(c, stacktrace.Propagate(ente.ErrBadRequest, fmt.Sprintf("request binding failed %s", err)))
+ return
+ }
+ diff, err := h.Controller.GetDiff(c, request)
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, "failed to fetch contact diff"))
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"diff": diff})
+}
+
+func (h *ContactHandler) Update(c *gin.Context) {
+ var request contactmodel.UpdateRequest
+ if err := c.ShouldBindJSON(&request); err != nil {
+ handler.Error(c, stacktrace.Propagate(ente.ErrBadRequest, fmt.Sprintf("request binding failed %s", err)))
+ return
+ }
+ resp, err := h.Controller.Update(c, c.Param("id"), request)
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, "failed to update contact"))
+ return
+ }
+ c.JSON(http.StatusOK, resp)
+}
+
+func (h *ContactHandler) Delete(c *gin.Context) {
+ if err := h.Controller.Delete(c, c.Param("id")); err != nil {
+ handler.Error(c, stacktrace.Propagate(err, "failed to delete contact"))
+ return
+ }
+ c.Status(http.StatusOK)
+}
+
+func (h *ContactHandler) GetProfilePictureUploadURL(c *gin.Context) {
+ var request contactmodel.ProfilePictureUploadURLRequest
+ if err := c.ShouldBindJSON(&request); err != nil {
+ handler.Error(c, stacktrace.Propagate(ente.ErrBadRequest, fmt.Sprintf("request binding failed %s", err)))
+ return
+ }
+ resp, err := h.Controller.GetProfilePictureUploadURL(c, c.Param("id"), request)
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, "failed to create profile picture upload url"))
+ return
+ }
+ c.JSON(http.StatusOK, resp)
+}
+
+func (h *ContactHandler) AttachProfilePicture(c *gin.Context) {
+ var request contactmodel.CommitProfilePictureRequest
+ if err := c.ShouldBindJSON(&request); err != nil {
+ handler.Error(c, stacktrace.Propagate(ente.ErrBadRequest, fmt.Sprintf("request binding failed %s", err)))
+ return
+ }
+ resp, err := h.Controller.AttachProfilePicture(c, c.Param("id"), request)
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, "failed to attach profile picture"))
+ return
+ }
+ c.JSON(http.StatusOK, resp)
+}
+
+func (h *ContactHandler) GetProfilePicture(c *gin.Context) {
+ resp, err := h.Controller.GetProfilePictureURL(c, c.Param("id"))
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, "failed to get profile picture url"))
+ return
+ }
+ c.JSON(http.StatusOK, resp)
+}
+
+func (h *ContactHandler) DeleteProfilePicture(c *gin.Context) {
+ resp, err := h.Controller.DeleteProfilePicture(c, c.Param("id"))
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, "failed to delete profile picture"))
+ return
+ }
+ c.JSON(http.StatusOK, resp)
+}
diff --git a/server/pkg/controller/contact/controller.go b/server/pkg/controller/contact/controller.go
new file mode 100644
index 0000000000..dcac7bb2c3
--- /dev/null
+++ b/server/pkg/controller/contact/controller.go
@@ -0,0 +1,178 @@
+package contact
+
+import (
+ "github.com/aws/aws-sdk-go/aws"
+ "github.com/aws/aws-sdk-go/service/s3"
+ "github.com/ente-io/museum/ente"
+ contactmodel "github.com/ente-io/museum/ente/contact"
+ basecontroller "github.com/ente-io/museum/pkg/controller"
+ contactrepo "github.com/ente-io/museum/pkg/repo/contact"
+ "github.com/ente-io/museum/pkg/utils/auth"
+ "github.com/ente-io/museum/pkg/utils/s3config"
+ "github.com/ente-io/stacktrace"
+ "github.com/gin-gonic/gin"
+)
+
+type Controller struct {
+ Repo *contactrepo.Repository
+ ObjectCleanupController *basecontroller.ObjectCleanupController
+ S3Config *s3config.S3Config
+}
+
+func New(
+ repo *contactrepo.Repository,
+ objectCleanupController *basecontroller.ObjectCleanupController,
+ s3Config *s3config.S3Config,
+) *Controller {
+ return &Controller{
+ Repo: repo,
+ ObjectCleanupController: objectCleanupController,
+ S3Config: s3Config,
+ }
+}
+
+func (c *Controller) Create(ctx *gin.Context, req contactmodel.CreateRequest) (*contactmodel.Entity, error) {
+ if err := req.Validate(); err != nil {
+ return nil, stacktrace.Propagate(err, "invalid create contact request")
+ }
+ userID := auth.GetUserID(ctx.Request.Header)
+ id, err := c.Repo.Create(ctx, userID, req)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ return c.Repo.Get(ctx, userID, id)
+}
+
+func (c *Controller) Get(ctx *gin.Context, contactID string) (*contactmodel.Entity, error) {
+ if !contactmodel.IsValidContactID(contactID) {
+ return nil, ente.NewBadRequestWithMessage("invalid contact id")
+ }
+ userID := auth.GetUserID(ctx.Request.Header)
+ return c.Repo.Get(ctx, userID, contactID)
+}
+
+func (c *Controller) GetDiff(ctx *gin.Context, req contactmodel.DiffRequest) ([]contactmodel.Entity, error) {
+ if req.Limit <= 0 || req.Limit > 5000 {
+ return nil, ente.NewBadRequestWithMessage("limit must be between 1 and 5000")
+ }
+ userID := auth.GetUserID(ctx.Request.Header)
+ return c.Repo.GetDiff(ctx, userID, *req.SinceTime, req.Limit)
+}
+
+func (c *Controller) Update(ctx *gin.Context, contactID string, req contactmodel.UpdateRequest) (*contactmodel.Entity, error) {
+ if !contactmodel.IsValidContactID(contactID) {
+ return nil, ente.NewBadRequestWithMessage("invalid contact id")
+ }
+ if err := req.Validate(); err != nil {
+ return nil, stacktrace.Propagate(err, "invalid update contact request")
+ }
+ userID := auth.GetUserID(ctx.Request.Header)
+ if err := c.Repo.Update(ctx, userID, contactID, req); err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ return c.Repo.Get(ctx, userID, contactID)
+}
+
+func (c *Controller) Delete(ctx *gin.Context, contactID string) error {
+ if !contactmodel.IsValidContactID(contactID) {
+ return ente.NewBadRequestWithMessage("invalid contact id")
+ }
+ userID := auth.GetUserID(ctx.Request.Header)
+ return c.Repo.Delete(ctx, userID, contactID)
+}
+
+func (c *Controller) GetProfilePictureUploadURL(ctx *gin.Context, contactID string, req contactmodel.ProfilePictureUploadURLRequest) (*contactmodel.ProfilePictureUploadURL, error) {
+ if !contactmodel.IsValidContactID(contactID) {
+ return nil, ente.NewBadRequestWithMessage("invalid contact id")
+ }
+ if err := req.Validate(); err != nil {
+ return nil, stacktrace.Propagate(err, "invalid profile picture upload-url request")
+ }
+
+ userID := auth.GetUserID(ctx.Request.Header)
+ entity, err := c.Repo.Get(ctx, userID, contactID)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ if entity.IsDeleted {
+ return nil, stacktrace.Propagate(ente.NewBadRequestWithMessage("contact is already deleted"), "")
+ }
+
+ attachmentID := contactmodel.NewAttachmentID()
+ objectKey := contactmodel.AttachmentObjectKey(userID, contactmodel.ProfilePicture, attachmentID)
+ dc := c.S3Config.GetAttachmentBucketID(string(contactmodel.ProfilePicture))
+
+ s3Client := c.S3Config.GetS3Client(dc)
+ putReq, _ := s3Client.PutObjectRequest(&s3.PutObjectInput{
+ Bucket: c.S3Config.GetBucket(dc),
+ Key: aws.String(objectKey),
+ ContentLength: aws.Int64(req.ContentLength),
+ ContentMD5: aws.String(req.ContentMD5),
+ })
+ url, err := putReq.Presign(basecontroller.PreSignedRequestValidityDuration)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "failed to presign profile picture upload url")
+ }
+ if err := c.ObjectCleanupController.AddTempObjectKey(objectKey, dc); err != nil {
+ return nil, stacktrace.Propagate(err, "failed to stage temp object for profile picture upload")
+ }
+
+ return &contactmodel.ProfilePictureUploadURL{
+ AttachmentID: attachmentID,
+ URL: url,
+ }, nil
+}
+
+func (c *Controller) AttachProfilePicture(ctx *gin.Context, contactID string, req contactmodel.CommitProfilePictureRequest) (*contactmodel.Entity, error) {
+ if !contactmodel.IsValidContactID(contactID) {
+ return nil, ente.NewBadRequestWithMessage("invalid contact id")
+ }
+ if err := req.Validate(); err != nil {
+ return nil, stacktrace.Propagate(err, "invalid attach profile picture request")
+ }
+ userID := auth.GetUserID(ctx.Request.Header)
+ return c.Repo.AttachProfilePicture(ctx, userID, contactID, req.AttachmentID, req.Size)
+}
+
+func (c *Controller) GetProfilePictureURL(ctx *gin.Context, contactID string) (*contactmodel.SignedURLResponse, error) {
+ if !contactmodel.IsValidContactID(contactID) {
+ return nil, ente.NewBadRequestWithMessage("invalid contact id")
+ }
+ userID := auth.GetUserID(ctx.Request.Header)
+ entity, err := c.Repo.Get(ctx, userID, contactID)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ if entity.IsDeleted || entity.ProfilePictureAttachmentID == nil {
+ return nil, &ente.ErrNotFoundError
+ }
+ attachment, err := c.Repo.GetAttachment(ctx, userID, *entity.ProfilePictureAttachmentID)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ if attachment.IsDeleted || attachment.AttachmentType != contactmodel.ProfilePicture {
+ return nil, &ente.ErrNotFoundError
+ }
+
+ objectKey := contactmodel.AttachmentObjectKey(userID, attachment.AttachmentType, attachment.AttachmentID)
+ s3Client := c.S3Config.GetS3Client(attachment.LatestBucket)
+ input := &s3.GetObjectInput{
+ Bucket: c.S3Config.GetBucket(attachment.LatestBucket),
+ Key: aws.String(objectKey),
+ ResponseContentDisposition: aws.String("attachment"),
+ }
+ getReq, _ := s3Client.GetObjectRequest(input)
+ url, err := getReq.Presign(basecontroller.PreSignedRequestValidityDuration)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "failed to presign profile picture download url")
+ }
+ return &contactmodel.SignedURLResponse{URL: url}, nil
+}
+
+func (c *Controller) DeleteProfilePicture(ctx *gin.Context, contactID string) (*contactmodel.Entity, error) {
+ if !contactmodel.IsValidContactID(contactID) {
+ return nil, ente.NewBadRequestWithMessage("invalid contact id")
+ }
+ userID := auth.GetUserID(ctx.Request.Header)
+ return c.Repo.DeleteProfilePicture(ctx, userID, contactID)
+}
diff --git a/server/pkg/controller/contact/controller_test.go b/server/pkg/controller/contact/controller_test.go
new file mode 100644
index 0000000000..e8d1420046
--- /dev/null
+++ b/server/pkg/controller/contact/controller_test.go
@@ -0,0 +1,337 @@
+package contact
+
+import (
+ "database/sql"
+ "errors"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ contactmodel "github.com/ente-io/museum/ente/contact"
+ "github.com/ente-io/museum/internal/testutil"
+ basecontroller "github.com/ente-io/museum/pkg/controller"
+ 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/s3config"
+ "github.com/gin-gonic/gin"
+ "github.com/spf13/viper"
+)
+
+func setupContactControllerTest(t *testing.T) (*Controller, *sql.DB, *gin.Context, *s3config.S3Config) {
+ t.Helper()
+
+ 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)
+ })
+
+ gin.SetMode(gin.TestMode)
+ recorder := httptest.NewRecorder()
+ ctx, _ := gin.CreateTestContext(recorder)
+ ctx.Request = httptest.NewRequest("GET", "/", nil)
+ ctx.Request.Header.Set("X-Auth-User-ID", "1")
+
+ s3Cfg := s3config.NewS3Config()
+ objectCleanupRepo := &repo.ObjectCleanupRepository{DB: db}
+ objectCleanupCtrl := &basecontroller.ObjectCleanupController{Repo: objectCleanupRepo}
+ contactRepository := &contactrepo.Repository{
+ DB: db,
+ ObjectCleanupRepo: objectCleanupRepo,
+ }
+ ctrl := New(contactRepository, objectCleanupCtrl, s3Cfg)
+ return ctrl, db, ctx, s3Cfg
+}
+
+func createContactForTest(t *testing.T, ctrl *Controller, ctx *gin.Context, contactUserID int64, encryptedKey string, encryptedData string) *contactmodel.Entity {
+ t.Helper()
+ entity, err := ctrl.Create(ctx, contactmodel.CreateRequest{
+ ContactUserID: contactUserID,
+ EncryptedKey: []byte(encryptedKey),
+ EncryptedData: []byte(encryptedData),
+ })
+ if err != nil {
+ t.Fatalf("Create() error = %v", err)
+ }
+ return entity
+}
+
+func mustInsertTestUser(t *testing.T, db *sql.DB, userID int64) {
+ t.Helper()
+ testutil.InsertUser(t, db, testutil.UserFixture{
+ UserID: userID,
+ Email: "[email protected]",
+ CreationTime: 1,
+ })
+}
+
+func TestContactCRUDAndDiff(t *testing.T) {
+ ctrl, db, ctx, _ := setupContactControllerTest(t)
+ mustInsertTestUser(t, db, 1)
+
+ created := createContactForTest(t, ctrl, ctx, 11, "wrapped-key-1", "payload-1")
+ if !strings.HasPrefix(created.ID, "ct_") {
+ t.Fatalf("contact id = %q, want ct_ prefix", created.ID)
+ }
+ if created.ContactUserID != 11 {
+ t.Fatalf("contactUserID = %d, want 11", created.ContactUserID)
+ }
+ if created.EncryptedKey == nil || string(*created.EncryptedKey) != "wrapped-key-1" {
+ t.Fatalf("unexpected encrypted key: %v", created.EncryptedKey)
+ }
+
+ got, err := ctrl.Get(ctx, created.ID)
+ if err != nil {
+ t.Fatalf("Get() error = %v", err)
+ }
+ if got.ID != created.ID {
+ t.Fatalf("Get().ID = %q, want %q", got.ID, created.ID)
+ }
+
+ updated, err := ctrl.Update(ctx, created.ID, contactmodel.UpdateRequest{
+ ContactUserID: 12,
+ EncryptedData: []byte("payload-2"),
+ })
+ if err != nil {
+ t.Fatalf("Update() error = %v", err)
+ }
+ if updated.ContactUserID != 12 {
+ t.Fatalf("updated contactUserID = %d, want 12", updated.ContactUserID)
+ }
+ if updated.EncryptedData == nil || string(*updated.EncryptedData) != "payload-2" {
+ t.Fatalf("updated encrypted data = %v", updated.EncryptedData)
+ }
+
+ diff, err := ctrl.GetDiff(ctx, contactmodel.DiffRequest{
+ SinceTime: ptrInt64(0),
+ 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].ID != created.ID || diff[0].ContactUserID != 12 {
+ t.Fatalf("unexpected diff row: %+v", diff[0])
+ }
+
+ if err := ctrl.Delete(ctx, created.ID); err != nil {
+ t.Fatalf("Delete() error = %v", err)
+ }
+ deleted, err := ctrl.Get(ctx, created.ID)
+ if err != nil {
+ t.Fatalf("Get() after delete error = %v", err)
+ }
+ if !deleted.IsDeleted {
+ t.Fatalf("deleted contact should be tombstoned")
+ }
+ if deleted.EncryptedKey != nil || deleted.EncryptedData != nil || deleted.ProfilePictureAttachmentID != nil {
+ t.Fatalf("deleted contact leaked encrypted fields or attachment ref: %+v", deleted)
+ }
+}
+
+func TestCreateContactRejectsDuplicateContactUserID(t *testing.T) {
+ ctrl, db, ctx, _ := setupContactControllerTest(t)
+ mustInsertTestUser(t, db, 1)
+
+ createContactForTest(t, ctrl, ctx, 21, "wrapped-key-1", "payload-1")
+ _, err := ctrl.Create(ctx, contactmodel.CreateRequest{
+ ContactUserID: 21,
+ EncryptedKey: []byte("wrapped-key-2"),
+ EncryptedData: []byte("payload-2"),
+ })
+ if err == nil {
+ t.Fatal("expected duplicate contactUserID create to fail")
+ }
+}
+
+func TestContactEntityEncryptedKeyIsImmutable(t *testing.T) {
+ ctrl, db, ctx, _ := setupContactControllerTest(t)
+ mustInsertTestUser(t, db, 1)
+
+ created := createContactForTest(t, ctrl, ctx, 31, "wrapped-key-1", "payload-1")
+ if _, err := db.Exec(`UPDATE contact_entity SET encrypted_key = $1 WHERE id = $2`, []byte("wrapped-key-2"), created.ID); err == nil {
+ t.Fatal("expected encrypted_key update to fail")
+ }
+}
+
+func TestDeletedContactMustClearProfilePictureReference(t *testing.T) {
+ ctrl, db, ctx, _ := setupContactControllerTest(t)
+ mustInsertTestUser(t, db, 1)
+
+ created := createContactForTest(t, ctrl, ctx, 35, "wrapped-key-1", "payload-1")
+ if _, err := db.Exec(
+ `UPDATE contact_entity
+ SET is_deleted = TRUE, encrypted_data = NULL, profile_picture_attachment_id = $1
+ WHERE id = $2`,
+ "ua_fakeAttachment",
+ created.ID,
+ ); err == nil {
+ t.Fatal("expected deleted contact with profile picture ref to violate constraint")
+ }
+}
+
+func TestUserAttachmentsRejectDuplicateBucketMembership(t *testing.T) {
+ _, db, _, _ := setupContactControllerTest(t)
+ mustInsertTestUser(t, db, 1)
+
+ _, err := db.Exec(
+ `INSERT INTO user_attachments(
+ attachment_id, user_id, attachment_type, size, latest_bucket, replicated_buckets
+ ) VALUES($1, $2, $3, $4, $5, ARRAY[$6]::s3region[])`,
+ "ua_duplicateBuckets",
+ 1,
+ "profile_picture",
+ 128,
+ "b2-eu-cen",
+ "b2-eu-cen",
+ )
+ if err == nil {
+ t.Fatal("expected duplicate attachment bucket membership to fail")
+ }
+}
+
+func TestProfilePictureLifecycle(t *testing.T) {
+ ctrl, db, ctx, s3Cfg := setupContactControllerTest(t)
+ mustInsertTestUser(t, db, 1)
+
+ created := createContactForTest(t, ctrl, ctx, 41, "wrapped-key-1", "payload-1")
+
+ upload1, err := ctrl.GetProfilePictureUploadURL(ctx, created.ID, contactmodel.ProfilePictureUploadURLRequest{
+ ContentLength: 128,
+ ContentMD5: "ZmFrZS1tZDU=",
+ })
+ if err != nil {
+ t.Fatalf("GetProfilePictureUploadURL() error = %v", err)
+ }
+ if !strings.HasPrefix(upload1.AttachmentID, "ua_") {
+ t.Fatalf("attachment id = %q, want ua_ prefix", upload1.AttachmentID)
+ }
+
+ objectKey1 := contactmodel.AttachmentObjectKey(1, contactmodel.ProfilePicture, upload1.AttachmentID)
+ var bucketID string
+ if err := db.QueryRow(`SELECT bucket_id FROM temp_objects WHERE object_key = $1`, objectKey1).Scan(&bucketID); err != nil {
+ t.Fatalf("temp_objects lookup failed: %v", err)
+ }
+ if bucketID != s3Cfg.GetAttachmentBucketID(string(contactmodel.ProfilePicture)) {
+ t.Fatalf("bucket_id = %q, want %q", bucketID, s3Cfg.GetAttachmentBucketID(string(contactmodel.ProfilePicture)))
+ }
+
+ withPicture, err := ctrl.AttachProfilePicture(ctx, created.ID, contactmodel.CommitProfilePictureRequest{
+ AttachmentID: upload1.AttachmentID,
+ Size: 128,
+ })
+ if err != nil {
+ t.Fatalf("AttachProfilePicture() error = %v", err)
+ }
+ if withPicture.ProfilePictureAttachmentID == nil || *withPicture.ProfilePictureAttachmentID != upload1.AttachmentID {
+ t.Fatalf("unexpected profile picture ref after attach: %+v", withPicture)
+ }
+ if err := db.QueryRow(`SELECT bucket_id FROM temp_objects WHERE object_key = $1`, objectKey1).Scan(&bucketID); !errors.Is(err, sql.ErrNoRows) {
+ t.Fatalf("temp_objects row should be removed after attach, got err=%v bucket=%q", err, bucketID)
+ }
+
+ signedURL, err := ctrl.GetProfilePictureURL(ctx, created.ID)
+ if err != nil {
+ t.Fatalf("GetProfilePictureURL() error = %v", err)
+ }
+ if signedURL.URL == "" {
+ t.Fatal("expected signed profile picture url")
+ }
+
+ upload2, err := ctrl.GetProfilePictureUploadURL(ctx, created.ID, contactmodel.ProfilePictureUploadURLRequest{
+ ContentLength: 256,
+ ContentMD5: "ZmFrZS1tZDUtMg==",
+ })
+ if err != nil {
+ t.Fatalf("second GetProfilePictureUploadURL() error = %v", err)
+ }
+ replaced, err := ctrl.AttachProfilePicture(ctx, created.ID, contactmodel.CommitProfilePictureRequest{
+ AttachmentID: upload2.AttachmentID,
+ Size: 256,
+ })
+ if err != nil {
+ t.Fatalf("second AttachProfilePicture() error = %v", err)
+ }
+ if replaced.ProfilePictureAttachmentID == nil || *replaced.ProfilePictureAttachmentID != upload2.AttachmentID {
+ t.Fatalf("unexpected profile picture ref after replace: %+v", replaced)
+ }
+
+ oldAttachment, err := ctrl.Repo.GetAttachment(ctx, 1, upload1.AttachmentID)
+ if err != nil {
+ t.Fatalf("GetAttachment(old) error = %v", err)
+ }
+ if !oldAttachment.IsDeleted {
+ t.Fatalf("old attachment should be marked deleted after replace")
+ }
+
+ cleared, err := ctrl.DeleteProfilePicture(ctx, created.ID)
+ if err != nil {
+ t.Fatalf("DeleteProfilePicture() error = %v", err)
+ }
+ if cleared.ProfilePictureAttachmentID != nil {
+ t.Fatalf("profile picture should be cleared, got %+v", cleared.ProfilePictureAttachmentID)
+ }
+ newAttachment, err := ctrl.Repo.GetAttachment(ctx, 1, upload2.AttachmentID)
+ if err != nil {
+ t.Fatalf("GetAttachment(new) error = %v", err)
+ }
+ if !newAttachment.IsDeleted {
+ t.Fatalf("current attachment should be marked deleted after picture removal")
+ }
+}
+
+func TestDeleteContactMarksCurrentProfilePictureDeleted(t *testing.T) {
+ ctrl, db, ctx, _ := setupContactControllerTest(t)
+ mustInsertTestUser(t, db, 1)
+
+ created := createContactForTest(t, ctrl, ctx, 51, "wrapped-key-1", "payload-1")
+ upload, err := ctrl.GetProfilePictureUploadURL(ctx, created.ID, contactmodel.ProfilePictureUploadURLRequest{
+ ContentLength: 128,
+ ContentMD5: "ZmFrZS1tZDU=",
+ })
+ if err != nil {
+ t.Fatalf("GetProfilePictureUploadURL() error = %v", err)
+ }
+ withPicture, err := ctrl.AttachProfilePicture(ctx, created.ID, contactmodel.CommitProfilePictureRequest{
+ AttachmentID: upload.AttachmentID,
+ Size: 128,
+ })
+ if err != nil {
+ t.Fatalf("AttachProfilePicture() error = %v", err)
+ }
+ if withPicture.ProfilePictureAttachmentID == nil {
+ t.Fatal("expected profile picture ref before delete")
+ }
+
+ if err := ctrl.Delete(ctx, created.ID); err != nil {
+ t.Fatalf("Delete() error = %v", err)
+ }
+ attachment, err := ctrl.Repo.GetAttachment(ctx, 1, upload.AttachmentID)
+ if err != nil {
+ t.Fatalf("GetAttachment() error = %v", err)
+ }
+ if !attachment.IsDeleted {
+ t.Fatalf("attachment should be marked deleted when contact is deleted")
+ }
+ deleted, err := ctrl.Get(ctx, created.ID)
+ if err != nil {
+ t.Fatalf("Get() after delete error = %v", err)
+ }
+ if deleted.ProfilePictureAttachmentID != nil {
+ t.Fatalf("deleted contact should not reference profile picture")
+ }
+}
+
+func ptrInt64(v int64) *int64 {
+ return &v
+}
diff --git a/server/pkg/middleware/request_logger.go b/server/pkg/middleware/request_logger.go
index b5bc29e79c..6dbe1c75d6 100644
--- a/server/pkg/middleware/request_logger.go
+++ b/server/pkg/middleware/request_logger.go
@@ -6,6 +6,7 @@ import (
"net/http"
"net/url"
"strconv"
+ "strings"
"time"
"github.com/ente-io/museum/pkg/utils/network"
@@ -38,6 +39,12 @@ func shouldSkipBodyLog(method string, path string) bool {
if path == "/user-entity/entity" && (method == "POST" || method == "PUT") {
return true
}
+ if path == "/contacts" && method == http.MethodPost {
+ return true
+ }
+ if strings.HasPrefix(path, "/contacts/") && method == http.MethodPut {
+ return true
+ }
if path == "/files/data" && method == "PUT" {
return true
}
diff --git a/server/pkg/repo/contact/contact.go b/server/pkg/repo/contact/contact.go
new file mode 100644
index 0000000000..942dcf5960
--- /dev/null
+++ b/server/pkg/repo/contact/contact.go
@@ -0,0 +1,395 @@
+package contact
+
+import (
+ "context"
+ "database/sql"
+ "errors"
+
+ "github.com/ente-io/museum/ente"
+ contactmodel "github.com/ente-io/museum/ente/contact"
+ "github.com/ente-io/stacktrace"
+ "github.com/lib/pq"
+)
+
+func (r *Repository) Create(ctx context.Context, userID int64, req contactmodel.CreateRequest) (string, error) {
+ id := contactmodel.NewContactID()
+ err := r.DB.QueryRowContext(
+ ctx,
+ `INSERT INTO contact_entity(id, user_id, contact_user_id, encrypted_key, encrypted_data)
+ VALUES($1, $2, $3, $4, $5)
+ RETURNING id`,
+ id,
+ userID,
+ req.ContactUserID,
+ req.EncryptedKey,
+ req.EncryptedData,
+ ).Scan(&id)
+ if err != nil {
+ var pqErr *pq.Error
+ if errors.As(err, &pqErr) && pqErr.Code == "23505" {
+ return "", stacktrace.Propagate(
+ ente.NewBadRequestWithMessage("contact already exists for contactUserID"),
+ "",
+ )
+ }
+ return "", stacktrace.Propagate(err, "failed to create contact")
+ }
+ return id, nil
+}
+
+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`,
+ id,
+ userID,
+ )
+ entity, err := scanEntity(row)
+ if err != nil {
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil, &ente.ErrNotFoundError
+ }
+ return nil, stacktrace.Propagate(err, "failed to get contact")
+ }
+ return entity, nil
+}
+
+func (r *Repository) Update(ctx context.Context, userID int64, id string, req contactmodel.UpdateRequest) error {
+ result, err := r.DB.ExecContext(
+ ctx,
+ `UPDATE contact_entity
+ SET contact_user_id = $1, encrypted_data = $2
+ WHERE id = $3 AND user_id = $4 AND is_deleted = FALSE`,
+ req.ContactUserID,
+ req.EncryptedData,
+ id,
+ userID,
+ )
+ if err != nil {
+ var pqErr *pq.Error
+ if errors.As(err, &pqErr) && pqErr.Code == "23505" {
+ return stacktrace.Propagate(
+ ente.NewBadRequestWithMessage("contact already exists for contactUserID"),
+ "",
+ )
+ }
+ return stacktrace.Propagate(err, "failed to update contact")
+ }
+ rowsAffected, err := result.RowsAffected()
+ if err != nil {
+ return stacktrace.Propagate(err, "")
+ }
+ if rowsAffected == 1 {
+ return nil
+ }
+ entity, getErr := r.Get(ctx, userID, id)
+ if getErr != nil {
+ return stacktrace.Propagate(getErr, "failed to fetch contact after update miss")
+ }
+ if entity.IsDeleted {
+ return stacktrace.Propagate(ente.NewBadRequestWithMessage("contact is already deleted"), "")
+ }
+ return stacktrace.NewError("exactly one row should be updated")
+}
+
+func (r *Repository) Delete(ctx context.Context, userID int64, id string) error {
+ tx, err := r.DB.BeginTx(ctx, nil)
+ if err != nil {
+ return stacktrace.Propagate(err, "")
+ }
+ defer tx.Rollback()
+
+ entity, err := r.getForUpdate(ctx, tx, userID, id)
+ if err != nil {
+ return stacktrace.Propagate(err, "")
+ }
+ if entity.IsDeleted {
+ return tx.Commit()
+ }
+
+ if entity.ProfilePictureAttachmentID != nil {
+ if err := markAttachmentDeletedTx(ctx, tx, userID, *entity.ProfilePictureAttachmentID); err != nil {
+ return stacktrace.Propagate(err, "")
+ }
+ }
+ if _, err := tx.ExecContext(
+ ctx,
+ `UPDATE contact_entity
+ SET is_deleted = TRUE,
+ encrypted_data = NULL,
+ profile_picture_attachment_id = NULL
+ WHERE id = $1 AND user_id = $2`,
+ id,
+ userID,
+ ); err != nil {
+ return stacktrace.Propagate(err, "failed to delete contact")
+ }
+ return stacktrace.Propagate(tx.Commit(), "")
+}
+
+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
+ LIMIT $3`,
+ userID,
+ sinceTime,
+ limit,
+ )
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "contact diff query failed")
+ }
+ defer rows.Close()
+
+ entities := make([]contactmodel.Entity, 0)
+ for rows.Next() {
+ entity, scanErr := scanEntity(rows)
+ if scanErr != nil {
+ return nil, stacktrace.Propagate(scanErr, "failed to scan contact diff row")
+ }
+ entities = append(entities, *entity)
+ }
+ return entities, nil
+}
+
+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 {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ defer tx.Rollback()
+
+ entity, err := r.getForUpdate(ctx, tx, userID, contactID)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ if entity.IsDeleted {
+ return nil, stacktrace.Propagate(ente.NewBadRequestWithMessage("contact is already deleted"), "")
+ }
+
+ objectKey := contactmodel.AttachmentObjectKey(userID, contactmodel.ProfilePicture, attachmentID)
+ var latestBucket string
+ if err := tx.QueryRowContext(
+ ctx,
+ `SELECT bucket_id FROM temp_objects WHERE object_key = $1 FOR UPDATE`,
+ objectKey,
+ ).Scan(&latestBucket); err != nil {
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil, stacktrace.Propagate(ente.NewBadRequestWithMessage("staged profile picture upload not found"), "")
+ }
+ return nil, stacktrace.Propagate(err, "failed to fetch staged profile picture")
+ }
+
+ if _, err := tx.ExecContext(
+ ctx,
+ `INSERT INTO user_attachments(attachment_id, user_id, attachment_type, size, latest_bucket)
+ VALUES($1, $2, $3, $4, $5)`,
+ attachmentID,
+ userID,
+ string(contactmodel.ProfilePicture),
+ size,
+ latestBucket,
+ ); err != nil {
+ var pqErr *pq.Error
+ if errors.As(err, &pqErr) && pqErr.Code == "23505" {
+ return nil, stacktrace.Propagate(ente.NewBadRequestWithMessage("attachmentID already exists"), "")
+ }
+ return nil, stacktrace.Propagate(err, "failed to insert attachment row")
+ }
+
+ if entity.ProfilePictureAttachmentID != nil && *entity.ProfilePictureAttachmentID != "" {
+ if err := markAttachmentDeletedTx(ctx, tx, userID, *entity.ProfilePictureAttachmentID); err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ }
+
+ if _, err := tx.ExecContext(
+ ctx,
+ `UPDATE contact_entity
+ SET profile_picture_attachment_id = $1
+ WHERE id = $2 AND user_id = $3 AND is_deleted = FALSE`,
+ attachmentID,
+ contactID,
+ userID,
+ ); err != nil {
+ return nil, stacktrace.Propagate(err, "failed to update contact profile picture")
+ }
+
+ if err := r.ObjectCleanupRepo.RemoveTempObjectFromDC(ctx, tx, objectKey, latestBucket); err != nil {
+ return nil, stacktrace.Propagate(err, "failed to remove profile picture from temp_objects")
+ }
+
+ if err := tx.Commit(); err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ return r.Get(ctx, userID, contactID)
+}
+
+func (r *Repository) DeleteProfilePicture(ctx context.Context, userID int64, contactID string) (*contactmodel.Entity, error) {
+ tx, err := r.DB.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ defer tx.Rollback()
+
+ entity, err := r.getForUpdate(ctx, tx, userID, contactID)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ if entity.IsDeleted {
+ return nil, stacktrace.Propagate(ente.NewBadRequestWithMessage("contact is already deleted"), "")
+ }
+ if entity.ProfilePictureAttachmentID != nil {
+ if err := markAttachmentDeletedTx(ctx, tx, userID, *entity.ProfilePictureAttachmentID); err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ if _, err := tx.ExecContext(
+ ctx,
+ `UPDATE contact_entity
+ SET profile_picture_attachment_id = NULL
+ WHERE id = $1 AND user_id = $2 AND is_deleted = FALSE`,
+ contactID,
+ userID,
+ ); err != nil {
+ return nil, stacktrace.Propagate(err, "failed to clear contact profile picture")
+ }
+ }
+ if err := tx.Commit(); err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ return r.Get(ctx, userID, contactID)
+}
+
+func (r *Repository) GetAttachment(ctx context.Context, userID int64, attachmentID string) (*contactmodel.Attachment, error) {
+ row := r.DB.QueryRowContext(
+ ctx,
+ `SELECT attachment_id, user_id, attachment_type, size, latest_bucket, replicated_buckets,
+ delete_from_buckets, inflight_rep_buckets, pending_sync, is_deleted, sync_locked_till,
+ created_at, updated_at
+ FROM user_attachments
+ WHERE attachment_id = $1 AND user_id = $2`,
+ attachmentID,
+ userID,
+ )
+ attachment, err := scanAttachment(row)
+ if err != nil {
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil, &ente.ErrNotFoundError
+ }
+ return nil, stacktrace.Propagate(err, "failed to get attachment")
+ }
+ return attachment, nil
+}
+
+func (r *Repository) getForUpdate(ctx context.Context, tx *sql.Tx, userID int64, id string) (*contactmodel.Entity, error) {
+ row := tx.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
+ FOR UPDATE`,
+ id,
+ userID,
+ )
+ entity, err := scanEntity(row)
+ if err != nil {
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil, &ente.ErrNotFoundError
+ }
+ return nil, stacktrace.Propagate(err, "failed to lock contact row")
+ }
+ return entity, nil
+}
+
+func markAttachmentDeletedTx(ctx context.Context, tx *sql.Tx, userID int64, attachmentID string) error {
+ _, err := tx.ExecContext(
+ ctx,
+ `UPDATE user_attachments
+ SET is_deleted = TRUE,
+ pending_sync = TRUE,
+ sync_locked_till = 0,
+ delete_from_buckets = array(
+ SELECT DISTINCT elem
+ FROM unnest(array_cat(array_cat(replicated_buckets, delete_from_buckets), inflight_rep_buckets)) AS elem
+ WHERE elem IS NOT NULL
+ ),
+ replicated_buckets = ARRAY[]::s3region[],
+ inflight_rep_buckets = ARRAY[]::s3region[]
+ WHERE attachment_id = $1
+ AND user_id = $2
+ AND attachment_type = $3
+ AND is_deleted = FALSE`,
+ attachmentID,
+ userID,
+ string(contactmodel.ProfilePicture),
+ )
+ return stacktrace.Propagate(err, "failed to mark attachment deleted")
+}
+
+type rowScanner interface {
+ Scan(dest ...interface{}) error
+}
+
+func scanEntity(scanner rowScanner) (*contactmodel.Entity, error) {
+ var (
+ entity contactmodel.Entity
+ pictureID sql.NullString
+ encryptedKey []byte
+ encryptedData []byte
+ )
+ if err := scanner.Scan(
+ &entity.ID,
+ &entity.UserID,
+ &entity.ContactUserID,
+ &pictureID,
+ &encryptedKey,
+ &encryptedData,
+ &entity.IsDeleted,
+ &entity.CreatedAt,
+ &entity.UpdatedAt,
+ ); err != nil {
+ return nil, err
+ }
+ if pictureID.Valid {
+ entity.ProfilePictureAttachmentID = &pictureID.String
+ }
+ if entity.IsDeleted {
+ entity.ProfilePictureAttachmentID = nil
+ entity.EncryptedKey = nil
+ entity.EncryptedData = nil
+ return &entity, nil
+ }
+ entity.EncryptedKey = &encryptedKey
+ entity.EncryptedData = &encryptedData
+ return &entity, nil
+}
+
+func scanAttachment(scanner rowScanner) (*contactmodel.Attachment, error) {
+ var attachment contactmodel.Attachment
+ if err := scanner.Scan(
+ &attachment.AttachmentID,
+ &attachment.UserID,
+ &attachment.AttachmentType,
+ &attachment.Size,
+ &attachment.LatestBucket,
+ pq.Array(&attachment.ReplicatedBuckets),
+ pq.Array(&attachment.DeleteFromBuckets),
+ pq.Array(&attachment.InflightRepBuckets),
+ &attachment.PendingSync,
+ &attachment.IsDeleted,
+ &attachment.SyncLockedTill,
+ &attachment.CreatedAt,
+ &attachment.UpdatedAt,
+ ); err != nil {
+ return nil, err
+ }
+ return &attachment, nil
+}
diff --git a/server/pkg/repo/contact/repository.go b/server/pkg/repo/contact/repository.go
new file mode 100644
index 0000000000..df0b1063f9
--- /dev/null
+++ b/server/pkg/repo/contact/repository.go
@@ -0,0 +1,12 @@
+package contact
+
+import (
+ "database/sql"
+
+ "github.com/ente-io/museum/pkg/repo"
+)
+
+type Repository struct {
+ DB *sql.DB
+ ObjectCleanupRepo *repo.ObjectCleanupRepository
+}
diff --git a/server/pkg/utils/s3config/attachment.go b/server/pkg/utils/s3config/attachment.go
new file mode 100644
index 0000000000..534d4110b8
--- /dev/null
+++ b/server/pkg/utils/s3config/attachment.go
@@ -0,0 +1,35 @@
+package s3config
+
+import (
+ "fmt"
+ "strings"
+)
+
+type AttachmentConfig struct {
+ ObjectBucketConfig map[string]ObjectBucketConfig `mapstructure:"attachment-config"`
+}
+
+func (a AttachmentConfig) HasConfig(attachmentType string) bool {
+ _, ok := a.ObjectBucketConfig[attachmentKey(attachmentType)]
+ return ok
+}
+
+func (a AttachmentConfig) GetPrimaryBucketID(attachmentType string) string {
+ config, ok := a.ObjectBucketConfig[attachmentKey(attachmentType)]
+ if !ok {
+ panic(fmt.Sprintf("no config for attachment type: %s, use HasConfig", attachmentType))
+ }
+ return config.PrimaryBucket
+}
+
+func (a AttachmentConfig) GetReplicaBuckets(attachmentType string) []string {
+ config, ok := a.ObjectBucketConfig[attachmentKey(attachmentType)]
+ if !ok {
+ panic(fmt.Sprintf("no config for attachment type: %s, use HasConfig", attachmentType))
+ }
+ return config.ReplicaBuckets
+}
+
+func attachmentKey(attachmentType string) string {
+ return strings.ToLower(strings.TrimSpace(attachmentType))
+}
diff --git a/server/pkg/utils/s3config/s3config.go b/server/pkg/utils/s3config/s3config.go
index d0858fc246..d6f69f2ee7 100644
--- a/server/pkg/utils/s3config/s3config.go
+++ b/server/pkg/utils/s3config/s3config.go
@@ -48,6 +48,9 @@ type S3Config struct {
// existing objectType (file, thumbnail) and will be used for new objectTypes. In the future,
// we can migrate existing objectTypes to this config.
fileDataConfig FileDataConfig
+ // attachmentConfig is the configuration for contact and future user attachments.
+ // If no explicit config is present, attachments default to hot storage with no replicas.
+ attachmentConfig AttachmentConfig
}
// # Datacenters
@@ -136,10 +139,10 @@ func (config *S3Config) initialize() {
Endpoint: aws.String(viper.GetString("s3." + dc + ".endpoint")),
Region: aws.String(viper.GetString("s3." + dc + ".region")),
}
- if usePathStyleURLs || viper.GetBool("s3." + dc + ".use_path_style_urls") || areLocalBuckets {
+ if usePathStyleURLs || viper.GetBool("s3."+dc+".use_path_style_urls") || areLocalBuckets {
s3Config.S3ForcePathStyle = aws.Bool(true)
}
- if areLocalBuckets || viper.GetBool("s3." + dc + ".disable_ssl") {
+ if areLocalBuckets || viper.GetBool("s3."+dc+".disable_ssl") {
s3Config.DisableSSL = aws.Bool(true)
}
s3Session, err := session.NewSession(&s3Config)
@@ -158,6 +161,10 @@ func (config *S3Config) initialize() {
log.Fatalf("Unable to decode into struct: %v\n", err)
return
}
+ if err := viper.Sub("s3").Unmarshal(&config.attachmentConfig); err != nil {
+ log.Fatalf("Unable to decode into struct: %v\n", err)
+ return
+ }
}
@@ -186,6 +193,20 @@ func (config *S3Config) GetReplicatedBuckets(oType ente.ObjectType) []string {
panic(fmt.Sprintf("ops not supported for object type: %s", oType))
}
+func (config *S3Config) GetAttachmentBucketID(attachmentType string) string {
+ if config.attachmentConfig.HasConfig(attachmentType) {
+ return config.attachmentConfig.GetPrimaryBucketID(attachmentType)
+ }
+ return config.hotDC
+}
+
+func (config *S3Config) GetReplicatedAttachmentBuckets(attachmentType string) []string {
+ if config.attachmentConfig.HasConfig(attachmentType) {
+ return config.attachmentConfig.GetReplicaBuckets(attachmentType)
+ }
+ return []string{}
+}
+
func (config *S3Config) IsBucketActive(bucketID string) bool {
return config.buckets[bucketID] != ""
}