π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Improve logging
Neeraj Gupta4006f7784ef0
diff --git a/server/pkg/controller/user/ott_send_limiter.go b/server/pkg/controller/user/ott_send_limiter.gonew file mode 100644index 0000000000..67da124415--- /dev/null+++ b/server/pkg/controller/user/ott_send_limiter.go@@ -0,0 +1,108 @@+package user++import (+ "sync"+ "time"+)++const (+ ottSendAttackWindow = 5 * time.Minute+ ottSendIPCooldown = 5 * time.Minute+ ottSendElevatedThreshold = 50+ ottSendSevereThreshold = 200+ ottSendSevereBlockDuration = 10 * time.Minute++ ottSendElevatedAlert = "OTT send volume reached 50/5m; limiting each IP to one request per 5m"+ ottSendSevereAlert = "OTT send volume reached 200/5m; blocking all OTT sends for 10m"+)++type ottSendLimiterDecision struct {+ allowed bool+ alert string+}++type OTTSendLimiter struct {+ mu sync.Mutex++ now func() time.Time++ attempts []time.Time+ ipNextAllowed map[string]time.Time+ blockedUntil time.Time+}++func NewOTTSendLimiter() *OTTSendLimiter {+ return newOTTSendLimiter(time.Now)+}++func newOTTSendLimiter(now func() time.Time) *OTTSendLimiter {+ return &OTTSendLimiter{+ now: now,+ ipNextAllowed: make(map[string]time.Time),+ }+}++func (l *OTTSendLimiter) IsGloballyBlocked() bool {+ l.mu.Lock()+ defer l.mu.Unlock()++ return l.isGloballyBlockedAt(l.now())+}++func (l *OTTSendLimiter) Allow(ip string) ottSendLimiterDecision {+ l.mu.Lock()+ defer l.mu.Unlock()++ now := l.now()+ l.prune(now)+ if l.isGloballyBlockedAt(now) {+ return ottSendLimiterDecision{}+ }++ l.attempts = append(l.attempts, now)+ if len(l.attempts) >= ottSendSevereThreshold {+ l.blockedUntil = now.Add(ottSendSevereBlockDuration)+ return ottSendLimiterDecision{alert: ottSendSevereAlert}+ }++ decision := ottSendLimiterDecision{allowed: true}+ if len(l.attempts) >= ottSendElevatedThreshold {+ if len(l.attempts) == ottSendElevatedThreshold {+ decision.alert = ottSendElevatedAlert+ }+ if nextAllowed, ok := l.ipNextAllowed[ip]; ok && now.Before(nextAllowed) {+ decision.allowed = false+ return decision+ }+ }++ l.ipNextAllowed[ip] = now.Add(ottSendIPCooldown)+ return decision+}++func (l *OTTSendLimiter) isGloballyBlockedAt(now time.Time) bool {+ if now.Before(l.blockedUntil) {+ return true+ }+ if !l.blockedUntil.IsZero() {+ l.blockedUntil = time.Time{}+ }+ return false+}++func (l *OTTSendLimiter) prune(now time.Time) {+ cutoff := now.Add(-ottSendAttackWindow)+ firstRecent := 0+ for firstRecent < len(l.attempts) && !l.attempts[firstRecent].After(cutoff) {+ firstRecent+++ }+ if firstRecent > 0 {+ l.attempts = l.attempts[firstRecent:]+ }++ for ip, nextAllowed := range l.ipNextAllowed {+ if !now.Before(nextAllowed) {+ delete(l.ipNextAllowed, ip)+ }+ }+}diff --git a/server/pkg/controller/user/ott_send_limiter_test.go b/server/pkg/controller/user/ott_send_limiter_test.gonew file mode 100644index 0000000000..bcde7f61aa--- /dev/null+++ b/server/pkg/controller/user/ott_send_limiter_test.go@@ -0,0 +1,117 @@+package user++import (+ "fmt"+ "testing"+ "time"+)++func TestOTTSendLimiterAllowsRepeatedIPBelowElevatedThreshold(t *testing.T) {+ now := time.Unix(1000, 0)+ limiter := newOTTSendLimiter(func() time.Time { return now })++ decision := limiter.Allow("203.0.113.1")+ if !decision.allowed || decision.alert != "" {+ t.Fatalf("first request decision=%+v, want allowed only", decision)+ }++ decision = limiter.Allow("203.0.113.1")+ if !decision.allowed || decision.alert != "" {+ t.Fatalf("second request below threshold decision=%+v, want allowed only", decision)+ }+}++func TestOTTSendLimiterBlocksRepeatedIPInElevatedMode(t *testing.T) {+ now := time.Unix(1000, 0)+ limiter := newOTTSendLimiter(func() time.Time { return now })++ for i := 0; i < ottSendElevatedThreshold-1; i++ {+ decision := limiter.Allow(fmt.Sprintf("203.0.113.%d", i+1))+ if !decision.allowed || decision.alert != "" {+ t.Fatalf("seed request %d decision=%+v, want allowed only", i, decision)+ }+ }++ decision := limiter.Allow("198.51.100.10")+ if !decision.allowed || decision.alert != ottSendElevatedAlert {+ t.Fatalf("first elevated request decision=%+v, want allowed with elevated activation", decision)+ }++ decision = limiter.Allow("198.51.100.10")+ if decision.allowed || decision.alert != "" {+ t.Fatalf("repeated elevated request decision=%+v, want blocked without activation", decision)+ }++ decision = limiter.Allow("198.51.100.51")+ if !decision.allowed || decision.alert != "" {+ t.Fatalf("request %d decision=%+v, want allowed without repeated alert", ottSendElevatedThreshold+1, decision)+ }+}++func TestOTTSendLimiterActivatesGlobalBlock(t *testing.T) {+ now := time.Unix(1000, 0)+ limiter := newOTTSendLimiter(func() time.Time { return now })++ for i := 0; i < ottSendSevereThreshold-1; i++ {+ decision := limiter.Allow(fmt.Sprintf("203.0.113.%d", i))+ if !decision.allowed || decision.alert == ottSendSevereAlert {+ t.Fatalf("seed request %d decision=%+v, want allowed without severe activation", i, decision)+ }+ }++ decision := limiter.Allow("198.51.100.10")+ if decision.allowed || decision.alert != ottSendSevereAlert {+ t.Fatalf("severe request decision=%+v, want blocked with severe activation", decision)+ }+ if !limiter.IsGloballyBlocked() {+ t.Fatal("limiter should be globally blocked after severe threshold")+ }+}++func TestOTTSendLimiterGlobalBlockExpires(t *testing.T) {+ now := time.Unix(1000, 0)+ limiter := newOTTSendLimiter(func() time.Time { return now })++ for i := 0; i < ottSendSevereThreshold; i++ {+ limiter.Allow(fmt.Sprintf("203.0.113.%d", i))+ }+ if !limiter.IsGloballyBlocked() {+ t.Fatal("limiter should be globally blocked")+ }++ now = now.Add(ottSendSevereBlockDuration - time.Nanosecond)+ if !limiter.IsGloballyBlocked() {+ t.Fatal("limiter should remain globally blocked before expiry")+ }++ now = now.Add(2 * time.Nanosecond)+ if limiter.IsGloballyBlocked() {+ t.Fatal("limiter should allow requests after global block expiry")+ }+}++func TestOTTSendLimiterPrunesExpiredAttemptsAndIPCooldowns(t *testing.T) {+ now := time.Unix(1000, 0)+ limiter := newOTTSendLimiter(func() time.Time { return now })++ decision := limiter.Allow("203.0.113.1")+ if !decision.allowed || decision.alert != "" {+ t.Fatalf("initial request decision=%+v, want allowed only", decision)+ }++ now = now.Add(ottSendAttackWindow + time.Nanosecond)+ decision = limiter.Allow("198.51.100.10")+ if !decision.allowed || decision.alert != "" {+ t.Fatalf("fresh request decision=%+v, want allowed only", decision)+ }++ if got := len(limiter.attempts); got != 1 {+ t.Fatalf("attempt count after prune = %d, want 1", got)+ }+ if _, ok := limiter.ipNextAllowed["203.0.113.1"]; ok {+ t.Fatal("expired IP cooldown should be pruned")+ }+ if _, ok := limiter.ipNextAllowed["198.51.100.10"]; !ok {+ t.Fatal("fresh IP cooldown should remain")+ }+}diff --git a/server/pkg/controller/user/user.go b/server/pkg/controller/user/user.goindex 3e867fb940..a6ea8c9846 100644--- a/server/pkg/controller/user/user.go+++ b/server/pkg/controller/user/user.go@@ -64,6 +64,7 @@ type UserController struct {UserCacheController *usercache.ControllerSRPLimiter *limiter.LimiterOTTLimiter *limiter.Limiter+ OTTSendLimiter *OTTSendLimiter}const (@@ -135,6 +136,7 @@ func NewUserController() *UserController {srpLimiter := util.NewRateLimiter("100-H")ottLimiter := util.NewRateLimiter("100-H")+ ottSendLimiter := NewOTTSendLimiter()return &UserController{UserRepo: userRepo,UsageRepo: usageRepo,@@ -164,6 +166,7 @@ func NewUserController(UserCacheController: userCacheController,SRPLimiter: srpLimiter,OTTLimiter: ottLimiter,+ OTTSendLimiter: ottSendLimiter,}}diff --git a/server/pkg/controller/user/userauth.go b/server/pkg/controller/user/userauth.goindex 714b56006a..f47dd7f9b2 100644--- a/server/pkg/controller/user/userauth.go+++ b/server/pkg/controller/user/userauth.go@@ -93,6 +93,10 @@ func hardcodedOTTForEmail(hardCodedOTT HardCodedOTT, email string) string {// SendEmailOTT generates and sends an OTT to the provided email addressfunc (c *UserController) SendEmailOTT(context *gin.Context, email string, purpose string, mobile bool) error {+ if c.OTTSendLimiter.IsGloballyBlocked() {+ return stacktrace.Propagate(ente.ErrTooManyBadRequest, "too many OTT requests")+ }+shouldSend, err := c.validateSendOTT(context, email, purpose)if err != nil {return err@@ -100,6 +104,32 @@ func (c *UserController) SendEmailOTT(context *gin.Context, email string, purposif !shouldSend {return nil}+ emailHash, err := crypto.GetHash(email, c.HashingKey)+ if err != nil {+ return stacktrace.Propagate(err, "")+ }+ // check if user has already requested for more than 10 codes in last 10mins+ app := auth.GetApp(context)+ otts, err := c.UserAuthRepo.GetValidOTTs(emailHash, app)+ if err != nil {+ return stacktrace.Propagate(err, "")+ }+ if len(otts) >= OTTActiveCodeLimit {+ alertMsg := fmt.Sprintf("Too many OTT requests for %s in %d minutes",+ emailUtil.GetMaskedEmailWithHint(email),+ OTTValidityDurationInMicroSeconds/(60*1000000))+ go c.DiscordController.NotifyPotentialAbuse(alertMsg)+ return stacktrace.Propagate(ente.ErrTooManyBadRequest, "too many OTT requests")+ }++ decision := c.OTTSendLimiter.Allow(network.GetClientIP(context))+ if decision.alert != "" {+ go c.DiscordController.NotifyPotentialAbuse(decision.alert)+ }+ if !decision.allowed {+ return stacktrace.Propagate(ente.ErrTooManyBadRequest, "too many OTT requests")+ }+ott, err := random.GenerateSixDigitOtp()if err != nil {return stacktrace.Propagate(err, "")@@ -114,20 +144,6 @@ func (c *UserController) SendEmailOTT(context *gin.Context, email string, purposott = hardCodedOTT}}- emailHash, err := crypto.GetHash(email, c.HashingKey)- if err != nil {- return stacktrace.Propagate(err, "")- }- // check if user has already requested for more than 10 codes in last 10mins- app := auth.GetApp(context)- otts, _ := c.UserAuthRepo.GetValidOTTs(emailHash, app)- if len(otts) >= OTTActiveCodeLimit {- alertMsg := fmt.Sprintf("Too many OTT requests for %s in %d minutes",- emailUtil.GetMaskedEmailWithHint(email),- OTTValidityDurationInMicroSeconds/(60*1000000))- go c.DiscordController.NotifyPotentialAbuse(alertMsg)- return stacktrace.Propagate(ente.ErrTooManyBadRequest, "too many OTT requests")- }err = c.UserAuthRepo.AddOTT(emailHash, app, ott, time.Microseconds()+OTTValidityDurationInMicroSeconds)if !hasHardcodedOTT {diff --git a/server/pkg/controller/user/userauth_send_ott_test.go b/server/pkg/controller/user/userauth_send_ott_test.goindex e3f33917c8..6993b59332 100644--- a/server/pkg/controller/user/userauth_send_ott_test.go+++ b/server/pkg/controller/user/userauth_send_ott_test.go@@ -3,15 +3,21 @@ package userimport ("database/sql""errors"+ "fmt"+ "net""net/http""net/http/httptest"+ "strings""testing"+ "time""github.com/ente/museum/ente""github.com/ente/museum/internal/testutil"+ discordCtrl "github.com/ente/museum/pkg/controller/discord""github.com/ente/museum/pkg/repo"util "github.com/ente/museum/pkg/utils""github.com/ente/museum/pkg/utils/crypto"+ timeUtil "github.com/ente/museum/pkg/utils/time""github.com/gin-gonic/gin")@@ -156,6 +162,7 @@ func TestSendEmailOTTDoesNotStoreOTTWhenDisclosureErrorSwallowed(t *testing.T) {})const email = "[email protected]"+ limiter := NewOTTSendLimiter()userAuthRepo := &repo.UserAuthRepository{DB: db}controller := &UserController{UserRepo: &repo.UserRepository{@@ -163,9 +170,10 @@ func TestSendEmailOTTDoesNotStoreOTTWhenDisclosureErrorSwallowed(t *testing.T) {SecretEncryptionKey: testutil.SecretEncryptionKey(),HashingKey: testutil.HashingKey(),},- UserAuthRepo: userAuthRepo,- HashingKey: testutil.HashingKey(),- OTTLimiter: util.NewRateLimiter("1-H"),+ UserAuthRepo: userAuthRepo,+ HashingKey: testutil.HashingKey(),+ OTTLimiter: util.NewRateLimiter("1-H"),+ OTTSendLimiter: limiter,HardCodedOTT: HardCodedOTT{Emails: []HardCodedOTTEmail{{@@ -197,6 +205,178 @@ func TestSendEmailOTTDoesNotStoreOTTWhenDisclosureErrorSwallowed(t *testing.T) {if len(otts) != 0 {t.Fatalf("swallowed disclosure error should not store ott, got %v", otts)}++ if got := len(limiter.attempts); got != 0 {+ t.Fatalf("disclosure-swallowed requests should not affect limiter attempts, got %d", got)+ }+ if got := len(limiter.ipNextAllowed); got != 0 {+ t.Fatalf("disclosure-swallowed requests should not affect IP cooldowns, got %d", got)+ }+}++func TestSendEmailOTTBlockedBySendLimiterDoesNotStoreOTT(t *testing.T) {+ testutil.WithServerRoot(t)+ db := testutil.RequireTestDB(t)+ testutil.ResetTables(t, db)+ t.Cleanup(func() {+ testutil.ResetTables(t, db)+ })++ now := timeUtil.Microseconds()+ limiter := newOTTSendLimiter(func() time.Time {+ return time.UnixMicro(now)+ })+ const ip = "198.51.100.10"+ for i := 0; i < ottSendElevatedThreshold-1; i++ {+ decision := limiter.Allow(fmt.Sprintf("203.0.113.%d", i))+ if !decision.allowed || decision.alert == ottSendSevereAlert {+ t.Fatalf("seed request %d decision=%+v, want allowed without severe activation", i, decision)+ }+ }+ decision := limiter.Allow(ip)+ if !decision.allowed || decision.alert != ottSendElevatedAlert {+ t.Fatalf("first elevated request decision=%+v, want allowed with elevated activation", decision)+ }++ const email = "[email protected]"+ userAuthRepo := &repo.UserAuthRepository{DB: db}+ controller := &UserController{+ UserRepo: &repo.UserRepository{+ DB: db,+ SecretEncryptionKey: testutil.SecretEncryptionKey(),+ HashingKey: testutil.HashingKey(),+ },+ UserAuthRepo: userAuthRepo,+ HashingKey: testutil.HashingKey(),+ OTTSendLimiter: limiter,+ HardCodedOTT: HardCodedOTT{+ Emails: []HardCodedOTTEmail{+ {+ Email: email,+ Value: "123456",+ },+ },+ },+ }++ err := controller.SendEmailOTT(newSendOTTTestContextWithIP(ip), email, ente.SignUpOTTPurpose, false)+ if !errors.Is(err, ente.ErrTooManyBadRequest) {+ t.Fatalf("SendEmailOTT error = %v, want %v", err, ente.ErrTooManyBadRequest)+ }++ emailHash, err := crypto.GetHash(email, testutil.HashingKey())+ if err != nil {+ t.Fatalf("failed to hash email: %v", err)+ }+ otts, err := userAuthRepo.GetValidOTTs(emailHash, ente.Photos)+ if err != nil {+ t.Fatalf("failed to get valid otts: %v", err)+ }+ if len(otts) != 0 {+ t.Fatalf("blocked send should not store ott, got %v", otts)+ }+}++func TestSendEmailOTTActiveCapDoesNotTouchSendLimiter(t *testing.T) {+ testutil.WithServerRoot(t)+ db := testutil.RequireTestDB(t)+ testutil.ResetTables(t, db)+ t.Cleanup(func() {+ testutil.ResetTables(t, db)+ })++ const email = "[email protected]"+ emailHash, err := crypto.GetHash(email, testutil.HashingKey())+ if err != nil {+ t.Fatalf("failed to hash email: %v", err)+ }+ userAuthRepo := &repo.UserAuthRepository{DB: db}+ for i := 0; i < OTTActiveCodeLimit; i++ {+ err := userAuthRepo.AddOTT(+ emailHash,+ ente.Photos,+ fmt.Sprintf("%06d", i),+ timeUtil.Microseconds()+OTTValidityDurationInMicroSeconds,+ )+ if err != nil {+ t.Fatalf("failed to seed active OTT %d: %v", i, err)+ }+ }++ limiter := NewOTTSendLimiter()+ controller := &UserController{+ UserRepo: &repo.UserRepository{+ DB: db,+ SecretEncryptionKey: testutil.SecretEncryptionKey(),+ HashingKey: testutil.HashingKey(),+ },+ UserAuthRepo: userAuthRepo,+ HashingKey: testutil.HashingKey(),+ DiscordController: newSendOTTTestDiscordController(),+ OTTSendLimiter: limiter,+ }++ err = controller.SendEmailOTT(newSendOTTTestContext(), email, ente.SignUpOTTPurpose, false)+ if !errors.Is(err, ente.ErrTooManyBadRequest) {+ t.Fatalf("SendEmailOTT error = %v, want %v", err, ente.ErrTooManyBadRequest)+ }+ if got := len(limiter.attempts); got != 0 {+ t.Fatalf("active-code-cap failure should not affect limiter attempts, got %d", got)+ }+ if got := len(limiter.ipNextAllowed); got != 0 {+ t.Fatalf("active-code-cap failure should not affect IP cooldowns, got %d", got)+ }+}++func TestSendEmailOTTReturnsValidOTTLookupError(t *testing.T) {+ testutil.WithServerRoot(t)+ db := testutil.RequireTestDB(t)+ testutil.ResetTables(t, db)+ t.Cleanup(func() {+ testutil.ResetTables(t, db)+ })++ closedDB, err := sql.Open("postgres", "sslmode=disable")+ if err != nil {+ t.Fatalf("failed to open closed test DB handle: %v", err)+ }+ if err := closedDB.Close(); err != nil {+ t.Fatalf("failed to close test DB handle: %v", err)+ }++ limiter := NewOTTSendLimiter()+ controller := &UserController{+ UserRepo: &repo.UserRepository{+ DB: db,+ SecretEncryptionKey: testutil.SecretEncryptionKey(),+ HashingKey: testutil.HashingKey(),+ },+ UserAuthRepo: &repo.UserAuthRepository{DB: closedDB},+ HashingKey: testutil.HashingKey(),+ OTTSendLimiter: limiter,+ }++ err = controller.SendEmailOTT(newSendOTTTestContext(), "[email protected]", ente.SignUpOTTPurpose, false)+ if err == nil || !strings.Contains(err.Error(), "database is closed") {+ t.Fatalf("SendEmailOTT error = %v, want database is closed", err)+ }+ if got := len(limiter.attempts); got != 0 {+ t.Fatalf("GetValidOTTs failure should not affect limiter attempts, got %d", got)+ }+}++func TestSendEmailOTTGlobalBlockShortCircuits(t *testing.T) {+ now := time.Unix(1000, 0)+ limiter := newOTTSendLimiter(func() time.Time { return now })+ limiter.blockedUntil = now.Add(time.Minute)+ controller := &UserController{+ OTTSendLimiter: limiter,+ }++ err := controller.SendEmailOTT(newSendOTTTestContext(), "[email protected]", ente.SignUpOTTPurpose, false)+ if !errors.Is(err, ente.ErrTooManyBadRequest) {+ t.Fatalf("SendEmailOTT error = %v, want %v", err, ente.ErrTooManyBadRequest)+ }}func newSendOTTTestContext() *gin.Context {@@ -207,6 +387,16 @@ func newSendOTTTestContext() *gin.Context {return ctx}+func newSendOTTTestContextWithIP(ip string) *gin.Context {+ ctx := newSendOTTTestContext()+ ctx.Request.RemoteAddr = net.JoinHostPort(ip, "1234")+ return ctx+}++func newSendOTTTestDiscordController() *discordCtrl.DiscordController {+ return discordCtrl.NewDiscordController(nil, "test", "test")+}+func insertCompleteSendOTTTestUser(t *testing.T, db *sql.DB, userRepo *repo.UserRepository, userID int64, email string) {t.Helper()insertedUserID := testutil.InsertUser(t, db, testutil.UserFixture{diff --git a/server/pkg/middleware/rate_limit.go b/server/pkg/middleware/rate_limit.goindex ee7596c4cd..e876097643 100644--- a/server/pkg/middleware/rate_limit.go+++ b/server/pkg/middleware/rate_limit.go@@ -95,7 +95,7 @@ func (r *RateLimitMiddleware) APIRateLimitMiddleware(urlSanitizer func(_ *gin.Coreturn}if limitContext.Reached {- msg := fmt.Sprintf("Global rate limit breached %s", requestPath)+ msg := fmt.Sprintf("π Global rate limit: %s", requestPath)go r.discordCtrl.NotifyPotentialAbuse(msg)log.Error(msg)c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{"error": "Rate limit breached, try later"})@@ -113,7 +113,7 @@ func (r *RateLimitMiddleware) APIRateLimitMiddleware(urlSanitizer func(_ *gin.Coreturn}if limitContext.Reached {- go r.discordCtrl.NotifyPotentialAbuse(fmt.Sprintf("Rate limit breached %s", requestPath))+ go r.discordCtrl.NotifyPotentialAbuse(fmt.Sprintf("π IP rate limit: %s", requestPath))log.Error(fmt.Sprintf("Rate limit breached %s", key))c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{"error": "Rate limit breached, try later"})return@@ -143,7 +143,7 @@ func (r *RateLimitMiddleware) APIRateLimitForUserMiddleware(urlSanitizer func(_return}if limitContext.Reached {- msg := fmt.Sprintf("Rate limit breached %d for path: %s", userID, requestPath)+ msg := fmt.Sprintf("π€ User rate limit: %s user=%d", requestPath, userID)go r.discordCtrl.NotifyPotentialAbuse(msg)log.Error(msg)c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{"error": "Rate limit breached, try later"})