π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Invalidate public link caches
Neeraj Guptaabfd47890447
diff --git a/server/cmd/museum/main.go b/server/cmd/museum/main.goindex 17df36df66..8be1231030 100644--- a/server/cmd/museum/main.go+++ b/server/cmd/museum/main.go@@ -223,7 +223,9 @@ func main() {embeddingRepo := &embedding.Repository{DB: db}authCache := cache.New(1*time.Minute, 15*time.Minute)- accessTokenCache := cache.New(1*time.Minute, 15*time.Minute)+ accessTokenCache := public.NewLinkCache(1*time.Minute, 15*time.Minute)+ fileLinkRepo.Cache = accessTokenCache+ collectionLinkRepo.Cache = accessTokenCachediscordController := discord.NewDiscordController(userRepo, hostName, environment)userLookupController := controller.NewUserLookupController(userRepo, discordController)rateLimiter := middleware.NewRateLimitMiddleware(discordController, 1000, 1*time.Second)diff --git a/server/pkg/middleware/collection_link.go b/server/pkg/middleware/collection_link.goindex 16350466f3..67e5c682d7 100644--- a/server/pkg/middleware/collection_link.go+++ b/server/pkg/middleware/collection_link.go@@ -12,6 +12,7 @@ import ("slices""strconv""strings"+ "time""github.com/ente/museum/pkg/repo/remotestore""github.com/gin-contrib/requestid"@@ -27,10 +28,9 @@ import ("github.com/ente/museum/pkg/repo""github.com/ente/museum/pkg/utils/auth""github.com/ente/museum/pkg/utils/network"- "github.com/ente/museum/pkg/utils/time"+ timeutil "github.com/ente/museum/pkg/utils/time""github.com/ente/stacktrace""github.com/gin-gonic/gin"- "github.com/patrickmn/go-cache""github.com/sirupsen/logrus")@@ -41,7 +41,7 @@ type CollectionLinkMiddleware struct {PublicCollectionCtrl *public2.CollectionLinkControllerCollectionRepo *repo.CollectionRepositoryAnonUsersRepo *socialrepo.AnonUsersRepository- Cache *cache.Cache+ Cache *public.LinkCacheBillingCtrl *controller.BillingControllerDiscordController *discord.DiscordControllerRemoteStoreRepo *remotestore.Repository@@ -63,11 +63,12 @@ func (m *CollectionLinkMiddleware) Authenticate(urlSanitizer func(_ *gin.ContextshouldCheckDeviceLimit := shouldCheckCollectionLinkDeviceLimit(reqPath)passwordValidated := false+ lookupStarted := time.Now()cacheKey := computeHashKeyForList([]string{accessToken, clientIP, userAgent, c.GetHeader("Origin")}, ":")var cachedValue interface{}cacheHit := falseif !shouldCheckDeviceLimit {- cachedValue, cacheHit = m.Cache.Get(cacheKey)+ cachedValue, cacheHit = m.Cache.Get(accessToken, cacheKey)}if !cacheHit {publicCollectionSummary, err = m.CollectionLinkRepo.GetCollectionSummaryByToken(c, accessToken)@@ -90,7 +91,7 @@ func (m *CollectionLinkMiddleware) Authenticate(urlSanitizer func(_ *gin.Context}if publicCollectionSummary.ValidTill > 0 && // expiry time is defined, 0 indicates no expiry- publicCollectionSummary.ValidTill < time.Microseconds() {+ publicCollectionSummary.ValidTill < timeutil.Microseconds() {c.AbortWithStatusJSON(http.StatusGone, gin.H{"code": ente.LinkExpired, "error": "expired token"})return}@@ -126,7 +127,7 @@ func (m *CollectionLinkMiddleware) Authenticate(urlSanitizer func(_ *gin.Context}if publicCollectionSummary.ValidTill > 0 && // expiry time is defined, 0 indicates no expiry- publicCollectionSummary.ValidTill < time.Microseconds() {+ publicCollectionSummary.ValidTill < timeutil.Microseconds() {c.AbortWithStatusJSON(http.StatusGone, gin.H{"code": ente.LinkExpired, "error": "expired token"})return}@@ -140,7 +141,7 @@ func (m *CollectionLinkMiddleware) Authenticate(urlSanitizer func(_ *gin.Context}if !cacheHit && !shouldCheckDeviceLimit {- m.Cache.Set(cacheKey, publicCollectionSummary, cache.DefaultExpiration)+ m.Cache.Set(cacheKey, publicCollectionSummary, lookupStarted)}publicCtx := ente.PublicAccessContext{@@ -184,7 +185,7 @@ func (m *CollectionLinkMiddleware) checkDeviceLimit(c *gin.Context, accessTokenif linkDeviceToken != "" {claim, err := public2.ValidateLinkDeviceToken(m.PublicCollectionCtrl.JwtSecret, linkDeviceToken, public2.LinkDeviceScopeCollection, linkID, accessToken)if err == nil {- if claim.ExpiryTime-time.Microseconds() < public2.LinkDeviceTokenRefreshBefore {+ if claim.ExpiryTime-timeutil.Microseconds() < public2.LinkDeviceTokenRefreshBefore {token, _, tokenErr := public2.NewLinkDeviceToken(m.PublicCollectionCtrl.JwtSecret, public2.LinkDeviceScopeCollection, linkID, accessToken, collectionSummary.ValidTill)return token, false, stacktrace.Propagate(tokenErr, "")}diff --git a/server/pkg/middleware/collection_link_test.go b/server/pkg/middleware/collection_link_test.goindex 6cf6ad532f..7327af8d88 100644--- a/server/pkg/middleware/collection_link_test.go+++ b/server/pkg/middleware/collection_link_test.go@@ -7,9 +7,14 @@ import ("time""github.com/ente/museum/ente"+ "github.com/ente/museum/internal/testutil"+ "github.com/ente/museum/pkg/controller"+ "github.com/ente/museum/pkg/repo"+ "github.com/ente/museum/pkg/repo/public"+ storagebonusrepo "github.com/ente/museum/pkg/repo/storagebonus""github.com/ente/museum/pkg/utils/auth"+ timeutil "github.com/ente/museum/pkg/utils/time""github.com/gin-gonic/gin"- "github.com/patrickmn/go-cache""github.com/stretchr/testify/require")@@ -20,10 +25,10 @@ func TestCollectionLinkCacheIsScopedToOrigin(t *testing.T) {userAgent = "test-agent")origins := []string{"https://albums.example", "https://gallery.example"}- linkCache := cache.New(time.Minute, time.Minute)+ linkCache := public.NewLinkCache(time.Minute, time.Minute)for i, origin := range origins {key := computeHashKeyForList([]string{accessToken, clientIP, userAgent, origin}, ":")- linkCache.Set(key, ente.PublicCollectionSummary{ID: int64(i + 1)}, cache.DefaultExpiration)+ linkCache.Set(key, ente.PublicCollectionSummary{ID: int64(i + 1)}, time.Now())}gin.SetMode(gin.TestMode)@@ -46,3 +51,76 @@ func TestCollectionLinkCacheIsScopedToOrigin(t *testing.T) {}require.Equal(t, []int64{1, 2}, ids)}++func TestCollectionLinkMutationsTakeEffectImmediately(t *testing.T) {+ testutil.WithServerRoot(t)+ db := testutil.RequireTestDB(t)+ testutil.ResetTables(t, db)+ t.Cleanup(func() { testutil.ResetTables(t, db) })++ now := timeutil.Microseconds()+ ownerID := testutil.InsertUser(t, db, testutil.UserFixture{+ Email: "[email protected]",+ CreationTime: now,+ })+ testutil.InsertSubscription(t, db, testutil.SubscriptionFixture{+ UserID: ownerID,+ Storage: 1,+ ExpiryTime: now + timeutil.MicroSecondsInOneHour,+ ProductID: "photos_yearly",+ })++ var collectionID int64+ err := db.QueryRow(`INSERT INTO collections+ (owner_id, encrypted_key, key_decryption_nonce, name, type, attributes, updation_time, app)+ VALUES ($1, 'key', 'nonce', 'Public collection', 'album', '{}', $2, $3)+ RETURNING collection_id`, ownerID, now, ente.Photos).Scan(&collectionID)+ require.NoError(t, err)+ const token = "public_collection_middleware_mutation"+ _, err = db.Exec(`INSERT INTO public_collection_tokens (collection_id, access_token)+ VALUES ($1, $2)`, collectionID, token)+ require.NoError(t, err)++ linkCache := public.NewLinkCache(time.Minute, time.Minute)+ collectionLinkRepo := public.NewCollectionLinkRepository(db, "")+ collectionLinkRepo.Cache = linkCache+ middleware := (&CollectionLinkMiddleware{+ CollectionLinkRepo: collectionLinkRepo,+ CollectionRepo: &repo.CollectionRepository{DB: db},+ Cache: linkCache,+ BillingCtrl: &controller.BillingController{+ BillingRepo: &repo.BillingRepository{DB: db},+ UserRepo: &repo.UserRepository{DB: db},+ StorageBonusRepo: &storagebonusrepo.Repository{DB: db},+ },+ }).Authenticate(func(c *gin.Context) string { return c.FullPath() })+ router := gin.New()+ router.GET("/public-collection/files/download/:fileID", middleware,+ func(c *gin.Context) { c.Status(http.StatusNoContent) })+ request := func() int {+ req := httptest.NewRequest(http.MethodGet, "/public-collection/files/download/1", nil)+ req.RemoteAddr = "192.0.2.1:1234"+ req.Header.Set("User-Agent", "test-agent")+ req.Header.Set("X-Auth-Access-Token", token)+ response := httptest.NewRecorder()+ router.ServeHTTP(response, req)+ return response.Code+ }++ require.Equal(t, http.StatusNoContent, request())+ _, cached := linkCache.Get(token, computeHashKeyForList([]string{token, "192.0.2.1", "test-agent", ""}, ":"))+ require.True(t, cached)+ collectionLinkRow, err := collectionLinkRepo.GetActiveCollectionLinkRow(t.Context(), collectionID)+ require.NoError(t, err)+ collectionLinkRow.ValidTill = 1+ require.NoError(t, collectionLinkRepo.UpdatePublicCollectionToken(t.Context(), collectionLinkRow))+ require.Equal(t, http.StatusGone, request())+ collectionLinkRow.ValidTill = 0+ passHash, nonce := "hash", "nonce"+ collectionLinkRow.PassHash = &passHash+ collectionLinkRow.Nonce = &nonce+ require.NoError(t, collectionLinkRepo.UpdatePublicCollectionToken(t.Context(), collectionLinkRow))+ require.Equal(t, http.StatusUnauthorized, request())+ require.NoError(t, collectionLinkRepo.DisableSharing(t.Context(), collectionID))+ require.Equal(t, http.StatusGone, request())+}diff --git a/server/pkg/middleware/file_link.go b/server/pkg/middleware/file_link.goindex 8558b6b101..aafc7ecf9e 100644--- a/server/pkg/middleware/file_link.go+++ b/server/pkg/middleware/file_link.go@@ -5,6 +5,7 @@ import ("fmt""net/http""slices"+ "time"publicCtrl "github.com/ente/museum/pkg/controller/public""github.com/ente/museum/pkg/repo/public"@@ -14,10 +15,9 @@ import ("github.com/ente/museum/pkg/controller/discord""github.com/ente/museum/pkg/utils/auth""github.com/ente/museum/pkg/utils/network"- "github.com/ente/museum/pkg/utils/time"+ timeutil "github.com/ente/museum/pkg/utils/time""github.com/ente/stacktrace""github.com/gin-gonic/gin"- "github.com/patrickmn/go-cache""github.com/sirupsen/logrus")@@ -26,7 +26,7 @@ var filePasswordWhiteListedURLs = []string{"/file-link/pass-info", "/file-link/vtype FileLinkMiddleware struct {FileLinkRepo *public.FileLinkRepositoryFileLinkCtrl *publicCtrl.FileLinkController- Cache *cache.Cache+ Cache *public.LinkCacheBillingCtrl *controller.BillingControllerDiscordController *discord.DiscordController}@@ -44,11 +44,12 @@ func (m *FileLinkMiddleware) Authenticate(urlSanitizer func(_ *gin.Context) strishouldCheckDeviceLimit := shouldCheckFileLinkDeviceLimit(reqPath)passwordValidated := false+ lookupStarted := time.Now()cacheKey := computeHashKeyForList([]string{accessToken, clientIP, userAgent}, ":")var cachedValue interface{}cacheHit := falseif !shouldCheckDeviceLimit {- cachedValue, cacheHit = m.Cache.Get(cacheKey)+ cachedValue, cacheHit = m.Cache.Get(accessToken, cacheKey)}var fileLinkRow *ente.FileLinkRowvar err error@@ -64,7 +65,7 @@ func (m *FileLinkMiddleware) Authenticate(urlSanitizer func(_ *gin.Context) strireturn}if fileLinkRow.ValidTill > 0 && // expiry time is defined, 0 indicates no expiry- fileLinkRow.ValidTill < time.Microseconds() {+ fileLinkRow.ValidTill < timeutil.Microseconds() {c.AbortWithStatusJSON(http.StatusGone, gin.H{"code": ente.LinkExpired, "error": "expired token"})return}@@ -99,7 +100,7 @@ func (m *FileLinkMiddleware) Authenticate(urlSanitizer func(_ *gin.Context) stri}if fileLinkRow.ValidTill > 0 && // expiry time is defined, 0 indicates no expiry- fileLinkRow.ValidTill < time.Microseconds() {+ fileLinkRow.ValidTill < timeutil.Microseconds() {c.AbortWithStatusJSON(http.StatusGone, gin.H{"code": ente.LinkExpired, "error": "expired token"})return}@@ -113,7 +114,7 @@ func (m *FileLinkMiddleware) Authenticate(urlSanitizer func(_ *gin.Context) stri}if !cacheHit && !shouldCheckDeviceLimit {- m.Cache.Set(cacheKey, fileLinkRow, cache.DefaultExpiration)+ m.Cache.Set(cacheKey, fileLinkRow, lookupStarted)}c.Set(auth.FileLinkAccessKey, &ente.FileLinkAccessContext{@@ -133,7 +134,7 @@ func (m *FileLinkMiddleware) checkDeviceLimit(c *gin.Context, accessToken stringif linkDeviceToken != "" {claim, err := publicCtrl.ValidateLinkDeviceToken(m.FileLinkCtrl.JwtSecret, linkDeviceToken, publicCtrl.LinkDeviceScopeFile, fileLinkRow.LinkID, accessToken)if err == nil {- if claim.ExpiryTime-time.Microseconds() < publicCtrl.LinkDeviceTokenRefreshBefore {+ if claim.ExpiryTime-timeutil.Microseconds() < publicCtrl.LinkDeviceTokenRefreshBefore {token, _, tokenErr := publicCtrl.NewLinkDeviceToken(m.FileLinkCtrl.JwtSecret, publicCtrl.LinkDeviceScopeFile, fileLinkRow.LinkID, accessToken, fileLinkRow.ValidTill)return token, false, stacktrace.Propagate(tokenErr, "")}diff --git a/server/pkg/middleware/file_link_test.go b/server/pkg/middleware/file_link_test.goindex 81b8e0266e..0d322379ea 100644--- a/server/pkg/middleware/file_link_test.go+++ b/server/pkg/middleware/file_link_test.go@@ -4,6 +4,7 @@ import ("net/http""net/http/httptest""testing"+ "time""github.com/ente/museum/internal/testutil""github.com/ente/museum/pkg/repo/public"@@ -48,3 +49,52 @@ func TestFileLinkGoneResponsePreservesLegacyError(t *testing.T) {})}}++func TestFileLinkMutationsTakeEffectImmediately(t *testing.T) {+ testutil.WithServerRoot(t)+ db := testutil.RequireTestDB(t)++ const token = "pft_middleware_mutation"+ _, err := db.Exec(`INSERT INTO public_file_tokens+ (id, file_id, owner_id, app, access_token)+ VALUES ($1, 1, 1, 'photos', $1)`, token)+ require.NoError(t, err)+ t.Cleanup(func() {+ _, err := db.Exec("DELETE FROM public_file_tokens WHERE id = $1", token)+ require.NoError(t, err)+ })++ linkCache := public.NewLinkCache(time.Minute, time.Minute)+ fileLinkRepo := public.NewFileLinkRepo(db)+ fileLinkRepo.Cache = linkCache+ middleware := &FileLinkMiddleware{FileLinkRepo: fileLinkRepo, Cache: linkCache}+ router := gin.New()+ router.GET("/file-link/file", middleware.Authenticate(func(c *gin.Context) string {+ return c.FullPath()+ }), func(c *gin.Context) { c.Status(http.StatusNoContent) })+ request := func() int {+ req := httptest.NewRequest(http.MethodGet, "/file-link/file", nil)+ req.RemoteAddr = "192.0.2.1:1234"+ req.Header.Set("User-Agent", "test-agent")+ req.Header.Set("X-Auth-Access-Token", token)+ response := httptest.NewRecorder()+ router.ServeHTTP(response, req)+ return response.Code+ }++ require.Equal(t, http.StatusNoContent, request())+ _, cached := linkCache.Get(token, computeHashKeyForList([]string{token, "192.0.2.1", "test-agent"}, ":"))+ require.True(t, cached)+ fileLinkRow, err := fileLinkRepo.GetActiveFileUrlToken(t.Context(), 1)+ require.NoError(t, err)+ fileLinkRow.ValidTill = 1+ require.NoError(t, fileLinkRepo.UpdateLink(t.Context(), *fileLinkRow))+ require.Equal(t, http.StatusGone, request())+ fileLinkRow.ValidTill = 0+ passHash := "hash"+ fileLinkRow.PassHash = &passHash+ require.NoError(t, fileLinkRepo.UpdateLink(t.Context(), *fileLinkRow))+ require.Equal(t, http.StatusUnauthorized, request())+ require.NoError(t, fileLinkRepo.DisableLinkForFiles(t.Context(), []int64{1}))+ require.Equal(t, http.StatusGone, request())+}diff --git a/server/pkg/repo/public/collection_link.go b/server/pkg/repo/public/collection_link.goindex a0ac06a818..05e9564611 100644--- a/server/pkg/repo/public/collection_link.go+++ b/server/pkg/repo/public/collection_link.go@@ -14,6 +14,7 @@ import ()type CollectionLinkRepo struct {+ Cache *LinkCacheDB *sql.DBalbumHost stringlockerHost string@@ -74,9 +75,17 @@ func (pcr *CollectionLinkRepo) Insert(ctx context.Context,}func (pcr *CollectionLinkRepo) DisableSharing(ctx context.Context, cID int64) error {- _, err := pcr.DB.ExecContext(ctx, `UPDATE public_collection_tokens SET is_disabled = true where- collection_id = $1 and is_disabled = false`, cID)- return stacktrace.Propagate(err, "failed to disable sharing")+ var accessToken string+ err := pcr.DB.QueryRowContext(ctx, `UPDATE public_collection_tokens SET is_disabled = true where+ collection_id = $1 and is_disabled = false RETURNING access_token`, cID).Scan(&accessToken)+ if errors.Is(err, sql.ErrNoRows) {+ return nil+ }+ if err != nil {+ return stacktrace.Propagate(err, "failed to disable sharing")+ }+ pcr.Cache.Invalidate(accessToken)+ return nil}// "Active" only means not disabled; links may be expired or over their limit.@@ -150,7 +159,11 @@ func (pcr *CollectionLinkRepo) UpdatePublicCollectionToken(ctx context.Context,pw_hash = $3, pw_nonce = $4, mem_limit = $5, ops_limit = $6, enable_download = $7, enable_collect = $8, enable_comment = $9, enable_join = $10, min_role = $11where id = $12`,pct.ValidTill, pct.DeviceLimit, pct.PassHash, pct.Nonce, pct.MemLimit, pct.OpsLimit, pct.EnableDownload, pct.EnableCollect, pct.EnableComment, pct.EnableJoin, minRole, pct.ID)- return stacktrace.Propagate(err, "failed to update public collection token")+ if err != nil {+ return stacktrace.Propagate(err, "failed to update public collection token")+ }+ pcr.Cache.Invalidate(pct.Token)+ return nil}func (pcr *CollectionLinkRepo) GetUniqueAccessCount(ctx context.Context, shareId int64) (int64, error) {diff --git a/server/pkg/repo/public/file_link.go b/server/pkg/repo/public/file_link.goindex 30e00cb481..168d6f6496 100644--- a/server/pkg/repo/public/file_link.go+++ b/server/pkg/repo/public/file_link.go@@ -5,6 +5,7 @@ import ("database/sql""errors""fmt"+"github.com/ente/museum/ente/base""github.com/lib/pq""github.com/spf13/viper"@@ -14,13 +15,14 @@ import ()type FileLinkRepository struct {+ Cache *LinkCacheDB *sql.DBphotoHost stringlockerHost string}type fileLinkUpdater interface {- ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)+ QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)}func NewFileLinkRepo(db *sql.DB) *FileLinkRepository {@@ -177,33 +179,57 @@ func (pcr *FileLinkRepository) GetFileUrls(ctx context.Context, userID int64, si}func (pcr *FileLinkRepository) DisableLinkForFiles(ctx context.Context, fileIDs []int64) error {- return disableLinkForFiles(ctx, pcr.DB, fileIDs)+ accessTokens, err := disableLinkForFiles(ctx, pcr.DB, fileIDs)+ if err != nil {+ return err+ }+ pcr.Cache.Invalidate(accessTokens...)+ return nil}-func (pcr *FileLinkRepository) DisableLinkForFilesTx(ctx context.Context, tx *sql.Tx, fileIDs []int64) error {+func (pcr *FileLinkRepository) DisableLinkForFilesTx(ctx context.Context, tx *sql.Tx, fileIDs []int64) ([]string, error) {return disableLinkForFiles(ctx, tx, fileIDs)}-func disableLinkForFiles(ctx context.Context, updater fileLinkUpdater, fileIDs []int64) error {+func disableLinkForFiles(ctx context.Context, updater fileLinkUpdater, fileIDs []int64) ([]string, error) {if len(fileIDs) == 0 {- return nil+ return nil, nil}- query := `UPDATE public_file_tokens SET is_disabled = TRUE WHERE file_id = ANY($1) AND is_disabled IS FALSE`- _, err := updater.ExecContext(ctx, query, pq.Array(fileIDs))+ rows, err := updater.QueryContext(ctx, `UPDATE public_file_tokens SET is_disabled = TRUE+ WHERE file_id = ANY($1) AND is_disabled IS FALSE RETURNING access_token`, pq.Array(fileIDs))if err != nil {- return stacktrace.Propagate(err, "failed to disable public file links")+ return nil, stacktrace.Propagate(err, "failed to disable public file links")}- return nil+ return scanAccessTokens(rows)}func (pcr *FileLinkRepository) DisableLinksForUser(ctx context.Context, userID int64) error {- _, err := pcr.DB.ExecContext(ctx, `UPDATE public_file_tokens SET is_disabled = TRUE WHERE owner_id = $1`, userID)+ rows, err := pcr.DB.QueryContext(ctx, `UPDATE public_file_tokens SET is_disabled = TRUE+ WHERE owner_id = $1 RETURNING access_token`, userID)if err != nil {return stacktrace.Propagate(err, "failed to disable public file link")}+ accessTokens, err := scanAccessTokens(rows)+ if err != nil {+ return err+ }+ pcr.Cache.Invalidate(accessTokens...)return nil}+func scanAccessTokens(rows *sql.Rows) ([]string, error) {+ defer rows.Close()+ var accessTokens []string+ for rows.Next() {+ var accessToken string+ if err := rows.Scan(&accessToken); err != nil {+ return nil, stacktrace.Propagate(err, "failed to read disabled public file link")+ }+ accessTokens = append(accessTokens, accessToken)+ }+ return accessTokens, stacktrace.Propagate(rows.Err(), "failed to read disabled public file links")+}+func (pcr *FileLinkRepository) GetFileUrlRowByToken(ctx context.Context, accessToken string) (*ente.FileLinkRow, error) {result, err := pcr.getActiveFileUrlRowByToken(ctx, accessToken)if err == nil {@@ -274,7 +300,11 @@ func (pcr *FileLinkRepository) UpdateLink(ctx context.Context, pct ente.FileLinkpw_hash = $3, pw_nonce = $4, mem_limit = $5, ops_limit = $6, enable_download = $7where id = $8`,pct.ValidTill, pct.DeviceLimit, pct.PassHash, pct.Nonce, pct.MemLimit, pct.OpsLimit, pct.EnableDownload, pct.LinkID)- return stacktrace.Propagate(err, "failed to update public file token")+ if err != nil {+ return stacktrace.Propagate(err, "failed to update public file token")+ }+ pcr.Cache.Invalidate(pct.Token)+ return nil}func (pcr *FileLinkRepository) GetUniqueAccessCount(ctx context.Context, linkId string) (int64, error) {diff --git a/server/pkg/repo/public/file_link_test.go b/server/pkg/repo/public/file_link_test.goindex d8fc3e69e4..c40c5cce05 100644--- a/server/pkg/repo/public/file_link_test.go+++ b/server/pkg/repo/public/file_link_test.go@@ -4,6 +4,7 @@ import ("database/sql""errors""testing"+ "time""github.com/ente/museum/ente""github.com/ente/museum/internal/testutil"@@ -47,6 +48,30 @@ func TestGetFileUrlRowByTokenReturnsNotFoundForUnknownToken(t *testing.T) {}}+func TestDisableLinksForUserInvalidatesTheirCacheEntries(t *testing.T) {+ repository, db := setupFileLinkRepositoryTest(t)+ repository.Cache = NewLinkCache(time.Minute, time.Minute)++ insertFileLinkToken(t, db, "pft_owner_1", "owner-token-1", 1, 11, false)+ insertFileLinkToken(t, db, "pft_owner_2", "owner-token-2", 2, 11, false)+ insertFileLinkToken(t, db, "pft_other", "other-token", 3, 22, false)+ for _, token := range []string{"owner-token-1", "owner-token-2", "other-token"} {+ repository.Cache.Set(token, true, time.Now())+ }++ if err := repository.DisableLinksForUser(t.Context(), 11); err != nil {+ t.Fatalf("DisableLinksForUser() error = %v", err)+ }+ for _, token := range []string{"owner-token-1", "owner-token-2"} {+ if _, cached := repository.Cache.Get(token, token); cached {+ t.Fatalf("cache entry %q was not invalidated", token)+ }+ }+ if _, cached := repository.Cache.Get("other-token", "other-token"); !cached {+ t.Fatal("unaffected cache entry was invalidated")+ }+}+func setupFileLinkRepositoryTest(t *testing.T) (*FileLinkRepository, *sql.DB) {t.Helper()diff --git a/server/pkg/repo/public/link_cache.go b/server/pkg/repo/public/link_cache.gonew file mode 100644index 0000000000..e5009abcc4--- /dev/null+++ b/server/pkg/repo/public/link_cache.go@@ -0,0 +1,59 @@+package public++import (+ "sync"+ "time"++ "github.com/ente/museum/pkg/utils/auth"+ "github.com/patrickmn/go-cache"+)++type LinkCache struct {+ cache *cache.Cache+ lifetime time.Duration+ mu sync.Mutex+}++type linkCacheEntry struct {+ value any+ expiresAt int64+}++func NewLinkCache(defaultExpiration, cleanupInterval time.Duration) *LinkCache {+ return &LinkCache{cache: cache.New(defaultExpiration, cleanupInterval), lifetime: defaultExpiration}+}++func (c *LinkCache) Get(accessToken, key string) (any, bool) {+ if _, bypass := c.cache.Get(linkCacheBypassKey(accessToken)); bypass {+ return nil, false+ }+ value, found := c.cache.Get(key)+ if !found {+ return nil, false+ }+ entry := value.(linkCacheEntry)+ return entry.value, time.Now().UnixNano() < entry.expiresAt+}++func (c *LinkCache) Set(key string, value any, lookupStarted time.Time) {+ expiresAt := lookupStarted.Add(c.lifetime).UnixNano()+ if remaining := time.Duration(expiresAt - time.Now().UnixNano()); remaining > 0 {+ c.cache.Set(key, linkCacheEntry{value: value, expiresAt: expiresAt}, remaining)+ }+}++func (c *LinkCache) Invalidate(accessTokens ...string) {+ if c == nil {+ return+ }+ c.mu.Lock()+ defer c.mu.Unlock()+ for _, accessToken := range accessTokens {+ c.cache.SetDefault(linkCacheBypassKey(accessToken), true)+ }+}++func linkCacheBypassKey(accessToken string) string {+ hash := auth.HashToken(accessToken)+ return "public-link-bypass:" + string(hash[:])+}diff --git a/server/pkg/repo/trash.go b/server/pkg/repo/trash.goindex 9284db8b29..ff278c2906 100644--- a/server/pkg/repo/trash.go+++ b/server/pkg/repo/trash.go@@ -168,7 +168,8 @@ func (t *TrashRepository) TrashFiles(ctx context.Context, userID int64, trash enif err != nil {return stacktrace.Propagate(err, "")}- if err = t.FileLinkRepo.DisableLinkForFilesTx(ctx, tx, fileIDs); err != nil {+ accessTokens, err := t.FileLinkRepo.DisableLinkForFilesTx(ctx, tx, fileIDs)+ if err != nil {return stacktrace.Propagate(err, "failed to disable file links for files being trashed")}if photosFileDelta != 0 || lockerFileDelta != 0 || ambiguousFileApp {@@ -180,7 +181,11 @@ func (t *TrashRepository) TrashFiles(ctx context.Context, userID int64, trash enreturn stacktrace.Propagate(err, "failed to update file counts")}}- return stacktrace.Propagate(tx.Commit(), "")+ if err = tx.Commit(); err != nil {+ return stacktrace.Propagate(err, "")+ }+ t.FileLinkRepo.Cache.Invalidate(accessTokens...)+ return nil}func (t *TrashRepository) CleanUpDeletedFilesFromCollection(ctx context.Context, fileIDs []int64, userID int64) error {diff --git a/server/pkg/repo/trash_test.go b/server/pkg/repo/trash_test.goindex 9a32813193..7e334c464e 100644--- a/server/pkg/repo/trash_test.go+++ b/server/pkg/repo/trash_test.go@@ -3,6 +3,7 @@ package repoimport ("database/sql""testing"+ "time""github.com/ente/museum/ente""github.com/ente/museum/internal/testutil"@@ -11,6 +12,9 @@ import (func TestTrashFilesUsesRequestItemsAsItsScope(t *testing.T) {repository, db := setupTrashTest(t)+ repository.FileLinkRepo.Cache = public.NewLinkCache(time.Minute, time.Minute)+ repository.FileLinkRepo.Cache.Set("requested-token", true, time.Now())+ repository.FileLinkRepo.Cache.Set("untouched-token", true, time.Now())ownerID := testutil.InsertUser(t, db, testutil.UserFixture{UserID: 1,Email: "[email protected]",@@ -78,10 +82,18 @@ func TestTrashFilesUsesRequestItemsAsItsScope(t *testing.T) {if !requestedLinkDisabled || untouchedLinkDisabled {t.Fatalf("unexpected public file link states: requested disabled=%t, untouched disabled=%t", requestedLinkDisabled, untouchedLinkDisabled)}+ if _, cached := repository.FileLinkRepo.Cache.Get("requested-token", "requested-token"); cached {+ t.Fatal("trashed file link cache entry was not invalidated")+ }+ if _, cached := repository.FileLinkRepo.Cache.Get("untouched-token", "untouched-token"); !cached {+ t.Fatal("untouched file link cache entry was invalidated")+ }}func TestTrashFilesRollsBackWhenFileLinkCleanupFails(t *testing.T) {repository, db := setupTrashTest(t)+ repository.FileLinkRepo.Cache = public.NewLinkCache(time.Minute, time.Minute)+ repository.FileLinkRepo.Cache.Set("failure-token", true, time.Now())ownerID := testutil.InsertUser(t, db, testutil.UserFixture{UserID: 1,Email: "[email protected]",@@ -142,6 +154,9 @@ func TestTrashFilesRollsBackWhenFileLinkCleanupFails(t *testing.T) {if linkDisabled {t.Fatal("public file link changed despite transaction rollback")}+ if _, cached := repository.FileLinkRepo.Cache.Get("failure-token", "failure-token"); !cached {+ t.Fatal("rolled-back file link invalidated its cache entry")+ }}func TestStaleCleanupInvalidatesOnlyRemovedOwnedMemberships(t *testing.T) {