π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Add storage warning login grace
Neeraj Gupta1229955eb7a6
diff --git a/server/mail-templates/storage-warning/storage_warning_login_grace.html b/server/mail-templates/storage-warning/storage_warning_login_grace.htmlnew file mode 100644index 0000000000..bdc190532e--- /dev/null+++ b/server/mail-templates/storage-warning/storage_warning_login_grace.html@@ -0,0 +1,22 @@+{{define "content"}}+<p>Hi,</p>++<p>+ Access to Ente Photos and Ente Locker for+ <strong>{{.AccountEmail}}</strong> has been temporarily restored until+ <strong>{{.GraceUntil}}</strong>.+</p>++<p>+ To keep access, renew your plan or reduce your storage usage to within your+ available storage before then.+</p>++<p>+ If the account is still over its available storage or still deletion-eligible+ after this {{.GraceDays}}-day grace period, Photos and Locker access will be+ restricted again.+</p>++<p>You may need to sign in again on your devices.</p>+{{end}}diff --git a/server/pkg/api/admin.go b/server/pkg/api/admin.goindex 8abab90b1c..2feae2d074 100644--- a/server/pkg/api/admin.go+++ b/server/pkg/api/admin.go@@ -343,7 +343,7 @@ func (h *AdminHandler) UnblockStorageWarningLogin(c *gin.Context) {"req_ctx": "unblock_storage_warning_login",})logger.Info("Start unblock storage warning login")- err = h.UserController.ClearStorageWarningDeletionLoginBlock(request.UserID)+ err = h.UserController.UnblockStorageWarningDeletionLogin(request.UserID, logger)if err != nil {logger.WithError(err).Error("Failed to unblock storage warning login")handler.Error(c, stacktrace.Propagate(err, ""))diff --git a/server/pkg/controller/email/storage_warning.go b/server/pkg/controller/email/storage_warning.goindex aea9c3af3a..145207e946 100644--- a/server/pkg/controller/email/storage_warning.go+++ b/server/pkg/controller/email/storage_warning.go@@ -106,6 +106,15 @@ var persistStorageWarningHistory = func(notificationHistoryRepo *repo.Notificatireturn notificationHistoryRepo.SetLastNotificationTimeToNowWithGroup(snapshot.RecipientID, templateID, historyGroup)}+// The login-grace marker is not a warning stage. It is fetched alongside stage+// history so the daily job can pause or resume terminal enforcement.+func storageWarningTemplateIDsWithLoginGrace(templateIDs []string) []string {+ result := make([]string, 0, len(templateIDs)+1)+ result = append(result, templateIDs...)+ result = append(result, repo.StorageWarningLoginGraceTemplateID)+ return result+}+var storageWarningStageOrder = []string{string(expiredWarningStage0),string(expiredWarningStage30),@@ -210,6 +219,12 @@ func (c *EmailNotificationController) SendStorageWarningMails() {log.WithError(err).Error("Failed to fetch storage warning candidates")return}+ graceCandidates, err := c.NotificationHistoryRepo.GetStorageWarningLoginGraceCandidates(ctx)+ if err != nil {+ log.WithError(err).Error("Failed to fetch storage warning login grace candidates")+ return+ }+ candidates = mergeStorageWarningCandidates(candidates, graceCandidates)processed := 0sent := 0@@ -316,6 +331,22 @@ func (c *EmailNotificationController) SendFamilyStorageWarningMails() {c.SendStorageWarningMails()}+func mergeStorageWarningCandidates(candidateSets ...[]repo.StorageWarningCandidate) []repo.StorageWarningCandidate {+ result := make([]repo.StorageWarningCandidate, 0)+ indices := make(map[int64]int)+ for _, candidates := range candidateSets {+ for _, candidate := range candidates {+ if index, ok := indices[candidate.RecipientID]; ok {+ result[index].IsFamilyPlan = result[index].IsFamilyPlan || candidate.IsFamilyPlan+ continue+ }+ indices[candidate.RecipientID] = len(result)+ result = append(result, candidate)+ }+ }+ return result+}+func (c *EmailNotificationController) cleanupActiveOverageWarningHistory(preserveRecipientIDs map[int64]struct{}) error {keepUserIDs := make([]int64, 0, len(preserveRecipientIDs))for userID := range preserveRecipientIDs {@@ -324,6 +355,38 @@ func (c *EmailNotificationController) cleanupActiveOverageWarningHistory(preservreturn c.NotificationHistoryRepo.DeleteNotificationHistoryByGroupExcludingUsers(storageWarningActiveOverageNotificationGroup, keepUserIDs)}+func (c *EmailNotificationController) clearStorageWarningLoginGrace(userID int64, logger *log.Entry) error {+ if c.NotificationHistoryRepo == nil {+ return nil+ }+ if err := c.NotificationHistoryRepo.ClearStorageWarningLoginGrace(userID); err != nil {+ if logger != nil {+ logger.WithError(err).Error("Failed to clear storage warning login grace")+ }+ return err+ }+ if logger != nil {+ logger.Info("Cleared storage warning login grace")+ }+ return nil+}++func (c *EmailNotificationController) clearRecoveredStorageWarningLoginState(userID int64, logger *log.Entry) error {+ if c.NotificationHistoryRepo == nil {+ return nil+ }+ // A cron/admin race can recreate the terminal login-block row while the grace+ // marker is active. Once the user recovers, remove both rows so clearing grace+ // does not expose the stale block again.+ if err := c.NotificationHistoryRepo.ClearStorageWarningDeletionScheduled(userID); err != nil {+ if logger != nil {+ logger.WithError(err).Error("Failed to clear storage warning deletion state after recovery")+ }+ return err+ }+ return c.clearStorageWarningLoginGrace(userID, logger)+}+func (c *EmailNotificationController) buildStorageWarningSnapshot(ctx context.Context, candidate repo.StorageWarningCandidate, now int64) (storageWarningSnapshot, error) {if candidate.IsFamilyPlan {return c.buildFamilyStorageWarningSnapshot(ctx, candidate.RecipientID, now)@@ -428,7 +491,7 @@ func (c *EmailNotificationController) buildIndividualStorageWarningSnapshot(ctxfunc (c *EmailNotificationController) decorateStorageWarningSnapshot(snapshot storageWarningSnapshot, now int64) (storageWarningSnapshot, error) {switch snapshot.Bucket {case storageWarningBucketExpired:- history, err := c.NotificationHistoryRepo.GetLastNotificationTimes(snapshot.RecipientID, expiredWarningTemplateIDs())+ history, err := c.NotificationHistoryRepo.GetLastNotificationTimes(snapshot.RecipientID, storageWarningTemplateIDsWithLoginGrace(expiredWarningTemplateIDs()))if err != nil {return storageWarningSnapshot{}, err}@@ -443,7 +506,7 @@ func (c *EmailNotificationController) decorateStorageWarningSnapshot(snapshot streturn snapshot, nil}case storageWarningBucketActiveOverage:- history, err := c.NotificationHistoryRepo.GetLastNotificationTimes(snapshot.RecipientID, activeOverageWarningTemplateIDs())+ history, err := c.NotificationHistoryRepo.GetLastNotificationTimes(snapshot.RecipientID, storageWarningTemplateIDsWithLoginGrace(activeOverageWarningTemplateIDs()))if err != nil {return storageWarningSnapshot{}, err}@@ -456,6 +519,12 @@ func (c *EmailNotificationController) decorateStorageWarningSnapshot(snapshot streturn snapshot, nil}snapshot.AutoDeleteDate = activeOverageWarningAutoDeleteDate(snapshot.WarningCycleStart, snapshot.ActiveOverageStage, now)+ case storageWarningBucketNone:+ history, err := c.NotificationHistoryRepo.GetLastNotificationTimes(snapshot.RecipientID, []string{repo.StorageWarningLoginGraceTemplateID})+ if err != nil {+ return storageWarningSnapshot{}, err+ }+ snapshot.NotificationHistory = history}return snapshot, nil}@@ -465,6 +534,35 @@ func (c *EmailNotificationController) processStorageWarningSnapshot(ctx context."recipient_id": snapshot.RecipientID,"is_family_plan": snapshot.IsFamilyPlan,})+ graceActive, graceExpired, graceUntil := storageWarningLoginGraceState(snapshot)+ currentBucket := storageWarningCurrentBucket(snapshot)+ if currentBucket == storageWarningBucketNone && snapshot.Bucket == storageWarningBucketNone {+ if graceActive || graceExpired {+ if err := c.clearRecoveredStorageWarningLoginState(snapshot.RecipientID, logger); err != nil {+ return storageWarningProcessResultSkipped, err+ }+ }+ return storageWarningProcessResultSkipped, nil+ }++ // A soft-unblock pauses the terminal state machine for the full grace+ // window. This must run before cadence checks because active-overage+ // reminder history may already have been cleaned after the original block.+ if graceActive {+ logger.WithFields(log.Fields{+ "bucket": snapshot.Bucket,+ "active_stage": snapshot.ActiveOverageStage,+ "expired_stage": snapshot.ExpiredStage,+ "login_grace_until": graceUntil,+ }).Info("Skipping storage warning due to active login grace")+ return storageWarningProcessResultSkipped, nil+ }+ if graceExpired {+ if snapshot.Bucket == storageWarningBucketNone {+ snapshot.Bucket = currentBucket+ }+ snapshot = storageWarningForceScheduledDeletionAfterLoginGrace(snapshot)+ }if snapshot.Bucket == storageWarningBucketNone {return storageWarningProcessResultSkipped, nil}@@ -476,19 +574,36 @@ func (c *EmailNotificationController) processStorageWarningSnapshot(ctx context.}if storageWarningTemplateSentInCycle(snapshot.NotificationHistory, templateID, snapshot.WarningCycleStart) {+ if graceExpired {+ if err := c.clearStorageWarningLoginGrace(snapshot.RecipientID, logger); err != nil {+ return storageWarningProcessResultSkipped, err+ }+ }return storageWarningProcessResultSkipped, nil}+ shouldResetUserAccess := storageWarningShouldResetUserAccess(snapshot)if cadenceBroken, cadenceAlert := storageWarningCadenceBroken(snapshot); cadenceBroken {- logger.WithFields(log.Fields{- "bucket": snapshot.Bucket,- "active_stage": snapshot.ActiveOverageStage,- "expired_stage": snapshot.ExpiredStage,- "warning_cycle_start": snapshot.WarningCycleStart,- }).Warn("Skipping storage warning due to broken stage cadence")- if c.DiscordController != nil {- c.DiscordController.NotifyAdminAction(cadenceAlert)+ if shouldResetUserAccess && graceExpired {+ logger.WithFields(log.Fields{+ "bucket": snapshot.Bucket,+ "active_stage": snapshot.ActiveOverageStage,+ "expired_stage": snapshot.ExpiredStage,+ "template_id": templateID,+ "login_grace_until": graceUntil,+ "warning_cycle_start": snapshot.WarningCycleStart,+ }).Info("Allowing storage warning scheduled deletion after login grace expiry")+ } else {+ logger.WithFields(log.Fields{+ "bucket": snapshot.Bucket,+ "active_stage": snapshot.ActiveOverageStage,+ "expired_stage": snapshot.ExpiredStage,+ "warning_cycle_start": snapshot.WarningCycleStart,+ }).Warn("Skipping storage warning due to broken stage cadence")+ if c.DiscordController != nil {+ c.DiscordController.NotifyAdminAction(cadenceAlert)+ }+ return storageWarningProcessResultSkipped, nil}- return storageWarningProcessResultSkipped, nil}templateData := map[string]interface{}{@@ -536,7 +651,6 @@ func (c *EmailNotificationController) processStorageWarningSnapshot(ctx context.if !isInStorageWarningRollout(snapshot.RecipientID, snapshot.AccountEmail) {return storageWarningProcessResultSkippedRollout, nil}- shouldResetUserAccess := storageWarningShouldResetUserAccess(snapshot)if shouldResetUserAccess && c.UserAccessResetter == nil {err := errors.New("storage warning user access resetter is not configured")logger.WithError(err).Error("Failed to restrict user access for storage scheduled deletion")@@ -574,6 +688,11 @@ func (c *EmailNotificationController) processStorageWarningSnapshot(ctx context.logger.WithError(err).Error("Failed to persist storage warning history")return storageWarningProcessResultSkipped, err}+ if graceExpired {+ if err := c.clearStorageWarningLoginGrace(snapshot.RecipientID, logger); err != nil {+ return storageWarningProcessResultSkipped, err+ }+ }logger.Info("Sent storage warning email")return storageWarningProcessResultSent, nil@@ -683,6 +802,8 @@ func storageWarningNotificationGroup(bucket storageWarningBucket) string {}func storageWarningHistoryGroup(snapshot storageWarningSnapshot) string {+ // Terminal rows are deliberately ungrouped because they are the login-block+ // marker. Group cleanup only applies to reminder history.if storageWarningShouldResetUserAccess(snapshot) {return ""}@@ -700,7 +821,48 @@ func storageWarningShouldResetUserAccess(snapshot storageWarningSnapshot) bool {}}+func storageWarningCurrentBucket(snapshot storageWarningSnapshot) storageWarningBucket {+ if snapshot.CurrentBucket != "" {+ return snapshot.CurrentBucket+ }+ return snapshot.Bucket+}++// storageWarningLoginGraceState evaluates the latest soft-unblock row. The+// daily job clears the row after recovery or re-block, so the timestamp itself+// defines the current window.+func storageWarningLoginGraceState(snapshot storageWarningSnapshot) (active bool, expired bool, graceUntil int64) {+ graceSentAt := snapshot.NotificationHistory[repo.StorageWarningLoginGraceTemplateID]+ if graceSentAt <= 0 {+ return false, false, 0+ }+ graceUntil = repo.StorageWarningLoginGraceUntil(graceSentAt)+ if repo.StorageWarningLoginGraceActive(graceSentAt, snapshot.EvaluatedAt) {+ return true, false, graceUntil+ }+ return false, true, graceUntil+}++func storageWarningForceScheduledDeletionAfterLoginGrace(snapshot storageWarningSnapshot) storageWarningSnapshot {+ switch snapshot.Bucket {+ case storageWarningBucketExpired:+ snapshot.ExpiredStage = expiredWarningStageScheduledDeletion+ case storageWarningBucketActiveOverage:+ snapshot.ActiveOverageStage = activeOverageWarningStageScheduledDeletion+ }+ if snapshot.WarningCycleStart <= 0 {+ snapshot.WarningCycleStart = snapshot.EvaluatedAt+ }+ if snapshot.AutoDeleteDate <= 0 {+ snapshot.AutoDeleteDate = snapshot.EvaluatedAt+ }+ return snapshot+}+func storageWarningShouldPreserveActiveOverageHistory(snapshot storageWarningSnapshot) bool {+ // Active-overage reminder rows are kept while the user is in a non-terminal+ // cycle. Once a terminal row exists, the row itself is enough to block login+ // and grouped reminder history may be cleaned.if snapshot.CurrentBucket != storageWarningBucketActiveOverage {return false}diff --git a/server/pkg/controller/email/storage_warning_overage.go b/server/pkg/controller/email/storage_warning_overage.goindex fea614f0fa..7faea2ae92 100644--- a/server/pkg/controller/email/storage_warning_overage.go+++ b/server/pkg/controller/email/storage_warning_overage.go@@ -132,6 +132,9 @@ func resolveActiveOverageWarning(now int64, history map[string]int64) activeOverCycleStart: cycleStart,}}+ // Without an active login-grace marker, stale cadence restarts the warning+ // ladder instead of deleting from an old final reminder. The grace handler+ // in processStorageWarningSnapshot can still force terminal re-block.return activeOverageWarningResolution{Stage: activeOverageWarningStage0,CycleStart: now,diff --git a/server/pkg/controller/email/storage_warning_test.go b/server/pkg/controller/email/storage_warning_test.goindex ebbee34a4c..ee60b4c6f2 100644--- a/server/pkg/controller/email/storage_warning_test.go+++ b/server/pkg/controller/email/storage_warning_test.go@@ -8,6 +8,7 @@ import ("github.com/ente-io/museum/ente"bonus "github.com/ente-io/museum/ente/storagebonus"+ "github.com/ente-io/museum/internal/testutil""github.com/ente-io/museum/pkg/repo""github.com/ente-io/museum/pkg/utils/billing""github.com/ente-io/museum/pkg/utils/rollout"@@ -858,6 +859,32 @@ func TestStorageWarningNotificationGroup(t *testing.T) {}}+func TestMergeStorageWarningCandidatesDeduplicatesAndKeepsFamilyPlan(t *testing.T) {+ candidates := mergeStorageWarningCandidates(+ []repo.StorageWarningCandidate{+ {RecipientID: 1, IsFamilyPlan: false},+ {RecipientID: 2, IsFamilyPlan: true},+ },+ []repo.StorageWarningCandidate{+ {RecipientID: 1, IsFamilyPlan: true},+ {RecipientID: 3, IsFamilyPlan: false},+ },+ )++ if len(candidates) != 3 {+ t.Fatalf("expected 3 merged candidates, got %d", len(candidates))+ }+ if candidates[0].RecipientID != 1 || !candidates[0].IsFamilyPlan {+ t.Fatalf("unexpected first candidate: %+v", candidates[0])+ }+ if candidates[1].RecipientID != 2 || !candidates[1].IsFamilyPlan {+ t.Fatalf("unexpected second candidate: %+v", candidates[1])+ }+ if candidates[2].RecipientID != 3 || candidates[2].IsFamilyPlan {+ t.Fatalf("unexpected third candidate: %+v", candidates[2])+ }+}+func TestStorageWarningShouldPreserveActiveOverageHistory(t *testing.T) {if !storageWarningShouldPreserveActiveOverageHistory(storageWarningSnapshot{CurrentBucket: storageWarningBucketActiveOverage, Bucket: storageWarningBucketNone}) {t.Fatal("expected active overage history to be preserved even when no stage is due")@@ -1049,6 +1076,268 @@ func TestProcessStorageWarningSnapshotScheduledDeletionResetsAccessAfterEmail(t}}+func TestProcessStorageWarningSnapshotScheduledDeletionSkipsDuringActiveLoginGrace(t *testing.T) {+ originalSendStorageWarningTemplatedEmail := sendStorageWarningTemplatedEmail+ originalPersistStorageWarningHistory := persistStorageWarningHistory+ defer func() {+ sendStorageWarningTemplatedEmail = originalSendStorageWarningTemplatedEmail+ persistStorageWarningHistory = originalPersistStorageWarningHistory+ }()++ sendStorageWarningTemplatedEmail = func(_ []string, _ string, _ string, _ string, _ string, _ string, _ map[string]interface{}, _ []map[string]interface{}) error {+ t.Fatal("did not expect email send during active login grace")+ return nil+ }+ persistStorageWarningHistory = func(_ *repo.NotificationHistoryRepository, _ storageWarningSnapshot, _ string) error {+ t.Fatal("did not expect history persistence during active login grace")+ return nil+ }++ now := int64(10) * storageWarningOneDayInMicroseconds+ graceSentAt := now - storageWarningOneDayInMicroseconds+ resetter := &recordingUserAccessResetter{}+ snapshot := storageWarningSnapshot{+ RecipientID: 12345,+ AccountEmail: "[email protected]",+ TotalUsage: storageWarningOverageThreshold + 10,+ AllottedStorage: 0,+ AvailableStorage: -10,+ Bucket: storageWarningBucketExpired,+ ExpiredStage: expiredWarningStageScheduledDeletion,+ EffectiveExpiry: 1,+ EvaluatedAt: now,+ WarningCycleStart: graceSentAt - storageWarningOneDayInMicroseconds,+ NotificationHistory: map[string]int64{+ storageWarningExpired119TemplateID: graceSentAt - storageWarningOneDayInMicroseconds,+ repo.StorageWarningLoginGraceTemplateID: graceSentAt,+ },+ }++ result, err := (&EmailNotificationController{UserAccessResetter: resetter}).processStorageWarningSnapshot(context.Background(), snapshot)+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if result != storageWarningProcessResultSkipped {+ t.Fatalf("unexpected result: got %q want %q", result, storageWarningProcessResultSkipped)+ }+ if resetter.callCount != 0 {+ t.Fatalf("expected no access reset during active login grace, got %d resets", resetter.callCount)+ }+}++func TestProcessStorageWarningSnapshotSkipsActiveOverageRestartDuringActiveLoginGrace(t *testing.T) {+ originalSendStorageWarningTemplatedEmail := sendStorageWarningTemplatedEmail+ originalPersistStorageWarningHistory := persistStorageWarningHistory+ defer func() {+ sendStorageWarningTemplatedEmail = originalSendStorageWarningTemplatedEmail+ persistStorageWarningHistory = originalPersistStorageWarningHistory+ }()++ sendStorageWarningTemplatedEmail = func(_ []string, _ string, _ string, _ string, _ string, _ string, _ map[string]interface{}, _ []map[string]interface{}) error {+ t.Fatal("did not expect warning email during active login grace")+ return nil+ }+ persistStorageWarningHistory = func(_ *repo.NotificationHistoryRepository, _ storageWarningSnapshot, _ string) error {+ t.Fatal("did not expect history persistence during active login grace")+ return nil+ }++ now := int64(10) * storageWarningOneDayInMicroseconds+ graceSentAt := now - storageWarningOneDayInMicroseconds+ resetter := &recordingUserAccessResetter{}+ snapshot := storageWarningSnapshot{+ RecipientID: 12345,+ AccountEmail: "[email protected]",+ TotalUsage: storageWarningOverageThreshold + 10,+ AllottedStorage: 0,+ AvailableStorage: -10,+ Bucket: storageWarningBucketActiveOverage,+ ActiveOverageStage: activeOverageWarningStage0,+ EvaluatedAt: now,+ WarningCycleStart: now,+ NotificationHistory: map[string]int64{repo.StorageWarningLoginGraceTemplateID: graceSentAt},+ }++ result, err := (&EmailNotificationController{UserAccessResetter: resetter}).processStorageWarningSnapshot(context.Background(), snapshot)+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if result != storageWarningProcessResultSkipped {+ t.Fatalf("unexpected result: got %q want %q", result, storageWarningProcessResultSkipped)+ }+ if resetter.callCount != 0 {+ t.Fatalf("expected no access reset during active login grace, got %d resets", resetter.callCount)+ }+}++func TestProcessStorageWarningSnapshotScheduledDeletionAllowsExpiredLoginGraceDespiteStaleCadence(t *testing.T) {+ originalSendStorageWarningTemplatedEmail := sendStorageWarningTemplatedEmail+ originalPersistStorageWarningHistory := persistStorageWarningHistory+ defer func() {+ sendStorageWarningTemplatedEmail = originalSendStorageWarningTemplatedEmail+ persistStorageWarningHistory = originalPersistStorageWarningHistory+ }()++ callOrder := []string{}+ sendStorageWarningTemplatedEmail = func(_ []string, _ string, _ string, _ string, _ string, _ string, _ map[string]interface{}, _ []map[string]interface{}) error {+ callOrder = append(callOrder, "send")+ return nil+ }+ persistStorageWarningHistory = func(_ *repo.NotificationHistoryRepository, _ storageWarningSnapshot, _ string) error {+ callOrder = append(callOrder, "persist")+ return nil+ }++ graceSentAt := int64(40) * storageWarningOneDayInMicroseconds+ now := graceSentAt + repo.StorageWarningLoginGraceDurationMicroseconds + 1+ resetter := &recordingUserAccessResetter{callOrder: &callOrder}+ snapshot := storageWarningSnapshot{+ RecipientID: 12345,+ AccountEmail: "[email protected]",+ TotalUsage: storageWarningOverageThreshold + 10,+ AllottedStorage: 0,+ AvailableStorage: -10,+ Bucket: storageWarningBucketExpired,+ ExpiredStage: expiredWarningStageScheduledDeletion,+ EffectiveExpiry: 1,+ EvaluatedAt: now,+ WarningCycleStart: 1,+ NotificationHistory: map[string]int64{+ storageWarningExpired119TemplateID: 1,+ repo.StorageWarningLoginGraceTemplateID: graceSentAt,+ },+ }++ result, err := (&EmailNotificationController{UserAccessResetter: resetter}).processStorageWarningSnapshot(context.Background(), snapshot)+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if result != storageWarningProcessResultSent {+ t.Fatalf("unexpected result: got %q want %q", result, storageWarningProcessResultSent)+ }+ if resetter.callCount != 1 {+ t.Fatalf("expected one access reset after login grace expiry, got %d", resetter.callCount)+ }+ if got, want := strings.Join(callOrder, ","), "send,reset,persist"; got != want {+ t.Fatalf("unexpected call order: got %q want %q", got, want)+ }+}++func TestProcessStorageWarningSnapshotExpiredLoginGraceReblocksActiveOverageRestart(t *testing.T) {+ originalSendStorageWarningTemplatedEmail := sendStorageWarningTemplatedEmail+ originalPersistStorageWarningHistory := persistStorageWarningHistory+ defer func() {+ sendStorageWarningTemplatedEmail = originalSendStorageWarningTemplatedEmail+ persistStorageWarningHistory = originalPersistStorageWarningHistory+ }()++ callOrder := []string{}+ sendStorageWarningTemplatedEmail = func(_ []string, _ string, _ string, _ string, _ string, templateName string, _ map[string]interface{}, _ []map[string]interface{}) error {+ callOrder = append(callOrder, "send")+ if templateName != storageWarningActiveOverageScheduledDeletionTemplate {+ t.Fatalf("unexpected template: got %q want %q", templateName, storageWarningActiveOverageScheduledDeletionTemplate)+ }+ return nil+ }+ var persistedTemplateID string+ persistStorageWarningHistory = func(_ *repo.NotificationHistoryRepository, _ storageWarningSnapshot, templateID string) error {+ callOrder = append(callOrder, "persist")+ persistedTemplateID = templateID+ return nil+ }++ graceSentAt := int64(40) * storageWarningOneDayInMicroseconds+ now := graceSentAt + repo.StorageWarningLoginGraceDurationMicroseconds + 1+ resetter := &recordingUserAccessResetter{callOrder: &callOrder}+ snapshot := storageWarningSnapshot{+ RecipientID: 12345,+ AccountEmail: "[email protected]",+ TotalUsage: storageWarningOverageThreshold + 10,+ AllottedStorage: 0,+ AvailableStorage: -10,+ Bucket: storageWarningBucketActiveOverage,+ ActiveOverageStage: activeOverageWarningStage0,+ EvaluatedAt: now,+ WarningCycleStart: now,+ NotificationHistory: map[string]int64{repo.StorageWarningLoginGraceTemplateID: graceSentAt},+ }++ result, err := (&EmailNotificationController{UserAccessResetter: resetter}).processStorageWarningSnapshot(context.Background(), snapshot)+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if result != storageWarningProcessResultSent {+ t.Fatalf("unexpected result: got %q want %q", result, storageWarningProcessResultSent)+ }+ if resetter.callCount != 1 {+ t.Fatalf("expected one access reset after login grace expiry, got %d", resetter.callCount)+ }+ if persistedTemplateID != repo.StorageWarningActiveOverageScheduledDeletionTemplateID {+ t.Fatalf("unexpected persisted template: got %q want %q", persistedTemplateID, repo.StorageWarningActiveOverageScheduledDeletionTemplateID)+ }+ if got, want := strings.Join(callOrder, ","), "send,reset,persist"; got != want {+ t.Fatalf("unexpected call order: got %q want %q", got, want)+ }+}++func TestProcessStorageWarningSnapshotClearsLoginGraceAfterRecovery(t *testing.T) {+ db := testutil.RequireTestDB(t)+ testutil.ResetTables(t, db)+ t.Cleanup(func() {+ testutil.ResetTables(t, db)+ })++ const userID int64 = 12348+ testutil.InsertUser(t, db, testutil.UserFixture{+ UserID: userID,+ Email: "[email protected]",+ CreationTime: 1,+ })+ graceSentAt := int64(40) * storageWarningOneDayInMicroseconds+ testutil.InsertNotificationHistory(t, db, testutil.NotificationHistoryFixture{+ UserID: userID,+ TemplateID: repo.StorageWarningLoginGraceTemplateID,+ SentTime: graceSentAt,+ })+ testutil.InsertNotificationHistory(t, db, testutil.NotificationHistoryFixture{+ UserID: userID,+ TemplateID: repo.StorageWarningExpiredScheduledDeletionTemplateID,+ SentTime: graceSentAt + 1,+ })++ notificationHistoryRepo := &repo.NotificationHistoryRepository{DB: db}+ result, err := (&EmailNotificationController{+ NotificationHistoryRepo: notificationHistoryRepo,+ }).processStorageWarningSnapshot(context.Background(), storageWarningSnapshot{+ RecipientID: userID,+ Bucket: storageWarningBucketNone,+ EvaluatedAt: graceSentAt + storageWarningOneDayInMicroseconds,+ NotificationHistory: map[string]int64{+ repo.StorageWarningLoginGraceTemplateID: graceSentAt,+ },+ })+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if result != storageWarningProcessResultSkipped {+ t.Fatalf("unexpected result: got %q want %q", result, storageWarningProcessResultSkipped)+ }+ graceSentAfterClear, err := notificationHistoryRepo.GetLastNotificationTime(userID, repo.StorageWarningLoginGraceTemplateID)+ if err != nil {+ t.Fatalf("failed to fetch login grace after recovery: %v", err)+ }+ if graceSentAfterClear != 0 {+ t.Fatalf("expected login grace to be cleared after recovery, got sent_time %d", graceSentAfterClear)+ }+ terminalRowExists, err := notificationHistoryRepo.IsStorageWarningDeletionScheduled(userID)+ if err != nil {+ t.Fatalf("failed to fetch terminal row after recovery: %v", err)+ }+ if terminalRowExists {+ t.Fatal("expected stale terminal row to be cleared after recovery")+ }+}+func TestBuildStorageWarningRunSummary(t *testing.T) {stats := newStorageWarningRunStats()stats.ProcessedUsers = 42diff --git a/server/pkg/controller/user/storage_warning_login_grace.go b/server/pkg/controller/user/storage_warning_login_grace.gonew file mode 100644index 0000000000..f2d23ff6b3--- /dev/null+++ b/server/pkg/controller/user/storage_warning_login_grace.go@@ -0,0 +1,85 @@+package user++import (+ stdtime "time"++ "github.com/ente-io/museum/pkg/repo"+ emailUtil "github.com/ente-io/museum/pkg/utils/email"+ "github.com/sirupsen/logrus"+)++const (+ storageWarningLoginGraceBaseTemplate = "ente_base.html"+ storageWarningLoginGraceTemplate = "storage-warning/storage_warning_login_grace.html"+ storageWarningLoginGraceSubject = "Temporary access restored to your Ente account"+ storageWarningLoginGraceFromName = "Ente"+ storageWarningLoginGraceFromEmail = "[email protected]"+)++var sendStorageWarningLoginGraceEmail = emailUtil.SendTemplatedEmailV2++// UnblockStorageWarningDeletionLogin grants a temporary login grace. It clears+// the terminal login-block rows, but it does not reverse every side effect of+// the original access reset such as sharing or family membership changes.+func (c *UserController) UnblockStorageWarningDeletionLogin(userID int64, logger *logrus.Entry) error {+ if c.NotificationHistoryRepo == nil {+ return nil+ }++ graceUntil, granted, err := c.NotificationHistoryRepo.GrantStorageWarningLoginGrace(userID)+ if err != nil {+ return err+ }+ if !granted {+ if logger != nil {+ logger.Info("Skipping storage warning login grace: no terminal login block found")+ }+ return nil+ }++ c.sendStorageWarningLoginGraceEmail(userID, graceUntil, logger)+ return nil+}++func (c *UserController) sendStorageWarningLoginGraceEmail(userID int64, graceUntil int64, logger *logrus.Entry) {+ if c.UserRepo == nil {+ if logger != nil {+ logger.Warn("Skipping storage warning login grace email: user repo is not configured")+ }+ return+ }++ user, err := c.UserRepo.GetUserByIDInternal(userID)+ if err != nil {+ if logger != nil {+ logger.WithError(err).Warn("Failed to fetch user for storage warning login grace email")+ }+ return+ }++ templateData := map[string]interface{}{+ "AccountEmail": user.Email,+ "GraceUntil": formatStorageWarningLoginGraceUntil(graceUntil),+ "GraceDays": repo.StorageWarningLoginGraceDays,+ }+ err = sendStorageWarningLoginGraceEmail(+ []string{user.Email},+ storageWarningLoginGraceFromName,+ storageWarningLoginGraceFromEmail,+ storageWarningLoginGraceSubject,+ storageWarningLoginGraceBaseTemplate,+ storageWarningLoginGraceTemplate,+ templateData,+ nil,+ )+ if err != nil && logger != nil {+ logger.WithError(err).Warn("Failed to send storage warning login grace email")+ }+}++func formatStorageWarningLoginGraceUntil(microseconds int64) string {+ if microseconds <= 0 {+ return ""+ }+ return stdtime.UnixMicro(microseconds).UTC().Format("January 2, 2006 at 15:04 UTC")+}diff --git a/server/pkg/controller/user/userauth.go b/server/pkg/controller/user/userauth.goindex 197e3e783f..0dae023dc3 100644--- a/server/pkg/controller/user/userauth.go+++ b/server/pkg/controller/user/userauth.go@@ -438,6 +438,21 @@ func (c *UserController) ensureStorageWarningDeletionLoginAllowed(userID int64,return stacktrace.Propagate(err, "failed to read storage warning deletion state")}if deletionScheduled {+ // Login blocking is terminal-row based. If a daily storage-warning run+ // races with an admin soft-unblock, the terminal row can reappear while+ // the grace window is still active, so login must honor grace directly.+ graceActive, graceUntil, err := c.NotificationHistoryRepo.IsStorageWarningLoginGraceActive(userID, time.Microseconds())+ if err != nil {+ return stacktrace.Propagate(err, "failed to read storage warning login grace")+ }+ if graceActive {+ log.WithFields(log.Fields{+ "user_id": userID,+ "app": app,+ "grace_until": graceUntil,+ }).Info("allowing login during storage warning grace")+ return nil+ }c.alertStorageWarningDeletionScheduledLoginBlock(userID, app)return storageWarningDeletionScheduledError()}diff --git a/server/pkg/controller/user/userauth_storage_warning_test.go b/server/pkg/controller/user/userauth_storage_warning_test.goindex eca48771bb..ebd17a0d27 100644--- a/server/pkg/controller/user/userauth_storage_warning_test.go+++ b/server/pkg/controller/user/userauth_storage_warning_test.go@@ -4,6 +4,9 @@ import ("testing""github.com/ente-io/museum/ente"+ "github.com/ente-io/museum/internal/testutil"+ "github.com/ente-io/museum/pkg/repo"+ "github.com/ente-io/museum/pkg/utils/time"logtest "github.com/sirupsen/logrus/hooks/test")@@ -30,3 +33,67 @@ func TestAlertStorageWarningDeletionScheduledLoginBlockLogsUserIDAndApp(t *testit.Fatalf("code field = %v, want %s", got, StorageWarningDeletionScheduledCode)}}++func TestEnsureStorageWarningDeletionLoginAllowedHonorsActiveLoginGrace(t *testing.T) {+ db := testutil.RequireTestDB(t)+ testutil.ResetTables(t, db)+ t.Cleanup(func() {+ testutil.ResetTables(t, db)+ })++ const userID int64 = 12345+ testutil.InsertUser(t, db, testutil.UserFixture{+ UserID: userID,+ Email: "[email protected]",+ CreationTime: 1,+ })+ testutil.InsertNotificationHistory(t, db, testutil.NotificationHistoryFixture{+ UserID: userID,+ TemplateID: repo.StorageWarningActiveOverageScheduledDeletionTemplateID,+ SentTime: 100,+ })+ testutil.InsertNotificationHistory(t, db, testutil.NotificationHistoryFixture{+ UserID: userID,+ TemplateID: repo.StorageWarningLoginGraceTemplateID,+ SentTime: time.Microseconds(),+ })++ err := (&UserController{+ NotificationHistoryRepo: &repo.NotificationHistoryRepository{DB: db},+ }).ensureStorageWarningDeletionLoginAllowed(userID, ente.Photos)+ if err != nil {+ t.Fatalf("expected active login grace to allow login, got %v", err)+ }+}++func TestEnsureStorageWarningDeletionLoginAllowedBlocksAfterLoginGraceExpires(t *testing.T) {+ db := testutil.RequireTestDB(t)+ testutil.ResetTables(t, db)+ t.Cleanup(func() {+ testutil.ResetTables(t, db)+ })++ const userID int64 = 12346+ testutil.InsertUser(t, db, testutil.UserFixture{+ UserID: userID,+ Email: "[email protected]",+ CreationTime: 1,+ })+ testutil.InsertNotificationHistory(t, db, testutil.NotificationHistoryFixture{+ UserID: userID,+ TemplateID: repo.StorageWarningExpiredScheduledDeletionTemplateID,+ SentTime: 100,+ })+ testutil.InsertNotificationHistory(t, db, testutil.NotificationHistoryFixture{+ UserID: userID,+ TemplateID: repo.StorageWarningLoginGraceTemplateID,+ SentTime: 200,+ })++ err := (&UserController{+ NotificationHistoryRepo: &repo.NotificationHistoryRepository{DB: db},+ }).ensureStorageWarningDeletionLoginAllowed(userID, ente.Photos)+ if err == nil {+ t.Fatal("expected expired login grace to block login")+ }+}diff --git a/server/pkg/repo/notificationhistory.go b/server/pkg/repo/notificationhistory.goindex 0c90a7ba3d..2b381d72e8 100644--- a/server/pkg/repo/notificationhistory.go+++ b/server/pkg/repo/notificationhistory.go@@ -1,6 +1,7 @@package repoimport (+ "context""database/sql""github.com/ente-io/stacktrace"@@ -16,6 +17,10 @@ type NotificationHistoryRepository struct {const (StorageWarningExpiredScheduledDeletionTemplateID = "storage_warning_expired_scheduled_deletion"StorageWarningActiveOverageScheduledDeletionTemplateID = "storage_warning_active_overage_scheduled_deletion"+ StorageWarningLoginGraceTemplateID = "storage_warning_login_grace_7d"+ StorageWarningLoginGraceNotificationGroup = "storage_warning_login_grace"+ StorageWarningLoginGraceDays = 7+ StorageWarningLoginGraceDurationMicroseconds = StorageWarningLoginGraceDays * 24 * time.MicroSecondsInOneHour)func (repo *NotificationHistoryRepository) GetLastNotificationTime(userID int64, templateID string) (int64, error) {@@ -106,6 +111,55 @@ func StorageWarningScheduledDeletionTemplateIDs() []string {}}+func StorageWarningLoginGraceUntil(sentAt int64) int64 {+ if sentAt <= 0 {+ return 0+ }+ return sentAt + StorageWarningLoginGraceDurationMicroseconds+}++func StorageWarningLoginGraceActive(sentAt int64, now int64) bool {+ graceUntil := StorageWarningLoginGraceUntil(sentAt)+ return graceUntil > 0 && now < graceUntil+}++// GetStorageWarningLoginGraceCandidates returns warning recipients with a+// grace marker, even if their current usage is below the normal candidate+// threshold. The daily job uses this to clear recovered grace rows or re-block+// after the grace window expires.+func (repo *NotificationHistoryRepository) GetStorageWarningLoginGraceCandidates(ctx context.Context) ([]StorageWarningCandidate, error) {+ rows, err := repo.DB.QueryContext(ctx, `+ SELECT+ nh.user_id AS recipient_id,+ u.family_admin_id IS NOT NULL AS is_family_plan+ FROM notification_history nh+ INNER JOIN users u+ ON u.user_id = nh.user_id+ WHERE+ nh.template_id = $1+ AND u.encrypted_email IS NOT NULL+ GROUP BY nh.user_id, u.family_admin_id+ ORDER BY nh.user_id+ `, StorageWarningLoginGraceTemplateID)+ if err != nil {+ return nil, stacktrace.Propagate(err, "failed to fetch storage warning login grace candidates")+ }+ defer rows.Close()++ candidates := make([]StorageWarningCandidate, 0)+ for rows.Next() {+ var candidate StorageWarningCandidate+ if err := rows.Scan(&candidate.RecipientID, &candidate.IsFamilyPlan); err != nil {+ return nil, stacktrace.Propagate(err, "failed to scan storage warning login grace candidate")+ }+ candidates = append(candidates, candidate)+ }+ if err := rows.Err(); err != nil {+ return nil, stacktrace.Propagate(err, "failed to iterate storage warning login grace candidates")+ }+ return candidates, nil+}+func (repo *NotificationHistoryRepository) HasAnyNotificationForTemplates(userID int64, templateIDs []string) (bool, error) {if len(templateIDs) == 0 {return false, nil@@ -138,3 +192,68 @@ func (repo *NotificationHistoryRepository) ClearStorageWarningDeletionScheduled(userID, pq.Array(StorageWarningScheduledDeletionTemplateIDs()))return stacktrace.Propagate(err, "failed to clear storage warning scheduled deletion history")}++func (repo *NotificationHistoryRepository) ClearStorageWarningLoginGrace(userID int64) error {+ _, err := repo.DB.Exec(+ `DELETE FROM notification_history+ WHERE user_id = $1+ AND template_id = $2`,+ userID, StorageWarningLoginGraceTemplateID)+ return stacktrace.Propagate(err, "failed to clear storage warning login grace")+}++func (repo *NotificationHistoryRepository) IsStorageWarningLoginGraceActive(userID int64, now int64) (bool, int64, error) {+ graceSentAt, err := repo.GetLastNotificationTime(userID, StorageWarningLoginGraceTemplateID)+ if err != nil {+ return false, 0, stacktrace.Propagate(err, "failed to read storage warning login grace")+ }+ graceUntil := StorageWarningLoginGraceUntil(graceSentAt)+ return StorageWarningLoginGraceActive(graceSentAt, now), graceUntil, nil+}++// GrantStorageWarningLoginGrace replaces terminal login-block rows with a+// soft-unblock marker. Duplicate grace rows are allowed; readers use the latest+// sent_time so a later admin action starts a fresh window.+func (repo *NotificationHistoryRepository) GrantStorageWarningLoginGrace(userID int64) (int64, bool, error) {+ now := time.Microseconds()+ tx, err := repo.DB.Begin()+ if err != nil {+ return 0, false, stacktrace.Propagate(err, "failed to start storage warning grace transaction")+ }+ defer tx.Rollback()++ result, err := tx.Exec(+ `DELETE FROM notification_history+ WHERE user_id = $1+ AND template_id = ANY($2)`,+ userID, pq.Array(StorageWarningScheduledDeletionTemplateIDs()))+ if err != nil {+ return 0, false, stacktrace.Propagate(err, "failed to clear storage warning scheduled deletion history")+ }+ deletedRows, err := result.RowsAffected()+ if err != nil {+ return 0, false, stacktrace.Propagate(err, "failed to read cleared storage warning scheduled deletion count")+ }+ if deletedRows == 0 {+ if err := tx.Commit(); err != nil {+ return 0, false, stacktrace.Propagate(err, "failed to commit storage warning grace transaction")+ }+ return 0, false, nil+ }++ _, err = tx.Exec(+ `INSERT INTO notification_history(user_id, template_id, sent_time, notification_group)+ VALUES($1, $2, $3, $4)`,+ userID,+ StorageWarningLoginGraceTemplateID,+ now,+ StorageWarningLoginGraceNotificationGroup)+ if err != nil {+ return 0, false, stacktrace.Propagate(err, "failed to grant storage warning login grace")+ }++ if err := tx.Commit(); err != nil {+ return 0, false, stacktrace.Propagate(err, "failed to commit storage warning grace transaction")+ }+ return now + StorageWarningLoginGraceDurationMicroseconds, true, nil+}diff --git a/server/pkg/repo/notificationhistory_test.go b/server/pkg/repo/notificationhistory_test.gonew file mode 100644index 0000000000..a57641956a--- /dev/null+++ b/server/pkg/repo/notificationhistory_test.go@@ -0,0 +1,173 @@+package repo++import (+ "context"+ "testing"++ "github.com/ente-io/museum/internal/testutil"+ "github.com/lib/pq"+)++func TestGrantStorageWarningLoginGraceClearsTerminalRowsAndInsertsGrace(t *testing.T) {+ db := getStorageWarningRepoTestDB(t)+ const userID int64 = 12345+ insertStorageWarningTestUser(t, db, userID, nil)+ testutil.InsertNotificationHistory(t, db, testutil.NotificationHistoryFixture{+ UserID: userID,+ TemplateID: StorageWarningExpiredScheduledDeletionTemplateID,+ SentTime: 100,+ })+ testutil.InsertNotificationHistory(t, db, testutil.NotificationHistoryFixture{+ UserID: userID,+ TemplateID: StorageWarningActiveOverageScheduledDeletionTemplateID,+ SentTime: 200,+ })++ graceUntil, granted, err := (&NotificationHistoryRepository{DB: db}).GrantStorageWarningLoginGrace(userID)+ if err != nil {+ t.Fatalf("GrantStorageWarningLoginGrace() error = %v", err)+ }+ if !granted {+ t.Fatal("expected login grace to be granted")+ }+ if graceUntil <= StorageWarningLoginGraceDurationMicroseconds {+ t.Fatalf("unexpected graceUntil: %d", graceUntil)+ }++ var terminalRows int+ if err := db.QueryRow(+ `SELECT count(*)+ FROM notification_history+ WHERE user_id = $1+ AND template_id = ANY($2)`,+ userID,+ pq.Array(StorageWarningScheduledDeletionTemplateIDs()),+ ).Scan(&terminalRows); err != nil {+ t.Fatalf("failed to count terminal rows: %v", err)+ }+ if terminalRows != 0 {+ t.Fatalf("terminal rows = %d, want 0", terminalRows)+ }++ var graceRows int+ var notificationGroup string+ if err := db.QueryRow(+ `SELECT count(*), max(notification_group)+ FROM notification_history+ WHERE user_id = $1+ AND template_id = $2`,+ userID,+ StorageWarningLoginGraceTemplateID,+ ).Scan(&graceRows, ¬ificationGroup); err != nil {+ t.Fatalf("failed to read grace row: %v", err)+ }+ if graceRows != 1 {+ t.Fatalf("grace rows = %d, want 1", graceRows)+ }+ if notificationGroup != StorageWarningLoginGraceNotificationGroup {+ t.Fatalf("notification group = %q, want %q", notificationGroup, StorageWarningLoginGraceNotificationGroup)+ }+}++func TestGrantStorageWarningLoginGraceSkipsWhenNoTerminalRowsExist(t *testing.T) {+ db := getStorageWarningRepoTestDB(t)+ const userID int64 = 12349+ insertStorageWarningTestUser(t, db, userID, nil)++ graceUntil, granted, err := (&NotificationHistoryRepository{DB: db}).GrantStorageWarningLoginGrace(userID)+ if err != nil {+ t.Fatalf("GrantStorageWarningLoginGrace() error = %v", err)+ }+ if granted {+ t.Fatal("expected login grace to be skipped when no terminal rows exist")+ }+ if graceUntil != 0 {+ t.Fatalf("graceUntil = %d, want 0", graceUntil)+ }++ active, _, err := (&NotificationHistoryRepository{DB: db}).IsStorageWarningLoginGraceActive(userID, 101)+ if err != nil {+ t.Fatalf("IsStorageWarningLoginGraceActive() error = %v", err)+ }+ if active {+ t.Fatal("expected no active login grace")+ }+}++func TestStorageWarningLoginGraceActiveUsesLatestSentTime(t *testing.T) {+ db := getStorageWarningRepoTestDB(t)+ const userID int64 = 12346+ insertStorageWarningTestUser(t, db, userID, nil)+ oldSentAt := int64(10)+ newSentAt := oldSentAt + StorageWarningLoginGraceDurationMicroseconds + 100+ testutil.InsertNotificationHistory(t, db, testutil.NotificationHistoryFixture{+ UserID: userID,+ TemplateID: StorageWarningLoginGraceTemplateID,+ SentTime: oldSentAt,+ })+ testutil.InsertNotificationHistory(t, db, testutil.NotificationHistoryFixture{+ UserID: userID,+ TemplateID: StorageWarningLoginGraceTemplateID,+ SentTime: newSentAt,+ })++ active, graceUntil, err := (&NotificationHistoryRepository{DB: db}).IsStorageWarningLoginGraceActive(userID, newSentAt+1)+ if err != nil {+ t.Fatalf("IsStorageWarningLoginGraceActive() error = %v", err)+ }+ if !active {+ t.Fatal("expected latest login grace to be active")+ }+ if want := newSentAt + StorageWarningLoginGraceDurationMicroseconds; graceUntil != want {+ t.Fatalf("graceUntil = %d, want %d", graceUntil, want)+ }+}++func TestClearStorageWarningLoginGrace(t *testing.T) {+ db := getStorageWarningRepoTestDB(t)+ const userID int64 = 12347+ insertStorageWarningTestUser(t, db, userID, nil)+ testutil.InsertNotificationHistory(t, db, testutil.NotificationHistoryFixture{+ UserID: userID,+ TemplateID: StorageWarningLoginGraceTemplateID,+ SentTime: 100,+ })++ if err := (&NotificationHistoryRepository{DB: db}).ClearStorageWarningLoginGrace(userID); err != nil {+ t.Fatalf("ClearStorageWarningLoginGrace() error = %v", err)+ }++ active, graceUntil, err := (&NotificationHistoryRepository{DB: db}).IsStorageWarningLoginGraceActive(userID, 101)+ if err != nil {+ t.Fatalf("IsStorageWarningLoginGraceActive() error = %v", err)+ }+ if active || graceUntil != 0 {+ t.Fatalf("unexpected grace after clear: active=%v graceUntil=%d", active, graceUntil)+ }+}++func TestGetStorageWarningLoginGraceCandidatesIncludesUsersBelowThreshold(t *testing.T) {+ db := getStorageWarningRepoTestDB(t)+ const userID int64 = 12348+ insertStorageWarningTestUser(t, db, userID, nil)+ insertStorageWarningTestUsage(t, db, userID, 5*testGiB)+ testutil.InsertNotificationHistory(t, db, testutil.NotificationHistoryFixture{+ UserID: userID,+ TemplateID: StorageWarningLoginGraceTemplateID,+ SentTime: 100,+ })++ candidates, err := (&NotificationHistoryRepository{DB: db}).GetStorageWarningLoginGraceCandidates(context.Background())+ if err != nil {+ t.Fatalf("GetStorageWarningLoginGraceCandidates() error = %v", err)+ }+ if len(candidates) != 1 {+ t.Fatalf("expected 1 grace candidate, got %d", len(candidates))+ }+ if candidates[0].RecipientID != userID {+ t.Fatalf("unexpected candidate: got %d want %d", candidates[0].RecipientID, userID)+ }+ if candidates[0].IsFamilyPlan {+ t.Fatal("expected grace individual candidate to not be marked as family plan")+ }+}diff --git a/server/pkg/utils/email/storage_warning_template_test.go b/server/pkg/utils/email/storage_warning_template_test.goindex 6f653ed716..add216ceb4 100644--- a/server/pkg/utils/email/storage_warning_template_test.go+++ b/server/pkg/utils/email/storage_warning_template_test.go@@ -14,10 +14,13 @@ func TestStorageWarningTemplatesIncludeAccountEmail(t *testing.T) {"AccountEmail": "[email protected]","AutoDeleteDate": "April 1, 2026","ExpiryDate": "March 1, 2026",+ "GraceUntil": "April 8, 2026 at 12:00 UTC",+ "GraceDays": 7,}templateNames := []string{"storage-warning/storage_warning_active_overage.html","storage-warning/storage_warning_expired.html",+ "storage-warning/storage_warning_login_grace.html",}for _, templateName := range templateNames {