This is an automated email from the ASF dual-hosted git repository. LinkinStars pushed a commit to branch dev in repository https://gitbox.apache.org/repos/asf/answer.git
commit c58049e169b3fa3a439195a78257681acd85364b Author: LinkinStars <[email protected]> AuthorDate: Tue Aug 25 17:29:24 2026 +0800 fix(security): revoke stale visit tokens --- internal/base/middleware/visit_img_auth_test.go | 155 ++++++++++++++++++++++++ internal/repo/auth/auth.go | 16 +++ internal/service/auth/auth.go | 7 +- 3 files changed, 175 insertions(+), 3 deletions(-) diff --git a/internal/base/middleware/visit_img_auth_test.go b/internal/base/middleware/visit_img_auth_test.go new file mode 100644 index 00000000..7d1858ce --- /dev/null +++ b/internal/base/middleware/visit_img_auth_test.go @@ -0,0 +1,155 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package middleware + +import ( + "context" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + + "github.com/apache/answer/internal/base/constant" + "github.com/apache/answer/internal/base/data" + "github.com/apache/answer/internal/entity" + authrepo "github.com/apache/answer/internal/repo/auth" + authservice "github.com/apache/answer/internal/service/auth" + "github.com/apache/answer/internal/service/siteinfo_common" + "github.com/gin-gonic/gin" +) + +type visitAuthTestSiteInfoRepo struct{} + +func (visitAuthTestSiteInfoRepo) SaveByType(context.Context, string, *entity.SiteInfo) error { + return nil +} + +func (visitAuthTestSiteInfoRepo) GetByType(context.Context, string, ...bool) (*entity.SiteInfo, bool, error) { + return &entity.SiteInfo{Content: `{"login_required":true}`}, true, nil +} + +func (visitAuthTestSiteInfoRepo) IsBrandingFileUsed(context.Context, string) (bool, error) { + return false, nil +} + +func TestVisitAuthRejectsRevokedAndSuspendedSessions(t *testing.T) { + ctx := context.Background() + cache, cleanup, err := data.NewCache(&data.CacheConf{}) + if err != nil { + t.Fatalf("create cache: %v", err) + } + t.Cleanup(cleanup) + + repo := authrepo.NewAuthRepo(&data.Data{Cache: cache}) + service := authservice.NewAuthService(repo, nil) + accessToken, visitToken, err := service.SetUserCacheInfo(ctx, &entity.UserCacheInfo{ + UserID: "visit-auth-user", + UserStatus: entity.UserStatusAvailable, + EmailStatus: entity.EmailStatusAvailable, + }) + if err != nil { + t.Fatalf("create session: %v", err) + } + + filePath := filepath.Join(t.TempDir(), "private.txt") + if err := os.WriteFile(filePath, []byte("private upload"), 0o600); err != nil { + t.Fatalf("create private upload: %v", err) + } + serve := func(token string) *httptest.ResponseRecorder { + gin.SetMode(gin.TestMode) + engine := gin.New() + siteInfo := siteinfo_common.NewSiteInfoCommonService(visitAuthTestSiteInfoRepo{}) + authMiddleware := NewAuthUserMiddleware(service, siteInfo) + engine.Use(authMiddleware.VisitAuth()) + engine.StaticFile("/uploads/post/private.txt", filePath) + req := httptest.NewRequest(http.MethodGet, "/uploads/post/private.txt", nil) + req.AddCookie(&http.Cookie{Name: constant.UserVisitCookiesCacheKey, Value: token}) + recorder := httptest.NewRecorder() + engine.ServeHTTP(recorder, req) + return recorder + } + + if response := serve(visitToken); response.Code != http.StatusOK { + t.Fatalf("fresh visit token returned %d, want %d", response.Code, http.StatusOK) + } + + service.RemoveUserAllTokens(ctx, "visit-auth-user") + if userInfo, err := service.GetUserCacheInfo(ctx, accessToken); err != nil || userInfo != nil { + t.Fatalf("revoked access token remained valid: userInfo=%v err=%v", userInfo, err) + } + if response := serve(visitToken); response.Code != http.StatusFound || response.Header().Get("Location") != "/403" { + t.Fatalf("revoked visit token returned status=%d location=%q, want 302 /403", response.Code, response.Header().Get("Location")) + } + + _, suspendedVisitToken, err := service.SetUserCacheInfo(ctx, &entity.UserCacheInfo{ + UserID: "suspended-visit-auth-user", + UserStatus: entity.UserStatusAvailable, + EmailStatus: entity.EmailStatusAvailable, + }) + if err != nil { + t.Fatalf("create suspended-user session: %v", err) + } + if err := service.SetUserStatus(ctx, &entity.UserCacheInfo{ + UserID: "suspended-visit-auth-user", + UserStatus: entity.UserStatusSuspended, + EmailStatus: entity.EmailStatusAvailable, + }); err != nil { + t.Fatalf("suspend user: %v", err) + } + if response := serve(suspendedVisitToken); response.Code != http.StatusFound || response.Header().Get("Location") != "/403" { + t.Fatalf("suspended visit token returned status=%d location=%q, want 302 /403", response.Code, response.Header().Get("Location")) + } +} + +func TestRemoveTokensExceptCurrentUserRevokesOnlyOtherVisitTokens(t *testing.T) { + ctx := context.Background() + cache, cleanup, err := data.NewCache(&data.CacheConf{}) + if err != nil { + t.Fatalf("create cache: %v", err) + } + t.Cleanup(cleanup) + + service := authservice.NewAuthService(authrepo.NewAuthRepo(&data.Data{Cache: cache}), nil) + currentAccessToken, currentVisitToken, err := service.SetUserCacheInfo(ctx, &entity.UserCacheInfo{ + UserID: "multi-session-user", + UserStatus: entity.UserStatusAvailable, + EmailStatus: entity.EmailStatusAvailable, + }) + if err != nil { + t.Fatalf("create current session: %v", err) + } + _, otherVisitToken, err := service.SetUserCacheInfo(ctx, &entity.UserCacheInfo{ + UserID: "multi-session-user", + UserStatus: entity.UserStatusAvailable, + EmailStatus: entity.EmailStatusAvailable, + }) + if err != nil { + t.Fatalf("create other session: %v", err) + } + + service.RemoveTokensExceptCurrentUser(ctx, "multi-session-user", currentAccessToken) + if !service.CheckUserVisitToken(ctx, currentVisitToken) { + t.Fatal("current visit token was revoked") + } + if service.CheckUserVisitToken(ctx, otherVisitToken) { + t.Fatal("other visit token remained valid") + } +} diff --git a/internal/repo/auth/auth.go b/internal/repo/auth/auth.go index 597352b2..7c957d78 100644 --- a/internal/repo/auth/auth.go +++ b/internal/repo/auth/auth.go @@ -224,6 +224,14 @@ func (ar *authRepo) RemoveUserTokens(ctx context.Context, userID string, remainT if token == remainToken { continue } + userInfo, err := ar.GetUserCacheInfo(ctx, token) + if err != nil { + log.Error(err) + } else if userInfo != nil && len(userInfo.VisitToken) > 0 { + if err := ar.RemoveUserVisitCacheInfo(ctx, userInfo.VisitToken); err != nil { + log.Error(err) + } + } if err := ar.RemoveUserCacheInfo(ctx, token); err != nil { log.Error(err) } else { @@ -233,6 +241,14 @@ func (ar *authRepo) RemoveUserTokens(ctx context.Context, userID string, remainT if err := ar.RemoveUserStatus(ctx, userID); err != nil { log.Error(err) } + if remainToken != "" { + mapping = map[string]bool{remainToken: true} + content, _ := json.Marshal(mapping) + if err := ar.data.Cache.SetString(ctx, key, string(content), constant.UserTokenCacheTime); err != nil { + log.Error(err) + } + return + } if err := ar.data.Cache.Del(ctx, key); err != nil { log.Error(err) } diff --git a/internal/service/auth/auth.go b/internal/service/auth/auth.go index a7827c78..ac86b7ab 100644 --- a/internal/service/auth/auth.go +++ b/internal/service/auth/auth.go @@ -102,13 +102,14 @@ func (as *AuthService) SetUserCacheInfo(ctx context.Context, userInfo *entity.Us func (as *AuthService) CheckUserVisitToken(ctx context.Context, visitToken string) bool { accessToken, err := as.authRepo.GetUserVisitCacheInfo(ctx, visitToken) - if err != nil { + if err != nil || len(accessToken) == 0 { return false } - if len(accessToken) == 0 { + userInfo, err := as.GetUserCacheInfo(ctx, accessToken) + if err != nil || userInfo == nil { return false } - return true + return userInfo.EmailStatus == entity.EmailStatusAvailable && userInfo.UserStatus == entity.UserStatusAvailable } func (as *AuthService) SetUserStatus(ctx context.Context, userInfo *entity.UserCacheInfo) (err error) {
