RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
fix(user): use string for user id in DAO and handler lookups (#21792)
xugangqiangd4f39825559c
diff --git a/internal/dao/user.go b/internal/dao/user.goindex 4cda5b3158..f4bfb039cd 100644--- a/internal/dao/user.go+++ b/internal/dao/user.go@@ -39,8 +39,11 @@ func (dao *UserDAO) Create(ctx context.Context, db *gorm.DB, user *entity.User)return db.WithContext(ctx).Create(user).Error}-// GetByID get user by ID-func (dao *UserDAO) GetByID(ctx context.Context, db *gorm.DB, id uint) (*entity.User, error) {+// GetByID gets a user by its string ID (a 32-char hex UUID, matching the+// VARCHAR(32) primary key in MySQL). The id is bound by value through the+// parameterized condition "id = ?", never passed as a bare string (which GORM+// would interpolate as raw SQL for non-numeric IDs).+func (dao *UserDAO) GetByID(ctx context.Context, db *gorm.DB, id string) (*entity.User, error) {var user entity.Usererr := db.WithContext(ctx).Take(&user, "id = ?", id).Errorif err != nil {@@ -49,16 +52,6 @@ func (dao *UserDAO) GetByID(ctx context.Context, db *gorm.DB, id uint) (*entity.return &user, nil}-// GetByIDString gets a user by its string ID.-func (dao *UserDAO) GetByIDString(ctx context.Context, db *gorm.DB, id string) (*entity.User, error) {- var user entity.User- err := db.WithContext(ctx).Where("id = ?", id).First(&user).Error- if err != nil {- return nil, err- }- return &user, nil-}-func (dao *UserDAO) GetByTenantID(ctx context.Context, db *gorm.DB, tenantID string) (*entity.User, error) {var user entity.Usererr := db.WithContext(ctx).Where("id = ?", tenantID).First(&user).Error@@ -210,9 +203,9 @@ func userListOrder(order UserListOrder, desc bool) (clause.OrderByColumn, error)return clause.OrderByColumn{Column: clause.Column{Table: "user", Name: field}, Desc: desc}, nil}-// Delete delete user-func (dao *UserDAO) Delete(ctx context.Context, db *gorm.DB, id uint) error {- return db.WithContext(ctx).Delete(&entity.User{}, id).Error+// Delete delete user by string ID.+func (dao *UserDAO) Delete(ctx context.Context, db *gorm.DB, id string) error {+ return db.WithContext(ctx).Where("id = ?", id).Delete(&entity.User{}).Error}// HardDelete hard delete user by string IDdiff --git a/internal/dao/user_test.go b/internal/dao/user_test.gonew file mode 100644index 0000000000..5666d6d16f--- /dev/null+++ b/internal/dao/user_test.go@@ -0,0 +1,102 @@+//+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.+//+// Licensed 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 dao++import (+ "errors"+ "testing"++ "github.com/glebarez/sqlite"+ "gorm.io/gorm"++ "ragflow/internal/entity"+)++// userID is a real RAGFlow user id: a 32-char hex UUID string produced by+// common.GenerateToken(). It is NOT an integer, so any code path that treats+// it as uint/int is fundamentally broken.+const userIDHex = "0a1b2c3d4e5f60718293a4b5c6d7e8f90"++func newUserTestDB(t *testing.T) *gorm.DB {+ t.Helper()+ db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})+ if err != nil {+ t.Fatalf("open sqlite: %v", err)+ }+ if err := db.AutoMigrate(&entity.User{}); err != nil {+ t.Fatalf("migrate user: %v", err)+ }+ return db+}++// TestUserDAOGetByIDAcceptsUUIDString guards the contract that user ids are+// strings (VARCHAR(32) in MySQL, 32-char hex). The DAO must accept the real+// id type and bind it by value, returning the matching row.+func TestUserDAOGetByIDAcceptsUUIDString(t *testing.T) {+ db := newUserTestDB(t)+ if err := db.Create(&entity.User{ID: userIDHex, Email: "[email protected]", Nickname: "alice"}).Error; err != nil {+ t.Fatalf("create user: %v", err)+ }++ got, err := NewUserDAO().GetByID(t.Context(), db, userIDHex)+ if err != nil {+ t.Fatalf("GetByID(%q) error = %v", userIDHex, err)+ }+ if got.ID != userIDHex {+ t.Fatalf("GetByID(%q).ID = %q, want %q", userIDHex, got.ID, userIDHex)+ }+ if got.Nickname != "alice" {+ t.Fatalf("GetByID(%q).Nickname = %q, want alice", userIDHex, got.Nickname)+ }+}++// TestUserDAOGetByIDUnknownUUIDReturnsNotFound is adversarial: a different+// (still validly-formatted) UUID must NOT match and must surface a not-found+// error rather than silently coercing to a numeric lookup.+func TestUserDAOGetByIDUnknownUUIDReturnsNotFound(t *testing.T) {+ db := newUserTestDB(t)+ if err := db.Create(&entity.User{ID: userIDHex, Email: "[email protected]", Nickname: "alice"}).Error; err != nil {+ t.Fatalf("create user: %v", err)+ }++ other := "ffffffffffffffffffffffffffffffff"+ _, err := NewUserDAO().GetByID(t.Context(), db, other)+ if err == nil {+ t.Fatalf("GetByID(%q) = nil error, want not-found", other)+ }+ if !errors.Is(err, gorm.ErrRecordNotFound) {+ t.Fatalf("GetByID(%q) error = %v, want ErrRecordNotFound", other, err)+ }+}++// TestUserDAODeleteAcceptsString guards that Delete also takes the real string+// id type and removes exactly the targeted row.+func TestUserDAODeleteAcceptsString(t *testing.T) {+ db := newUserTestDB(t)+ if err := db.Create(&entity.User{ID: userIDHex, Email: "[email protected]", Nickname: "alice"}).Error; err != nil {+ t.Fatalf("create user: %v", err)+ }++ if err := NewUserDAO().Delete(t.Context(), db, userIDHex); err != nil {+ t.Fatalf("Delete(%q) error = %v", userIDHex, err)+ }++ _, err := NewUserDAO().GetByID(t.Context(), db, userIDHex)+ if !errors.Is(err, gorm.ErrRecordNotFound) {+ t.Fatalf("after Delete, GetByIDString(%q) error = %v, want ErrRecordNotFound", userIDHex, err)+ }+}diff --git a/internal/handler/user.go b/internal/handler/user.goindex a163ac270b..54e878364e 100644--- a/internal/handler/user.go+++ b/internal/handler/user.go@@ -24,7 +24,6 @@ import ("ragflow/internal/engine/kvrocks""ragflow/internal/server""ragflow/internal/server/local"- "strconv""time""ragflow/internal/service"@@ -297,14 +296,9 @@ func (h *UserHandler) LoginByEmail(c *gin.Context) {// @Router /api/v1/users/{id} [get]func (h *UserHandler) GetUserByID(c *gin.Context) {ctx := c.Request.Context()- idStr := c.Param("id")- id, err := strconv.ParseUint(idStr, 10, 32)- if err != nil {- common.ResponseWithCodeData(c, common.CodeBadRequest, false, "invalid user id")- return- }+ id := c.Param("id")- user, code, err := h.userService.GetUserByID(ctx, uint(id))+ user, code, err := h.userService.GetUserByID(ctx, id)if err != nil {common.ResponseWithCodeData(c, code, false, err.Error())returndiff --git a/internal/handler/user_get_by_id_test.go b/internal/handler/user_get_by_id_test.gonew file mode 100644index 0000000000..4e5f339d6a--- /dev/null+++ b/internal/handler/user_get_by_id_test.go@@ -0,0 +1,128 @@+//+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.+//+// Licensed 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 handler++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/gin-gonic/gin"+ "github.com/glebarez/sqlite"+ "gorm.io/gorm"++ "ragflow/internal/dao"+ "ragflow/internal/entity"+ "ragflow/internal/service"+)++// userIDHex is a real RAGFlow user id: a 32-char hex UUID string. The previous+// implementation parsed it with strconv.ParseUint, which rejects any+// non-numeric id and returned a body code 400 for every real user. This test+// pins the corrected behavior: a UUID string id must resolve the user (HTTP 200+// with the user in the response body).+const userIDHex = "0a1b2c3d4e5f60718293a4b5c6d7e8f90"++func TestGetUserByIDResolvesUUIDString(t *testing.T) {+ gin.SetMode(gin.TestMode)++ db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})+ if err != nil {+ t.Fatalf("open sqlite: %v", err)+ }+ if err := db.AutoMigrate(&entity.User{}); err != nil {+ t.Fatalf("migrate user: %v", err)+ }+ if err := db.Create(&entity.User{ID: userIDHex, Email: "[email protected]", Nickname: "alice"}).Error; err != nil {+ t.Fatalf("create user: %v", err)+ }++ orig := dao.DB+ dao.DB = db+ t.Cleanup(func() { dao.DB = orig })++ r := gin.New()+ r.GET("/users/:id", NewUserHandler(service.NewUserService(), service.NewUserTenantService()).GetUserByID)++ w := httptest.NewRecorder()+ req := httptest.NewRequest(http.MethodGet, "/users/"+userIDHex, nil)+ r.ServeHTTP(w, req)++ if w.Code != http.StatusOK {+ t.Fatalf("GET /users/%s status = %d, want 200 (body=%s)", userIDHex, w.Code, w.Body.String())+ }++ var body struct {+ Data struct {+ ID string `json:"id"`+ Nickname string `json:"nickname"`+ } `json:"data"`+ }+ if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {+ t.Fatalf("decode body: %v (body=%s)", err, w.Body.String())+ }+ if body.Data.ID != userIDHex {+ t.Fatalf("response id = %q, want %q", body.Data.ID, userIDHex)+ }+ if body.Data.Nickname != "alice" {+ t.Fatalf("response nickname = %q, want alice", body.Data.Nickname)+ }+}++// TestGetUserByIDMissingUUIDReturnsNotFound is adversarial: a well-formed but+// unknown UUID string must surface a not-found error (body code 404), never the+// "invalid user id" body code 400 that the old numeric ParseUint path produced+// for any non-integer id. ResponseWithCodeData always returns HTTP 200, so we+// assert on the body's business code field.+func TestGetUserByIDMissingUUIDReturnsNotFound(t *testing.T) {+ gin.SetMode(gin.TestMode)++ db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})+ if err != nil {+ t.Fatalf("open sqlite: %v", err)+ }+ if err := db.AutoMigrate(&entity.User{}); err != nil {+ t.Fatalf("migrate user: %v", err)+ }++ orig := dao.DB+ dao.DB = db+ t.Cleanup(func() { dao.DB = orig })++ r := gin.New()+ r.GET("/users/:id", NewUserHandler(service.NewUserService(), service.NewUserTenantService()).GetUserByID)++ missing := "ffffffffffffffffffffffffffffffff"+ w := httptest.NewRecorder()+ req := httptest.NewRequest(http.MethodGet, "/users/"+missing, nil)+ r.ServeHTTP(w, req)++ if w.Code != http.StatusOK {+ t.Fatalf("GET /users/%s status = %d, want 200 (body=%s)", missing, w.Code, w.Body.String())+ }+ var body struct {+ Code int `json:"code"`+ Message string `json:"message"`+ }+ if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {+ t.Fatalf("decode body: %v (body=%s)", err, w.Body.String())+ }+ if body.Code != 404 {+ t.Fatalf("GET /users/%s body code = %d, want 404 not-found (message=%q)", missing, body.Code, body.Message)+ }+}diff --git a/internal/service/user.go b/internal/service/user.goindex b91103e2b2..463b91d10d 100644--- a/internal/service/user.go+++ b/internal/service/user.go@@ -340,8 +340,8 @@ func (s *UserService) LoginByEmail(ctx context.Context, req *EmailLoginRequest)return user, common.CodeSuccess, nil}-// GetUserByID get user by ID-func (s *UserService) GetUserByID(ctx context.Context, id uint) (*UserResponse, common.ErrorCode, error) {+// GetUserByID get user by ID (a 32-char hex UUID string).+func (s *UserService) GetUserByID(ctx context.Context, id string) (*UserResponse, common.ErrorCode, error) {user, err := s.userDAO.GetByID(ctx, dao.DB, id)if err != nil {return nil, common.CodeNotFound, err@@ -777,7 +777,7 @@ func (s *UserService) resolveAPITokenIdentity(ctx context.Context, apiToken *entreturn nil, common.CodeUnauthorized, fmt.Errorf("API token is missing user identity")}- user, err := s.userDAO.GetByIDString(ctx, dao.DB, *apiToken.UserID)+ user, err := s.userDAO.GetByID(ctx, dao.DB, *apiToken.UserID)if err != nil {return nil, common.CodeUnauthorized, fmt.Errorf("user not found for API token")}diff --git a/internal/service/user_resolve_api_token_test.go b/internal/service/user_resolve_api_token_test.gonew file mode 100644index 0000000000..c7edcc4af3--- /dev/null+++ b/internal/service/user_resolve_api_token_test.go@@ -0,0 +1,111 @@+//+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.+//+// Licensed 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 service++import (+ "context"+ "testing"++ "github.com/glebarez/sqlite"+ "gorm.io/gorm"++ "ragflow/internal/common"+ "ragflow/internal/dao"+ "ragflow/internal/entity"+)++// userIDHex is a real RAGFlow user id: a 32-char hex UUID string produced by+// common.GenerateToken(). It is NOT an integer, so any code path that treats it+// as uint/int is fundamentally broken.+const apiTokenUserIDHex = "0a1b2c3d4e5f60718293a4b5c6d7e8f90"++func newAPITokenTestDB(t *testing.T) *gorm.DB {+ t.Helper()+ db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})+ if err != nil {+ t.Fatalf("open sqlite: %v", err)+ }+ if err := db.AutoMigrate(&entity.User{}); err != nil {+ t.Fatalf("migrate user: %v", err)+ }+ return db+}++// TestResolveAPITokenIdentityResolvesUserByStringID guards that the API-token+// identity path resolves a user by its real string id (a 32-char hex UUID). It+// must use the single canonical string-ID lookup on UserDAO, never a numeric+// contract that would reject every real id.+func TestResolveAPITokenIdentityResolvesUserByStringID(t *testing.T) {+ db := newAPITokenTestDB(t)+ accessToken := "secret-token-value"+ if err := db.Create(&entity.User{+ ID: apiTokenUserIDHex,+ Email: "[email protected]",+ Nickname: "alice",+ AccessToken: &accessToken,+ }).Error; err != nil {+ t.Fatalf("create user: %v", err)+ }++ orig := dao.DB+ dao.DB = db+ t.Cleanup(func() { dao.DB = orig })++ uid := apiTokenUserIDHex+ apiToken := &entity.APIToken{UserID: &uid, TenantID: "tenant-1"}+ identity, code, err := (&UserService{}).resolveAPITokenIdentity(context.Background(), apiToken)+ if err != nil {+ t.Fatalf("resolveAPITokenIdentity() error = %v, code = %v; want nil", err, code)+ }+ if code != common.CodeSuccess {+ t.Fatalf("resolveAPITokenIdentity() code = %v, want success", code)+ }+ if identity == nil || identity.User == nil || identity.User.ID != apiTokenUserIDHex {+ t.Fatalf("resolveAPITokenIdentity() identity user id = %v, want %q", identityUserID(identity), apiTokenUserIDHex)+ }+}++// TestResolveAPITokenIdentityUnknownUserReturnsUnauthorized is adversarial: a+// well-formed but unknown UUID must surface an unauthorized error, never a+// numeric-coercion failure that would mask the lookup.+func TestResolveAPITokenIdentityUnknownUserReturnsUnauthorized(t *testing.T) {+ db := newAPITokenTestDB(t)++ orig := dao.DB+ dao.DB = db+ t.Cleanup(func() { dao.DB = orig })++ missing := "ffffffffffffffffffffffffffffffff"+ apiToken := &entity.APIToken{UserID: &missing, TenantID: "tenant-1"}+ identity, code, err := (&UserService{}).resolveAPITokenIdentity(context.Background(), apiToken)+ if err == nil {+ t.Fatalf("resolveAPITokenIdentity() = nil error, want unauthorized")+ }+ if code != common.CodeUnauthorized {+ t.Fatalf("resolveAPITokenIdentity() code = %v, want unauthorized", code)+ }+ if identity != nil {+ t.Fatalf("resolveAPITokenIdentity() identity = %v, want nil", identity)+ }+}++func identityUserID(identity *AuthIdentity) string {+ if identity == nil || identity.User == nil {+ return ""+ }+ return identity.User.ID+}