From d8cb177440ceaae422d5bfd96c258d47af4e0f1d Mon Sep 17 00:00:00 2001 From: CaIon Date: Sat, 5 Sep 2026 20:02:46 +0800 Subject: [PATCH] feat(security): add access token management and audit logs Move account security settings into a dedicated page and add token status, rotation, revocation, and access history. Store audit events with role snapshots and JSON metadata, add audit.read authorization and an independent audit page, and upgrade the ClickHouse driver to v2.46.0. --- controller/access_token.go | 78 ++ controller/access_token_audit_test.go | 855 ++++++++++++++++++ controller/audit.go | 23 +- controller/billing_option_test.go | 2 +- controller/channel_task_plugin_bind_test.go | 2 +- controller/channel_test_internal_test.go | 10 +- controller/model_list_test.go | 2 +- controller/relay.go | 5 + controller/secure_verification.go | 2 +- controller/subscription.go | 8 +- controller/twofa.go | 8 +- controller/user.go | 12 +- controller/user_manage_test.go | 2 +- go.mod | 23 +- go.sum | 42 +- middleware/audit.go | 84 +- middleware/auth.go | 7 + middleware/auth_test.go | 5 +- model/audit_log.go | 269 ++++++ model/audit_other.go | 95 ++ model/log.go | 98 +- model/main.go | 6 + model/user.go | 88 +- router/api-router.go | 8 +- router/main.go | 1 + router/plugin_router_test.go | 30 + router/web-router.go | 1 + service/authz/authz_test.go | 2 + service/authz/resources_audit.go | 17 + .../layout/components/mobile-drawer.tsx | 19 +- web/src/components/profile-dropdown.tsx | 10 +- .../components/secure-verification-dialog.tsx | 6 +- .../profile/__tests__/settings.test.tsx | 194 ++++ web/src/features/profile/api.ts | 16 +- .../dialogs/access-token-dialog.tsx | 198 ---- .../components/profile-security-card.tsx | 151 ---- .../components/profile-settings-card.tsx | 42 +- .../components/sidebar-modules-card.tsx | 10 + .../components/tabs/notification-tab.tsx | 85 +- web/src/features/profile/hooks/index.ts | 2 - .../profile/hooks/use-access-token.ts | 71 -- web/src/features/profile/index.tsx | 8 - web/src/features/profile/lib/user-settings.ts | 50 + web/src/features/profile/types.ts | 3 + .../features/security/__tests__/page.test.tsx | 283 ++++++ web/src/features/security/api.ts | 53 ++ .../__tests__/access-token-card.test.tsx | 220 +++++ .../__tests__/login-session-utils.test.ts | 0 .../__tests__/privacy-card.test.tsx | 120 +++ .../security/components/access-token-card.tsx | 221 +++++ .../components/account-action-card.tsx | 93 ++ .../components/account-bindings.tsx} | 163 ++-- .../dialogs/access-token-dialog.tsx | 66 ++ .../dialogs/change-password-dialog.tsx | 5 +- .../dialogs/delete-account-dialog.tsx | 3 +- .../components/dialogs/email-bind-dialog.tsx | 17 +- .../dialogs/telegram-bind-dialog.tsx | 3 +- .../dialogs/two-fa-backup-dialog.tsx | 42 +- .../dialogs/two-fa-disable-dialog.tsx | 2 +- .../dialogs/two-fa-setup-dialog.tsx | 17 +- .../components/dialogs/wechat-bind-dialog.tsx | 3 +- .../components/login-session-dialogs.tsx | 0 .../components/login-session-item.tsx | 0 .../components/login-session-utils.ts | 0 .../components/login-sessions-card.tsx | 8 +- .../components/passkey-card.tsx | 0 .../security/components/privacy-card.tsx | 90 ++ .../components/two-fa-card.tsx | 2 +- .../security/hooks/use-access-token.ts | 68 ++ .../{profile => security}/hooks/use-two-fa.ts | 3 +- web/src/features/security/index.tsx | 144 +++ .../system-settings/maintenance/config.ts | 2 + .../maintenance/sidebar-modules-section.tsx | 8 + .../audit/__tests__/details.test.tsx | 289 ++++++ .../audit/__tests__/viewer.test.tsx | 561 ++++++++++++ web/src/features/usage-logs/audit/api.ts | 65 ++ .../audit/components/audit-detail-fields.tsx | 63 ++ .../audit/components/audit-detail-value.tsx | 51 ++ .../audit/components/audit-log-columns.tsx | 149 +++ .../components/audit-log-details-dialog.tsx | 165 ++++ .../audit/components/audit-log-filter-bar.tsx | 249 +++++ .../audit/components/audit-log-viewer.tsx | 171 ++++ web/src/features/usage-logs/audit/index.tsx | 126 +++ .../usage-logs/audit/lib/audit-details.ts | 279 ++++++ .../__tests__/log-type-filter.test.tsx | 125 +++ .../components/common-logs-filter-bar.tsx | 52 +- .../compact-date-time-range-picker.tsx | 2 + .../components/dialogs/details-dialog.tsx | 64 +- .../components/dialogs/log-detail-layout.tsx | 85 ++ web/src/features/usage-logs/constants.ts | 5 +- web/src/features/usage-logs/index.tsx | 8 +- web/src/features/usage-logs/lib/format.ts | 11 + .../components/__tests__/permissions.test.tsx | 145 +++ .../users/components/users-mutate-drawer.tsx | 28 +- .../hooks/__tests__/sidebar-config.test.tsx | 182 ++++ web/src/hooks/use-sidebar-config.ts | 4 + web/src/hooks/use-sidebar-data.ts | 14 +- web/src/i18n/locales/en.json | 65 ++ web/src/i18n/locales/fr.json | 65 ++ web/src/i18n/locales/ja.json | 65 ++ web/src/i18n/locales/ru.json | 67 +- web/src/i18n/locales/vi.json | 65 ++ web/src/i18n/locales/zh-TW.json | 67 +- web/src/i18n/locales/zh.json | 67 +- web/src/i18n/static-keys.ts | 6 + web/src/lib/__tests__/http-cache.test.ts | 78 ++ web/src/lib/admin-permissions.ts | 1 + web/src/lib/auth-session.ts | 3 +- web/src/lib/http-client.ts | 3 +- web/src/routeTree.gen.ts | 44 + .../routes/_authenticated/security/index.tsx | 25 + .../_authenticated/usage-logs/audit.tsx | 25 + 112 files changed, 6872 insertions(+), 953 deletions(-) create mode 100644 controller/access_token.go create mode 100644 controller/access_token_audit_test.go create mode 100644 model/audit_log.go create mode 100644 model/audit_other.go create mode 100644 service/authz/resources_audit.go create mode 100644 web/src/features/profile/__tests__/settings.test.tsx delete mode 100644 web/src/features/profile/components/dialogs/access-token-dialog.tsx delete mode 100644 web/src/features/profile/components/profile-security-card.tsx delete mode 100644 web/src/features/profile/hooks/use-access-token.ts create mode 100644 web/src/features/profile/lib/user-settings.ts create mode 100644 web/src/features/security/__tests__/page.test.tsx create mode 100644 web/src/features/security/api.ts create mode 100644 web/src/features/security/components/__tests__/access-token-card.test.tsx rename web/src/features/{profile => security}/components/__tests__/login-session-utils.test.ts (100%) create mode 100644 web/src/features/security/components/__tests__/privacy-card.test.tsx create mode 100644 web/src/features/security/components/access-token-card.tsx create mode 100644 web/src/features/security/components/account-action-card.tsx rename web/src/features/{profile/components/tabs/account-bindings-tab.tsx => security/components/account-bindings.tsx} (82%) create mode 100644 web/src/features/security/components/dialogs/access-token-dialog.tsx rename web/src/features/{profile => security}/components/dialogs/change-password-dialog.tsx (98%) rename web/src/features/{profile => security}/components/dialogs/delete-account-dialog.tsx (98%) rename web/src/features/{profile => security}/components/dialogs/email-bind-dialog.tsx (95%) rename web/src/features/{profile => security}/components/dialogs/telegram-bind-dialog.tsx (99%) rename web/src/features/{profile => security}/components/dialogs/two-fa-backup-dialog.tsx (86%) rename web/src/features/{profile => security}/components/dialogs/two-fa-disable-dialog.tsx (99%) rename web/src/features/{profile => security}/components/dialogs/two-fa-setup-dialog.tsx (96%) rename web/src/features/{profile => security}/components/dialogs/wechat-bind-dialog.tsx (98%) rename web/src/features/{profile => security}/components/login-session-dialogs.tsx (100%) rename web/src/features/{profile => security}/components/login-session-item.tsx (100%) rename web/src/features/{profile => security}/components/login-session-utils.ts (100%) rename web/src/features/{profile => security}/components/login-sessions-card.tsx (99%) rename web/src/features/{profile => security}/components/passkey-card.tsx (100%) create mode 100644 web/src/features/security/components/privacy-card.tsx rename web/src/features/{profile => security}/components/two-fa-card.tsx (99%) create mode 100644 web/src/features/security/hooks/use-access-token.ts rename web/src/features/{profile => security}/hooks/use-two-fa.ts (96%) create mode 100644 web/src/features/security/index.tsx create mode 100644 web/src/features/usage-logs/audit/__tests__/details.test.tsx create mode 100644 web/src/features/usage-logs/audit/__tests__/viewer.test.tsx create mode 100644 web/src/features/usage-logs/audit/api.ts create mode 100644 web/src/features/usage-logs/audit/components/audit-detail-fields.tsx create mode 100644 web/src/features/usage-logs/audit/components/audit-detail-value.tsx create mode 100644 web/src/features/usage-logs/audit/components/audit-log-columns.tsx create mode 100644 web/src/features/usage-logs/audit/components/audit-log-details-dialog.tsx create mode 100644 web/src/features/usage-logs/audit/components/audit-log-filter-bar.tsx create mode 100644 web/src/features/usage-logs/audit/components/audit-log-viewer.tsx create mode 100644 web/src/features/usage-logs/audit/index.tsx create mode 100644 web/src/features/usage-logs/audit/lib/audit-details.ts create mode 100644 web/src/features/usage-logs/components/__tests__/log-type-filter.test.tsx create mode 100644 web/src/features/usage-logs/components/dialogs/log-detail-layout.tsx create mode 100644 web/src/features/users/components/__tests__/permissions.test.tsx create mode 100644 web/src/hooks/__tests__/sidebar-config.test.tsx create mode 100644 web/src/lib/__tests__/http-cache.test.ts create mode 100644 web/src/routes/_authenticated/security/index.tsx create mode 100644 web/src/routes/_authenticated/usage-logs/audit.tsx diff --git a/controller/access_token.go b/controller/access_token.go new file mode 100644 index 0000000000..cec083b4dd --- /dev/null +++ b/controller/access_token.go @@ -0,0 +1,78 @@ +package controller + +import ( + "github.com/QuantumNous/new-api/common" + "github.com/QuantumNous/new-api/model" + "github.com/gin-gonic/gin" + "strconv" +) + +func GetAccessTokenStatus(c *gin.Context) { + status, err := model.GetUserAccessTokenStatus(c.GetInt("id")) + if err != nil { + common.ApiError(c, err) + return + } + common.ApiSuccess(c, status) +} + +func RevokeAccessToken(c *gin.Context) { + ref, err := model.RevokeUserAccessToken(c.GetInt("id")) + if err != nil { + common.ApiError(c, err) + return + } + if ref != "" { + recordUserSecurityAudit(c, c.GetInt("id"), "access_token.revoke", map[string]interface{}{"token_ref": ref}) + } + common.ApiSuccess(c, nil) +} + +func GetAuditLogs(c *gin.Context) { + page := common.GetPageQuery(c) + if page.Page < 1 || page.PageSize < 1 || page.Page > 100000000 { + common.ApiErrorMsg(c, "Invalid audit pagination") + return + } + filter := model.AuditLogFilter{Username: c.Query("username"), Category: c.Query("category"), TokenRef: c.Query("token_ref"), ExcludeTokenRef: c.Query("exclude_token_ref"), RequestId: c.Query("request_id")} + viewerRole := c.GetInt("role") + if c.FullPath() == "/api/audit/self" { + filter.UserId = c.GetInt("id") + filter.Username = "" + filter.SelfView = true + } + if !model.ValidAuditCategory(filter.Category) || !model.ValidTokenFingerprint(filter.TokenRef) || !model.ValidTokenFingerprint(filter.ExcludeTokenRef) { + common.ApiErrorMsg(c, "Invalid audit filters") + return + } + for name, target := range map[string]*int64{"start_timestamp": &filter.StartTimestamp, "end_timestamp": &filter.EndTimestamp} { + if raw := c.Query(name); raw != "" { + parsed, err := strconv.ParseInt(raw, 10, 64) + if err != nil || parsed < 0 { + common.ApiErrorMsg(c, "Invalid audit time range") + return + } + *target = parsed + } + } + if filter.EndTimestamp > 0 && filter.EndTimestamp < filter.StartTimestamp { + common.ApiErrorMsg(c, "Invalid audit time range") + return + } + if raw := c.Query("success"); raw != "" { + if raw != "true" && raw != "false" { + common.ApiErrorMsg(c, "Invalid audit result") + return + } + success := raw == "true" + filter.Success = &success + } + logs, total, err := model.GetAuditLogs(filter, page.GetStartIdx(), page.GetPageSize(), viewerRole) + if err != nil { + common.ApiError(c, err) + return + } + page.SetItems(logs) + page.SetTotal(int(total)) + common.ApiSuccess(c, page) +} diff --git a/controller/access_token_audit_test.go b/controller/access_token_audit_test.go new file mode 100644 index 0000000000..cb43a6b693 --- /dev/null +++ b/controller/access_token_audit_test.go @@ -0,0 +1,855 @@ +package controller + +import ( + "context" + "errors" + "fmt" + sqlmysql "github.com/go-sql-driver/mysql" + "gorm.io/driver/clickhouse" + "net" + "net/http" + "net/http/httptest" + "net/url" + "os" + "strings" + "testing" + "time" + + "github.com/QuantumNous/new-api/common" + "github.com/QuantumNous/new-api/middleware" + "github.com/QuantumNous/new-api/model" + "github.com/QuantumNous/new-api/service" + "github.com/QuantumNous/new-api/service/authz" + "github.com/gin-gonic/gin" + "github.com/glebarez/sqlite" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gorm.io/driver/mysql" + "gorm.io/driver/postgres" + "gorm.io/gorm" +) + +func setupAccessTokenAudit(t *testing.T) (*model.User, string) { + t.Helper() + previousDB, previousLogDB := model.DB, model.LOG_DB + previousMain, previousLog := common.MainDatabaseType(), common.LogDatabaseType() + previousRedis := common.RedisEnabled + db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) + require.NoError(t, err) + require.NoError(t, db.AutoMigrate(&model.User{}, &model.UserSession{}, &model.Log{}, &model.AuditLog{}, &model.CasbinRule{}, &model.AuthzRole{})) + model.DB, model.LOG_DB = db, db + common.SetDatabaseTypes(common.DatabaseTypeSQLite, common.DatabaseTypeSQLite) + common.RedisEnabled = false + previousMaster := common.IsMasterNode + common.IsMasterNode = true + require.NoError(t, authz.Init(db)) + t.Cleanup(func() { + model.DB, model.LOG_DB = previousDB, previousLogDB + common.IsMasterNode = previousMaster + common.SetDatabaseTypes(previousMain, previousLog) + common.RedisEnabled = previousRedis + }) + token := "legacy-opaque-token" + user := &model.User{Username: "audit-owner", Password: "placeholder", Role: common.RoleAdminUser, Status: common.UserStatusEnabled, Group: "default", AccessToken: &token, AuthVersion: 1, AffCode: "audit-owner"} + require.NoError(t, db.Create(user).Error) + return user, token +} + +func auditRequest(router http.Handler, method, path, token string) *httptest.ResponseRecorder { + request := httptest.NewRequest(method, path, strings.NewReader(`{"secret":"body-must-not-be-logged"}`)) + request.Header.Set("Authorization", "Bearer "+token) + request.Header.Set("User-Agent", "audit-test-client") + request.RemoteAddr = "192.0.2.8:4567" + response := httptest.NewRecorder() + router.ServeHTTP(response, request) + return response +} + +func TestAccessTokenLifecycleAndLateRequests(t *testing.T) { + user, old := setupAccessTokenAudit(t) + router := gin.New() + router.Use(middleware.RequestId(), middleware.AccessTokenAudit()) + router.GET("/api/user/token/status", middleware.UserAuth(), GetAccessTokenStatus) + router.GET("/api/user/token", middleware.UserAuth(), GenerateAccessToken) + router.POST("/api/user/token", middleware.UserAuth(), GenerateAccessToken) + router.DELETE("/api/user/token", middleware.UserAuth(), RevokeAccessToken) + // Rotate during the handler, after authentication has captured the old PAT. + router.POST("/rotate-in-flight", middleware.UserAuth(), func(c *gin.Context) { + require.NoError(t, model.UpdateUserAccessToken(user.Id, "new-token")) + c.JSON(200, gin.H{"success": true}) + }) + status, err := model.GetUserAccessTokenStatus(user.Id) + require.NoError(t, err) + assert.True(t, status.Exists) + assert.Nil(t, status.CreatedAt) + assert.Nil(t, status.LastUsedAt) + assert.NotContains(t, auditRequest(router, "GET", "/api/user/token/status", old).Body.String(), old) + require.Equal(t, 200, auditRequest(router, "POST", "/rotate-in-flight", old).Code) + status, err = model.GetUserAccessTokenStatus(user.Id) + require.NoError(t, err) + assert.Equal(t, model.AccessTokenFingerprint("new-token"), status.TokenRef) + assert.NotNil(t, status.CreatedAt) + assert.Nil(t, status.LastUsedAt, "in-flight old requests must not mark the new generation as used") + assert.Equal(t, 401, auditRequest(router, "GET", "/api/user/token/status", old).Code) + for _, method := range []string{"POST", "GET"} { + response := auditRequest(router, method, "/api/user/token", "new-token") + var result struct { + Success bool + Data string + } + require.NoError(t, common.Unmarshal(response.Body.Bytes(), &result)) + require.True(t, result.Success) + require.GreaterOrEqual(t, len(result.Data), 28) + require.LessOrEqual(t, len(result.Data), 32) + assert.Equal(t, 401, auditRequest(router, "GET", "/api/user/token/status", "new-token").Code) + require.NoError(t, model.UpdateUserAccessToken(user.Id, "new-token")) + } + response := auditRequest(router, "DELETE", "/api/user/token", "new-token") + assert.Contains(t, response.Body.String(), `"success":true`) + assert.Equal(t, 401, auditRequest(router, "GET", "/api/user/token/status", "new-token").Code) + ref, err := model.RevokeUserAccessToken(user.Id) + require.NoError(t, err) + assert.Empty(t, ref, "repeated revocation is idempotent") + status, err = model.GetUserAccessTokenStatus(user.Id) + require.NoError(t, err) + assert.False(t, status.Exists) + assert.Nil(t, status.CreatedAt) + var history []model.AuditLog + require.NoError(t, model.LOG_DB.Find(&history).Error) + require.NotEmpty(t, history) + encoded, err := common.Marshal(history) + require.NoError(t, err) + for _, secret := range []string{old, "new-token", "body-must-not-be-logged", "Authorization"} { + assert.NotContains(t, string(encoded), secret) + } +} + +func TestAccessTokenAuditsResultsAndExcludesBrowserSessions(t *testing.T) { + user, pat := setupAccessTokenAudit(t) + router := gin.New() + router.Use(middleware.RequestId(), middleware.AccessTokenAudit()) + router.NoRoute(func(c *gin.Context) { c.JSON(404, gin.H{"success": false}) }) + router.GET("/public", func(c *gin.Context) { c.JSON(200, gin.H{"success": true}) }) + router.GET("/rate-limited", func(c *gin.Context) { c.AbortWithStatusJSON(429, gin.H{"success": false}) }, middleware.UserAuth()) + router.GET("/read/:id", middleware.UserAuth(), func(c *gin.Context) { c.JSON(200, gin.H{"success": true}) }) + router.POST("/write", middleware.AdminAuth(), func(c *gin.Context) { + recordManageAudit(c, "option.update", map[string]interface{}{"key": "safe-setting"}) + c.JSON(200, gin.H{"success": true}) + }) + router.POST("/business-failure", middleware.AdminAuth(), func(c *gin.Context) { c.JSON(200, gin.H{"success": false, "message": "secret-response"}) }) + router.GET("/forbidden", middleware.RootAuth(), func(c *gin.Context) { c.Status(204) }) + cases := []struct { + method, path string + status int + success bool + }{{"GET", "/missing", 404, false}, {"GET", "/public", 200, true}, {"GET", "/rate-limited", 429, false}, {"GET", "/read/sensitive-id?password=secret-query", 200, true}, {"POST", "/write", 200, true}, {"POST", "/business-failure", 200, false}, {"GET", "/forbidden", 403, false}} + for _, tc := range cases { + response := auditRequest(router, tc.method, tc.path, pat) + require.Equal(t, tc.status, response.Code) + var access model.AuditLog + require.NoError(t, model.LOG_DB.Where("request_id = ? AND category = ?", response.Header().Get(common.RequestIdKey), model.AuditCategoryAccessToken).First(&access).Error) + assert.Equal(t, tc.success, access.Success) + assert.Equal(t, tc.status, access.Status) + assert.Equal(t, user.Id, access.UserId) + assert.Equal(t, "192.0.2.8", access.Ip) + assert.Equal(t, "audit-test-client", access.UserAgent) + assert.NotContains(t, access.Route, "sensitive-id") + } + var operationCount int64 + require.NoError(t, model.LOG_DB.Model(&model.AuditLog{}).Where("category = ?", model.AuditCategoryOperation).Count(&operationCount).Error) + assert.EqualValues(t, 2, operationCount, "manual operation must not be duplicated by fallback") + now := time.Now().Unix() + session := &model.UserSession{SID: "audit-session", UserID: user.Id, Version: 1, UserAuthVersion: 1, Status: model.UserSessionStatusActive, RefreshHash: "refresh-placeholder", LoginMethod: "password", LastActiveAt: now, ExpiresAt: now + 3600} + require.NoError(t, model.CreateUserSession(session)) + jwt, _, err := service.IssueAccessToken(service.AuthIdentity{UserID: user.Id, SessionID: session.SID, UserAuthVersion: 1, SessionVersion: 1}) + require.NoError(t, err) + assert.Equal(t, 200, auditRequest(router, "GET", "/read/123", jwt).Code) + assert.Equal(t, 401, auditRequest(router, "GET", "/read/123", "unknown-token").Code) + entries, total, err := model.GetAuditLogs(model.AuditLogFilter{Category: model.AuditCategoryAccessToken}, 0, 20, common.RoleRootUser) + require.NoError(t, err) + assert.EqualValues(t, 7, total) + encoded, err := common.Marshal(entries) + require.NoError(t, err) + for _, secret := range []string{pat, jwt, "secret-query", "secret-response", "body-must-not-be-logged", "sensitive-id"} { + assert.NotContains(t, string(encoded), secret) + } +} + +func TestAuditIsolationVisibilityAndFailureContracts(t *testing.T) { + user, pat := setupAccessTokenAudit(t) + metadata := model.AuditOther{ + Op: &model.AuditOperation{Action: "generic"}, + AdminInfo: &model.AuditAdminInfo{AdminID: 1}, + RootInfo: model.AuditFields{"private": "root-only"}, + } + for _, owner := range []int{user.Id, user.Id + 1} { + model.RecordAuditLog(nil, model.AuditLog{ActorRole: common.RoleAdminUser, UserId: owner, Username: fmt.Sprint(owner), Category: model.AuditCategorySecurity, Success: false, Other: metadata}) + } + router := gin.New() + router.Use(middleware.RequestId(), middleware.AccessTokenAudit()) + router.GET("/api/audit/self", middleware.UserAuth(), GetAuditLogs) + router.GET("/api/audit", middleware.AdminAuth(), middleware.RequirePermission(authz.AuditRead), GetAuditLogs) + response := auditRequest(router, "GET", "/api/audit/self?username=other&user_id=2&category=security&success=false&page_size=1", pat) + var result struct { + Success bool + Data struct { + Items []model.AuditLog + Total int + } + } + require.NoError(t, common.Unmarshal(response.Body.Bytes(), &result)) + require.True(t, result.Success) + require.Equal(t, 1, result.Data.Total) + require.Len(t, result.Data.Items, 1) + assert.Equal(t, user.Id, result.Data.Items[0].UserId) + assert.NotContains(t, response.Body.String(), "admin_info") + assert.NotContains(t, response.Body.String(), "root-only") + var payload struct { + Data struct { + Items []struct { + Other map[string]interface{} `json:"other"` + } + } + } + require.NoError(t, common.Unmarshal(response.Body.Bytes(), &payload), "audit metadata must be a JSON object, not an encoded string") + require.Len(t, payload.Data.Items, 1) + assert.Contains(t, payload.Data.Items[0].Other, "op") + require.NoError(t, authz.SetUserPermissions(user.Id, authz.PermissionsMap{authz.ResourceAudit: {authz.ActionRead: true}})) + response = auditRequest(router, "GET", "/api/audit?category=security", pat) + assert.Contains(t, response.Body.String(), "admin_info") + assert.NotContains(t, response.Body.String(), "root-only") + for _, query := range []string{"success=bad", "category=bad", "token_ref=secret", "start_timestamp=-1", "start_timestamp=2&end_timestamp=1", "p=-1", "page_size=-1"} { + assert.Contains(t, auditRequest(router, "GET", "/api/audit/self?"+query, pat).Body.String(), `"success":false`) + } + require.NoError(t, model.LOG_DB.Callback().Query().Before("gorm:query").Register("audit:fail", func(tx *gorm.DB) { + if tx.Statement.Table == "audit_logs" { + tx.AddError(errors.New("audit store unavailable")) + } + })) + _, err := model.GetUserAccessTokenStatus(user.Id) + require.Error(t, err, "audit query failure must not look like never used") + model.LOG_DB.Callback().Query().Remove("audit:fail") + require.NoError(t, model.DB.Callback().Update().Before("gorm:update").Register("audit:write-fail", func(tx *gorm.DB) { tx.AddError(errors.New("write unavailable")) })) + require.Error(t, model.UpdateUserAccessToken(user.Id, "replacement")) + _, err = model.RevokeUserAccessToken(user.Id) + require.Error(t, err) + model.DB.Callback().Update().Remove("audit:write-fail") + status, err := model.GetUserAccessTokenStatus(user.Id) + require.NoError(t, err) + assert.Equal(t, model.AccessTokenFingerprint(pat), status.TokenRef) +} + +func TestAuditRoleVisibilityAndPermissions(t *testing.T) { + admin, pat := setupAccessTokenAudit(t) + rootToken := "root-audit-token" + root := &model.User{Username: "root-audit", Role: common.RoleRootUser, Status: common.UserStatusEnabled, AuthVersion: 1, AccessToken: &rootToken, AffCode: "root-audit"} + require.NoError(t, model.DB.Create(root).Error) + metadata := model.AuditOther{ + AdminInfo: &model.AuditAdminInfo{AdminID: 1}, + RootInfo: model.AuditFields{"private": "root-only"}, + } + for i, role := range []int{1, 10, 100, 0, -1, 99} { + model.RecordAuditLog(nil, model.AuditLog{ActorRole: role, UserId: admin.Id, Username: admin.Username, Category: model.AuditCategorySecurity, RequestId: fmt.Sprintf("role-%d", role), CreatedAt: int64(100 + i), Other: metadata}) + } + model.RecordAuditLog(nil, model.AuditLog{ActorRole: 100, UserId: root.Id, Username: root.Username, Category: model.AuditCategorySecurity, RequestId: "root-owned", Other: metadata}) + router := gin.New() + router.Use(middleware.RequestId(), middleware.AccessTokenAudit()) + router.GET("/api/audit", middleware.AdminAuth(), middleware.RequirePermission(authz.AuditRead), GetAuditLogs) + router.GET("/api/audit/self", middleware.UserAuth(), GetAuditLogs) + now := time.Now().Unix() + session := &model.UserSession{SID: "audit-permissions-session", UserID: admin.Id, Version: 1, UserAuthVersion: 1, Status: model.UserSessionStatusActive, RefreshHash: "placeholder", LoginMethod: "password", LastActiveAt: now, ExpiresAt: now + 3600} + require.NoError(t, model.CreateUserSession(session)) + jwt, _, err := service.IssueAccessToken(service.AuthIdentity{UserID: admin.Id, SessionID: session.SID, UserAuthVersion: 1, SessionVersion: 1}) + require.NoError(t, err) + for _, credential := range []string{pat, jwt} { + assert.Equal(t, http.StatusForbidden, auditRequest(router, "GET", "/api/audit", credential).Code) + } + require.NoError(t, model.DB.Transaction(func(tx *gorm.DB) error { + return authz.SetUserPermissionsInTx(tx, admin.Id, authz.PermissionsMap{authz.ResourceAudit: {authz.ActionRead: true}}) + })) + require.NoError(t, authz.ReloadPolicy()) + for _, credential := range []string{pat, jwt} { + for _, endpoint := range []string{"/api/audit", "/api/audit/self"} { + response := auditRequest(router, "GET", endpoint+"?category=security&page_size=1", credential) + assert.Equal(t, http.StatusOK, response.Code) + var result struct { + Data struct { + Total int + Items []model.AuditLog + } + } + require.NoError(t, common.Unmarshal(response.Body.Bytes(), &result)) + assert.Equal(t, 2, result.Data.Total) + require.Len(t, result.Data.Items, 1) + assert.Equal(t, 10, result.Data.Items[0].ActorRole) + assert.NotContains(t, response.Body.String(), "root-only") + for _, filter := range []string{"request_id=role-100", "username=" + root.Username, "request_id=role-0"} { + filtered := auditRequest(router, "GET", endpoint+"?category=security&"+filter, credential) + // self ignores supplied usernames, while still excluding every root row. + if endpoint == "/api/audit/self" && strings.HasPrefix(filter, "username=") { + continue + } + assert.Contains(t, filtered.Body.String(), `"total":0`) + } + } + } + rootSelf := auditRequest(router, "GET", "/api/audit/self?category=security", rootToken) + assert.Contains(t, rootSelf.Body.String(), `"actor_role":100`) + assert.NotContains(t, rootSelf.Body.String(), "admin_info") + rootAll := auditRequest(router, "GET", "/api/audit?category=security", rootToken) + assert.Contains(t, rootAll.Body.String(), `"total":7`) + assert.Contains(t, rootAll.Body.String(), "root-only") + require.NoError(t, authz.SetUserPermissions(admin.Id, authz.PermissionsMap{authz.ResourceAudit: {authz.ActionRead: false}})) + for _, credential := range []string{pat, jwt} { + assert.Equal(t, http.StatusForbidden, auditRequest(router, "GET", "/api/audit", credential).Code) + assert.Equal(t, http.StatusOK, auditRequest(router, "GET", "/api/audit/self", credential).Code) + } +} + +func TestAuditRoleSnapshotSurvivesActorChanges(t *testing.T) { + user, pat := setupAccessTokenAudit(t) + user.Role = common.RoleRootUser + require.NoError(t, model.DB.Model(user).Update("role", user.Role).Error) + router := gin.New() + router.Use(middleware.RequestId(), middleware.AccessTokenAudit()) + router.POST("/change-role", middleware.UserAuth(), func(c *gin.Context) { + recordLoginAudit(user, c) + recordUserSecurityAudit(c, user.Id, "user.security_verify", nil) + recordSubscriptionResetUserLogs(c, &model.SubscriptionResetResult{ResetCount: 1, PlanId: 1, PlanTitle: "Plan", AffectedUserIds: []int{999}}, auditOperatorInfo(c)) + require.NoError(t, model.DB.Model(user).Update("role", common.RoleAdminUser).Error) + c.Status(200) + }) + require.Equal(t, http.StatusOK, auditRequest(router, "POST", "/change-role", pat).Code) + entries, total, err := model.GetAuditLogs(model.AuditLogFilter{}, 0, 20, common.RoleAdminUser) + require.NoError(t, err) + assert.Zero(t, total) + assert.Empty(t, entries) + status, err := model.GetUserAccessTokenStatus(user.Id) + require.NoError(t, err) + assert.Nil(t, status.LastUsedAt, "a root request must not leak through the last-use summary after demotion") + require.NoError(t, model.DB.Unscoped().Delete(user).Error) + entries, total, err = model.GetAuditLogs(model.AuditLogFilter{}, 0, 20, common.RoleRootUser) + require.NoError(t, err) + assert.EqualValues(t, 4, total) + for _, entry := range entries { + assert.Equal(t, common.RoleRootUser, entry.ActorRole) + } +} + +func TestSecurityAndOperationEventsUseAuditTable(t *testing.T) { + user, _ := setupAccessTokenAudit(t) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest("POST", "/event", nil) + c.Set("id", user.Id) + c.Set("username", user.Username) + c.Set("role", user.Role) + c.Set(common.RequestIdKey, "correlated-request") + recordLoginAudit(user, c) + for _, action := range []string{"user.passkey_register", "user.passkey_delete", "user.2fa_setup", "user.2fa_enable", "user.2fa_disable_self", "user.2fa_backup_codes", "user.security_verify"} { + recordUserSecurityAudit(c, user.Id, action, nil) + } + recordManageAudit(c, "option.update", map[string]interface{}{"key": "safe"}) + recordSubscriptionResetUserLogs(c, &model.SubscriptionResetResult{ResetCount: 1, PlanId: 1, PlanTitle: "Plan", AffectedUserIds: []int{user.Id}}, &model.AuditAdminInfo{AdminID: user.Id}) + for _, typ := range []int{model.LogTypeTopup, model.LogTypeConsume, model.LogTypeRefund, model.LogTypeSystem} { + model.RecordLog(user.Id, typ, "business entry") + } + var audits []model.AuditLog + require.NoError(t, model.LOG_DB.Find(&audits).Error) + assert.Len(t, audits, 10) + for _, entry := range audits { + assert.Equal(t, "correlated-request", entry.RequestId) + assert.Equal(t, user.Role, entry.ActorRole) + } + var logs []model.Log + require.NoError(t, model.LOG_DB.Find(&logs).Error) + assert.Len(t, logs, 4) + _, err := model.DeleteOldLogBatch(context.Background(), time.Now().Unix()+1, 100) + require.NoError(t, err) + var count int64 + require.NoError(t, model.LOG_DB.Model(&model.AuditLog{}).Count(&count).Error) + assert.EqualValues(t, 10, count) +} + +// Released schemas copied from v1.0.0-rc.33; only the Go type names differ. + +type releasedAuditUser struct { + Id int `json:"id"` + Username string `json:"username" gorm:"unique;index" validate:"max=20"` + Password string `json:"password" gorm:"not null;" validate:"min=8,max=20"` + OriginalPassword string `json:"original_password" gorm:"-:all"` // this field is only for Password change verification, don't save it to database! + DisplayName string `json:"display_name" gorm:"index" validate:"max=20"` + Role int `json:"role" gorm:"type:int;default:1"` // admin, common + Status int `json:"status" gorm:"type:int;default:1"` // enabled, disabled + Email string `json:"email" gorm:"index" validate:"max=50"` + GitHubId string `json:"github_id" gorm:"column:github_id;index"` + DiscordId string `json:"discord_id" gorm:"column:discord_id;index"` + OidcId string `json:"oidc_id" gorm:"column:oidc_id;index"` + WeChatId string `json:"wechat_id" gorm:"column:wechat_id;index"` + TelegramId string `json:"telegram_id" gorm:"column:telegram_id;index"` + VerificationCode string `json:"verification_code" gorm:"-:all"` // this field is only for Email verification, don't save it to database! + AccessToken *string `json:"-" gorm:"type:char(32);column:access_token;uniqueIndex"` // this token is for system management + Quota int `json:"quota" gorm:"type:int;default:0"` + UsedQuota int `json:"used_quota" gorm:"type:int;default:0;column:used_quota"` // used quota + RequestCount int `json:"request_count" gorm:"type:int;default:0;"` // request number + Group string `json:"group" gorm:"type:varchar(64);default:'default'"` + AffCode string `json:"aff_code" gorm:"type:varchar(32);column:aff_code;uniqueIndex"` + AffCount int `json:"aff_count" gorm:"type:int;default:0;column:aff_count"` + AffQuota int `json:"aff_quota" gorm:"type:int;default:0;column:aff_quota"` // 邀请剩余额度 + AffHistoryQuota int `json:"aff_history_quota" gorm:"type:int;default:0;column:aff_history"` // 邀请历史额度 + InviterId int `json:"inviter_id" gorm:"type:int;column:inviter_id;index"` + DeletedAt gorm.DeletedAt `gorm:"index"` + LinuxDOId string `json:"linux_do_id" gorm:"column:linux_do_id;index"` + Setting string `json:"setting" gorm:"type:text;column:setting"` + Remark string `json:"remark,omitempty" gorm:"type:varchar(255)" validate:"max=255"` + StripeCustomer string `json:"stripe_customer" gorm:"type:varchar(64);column:stripe_customer;index"` + CreatedAt int64 `json:"created_at" gorm:"autoCreateTime;column:created_at"` + LastLoginAt int64 `json:"last_login_at" gorm:"default:0;column:last_login_at"` + AuthVersion int64 `json:"-" gorm:"type:bigint;not null;default:1;column:auth_version"` + AdminPermissions map[string]map[string]bool `json:"admin_permissions,omitempty" gorm:"-:all"` +} + +func (releasedAuditUser) TableName() string { return "users" } + +type releasedAuditLog struct { + Id int `json:"id" gorm:"index:idx_created_at_id,priority:2;index:idx_user_id_id,priority:2"` + UserId int `json:"user_id" gorm:"index;index:idx_user_id_id,priority:1"` + CreatedAt int64 `json:"created_at" gorm:"bigint;index:idx_created_at_id,priority:1;index:idx_created_at_type"` + Type int `json:"type" gorm:"index:idx_created_at_type"` + Content string `json:"content"` + Username string `json:"username" gorm:"index;index:index_username_model_name,priority:2;default:''"` + TokenName string `json:"token_name" gorm:"index;default:''"` + ModelName string `json:"model_name" gorm:"index;index:index_username_model_name,priority:1;default:''"` + Quota int `json:"quota" gorm:"default:0"` + PromptTokens int `json:"prompt_tokens" gorm:"default:0"` + CompletionTokens int `json:"completion_tokens" gorm:"default:0"` + UseTime int `json:"use_time" gorm:"default:0"` + IsStream bool `json:"is_stream"` + ChannelId int `json:"channel" gorm:"index"` + ChannelName string `json:"channel_name" gorm:"->"` + TokenId int `json:"token_id" gorm:"default:0;index"` + Group string `json:"group" gorm:"index"` + Ip string `json:"ip" gorm:"index;default:''"` + RequestId string `json:"request_id,omitempty" gorm:"type:varchar(64);index:idx_logs_request_id;default:''"` + UpstreamRequestId string `json:"upstream_request_id,omitempty" gorm:"type:varchar(128);index:idx_logs_upstream_request_id;default:''"` + Other string `json:"other"` +} + +func (releasedAuditLog) TableName() string { return "logs" } + +// External tests create a new database per case on a loopback-only disposable +// instance. They never drop databases or tables supplied through an environment variable. +func newAuditTestDatabase(t *testing.T, kind, dsn string) (*gorm.DB, string) { + t.Helper() + if kind == "sqlite" { + path := t.TempDir() + "/audit.db" + db, err := gorm.Open(sqlite.Open(path), &gorm.Config{}) + require.NoError(t, err) + return db, path + } + require.NotEmpty(t, dsn) + name := fmt.Sprintf("newapi_audit_%d", time.Now().UnixNano()) + var original, isolated gorm.Dialector + var newDSN string + if kind == "mysql" { + config, err := sqlmysql.ParseDSN(dsn) + require.NoError(t, err) + require.Equal(t, "tcp", config.Net) + host, _, err := net.SplitHostPort(config.Addr) + require.NoError(t, err) + require.True(t, net.ParseIP(host).IsLoopback(), "database tests only permit loopback instances") + original = mysql.Open(dsn) + config.DBName = name + newDSN = config.FormatDSN() + isolated = mysql.Open(newDSN) + } else { + parsed, err := url.Parse(dsn) + require.NoError(t, err) + require.True(t, net.ParseIP(parsed.Hostname()).IsLoopback(), "database tests only permit loopback instances") + parsed.Path = "/" + name + newDSN = parsed.String() + if kind == "clickhouse" { + original = clickhouse.Open(dsn) + isolated = clickhouse.Open(newDSN) + } else { + original = postgres.Open(dsn) + isolated = postgres.Open(newDSN) + } + } + admin, err := gorm.Open(original, &gorm.Config{}) + require.NoError(t, err) + // No IF NOT EXISTS: a collision fails before any test data can be written. + createSQL := "CREATE DATABASE " + name + if kind == "mysql" { + createSQL += " CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci" + } + require.NoError(t, admin.Exec(createSQL).Error) + sqlDB, err := admin.DB() + require.NoError(t, err) + require.NoError(t, sqlDB.Close()) + db, err := gorm.Open(isolated, &gorm.Config{}) + require.NoError(t, err) + t.Logf("isolated database: %s (%s)", name, kind) + t.Cleanup(func() { + connection, err := db.DB() + if err == nil { + _ = connection.Close() + } + }) + return db, newDSN +} + +func verifyAuditRoleStorage(t *testing.T) { + t.Helper() + for i, role := range []int{1, 10, 100, 0, 99} { + model.RecordAuditLog(nil, model.AuditLog{ActorRole: role, UserId: 1, Username: "role-owner", CreatedAt: int64(200 + i), Category: model.AuditCategoryOperation, RequestId: fmt.Sprintf("matrix-role-%d", role)}) + } + filter := model.AuditLogFilter{Category: model.AuditCategoryOperation} + visible, total, err := model.GetAuditLogs(filter, 0, 1, common.RoleAdminUser) + require.NoError(t, err) + assert.EqualValues(t, 2, total) + require.Len(t, visible, 1) + assert.Equal(t, common.RoleAdminUser, visible[0].ActorRole) + visible, total, err = model.GetAuditLogs(filter, 1, 1, common.RoleCommonUser) + require.NoError(t, err) + assert.EqualValues(t, 2, total) + require.Len(t, visible, 1) + assert.Equal(t, common.RoleCommonUser, visible[0].ActorRole) + filter.RequestId = "matrix-role-100" + visible, total, err = model.GetAuditLogs(filter, 0, 20, common.RoleAdminUser) + require.NoError(t, err) + assert.Zero(t, total) + assert.Empty(t, visible) + visible, total, err = model.GetAuditLogs(filter, 0, 20, common.RoleRootUser) + require.NoError(t, err) + assert.EqualValues(t, 1, total) + require.Len(t, visible, 1) + assert.Equal(t, common.RoleRootUser, visible[0].ActorRole) +} + +func verifyAuditJSONStorage(t *testing.T) { + t.Helper() + columns, err := model.LOG_DB.Migrator().ColumnTypes(&model.AuditLog{}) + require.NoError(t, err) + var otherType string + for _, column := range columns { + if column.Name() == "other" { + otherType = strings.ToLower(column.DatabaseTypeName()) + } + } + assert.Equal(t, "json", otherType) + + metadata := model.AuditOther{ + Op: &model.AuditOperation{Action: "channel.update", Params: model.AuditFields{ + "id": 42, "name": "渠道", "changed_fields": []string{}, "large_id": uint64(9007199254740993), + "extra": map[string]interface{}{"attempts": 0, "permitted": false, "ratio": 1.25, "targets": []int{1, 2}}, + }}, + AdminInfo: &model.AuditAdminInfo{AdminID: 1}, + AuditInfo: &model.AuditRequestInfo{Method: "PUT", Route: "/api/channel/", Path: "/api/channel/", Status: 200, Success: false}, + RootInfo: model.AuditFields{"private": "root-only"}, + } + model.RecordAuditLog(nil, model.AuditLog{ActorRole: common.RoleCommonUser, UserId: 1, Username: "json-owner", Category: model.AuditCategorySecurity, RequestId: "matrix-json", Other: metadata}) + filter := model.AuditLogFilter{RequestId: "matrix-json"} + entries, total, err := model.GetAuditLogs(filter, 0, 20, common.RoleRootUser) + require.NoError(t, err) + require.EqualValues(t, 1, total) + require.Len(t, entries, 1) + stored, err := common.Marshal(entries[0].Other) + require.NoError(t, err) + expected, err := common.Marshal(metadata) + require.NoError(t, err) + assert.JSONEq(t, string(expected), string(stored)) + require.NotNil(t, entries[0].Other.Op) + assert.Equal(t, "channel.update", entries[0].Other.Op.Action) + require.NotNil(t, entries[0].Other.AuditInfo) + assert.False(t, entries[0].Other.AuditInfo.Success) + var details struct { + Op struct { + Params struct { + LargeId uint64 `json:"large_id"` + } + } + } + require.NoError(t, common.Unmarshal(stored, &details)) + assert.EqualValues(t, 9007199254740993, details.Op.Params.LargeId, "JSON numbers must retain their type and precision") + for _, role := range []int{common.RoleCommonUser, common.RoleAdminUser} { + entries, _, err = model.GetAuditLogs(filter, 0, 20, role) + require.NoError(t, err) + require.Len(t, entries, 1) + assert.Nil(t, entries[0].Other.RootInfo) + if role == common.RoleCommonUser { + assert.Nil(t, entries[0].Other.AdminInfo) + assert.Nil(t, entries[0].Other.AuditInfo) + } else { + assert.NotNil(t, entries[0].Other.AdminInfo) + assert.NotNil(t, entries[0].Other.AuditInfo) + } + } + model.RecordAuditLog(nil, model.AuditLog{ActorRole: common.RoleCommonUser, UserId: 1, Username: "json-owner", RequestId: "matrix-json-empty", Other: model.AuditOther{}}) + entries, _, err = model.GetAuditLogs(model.AuditLogFilter{RequestId: "matrix-json-empty"}, 0, 20, common.RoleRootUser) + require.NoError(t, err) + require.Len(t, entries, 1) + empty, err := common.Marshal(entries[0].Other) + require.NoError(t, err) + assert.JSONEq(t, `{}`, string(empty)) + for i := 0; i < 2; i++ { + require.NoError(t, model.InitLogDB()) + } + entries, total, err = model.GetAuditLogs(filter, 0, 20, common.RoleRootUser) + require.NoError(t, err) + require.EqualValues(t, 1, total) + require.Len(t, entries, 1) + stored, err = common.Marshal(entries[0].Other) + require.NoError(t, err) + assert.JSONEq(t, string(expected), string(stored), "repeated startup must retain structured audit metadata") +} + +func TestAuditOtherDatabaseEncoding(t *testing.T) { + const payload = `{"op":{"action":"channel.update","params":{"id":9007199254740993,"nested":{"count":0,"enabled":false}}},"admin_info":{"admin_id":1,"admin_username":"root","admin_role":100,"auth_method":"session"},"audit_info":{"method":"PUT","route":"/api/channel/","path":"/api/channel/","status":200,"success":false},"root_info":{"generation":18446744073709551615}}` + for _, input := range []interface{}{payload, []byte(payload)} { + var other model.AuditOther + require.NoError(t, other.Scan(input)) + require.NotNil(t, other.Op) + assert.Equal(t, "channel.update", other.Op.Action) + require.NotNil(t, other.AdminInfo) + assert.Equal(t, 100, other.AdminInfo.AdminRole) + require.NotNil(t, other.AuditInfo) + assert.False(t, other.AuditInfo.Success) + encoded, err := other.Value() + require.NoError(t, err) + text, ok := encoded.(string) + require.True(t, ok, "PostgreSQL simple protocol requires a string parameter") + assert.JSONEq(t, payload, text) + assert.Contains(t, text, "9007199254740993") + assert.Contains(t, text, "18446744073709551615") + for _, empty := range []interface{}{nil, "", []byte(`null`), "{}"} { + require.NoError(t, other.Scan(input)) + require.NoError(t, other.Scan(empty)) + encoded, err = other.Value() + require.NoError(t, err) + assert.Equal(t, "{}", encoded, "empty input must clear fields from the previous row") + } + } + var invalid model.AuditOther + assert.Error(t, invalid.Scan(42)) + assert.Error(t, invalid.Scan([]byte(`{broken`))) +} + +func TestAuditDatabaseMatrix(t *testing.T) { + previousDB, previousLogDB := model.DB, model.LOG_DB + previousMain, previousLog := common.MainDatabaseType(), common.LogDatabaseType() + previousRedis := common.RedisEnabled + previousMaster, previousSQLite := common.IsMasterNode, common.SQLitePath + common.IsMasterNode = true + common.RedisEnabled = false + t.Cleanup(func() { + common.IsMasterNode, common.SQLitePath = previousMaster, previousSQLite + model.DB, model.LOG_DB = previousDB, previousLogDB + common.SetDatabaseTypes(previousMain, previousLog) + common.RedisEnabled = previousRedis + }) + cases := []struct { + name, env string + typ common.DatabaseType + }{ + {"sqlite", "", common.DatabaseTypeSQLite}, {"mysql", "AUDIT_MYSQL_DSN", common.DatabaseTypeMySQL}, {"postgres", "AUDIT_POSTGRES_DSN", common.DatabaseTypePostgreSQL}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + dsn := os.Getenv(tc.env) + if tc.env != "" && dsn == "" { + t.Skip(tc.env + " is not configured") + } + for _, upgrade := range []bool{false, true} { + t.Run(fmt.Sprintf("upgrade=%v", upgrade), func(t *testing.T) { + db, isolatedDSN := newAuditTestDatabase(t, tc.name, dsn) + t.Setenv("LOG_SQL_DSN", "") + if tc.name == "sqlite" { + common.SQLitePath = isolatedDSN + t.Setenv("SQL_DSN", "local") + } else { + t.Setenv("SQL_DSN", isolatedDSN) + } + model.DB, model.LOG_DB = db, db + common.SetDatabaseTypes(tc.typ, tc.typ) + versionSQL := "SELECT version()" + if tc.name == "sqlite" { + versionSQL = "SELECT sqlite_version()" + } + var version string + require.NoError(t, db.Raw(versionSQL).Scan(&version).Error) + t.Logf("database version: %s", version) + if upgrade { + require.NoError(t, db.AutoMigrate(&releasedAuditUser{}, &releasedAuditLog{})) + legacy := "released-token" + require.NoError(t, db.Create(&releasedAuditUser{Username: "released-owner", Password: "placeholder", AccessToken: &legacy, AffCode: "released-aff", Quota: 1234}).Error) + require.NoError(t, db.Create(&releasedAuditLog{UserId: 1, Type: model.LogTypeLogin, Content: "historical login", CreatedAt: 100, RequestId: "legacy-request"}).Error) + } + for i := 0; i < 2; i++ { + require.NoError(t, model.InitDB()) + require.NoError(t, model.InitLogDB()) + } + if !upgrade { + require.NoError(t, db.Create(&model.User{Username: "fresh-owner", Password: "placeholder", AffCode: "fresh-aff"}).Error) + } + status, err := model.GetUserAccessTokenStatus(1) + require.NoError(t, err) + assert.Equal(t, upgrade, status.Exists) + assert.Nil(t, status.CreatedAt) + if upgrade { + assert.Equal(t, model.AccessTokenFingerprint("released-token"), status.TokenRef) + legacyUser, validationErr := model.ValidateAccessToken("released-token") + require.NoError(t, validationErr) + require.NotNil(t, legacyUser) + var user model.User + require.NoError(t, db.First(&user, 1).Error) + assert.Equal(t, 1234, user.Quota) + var old model.Log + require.NoError(t, db.First(&old).Error) + assert.Equal(t, "historical login", old.Content) + } + require.NoError(t, model.UpdateUserAccessToken(1, "matrix-token")) + require.Error(t, db.Create(&model.User{Username: "duplicate", Password: "placeholder", AffCode: "duplicate-aff", AccessToken: common.GetPointer("matrix-token")}).Error, "PAT uniqueness must survive upgrade") + for _, timestamp := range []int64{101, 102, 103} { + model.RecordAuditLog(nil, model.AuditLog{ActorRole: common.RoleAdminUser, UserId: 1, Username: "owner", CreatedAt: timestamp, Category: model.AuditCategoryAccessToken, TokenRef: model.AccessTokenFingerprint("matrix-token"), Ip: "192.0.2.1", Success: timestamp != 102}) + } + first, total, err := model.GetAuditLogs(model.AuditLogFilter{UserId: 1}, 0, 2, common.RoleCommonUser) + require.NoError(t, err) + assert.EqualValues(t, 3, total) + require.Len(t, first, 2) + assert.EqualValues(t, 103, first[0].CreatedAt) + second, _, err := model.GetAuditLogs(model.AuditLogFilter{UserId: 1}, 2, 2, common.RoleCommonUser) + require.NoError(t, err) + require.Len(t, second, 1) + assert.EqualValues(t, 101, second[0].CreatedAt) + failure := false + failed, _, err := model.GetAuditLogs(model.AuditLogFilter{UserId: 1, Success: &failure}, 0, 10, 1) + require.NoError(t, err) + require.Len(t, failed, 1) + assert.EqualValues(t, 102, failed[0].CreatedAt) + status, err = model.GetUserAccessTokenStatus(1) + require.NoError(t, err) + require.NotNil(t, status.LastUsedAt) + assert.EqualValues(t, 103, *status.LastUsedAt) + _, err = model.RevokeUserAccessToken(1) + require.NoError(t, err) + _, err = model.RevokeUserAccessToken(1) + require.NoError(t, err) + require.NoError(t, model.MigrateAuditLogs()) + _, total, err = model.GetAuditLogs(model.AuditLogFilter{UserId: 1}, 0, 10, 1) + require.NoError(t, err) + assert.EqualValues(t, 3, total) + verifyAuditRoleStorage(t) + verifyAuditJSONStorage(t) + require.NoError(t, authz.Init(model.DB)) + assert.False(t, authz.Can(1, common.RoleAdminUser, authz.AuditRead)) + require.NoError(t, model.DB.Transaction(func(tx *gorm.DB) error { + return authz.SetUserPermissionsInTx(tx, 1, authz.PermissionsMap{authz.ResourceAudit: {authz.ActionRead: true}}) + })) + require.NoError(t, authz.ReloadPolicy()) + assert.True(t, authz.Can(1, common.RoleAdminUser, authz.AuditRead)) + require.NoError(t, authz.Init(model.DB)) + require.NoError(t, authz.Init(model.DB)) + assert.True(t, authz.Can(1, common.RoleAdminUser, authz.AuditRead)) + require.NoError(t, model.DB.Transaction(func(tx *gorm.DB) error { + return authz.SetUserPermissionsInTx(tx, 1, authz.PermissionsMap{authz.ResourceAudit: {authz.ActionRead: false}}) + })) + require.NoError(t, authz.ReloadPolicy()) + assert.False(t, authz.Can(1, common.RoleAdminUser, authz.AuditRead)) + assert.True(t, authz.Can(1, common.RoleRootUser, authz.AuditRead)) + }) + } + }) + } +} + +func TestIndependentAuditLogStores(t *testing.T) { + _, _ = setupAccessTokenAudit(t) + previousMaster := common.IsMasterNode + common.IsMasterNode = true + t.Cleanup(func() { common.IsMasterNode = previousMaster }) + for _, tc := range []struct{ kind, env string }{{"mysql", "AUDIT_MYSQL_DSN"}, {"postgres", "AUDIT_POSTGRES_DSN"}, {"clickhouse", "AUDIT_CLICKHOUSE_DSN"}} { + for _, upgrade := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/upgrade=%v", tc.kind, upgrade), func(t *testing.T) { + dsn := os.Getenv(tc.env) + if dsn == "" { + t.Skip(tc.env + " is not configured") + } + logDB, isolatedDSN := newAuditTestDatabase(t, tc.kind, dsn) + if upgrade { + if tc.kind == "clickhouse" { + require.NoError(t, logDB.Exec(releasedClickHouseLogSchema).Error) + } else { + require.NoError(t, logDB.AutoMigrate(&releasedAuditLog{})) + } + require.NoError(t, logDB.Create(&releasedAuditLog{UserId: 1, Username: "legacy", CreatedAt: time.Now().Unix(), Type: model.LogTypeLogin, Content: "retained historical login", RequestId: "legacy-split-request"}).Error) + } + t.Setenv("LOG_SQL_DSN", isolatedDSN) + t.Setenv("LOG_SQL_CLICKHOUSE_TTL_DAYS", "7") + require.NoError(t, model.InitLogDB()) + require.NoError(t, model.InitLogDB()) + if upgrade { + var old model.Log + require.NoError(t, model.LOG_DB.Where("request_id = ?", "legacy-split-request").Take(&old).Error) + assert.Equal(t, "retained historical login", old.Content) + } + require.NoError(t, model.UpdateUserAccessToken(1, "independent-pat")) + model.RecordAuditLog(nil, model.AuditLog{ActorRole: common.RoleAdminUser, UserId: 1, Username: "independent", Category: model.AuditCategoryAccessToken, TokenRef: model.AccessTokenFingerprint("independent-pat"), Ip: "192.0.2.8", Success: false, Status: 403}) + entries, total, err := model.GetAuditLogs(model.AuditLogFilter{UserId: 1}, 0, 20, common.RoleAdminUser) + require.NoError(t, err) + assert.EqualValues(t, 1, total) + require.Len(t, entries, 1) + assert.False(t, entries[0].Success) + status, err := model.GetUserAccessTokenStatus(1) + require.NoError(t, err) + require.NotNil(t, status.LastUsedAt) + assert.Equal(t, "192.0.2.8", status.LastUsedIp) + model.RecordLog(1, model.LogTypeTopup, "independent business") + _, err = model.DeleteOldLogBatch(context.Background(), time.Now().Unix()+1, 100) + require.NoError(t, err) + _, total, err = model.GetAuditLogs(model.AuditLogFilter{UserId: 1}, 0, 20, 1) + require.NoError(t, err) + assert.EqualValues(t, 1, total) + var mainCount int64 + require.NoError(t, model.DB.Model(&model.AuditLog{}).Count(&mainCount).Error) + assert.Zero(t, mainCount) + verifyAuditRoleStorage(t) + verifyAuditJSONStorage(t) + if tc.kind == "clickhouse" { + var create string + require.NoError(t, model.LOG_DB.Raw("SHOW CREATE TABLE audit_logs").Scan(&create).Error) + assert.NotContains(t, strings.ToUpper(create), "TTL") + require.NoError(t, model.LOG_DB.Raw("SHOW CREATE TABLE logs").Scan(&create).Error) + assert.Contains(t, strings.ToUpper(create), "TTL") + } + }) + } + } +} + +// ClickHouse logs schema from v1.0.0-rc.33. +const releasedClickHouseLogSchema = ` +CREATE TABLE IF NOT EXISTS logs ( + id Int64 DEFAULT 0, + user_id Int32 DEFAULT 0, + created_at Int64 DEFAULT 0, + type Int32 DEFAULT 0, + content String DEFAULT '', + username String DEFAULT '', + token_name String DEFAULT '', + model_name String DEFAULT '', + quota Int32 DEFAULT 0, + prompt_tokens Int32 DEFAULT 0, + completion_tokens Int32 DEFAULT 0, + use_time Int32 DEFAULT 0, + is_stream UInt8 DEFAULT 0, + channel_id Int32 DEFAULT 0, + token_id Int32 DEFAULT 0, + ` + "`group`" + ` String DEFAULT '', + ip String DEFAULT '', + request_id String DEFAULT '', + upstream_request_id String DEFAULT '', + other String DEFAULT '' +) +ENGINE = MergeTree() +PARTITION BY toYYYYMM(toDateTime(created_at)) +ORDER BY (created_at, request_id)` diff --git a/controller/audit.go b/controller/audit.go index d6974b9008..f6a934907e 100644 --- a/controller/audit.go +++ b/controller/audit.go @@ -26,6 +26,13 @@ var auditContentTemplates = map[string]string{ "user.binding_clear": "Cleared ${bindingType} binding for user ${username}", "user.2fa_disable": "Force-disabled two-factor authentication for the user", "user.passkey_register": "Registered a passkey", + "access_token.generate": "Generated a system access token", + "access_token.revoke": "Revoked the system access token", + "user.2fa_setup": "Started two-factor authentication setup", + "user.2fa_enable": "Enabled two-factor authentication", + "user.2fa_disable_self": "Disabled two-factor authentication", + "user.2fa_backup_codes": "Regenerated two-factor backup codes", + "user.security_verify": "Completed security verification", "user.passkey_delete": "Deleted a passkey", "user.reset_passkey": "Reset the user passkey", "option.update": "Updated system setting ${key}", @@ -66,12 +73,12 @@ func auditContentEN(action string, params map[string]interface{}) string { } // auditOperatorInfo 从上下文构建操作者身份信息(管理员 id/用户名/角色)。 -func auditOperatorInfo(c *gin.Context) map[string]interface{} { - return map[string]interface{}{ - "admin_id": c.GetInt("id"), - "admin_username": c.GetString("username"), - "admin_role": c.GetInt("role"), - "auth_method": auditAuthMethod(c), +func auditOperatorInfo(c *gin.Context) *model.AuditAdminInfo { + return &model.AuditAdminInfo{ + AdminID: c.GetInt("id"), + AdminUsername: c.GetString("username"), + AdminRole: c.GetInt("role"), + AuthMethod: auditAuthMethod(c), } } @@ -104,12 +111,12 @@ func recordManageAuditFor(c *gin.Context, targetUserId int, action string, param if _, ok := params["target_user_id"]; !ok && targetUserId > 0 && targetUserId != operatorUserId { params["target_user_id"] = targetUserId } - model.RecordOperationAuditLog(operatorUserId, auditContentEN(action, params), c.ClientIP(), action, params, auditOperatorInfo(c), nil) + model.RecordOperationAuditLog(operatorUserId, c.GetInt("role"), auditContentEN(action, params), c.ClientIP(), action, params, auditOperatorInfo(c), nil, c) markAuditLogged(c) } // recordUserSecurityAudit 记录普通用户自己的安全敏感操作(如 passkey 绑定/解绑)。 // 这类日志没有管理员操作者,不写 admin_info;同时不依赖 AdminAuth/RootAuth 的兜底。 func recordUserSecurityAudit(c *gin.Context, userId int, action string, params map[string]interface{}) { - model.RecordOperationAuditLog(userId, auditContentEN(action, params), c.ClientIP(), action, params, nil, nil) + model.RecordOperationAuditLog(userId, c.GetInt("role"), auditContentEN(action, params), c.ClientIP(), action, params, nil, nil, c) } diff --git a/controller/billing_option_test.go b/controller/billing_option_test.go index cf6b37ea53..529fa6e8e8 100644 --- a/controller/billing_option_test.go +++ b/controller/billing_option_test.go @@ -113,7 +113,7 @@ func setupBillingAliasOptionDB(t *testing.T) { previousRedis := common.RedisEnabled database, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) require.NoError(t, err) - require.NoError(t, database.AutoMigrate(&model.Channel{}, &model.Option{}, &model.Log{}, &model.User{})) + require.NoError(t, database.AutoMigrate(&model.Channel{}, &model.Option{}, &model.Log{}, &model.AuditLog{}, &model.User{})) model.DB = database model.LOG_DB = database common.SetMainDatabaseType(common.DatabaseTypeSQLite) diff --git a/controller/channel_task_plugin_bind_test.go b/controller/channel_task_plugin_bind_test.go index b8f3266615..192e57fb9e 100644 --- a/controller/channel_task_plugin_bind_test.go +++ b/controller/channel_task_plugin_bind_test.go @@ -31,7 +31,7 @@ func setupTaskPluginBindChannelTest(t *testing.T) { sqlDB, err := database.DB() require.NoError(t, err) sqlDB.SetMaxOpenConns(1) - require.NoError(t, database.AutoMigrate(&model.Channel{}, &model.Ability{}, &model.CasbinRule{}, &model.AuthzRole{}, &model.Log{}, &model.User{})) + require.NoError(t, database.AutoMigrate(&model.Channel{}, &model.Ability{}, &model.CasbinRule{}, &model.AuthzRole{}, &model.Log{}, &model.AuditLog{}, &model.User{})) model.DB = database model.LOG_DB = database require.NoError(t, authz.Init(database)) diff --git a/controller/channel_test_internal_test.go b/controller/channel_test_internal_test.go index 5f19aeb866..66a394aada 100644 --- a/controller/channel_test_internal_test.go +++ b/controller/channel_test_internal_test.go @@ -166,7 +166,7 @@ func TestCopyChannelRejectsInvalidLegacyProxySettings(t *testing.T) { func TestDeleteChannelResetsProxyCacheWhenPreReadFails(t *testing.T) { db := setupModelListControllerTestDB(t) - require.NoError(t, db.AutoMigrate(&model.Log{})) + require.NoError(t, db.AutoMigrate(&model.Log{}, &model.AuditLog{})) service.ResetProxyClientCache() t.Cleanup(service.ResetProxyClientCache) @@ -189,7 +189,7 @@ func TestDeleteChannelResetsProxyCacheWhenPreReadFails(t *testing.T) { func TestDeleteChannelBatchReportsAndAuditsActualDeletedCount(t *testing.T) { db := setupModelListControllerTestDB(t) - require.NoError(t, db.AutoMigrate(&model.Log{})) + require.NoError(t, db.AutoMigrate(&model.Log{}, &model.AuditLog{})) channel := &model.Channel{Name: "existing", Key: "test-key"} require.NoError(t, db.Create(channel).Error) @@ -210,14 +210,16 @@ func TestDeleteChannelBatchReportsAndAuditsActualDeletedCount(t *testing.T) { assert.True(t, response.Success) assert.Equal(t, int64(1), response.Data) - var auditLog model.Log + var auditLog model.AuditLog require.NoError(t, db.Order("id desc").First(&auditLog).Error) var auditData struct { Operation struct { Params map[string]any `json:"params"` } `json:"op"` } - require.NoError(t, common.UnmarshalJsonStr(auditLog.Other, &auditData)) + encodedAudit, err := common.Marshal(auditLog.Other) + require.NoError(t, err) + require.NoError(t, common.Unmarshal(encodedAudit, &auditData)) assert.Equal(t, float64(1), auditData.Operation.Params["count"]) } diff --git a/controller/model_list_test.go b/controller/model_list_test.go index 812207b8fd..d1b8b83ffe 100644 --- a/controller/model_list_test.go +++ b/controller/model_list_test.go @@ -535,7 +535,7 @@ func TestCheckUpdatePasswordRejectsHistoricalEmptyPassword(t *testing.T) { func TestSetupLoginDoesNotTouchPasswordWhenPasswordFieldOmitted(t *testing.T) { db := setupModelListControllerTestDB(t) - require.NoError(t, db.AutoMigrate(&model.Log{}, &model.UserSession{})) + require.NoError(t, db.AutoMigrate(&model.Log{}, &model.AuditLog{}, &model.UserSession{})) hashedPassword, err := common.Password2Hash("CurrentPassword123") require.NoError(t, err) diff --git a/controller/relay.go b/controller/relay.go index 9da14e339f..ca9b35d8ba 100644 --- a/controller/relay.go +++ b/controller/relay.go @@ -486,6 +486,11 @@ func RelayNotImplemented(c *gin.Context) { } func RelayNotFound(c *gin.Context) { + // The web fallback may already have applied static-asset cache headers. + // A missing API or asset can appear after an upgrade; never cache its 404. + c.Header("Cache-Control", "no-store, no-cache, must-revalidate, private, max-age=0") + c.Header("Pragma", "no-cache") + c.Header("Expires", "0") err := types.OpenAIError{ Message: fmt.Sprintf("Invalid URL (%s %s)", c.Request.Method, c.Request.URL.Path), Type: "invalid_request_error", diff --git a/controller/secure_verification.go b/controller/secure_verification.go index f4d4ba8299..4095225073 100644 --- a/controller/secure_verification.go +++ b/controller/secure_verification.go @@ -65,7 +65,7 @@ func UniversalVerify(c *gin.Context) { common.ApiError(c, err) return } - model.RecordLog(identity.UserID, model.LogTypeSystem, "通用安全验证成功 (验证方式: 2FA)") + recordUserSecurityAudit(c, identity.UserID, "user.security_verify", map[string]interface{}{"method": "2fa"}) c.JSON(http.StatusOK, gin.H{ "success": true, "message": "验证成功", diff --git a/controller/subscription.go b/controller/subscription.go index 22cee9d539..3f22f373eb 100644 --- a/controller/subscription.go +++ b/controller/subscription.go @@ -407,13 +407,13 @@ func resolveAdvanceResetTime(value *bool) bool { return *value } -func recordSubscriptionResetUserLogs(result *model.SubscriptionResetResult, adminInfo map[string]interface{}) { +func recordSubscriptionResetUserLogs(c *gin.Context, result *model.SubscriptionResetResult, adminInfo *model.AuditAdminInfo) { if result == nil || result.ResetCount == 0 { return } content := fmt.Sprintf("管理员重置订阅套餐 %s(ID: %d)额度", result.PlanTitle, result.PlanId) for _, userId := range result.AffectedUserIds { - model.RecordLogWithAdminInfo(userId, model.LogTypeManage, content, adminInfo) + model.RecordLogWithAdminInfo(userId, model.LogTypeManage, content, adminInfo, c) } } @@ -466,7 +466,7 @@ func AdminResetUserSubscriptionsByPlan(c *gin.Context) { common.ApiError(c, err) return } - recordSubscriptionResetUserLogs(result, auditOperatorInfo(c)) + recordSubscriptionResetUserLogs(c, result, auditOperatorInfo(c)) recordManageAuditFor(c, userId, "subscription.user_plan_reset", map[string]interface{}{ "target_user_id": userId, "plan_id": result.PlanId, @@ -495,7 +495,7 @@ func AdminResetPlanSubscriptions(c *gin.Context) { common.ApiError(c, err) return } - recordSubscriptionResetUserLogs(result, auditOperatorInfo(c)) + recordSubscriptionResetUserLogs(c, result, auditOperatorInfo(c)) common.SysLog(fmt.Sprintf("admin reset subscription plan %d quota: reset_count=%d user_count=%d advance_reset_time=%t", result.PlanId, result.ResetCount, result.UserCount, result.AdvanceResetTime)) recordManageAudit(c, "subscription.plan_reset", map[string]interface{}{ diff --git a/controller/twofa.go b/controller/twofa.go index 27aae855dc..ff73707443 100644 --- a/controller/twofa.go +++ b/controller/twofa.go @@ -117,7 +117,7 @@ func Setup2FA(c *gin.Context) { } // 记录操作日志 - model.RecordLog(userId, model.LogTypeSystem, "开始设置两步验证") + recordUserSecurityAudit(c, userId, "user.2fa_setup", nil) c.JSON(http.StatusOK, gin.H{ "success": true, @@ -199,7 +199,7 @@ func Enable2FA(c *gin.Context) { } // 记录操作日志 - model.RecordLog(userId, model.LogTypeSystem, "成功启用两步验证") + recordUserSecurityAudit(c, userId, "user.2fa_enable", nil) c.JSON(http.StatusOK, gin.H{ "success": true, @@ -282,7 +282,7 @@ func Disable2FA(c *gin.Context) { } // 记录操作日志 - model.RecordLog(userId, model.LogTypeSystem, "禁用两步验证") + recordUserSecurityAudit(c, userId, "user.2fa_disable_self", nil) c.JSON(http.StatusOK, gin.H{ "success": true, @@ -412,7 +412,7 @@ func RegenerateBackupCodes(c *gin.Context) { } // 记录操作日志 - model.RecordLog(userId, model.LogTypeSystem, "重新生成两步验证备用码") + recordUserSecurityAudit(c, userId, "user.2fa_backup_codes", nil) data := authRotationData(bundle) data["backup_codes"] = backupCodes diff --git a/controller/user.go b/controller/user.go index f2eb20a563..aaf1b3d041 100644 --- a/controller/user.go +++ b/controller/user.go @@ -169,14 +169,14 @@ func loginMethodFromContext(c *gin.Context) string { func recordLoginAudit(user *model.User, c *gin.Context) { method := loginMethodFromContext(c) ip := c.ClientIP() - extra := map[string]interface{}{ - "login_method": method, - "user_agent": c.Request.UserAgent(), + extra := model.AuditOther{ + LoginMethod: method, + UserAgent: c.Request.UserAgent(), } content := fmt.Sprintf("Logged in successfully via %s", method) - model.RecordLoginLog(user.Id, user.Username, content, ip, "login", map[string]interface{}{ + model.RecordLoginLog(user.Id, user.Role, user.Username, content, ip, "login", map[string]interface{}{ "method": method, - }, extra) + }, extra, c) } // setupLogin creates a server-controlled login Session and returns the shared @@ -447,6 +447,8 @@ func GenerateAccessToken(c *gin.Context) { return } + recordUserSecurityAudit(c, id, "access_token.generate", map[string]interface{}{"token_ref": model.AccessTokenFingerprint(key)}) + c.JSON(http.StatusOK, gin.H{ "success": true, "message": "", diff --git a/controller/user_manage_test.go b/controller/user_manage_test.go index 9856407863..4b4ddecab3 100644 --- a/controller/user_manage_test.go +++ b/controller/user_manage_test.go @@ -32,7 +32,7 @@ func setupManageUserTestDB(t *testing.T) *gorm.DB { require.NoError(t, err) model.DB, model.LOG_DB = db, db require.NoError(t, db.AutoMigrate( - &model.User{}, &model.UserSession{}, &model.Log{}, &model.CasbinRule{}, &model.AuthzRole{}, + &model.User{}, &model.UserSession{}, &model.Log{}, &model.AuditLog{}, &model.CasbinRule{}, &model.AuthzRole{}, )) t.Cleanup(func() { diff --git a/go.mod b/go.mod index b0f997f2ee..d5d9e372da 100644 --- a/go.mod +++ b/go.mod @@ -6,7 +6,7 @@ go 1.25.1 require ( github.com/Calcium-Ion/go-epay v0.0.4 github.com/abema/go-mp4 v1.4.1 - github.com/andybalholm/brotli v1.1.1 + github.com/andybalholm/brotli v1.2.0 github.com/anknown/ahocorasick v0.0.0-20190904063843-d75dbd5169c0 github.com/aws/aws-sdk-go-v2 v1.41.5 github.com/aws/aws-sdk-go-v2/credentials v1.19.10 @@ -31,7 +31,7 @@ require ( github.com/jfreymuth/oggvorbis v1.0.5 github.com/jinzhu/copier v0.4.0 github.com/joho/godotenv v1.5.1 - github.com/klauspost/compress v1.18.0 + github.com/klauspost/compress v1.18.3 github.com/mewkiz/flac v1.0.13 github.com/nicksnyder/go-i18n/v2 v2.6.1 github.com/pkg/errors v0.9.1 @@ -67,7 +67,7 @@ require ( ) require ( - github.com/ClickHouse/ch-go v0.65.0 // indirect + github.com/ClickHouse/ch-go v0.71.0 // indirect github.com/bmatcuk/doublestar/v4 v4.6.1 // indirect github.com/casbin/govaluate v1.10.0 // indirect github.com/dlclark/regexp2/v2 v2.2.2 // indirect @@ -75,14 +75,15 @@ require ( github.com/go-faster/errors v0.7.1 // indirect github.com/go-sourcemap/sourcemap v2.1.3+incompatible // indirect github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e // indirect - github.com/hashicorp/go-version v1.7.0 // indirect - github.com/paulmach/orb v0.11.1 // indirect - github.com/pierrec/lz4/v4 v4.1.22 // indirect + github.com/hashicorp/go-version v1.8.0 // indirect + github.com/paulmach/orb v0.12.0 // indirect + github.com/pierrec/lz4/v4 v4.1.25 // indirect github.com/rogpeppe/go-internal v1.13.1 // indirect - github.com/segmentio/asm v1.2.0 // indirect + github.com/segmentio/asm v1.2.1 // indirect github.com/yuin/gopher-lua v1.1.1 // indirect - go.opentelemetry.io/otel v1.34.0 // indirect - go.opentelemetry.io/otel/trace v1.34.0 // indirect + go.opentelemetry.io/otel v1.41.0 // indirect + go.opentelemetry.io/otel/trace v1.41.0 // indirect + go.yaml.in/yaml/v3 v3.0.4 // indirect ) require ( @@ -157,7 +158,7 @@ require ( github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.2.12 // indirect github.com/x448/float16 v0.8.4 // indirect - github.com/yusufpapurcu/wmi v1.2.3 // indirect + github.com/yusufpapurcu/wmi v1.2.4 // indirect golang.org/x/arch v0.21.0 // indirect golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b // indirect google.golang.org/protobuf v1.36.5 // indirect @@ -168,7 +169,7 @@ require ( ) require ( - github.com/ClickHouse/clickhouse-go/v2 v2.32.0 + github.com/ClickHouse/clickhouse-go/v2 v2.46.0 github.com/QuantumNous/new-api/relaykit v0.0.0 ) diff --git a/go.sum b/go.sum index c9c7229a0f..1adf62ce1c 100644 --- a/go.sum +++ b/go.sum @@ -634,12 +634,12 @@ github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym github.com/Calcium-Ion/go-epay v0.0.4 h1:C96M7WfRLadcIVscWzwLiYs8etI1wrDmtFMuK2zP22A= github.com/Calcium-Ion/go-epay v0.0.4/go.mod h1:cxo/ZOg8ClvE3VAnCmEzbuyAZINSq7kFEN9oHj5WQ2U= github.com/ClickHouse/ch-go v0.58.2/go.mod h1:Ap/0bEmiLa14gYjCiRkYGbXvbe8vwdrfTYWhsuQ99aw= -github.com/ClickHouse/ch-go v0.65.0 h1:vZAXfTQliuNNefqkPDewX3kgRxN6Q4vUENnnY+ynTRY= -github.com/ClickHouse/ch-go v0.65.0/go.mod h1:tCM0XEH5oWngoi9Iu/8+tjPBo04I/FxNIffpdjtwx3k= +github.com/ClickHouse/ch-go v0.71.0 h1:bUdZ/EZj/LcVHsMqaRUP2holqygrPWQKeMjc6nZoyRM= +github.com/ClickHouse/ch-go v0.71.0/go.mod h1:NwbNc+7jaqfY58dmdDUbG4Jl22vThgx1cYjBw0vtgXw= github.com/ClickHouse/clickhouse-go v1.5.4/go.mod h1:EaI/sW7Azgz9UATzd5ZdZHRUhHgv5+JMS9NSr2smCJI= github.com/ClickHouse/clickhouse-go/v2 v2.15.0/go.mod h1:kXt1SRq0PIRa6aKZD7TnFnY9PQKmc2b13sHtOYcK6cQ= -github.com/ClickHouse/clickhouse-go/v2 v2.32.0 h1:zVWJUmUGdtCApM/vRfQhruGXIm1M643bk68B3IYbR1I= -github.com/ClickHouse/clickhouse-go/v2 v2.32.0/go.mod h1:rGFIgeNbJVggBp2C+0FXOdfjsMlpsKx7FUYnHHyy2KE= +github.com/ClickHouse/clickhouse-go/v2 v2.46.0 h1:s3eRy+hYmu5uzotB6ZhDofgHu8kDgGN/fpmjxRkqSpk= +github.com/ClickHouse/clickhouse-go/v2 v2.46.0/go.mod h1:giJfUVlMkcfUEPVfRpt51zZaGEx9i17gCos8gBl392c= github.com/DmitriyVTitov/size v1.5.0 h1:/PzqxYrOyOUX1BXj6J9OuVRVGe+66VL4D9FlUaW515g= github.com/DmitriyVTitov/size v1.5.0/go.mod h1:le6rNI4CoLQV1b9gzp1+3d7hMAD/uu2QcJ+aYbNgiU0= github.com/JohnCGriffin/overflow v0.0.0-20211019200055-46fa312c352c/go.mod h1:X0CRv0ky0k6m906ixxpzmDRLvX58TFUKS2eePweuyxk= @@ -704,8 +704,8 @@ github.com/alicebob/miniredis/v2 v2.38.0/go.mod h1:TcL7YfarKPGDAthEtl5NBeHZfeUQj github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8= github.com/andybalholm/brotli v1.0.4/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig= github.com/andybalholm/brotli v1.0.6/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig= -github.com/andybalholm/brotli v1.1.1 h1:PR2pgnyFznKEugtsUo0xLdDop5SKXd5Qf5ysW+7XdTA= -github.com/andybalholm/brotli v1.1.1/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA= +github.com/andybalholm/brotli v1.2.0 h1:ukwgCxwYrmACq68yiUqwIWnGY0cTPox/M94sVwToPjQ= +github.com/andybalholm/brotli v1.2.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY= github.com/anknown/ahocorasick v0.0.0-20190904063843-d75dbd5169c0 h1:onfun1RA+KcxaMk1lfrRnwCd1UUuOjJM/lri5eM1qMs= github.com/anknown/ahocorasick v0.0.0-20190904063843-d75dbd5169c0/go.mod h1:4yg+jNTYlDEzBjhGS96v+zjyA3lfXlFd5CiTLIkPBLI= github.com/anknown/darts v0.0.0-20151216065714-83ff685239e6 h1:HblK3eJHq54yET63qPCTJnks3loDse5xRmmqHgHzwoI= @@ -1411,8 +1411,8 @@ github.com/hashicorp/go-syslog v1.0.0/go.mod h1:qPfqrKkXGihmCqbJM2mZgkZGvKG1dFdv github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= github.com/hashicorp/go-version v1.6.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= -github.com/hashicorp/go-version v1.7.0 h1:5tqGy27NaOTB8yJKUZELlFAS/LTKJkrmONwQKeRZfjY= -github.com/hashicorp/go-version v1.7.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= +github.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4= +github.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/go.net v0.0.1/go.mod h1:hjKkEWcCURg++eb33jQU7oqQcI9XDCnUzHA0oac0k90= github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= @@ -1501,8 +1501,8 @@ github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47e github.com/klauspost/compress v1.15.9/go.mod h1:PhcZ0MbTNciWF3rruxRgKxI5NkcHHrHUDtV4Yw2GlzU= github.com/klauspost/compress v1.16.0/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= github.com/klauspost/compress v1.16.7/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= -github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= -github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= +github.com/klauspost/compress v1.18.3 h1:9PJRvfbmTabkOX8moIpXPbMMbYN60bWImDDU7L+/6zw= +github.com/klauspost/compress v1.18.3/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4= github.com/klauspost/cpuid/v2 v2.0.4/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= @@ -1734,8 +1734,8 @@ github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FI github.com/pascaldekloe/name v1.0.0/go.mod h1:Z//MfYJnH4jVpQ9wkclwu2I2MkHmXTlT9wR5UZScttM= github.com/pascaldekloe/name v1.0.1/go.mod h1:Z//MfYJnH4jVpQ9wkclwu2I2MkHmXTlT9wR5UZScttM= github.com/paulmach/orb v0.10.0/go.mod h1:5mULz1xQfs3bmQm63QEJA6lNGujuRafwA5S/EnuLaLU= -github.com/paulmach/orb v0.11.1 h1:3koVegMC4X/WeiXYz9iswopaTwMem53NzTJuTF20JzU= -github.com/paulmach/orb v0.11.1/go.mod h1:5mULz1xQfs3bmQm63QEJA6lNGujuRafwA5S/EnuLaLU= +github.com/paulmach/orb v0.12.0 h1:z+zOwjmG3MyEEqzv92UN49Lg1JFYx0L9GpGKNVDKk1s= +github.com/paulmach/orb v0.12.0/go.mod h1:5mULz1xQfs3bmQm63QEJA6lNGujuRafwA5S/EnuLaLU= github.com/paulmach/protoscan v0.2.1/go.mod h1:SpcSwydNLrxUGSDvXvO0P7g7AuhJ7lcKfDlhJCDw2gY= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= github.com/pelletier/go-toml v1.8.1/go.mod h1:T2/BmBdy8dvIRq1a/8aqjN41wvWlN4lrapLU/GW4pbc= @@ -1753,8 +1753,8 @@ github.com/phpdave11/gofpdi v1.0.13/go.mod h1:vBmVV0Do6hSBHC8uKUQ71JGW+ZGQq74llk github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY= github.com/pierrec/lz4/v4 v4.1.15/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= github.com/pierrec/lz4/v4 v4.1.18/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= -github.com/pierrec/lz4/v4 v4.1.22 h1:cKFw6uJDK+/gfw5BcDL0JL5aBsAFdsIT18eRtLj7VIU= -github.com/pierrec/lz4/v4 v4.1.22/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= +github.com/pierrec/lz4/v4 v4.1.25 h1:kocOqRffaIbU5djlIBr7Wh+cx82C0vtFb0fOurZHqD0= +github.com/pierrec/lz4/v4 v4.1.25/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4= github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.1-0.20171018195549-f15c970de5b7/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= @@ -1860,8 +1860,9 @@ github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg github.com/seccomp/libseccomp-golang v0.9.1/go.mod h1:GbW5+tmTXfcxTToHLXlScSlAvWlF4P2Ca7zGrPiEpWo= github.com/seccomp/libseccomp-golang v0.9.2-0.20210429002308-3879420cc921/go.mod h1:JA8cRccbGaA1s33RQf7Y1+q9gHmZX1yB/z9WDN1C6fg= github.com/seccomp/libseccomp-golang v0.9.2-0.20220502022130-f33da4d89646/go.mod h1:JA8cRccbGaA1s33RQf7Y1+q9gHmZX1yB/z9WDN1C6fg= -github.com/segmentio/asm v1.2.0 h1:9BQrFxC+YOHJlTlHGkTrFWf59nbL3XnCoFLTwDCI7ys= github.com/segmentio/asm v1.2.0/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs= +github.com/segmentio/asm v1.2.1 h1:DTNbBqs57ioxAD4PrArqftgypG4/qNpXoJx8TVXxPR0= +github.com/segmentio/asm v1.2.1/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs= github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= github.com/shirou/gopsutil v2.19.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA= github.com/shirou/gopsutil v3.21.11+incompatible h1:+1+c1VGhc88SSonWP6foOcLhvnKlUeu/erjjvaPEYiI= @@ -2038,8 +2039,9 @@ github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1 github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M= github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw= -github.com/yusufpapurcu/wmi v1.2.3 h1:E1ctvB7uKFMOJw3fdOW32DwGE9I7t++CRUEMKvFoFiw= github.com/yusufpapurcu/wmi v1.2.3/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= +github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0= +github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= github.com/yvasiyarov/go-metrics v0.0.0-20140926110328-57bccd1ccd43/go.mod h1:aX5oPXxHm3bOH+xeAttToC8pqch2ScQN/JoXYupl6xs= github.com/yvasiyarov/gorelic v0.0.0-20141212073537-a9bba5b9ab50/go.mod h1:NUSPSUX/bi6SeDMUh6brw0nXpxHnc96TguQh0+r/ssA= github.com/yvasiyarov/newrelic_platform_go v0.0.0-20140908184405-b21fdbd4370f/go.mod h1:GlGEuHIJweS1mbCqG+7vt2nvWLzLLnRHbXz5JKd/Qbg= @@ -2094,8 +2096,8 @@ go.opentelemetry.io/otel v1.10.0/go.mod h1:NbvWjCthWHKBEUMpf0/v8ZRZlni86PpGFEMA9 go.opentelemetry.io/otel v1.14.0/go.mod h1:o4buv+dJzx8rohcUeRmWUZhqupFvzWis188WlggnNeU= go.opentelemetry.io/otel v1.16.0/go.mod h1:vl0h9NUa1D5s1nv3A5vZOYWn8av4K8Ml6JDeHrT/bx4= go.opentelemetry.io/otel v1.19.0/go.mod h1:i0QyjOq3UPoTzff0PJB2N66fb4S0+rSbSB15/oyH9fY= -go.opentelemetry.io/otel v1.34.0 h1:zRLXxLCgL1WyKsPVrgbSdMN4c0FMkDAskSTQP+0hdUY= -go.opentelemetry.io/otel v1.34.0/go.mod h1:OWFPOQ+h4G8xpyjgqo4SxJYdDQ/qmRH+wivy7zzx9oI= +go.opentelemetry.io/otel v1.41.0 h1:YlEwVsGAlCvczDILpUXpIpPSL/VPugt7zHThEMLce1c= +go.opentelemetry.io/otel v1.41.0/go.mod h1:Yt4UwgEKeT05QbLwbyHXEwhnjxNO6D8L5PQP51/46dE= go.opentelemetry.io/otel/exporters/otlp v0.20.0/go.mod h1:YIieizyaN77rtLJra0buKiNBOm9XQfkPEKBeuhoMwAM= go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.3.0/go.mod h1:VpP4/RMn8bv8gNo9uK7/IMY4mtWLELsS+JIP0inH0h4= go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.7.0/go.mod h1:M1hVZHNxcbkAlcvrOMlpQ4YOO3Awf+4N2dxkZL3xm04= @@ -2138,8 +2140,8 @@ go.opentelemetry.io/otel/trace v1.10.0/go.mod h1:Sij3YYczqAdz+EhmGhE6TpTxUO5/F/A go.opentelemetry.io/otel/trace v1.14.0/go.mod h1:8avnQLK+CG77yNLUae4ea2JDQ6iT+gozhnZjy/rw9G8= go.opentelemetry.io/otel/trace v1.16.0/go.mod h1:Yt9vYq1SdNz3xdjZZK7wcXv1qv2pwLkqr2QVwea0ef0= go.opentelemetry.io/otel/trace v1.19.0/go.mod h1:mfaSyvGyEJEI0nyV2I4qhNQnbBOUUmYZpYojqMnX2vo= -go.opentelemetry.io/otel/trace v1.34.0 h1:+ouXS2V8Rd4hp4580a8q23bg0azF2nI8cqLYnC8mh/k= -go.opentelemetry.io/otel/trace v1.34.0/go.mod h1:Svm7lSjQD7kG7KJ/MUHPVXSDGz2OX4h0M2jHBhmSfRE= +go.opentelemetry.io/otel/trace v1.41.0 h1:Vbk2co6bhj8L59ZJ6/xFTskY+tGAbOnCtQGVVa9TIN0= +go.opentelemetry.io/otel/trace v1.41.0/go.mod h1:U1NU4ULCoxeDKc09yCWdWe+3QoyweJcISEVa1RBzOis= go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI= go.opentelemetry.io/proto/otlp v0.9.0/go.mod h1:1vKfU9rv61e9EVGthD1zNvUbiwPcimSsOPU9brfSHJg= go.opentelemetry.io/proto/otlp v0.11.0/go.mod h1:QpEjXPrNQzrFDZgoTo49dgHR9RYRSrg3NAKnUGl9YpQ= diff --git a/middleware/audit.go b/middleware/audit.go index 851e48358a..dcd254e9d6 100644 --- a/middleware/audit.go +++ b/middleware/audit.go @@ -6,8 +6,8 @@ import ( "github.com/QuantumNous/new-api/common" "github.com/QuantumNous/new-api/constant" "github.com/QuantumNous/new-api/model" + "github.com/QuantumNous/new-api/service" - "github.com/bytedance/gopkg/util/gopool" "github.com/gin-gonic/gin" ) @@ -158,26 +158,22 @@ func finishAdminAudit(c *gin.Context, writer *auditResponseWriter) { // content 为英文兜底文本(供导出等非本地化消费者使用)。 content := method + " " + route - adminInfo := map[string]interface{}{ - "admin_id": operatorId, - "admin_username": operatorName, - "admin_role": operatorRole, - "auth_method": auditAuthMethod(c), + adminInfo := &model.AuditAdminInfo{ + AdminID: operatorId, + AdminUsername: operatorName, + AdminRole: operatorRole, + AuthMethod: auditAuthMethod(c), } - auditInfo := map[string]interface{}{ - "method": method, - "route": route, - "path": c.Request.URL.Path, - "status": status, - "success": success, - } - if len(routeParams) > 0 { - auditInfo["params"] = routeParams + auditInfo := &model.AuditRequestInfo{ + Method: method, + Route: route, + Path: route, + Status: status, + Success: success, + Params: routeParams, } - gopool.Go(func() { - model.RecordOperationAuditLog(operatorId, content, ip, action, opParams, adminInfo, auditInfo) - }) + model.RecordOperationAuditLog(operatorId, operatorRole, content, ip, action, opParams, adminInfo, auditInfo, c) } func auditAuthMethod(c *gin.Context) string { @@ -204,3 +200,55 @@ func auditResponseSuccess(status int, body []byte) bool { } return status < 400 } + +const accessTokenAuditContextKey = "access_token_request_audit" + +type accessTokenRequestAudit struct { + entry model.AuditLog + writer *auditResponseWriter +} + +// AccessTokenAudit also captures public reads and rejections before route-level +// authentication (for example, rate limiting). It does not grant authentication. +func AccessTokenAudit() gin.HandlerFunc { + return func(c *gin.Context) { + raw, present := authorizationToken(c.GetHeader("Authorization")) + if present { + _, internal, _ := service.ParseDashboardAccessToken(raw) + if !internal { + user, err := model.ValidateAccessToken(raw) + if err == nil && user != nil && user.Id > 0 { + beginAccessTokenAudit(c, user, raw) + defer finishAccessTokenAudit(c) + } + } + } + c.Next() + } +} + +func beginAccessTokenAudit(c *gin.Context, user *model.User, token string) { + if _, exists := c.Get(accessTokenAuditContextKey); exists { + return + } + writer := &auditResponseWriter{ResponseWriter: c.Writer, body: bytes.NewBuffer(nil), maxSize: 64 * 1024} + c.Writer = writer + c.Set(accessTokenAuditContextKey, &accessTokenRequestAudit{ + entry: model.AuditLog{UserId: user.Id, Username: user.Username, ActorRole: user.Role, Category: model.AuditCategoryAccessToken, AuthMethod: "access_token", TokenRef: model.AccessTokenFingerprint(token), CreatedAt: common.GetTimestamp(), EventId: common.NewRequestId()}, + writer: writer, + }) +} + +func finishAccessTokenAudit(c *gin.Context) { + value, exists := c.Get(accessTokenAuditContextKey) + if !exists { + return + } + audit, ok := value.(*accessTokenRequestAudit) + if !ok { + return + } + audit.entry.Status = audit.writer.Status() + audit.entry.Success = auditResponseSuccess(audit.entry.Status, audit.writer.body.Bytes()) + model.RecordAuditLog(c, audit.entry) +} diff --git a/middleware/auth.go b/middleware/auth.go index f70ce96ee7..5ad83f8918 100644 --- a/middleware/auth.go +++ b/middleware/auth.go @@ -45,6 +45,9 @@ func validUserInfo(username string, role int) bool { } func authHelper(c *gin.Context, minRole int) { + if _, started := c.Get(accessTokenAuditContextKey); !started { + defer finishAccessTokenAudit(c) + } user, identity, useAccessToken, err := authenticateDashboardRequest(c) if err != nil { writeDashboardAuthError(c, err) @@ -79,6 +82,9 @@ func authHelper(c *gin.Context, minRole int) { func TryUserAuth() func(c *gin.Context) { return func(c *gin.Context) { + if _, started := c.Get(accessTokenAuditContextKey); !started { + defer finishAccessTokenAudit(c) + } user, identity, credentialKind, err := classifyDashboardCredential(c) if err != nil { writeDashboardAuthError(c, err) @@ -172,6 +178,7 @@ func classifyDashboardCredential(c *gin.Context) (*model.UserBase, service.AuthI if patUser == nil || patUser.Id <= 0 { return nil, service.AuthIdentity{}, dashboardCredentialUnmatched, nil } + beginAccessTokenAudit(c, patUser, raw) user, err := model.GetUserCache(patUser.Id) if err != nil { return nil, service.AuthIdentity{}, dashboardCredentialPAT, err diff --git a/middleware/auth_test.go b/middleware/auth_test.go index db7fb343c4..040ec62c03 100644 --- a/middleware/auth_test.go +++ b/middleware/auth_test.go @@ -24,18 +24,21 @@ import ( func setupDashboardAuthMiddlewareTest(t *testing.T) { t.Helper() previousDB := model.DB + previousLogDB := model.LOG_DB previousType := common.MainDatabaseType() previousRedis := common.RedisEnabled previousSecret := common.SessionSecret db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) require.NoError(t, err) - require.NoError(t, db.AutoMigrate(&model.User{}, &model.UserSession{})) + require.NoError(t, db.AutoMigrate(&model.User{}, &model.UserSession{}, &model.AuditLog{})) model.DB = db + model.LOG_DB = db common.SetMainDatabaseType(common.DatabaseTypeSQLite) common.RedisEnabled = false common.SessionSecret = "middleware-auth-test-secret" t.Cleanup(func() { model.DB = previousDB + model.LOG_DB = previousLogDB common.SetMainDatabaseType(previousType) common.RedisEnabled = previousRedis common.SessionSecret = previousSecret diff --git a/model/audit_log.go b/model/audit_log.go new file mode 100644 index 0000000000..4192bf7c59 --- /dev/null +++ b/model/audit_log.go @@ -0,0 +1,269 @@ +package model + +import ( + "context" + "crypto/sha256" + "errors" + "fmt" + "strings" + + "github.com/ClickHouse/clickhouse-go/v2" + "github.com/QuantumNous/new-api/common" + "github.com/QuantumNous/new-api/logger" + "github.com/gin-gonic/gin" + "gorm.io/gorm" +) + +const ( + AuditCategoryLogin = "login" + AuditCategorySecurity = "security" + AuditCategoryOperation = "operation" + AuditCategoryAccessToken = "access_token" +) + +// AuditLog is retained independently of usage logs and their cleanup/TTL policy. +// TokenRef identifies a PAT generation without storing its bearer credential. +type AuditLog struct { + Id int `json:"id"` + EventId string `json:"event_id" gorm:"type:varchar(64);uniqueIndex"` + UserId int `json:"user_id" gorm:"index:idx_audit_user_time,priority:1"` + Username string `json:"username" gorm:"type:varchar(64);index"` + ActorRole int `json:"actor_role"` // Immutable role of the actor when the event began, not the log owner. + CreatedAt int64 `json:"created_at" gorm:"type:bigint;index:idx_audit_user_time,priority:2;index:idx_audit_token_time,priority:2;index"` + Category string `json:"category" gorm:"type:varchar(24);index"` + Action string `json:"action" gorm:"type:varchar(128)"` + TokenRef string `json:"token_ref" gorm:"type:varchar(64);index:idx_audit_token_time,priority:1"` + AuthMethod string `json:"auth_method" gorm:"type:varchar(24)"` + Ip string `json:"ip" gorm:"type:varchar(64)"` + UserAgent string `json:"user_agent" gorm:"type:varchar(512)"` + Method string `json:"method" gorm:"type:varchar(16)"` + Route string `json:"route" gorm:"type:varchar(255)"` + Status int `json:"status"` + Success bool `json:"success"` + RequestId string `json:"request_id" gorm:"type:varchar(64);index"` + Content string `json:"content" gorm:"type:text"` + Other AuditOther `json:"other" gorm:"type:json"` +} + +type AuditLogFilter struct { + SelfView bool // Server-selected metadata projection, independent of the viewer's actual role. + UserId int + Username string + Category string + TokenRef string + ExcludeTokenRef string + RequestId string + StartTimestamp int64 + EndTimestamp int64 + Success *bool +} + +func AccessTokenFingerprint(token string) string { + // PostgreSQL returns CHAR(32) tokens padded with spaces. Normalize that + // storage padding so persisted tokens and incoming credentials share a ref. + token = strings.TrimRight(token, " ") + if token == "" { + return "" + } + digest := sha256.Sum256([]byte(token)) + return fmt.Sprintf("%x", digest) +} + +// RecordAuditLog captures safe request metadata only; raw URLs, query strings, +// credentials and response/request bodies must never enter this table. +func RecordAuditLog(c *gin.Context, entry AuditLog) { + ctx := context.Background() + if c != nil && c.Request != nil { + ctx = c.Request.Context() + entry.RequestId = c.GetString(common.RequestIdKey) + entry.Ip = c.ClientIP() + entry.UserAgent = c.Request.UserAgent() + entry.Method = c.Request.Method + entry.Route = c.FullPath() + if entry.Status == 0 { + entry.Status = c.Writer.Status() + } + if entry.AuthMethod == "" { + entry.AuthMethod = "session" + if c.GetBool("use_access_token") { + entry.AuthMethod = "access_token" + } + } + } + if entry.CreatedAt == 0 { + entry.CreatedAt = common.GetTimestamp() + } + if entry.RequestId == "" { + entry.RequestId = common.NewRequestId() + } + if entry.EventId == "" { + entry.EventId = common.NewRequestId() + } + switch entry.ActorRole { + case common.RoleCommonUser, common.RoleAdminUser, common.RoleRootUser: + default: + logger.LogError(ctx, fmt.Sprintf("audit actor role unavailable (request_id=%s, actor_role=%d)", entry.RequestId, entry.ActorRole)) + entry.ActorRole = 0 // Unknown actors remain visible to root only. + } + if entry.Username == "" { + entry.Username, _ = GetUsernameById(entry.UserId, false) + } + ua := []rune(entry.UserAgent) + if len(ua) > 512 { + entry.UserAgent = string(ua[:512]) + } + if LOG_DB == nil { + logger.LogError(ctx, fmt.Sprintf("audit log write failed (request_id=%s): log database unavailable", entry.RequestId)) + return + } + var row interface{} = &entry + if common.UsingLogDatabase(common.DatabaseTypeClickHouse) { + encoded, err := common.Marshal(entry.Other) + if err != nil { + logger.LogError(ctx, fmt.Sprintf("audit log write failed (request_id=%s): %v", entry.RequestId, err)) + return + } + // The ClickHouse GORM insert callback passes structs to the native + // driver without resolving their Valuer. Bind this column's JSON + // encoding while retaining AuditOther in the domain and API models. + row = &struct { + AuditLog `gorm:"embedded"` + EncodedOther string `gorm:"column:other;type:json"` + }{AuditLog: entry, EncodedOther: string(encoded)} + } + if err := LOG_DB.Table("audit_logs").Create(row).Error; err != nil { + logger.LogError(ctx, fmt.Sprintf("audit log write failed (request_id=%s): %v", entry.RequestId, err)) + } +} + +func GetAuditLogs(filter AuditLogFilter, start, limit, viewerRole int) ([]*AuditLog, int64, error) { + query := LOG_DB.Model(&AuditLog{}) + if common.UsingLogDatabase(common.DatabaseTypeClickHouse) { + // Decode native JSON through database/sql as text for AuditOther.Scan. + // Preserve numeric metadata instead of returning quoted Int64 values. + query = query.WithContext(clickhouse.Context(query.Statement.Context, clickhouse.WithSettings(clickhouse.Settings{ + "output_format_native_write_json_as_string": 1, + "output_format_json_quote_64bit_integers": 0, + }))) + } + if viewerRole < common.RoleRootUser { + query = query.Where("actor_role IN ?", []int{common.RoleCommonUser, common.RoleAdminUser}) + } + if filter.UserId > 0 { + query = query.Where("user_id = ?", filter.UserId) + } + if filter.Username != "" { + query = query.Where("username = ?", filter.Username) + } + if filter.Category != "" { + query = query.Where("category = ?", filter.Category) + } + if filter.TokenRef != "" { + query = query.Where("token_ref = ?", filter.TokenRef) + } + if filter.ExcludeTokenRef != "" { + query = query.Where("token_ref <> ?", filter.ExcludeTokenRef) + } + if filter.RequestId != "" { + query = query.Where("request_id = ?", filter.RequestId) + } + if filter.StartTimestamp > 0 { + query = query.Where("created_at >= ?", filter.StartTimestamp) + } + if filter.EndTimestamp > 0 { + query = query.Where("created_at <= ?", filter.EndTimestamp) + } + if filter.Success != nil { + query = query.Where("success = ?", *filter.Success) + } + var total int64 + if err := query.Count(&total).Error; err != nil { + return nil, 0, err + } + logs := make([]*AuditLog, 0) + if err := query.Order("created_at DESC").Order("event_id DESC").Offset(start).Limit(limit).Find(&logs).Error; err != nil { + return nil, 0, err + } + visibility := logOtherVisibilityUser + if !filter.SelfView && viewerRole >= common.RoleRootUser { + visibility = logOtherVisibilityRoot + } else if !filter.SelfView && viewerRole >= common.RoleAdminUser { + visibility = logOtherVisibilityAdmin + } + for _, entry := range logs { + if visibility != logOtherVisibilityRoot { + entry.Other.RootInfo = nil + } + if visibility == logOtherVisibilityUser { + entry.Other.AdminInfo = nil + entry.Other.AuditInfo = nil + } + } + return logs, total, nil +} + +type UserAccessTokenStatus struct { + Exists bool `json:"exists"` + TokenRef string `json:"token_ref"` + CreatedAt *int64 `json:"created_at"` + LastUsedAt *int64 `json:"last_used_at"` + LastUsedIp string `json:"last_used_ip"` +} + +func GetUserAccessTokenStatus(userId int) (*UserAccessTokenStatus, error) { + var user User + if err := DB.Select("id", "role", "access_token", "access_token_created_at").First(&user, userId).Error; err != nil { + return nil, err + } + status := &UserAccessTokenStatus{Exists: user.GetAccessToken() != ""} + if !status.Exists { + return status, nil + } + status.TokenRef = AccessTokenFingerprint(user.GetAccessToken()) + status.CreatedAt = user.AccessTokenCreatedAt + var latest AuditLog + query := LOG_DB.Select("created_at", "ip").Where("user_id = ? AND token_ref = ? AND category = ?", userId, status.TokenRef, AuditCategoryAccessToken) + if user.Role < common.RoleRootUser { + query = query.Where("actor_role IN ?", []int{common.RoleCommonUser, common.RoleAdminUser}) + } + err := query.Order("created_at DESC").Order("event_id DESC").Take(&latest).Error + if errors.Is(err, gorm.ErrRecordNotFound) { + return status, nil + } + if err != nil { + return nil, err + } + status.LastUsedAt = &latest.CreatedAt + status.LastUsedIp = latest.Ip + return status, nil +} + +// MigrateAuditLogs also supports independently configured ClickHouse log stores. +// No TTL clause or usage-log cleanup integration is intentional. +func MigrateAuditLogs() error { + if !common.UsingLogDatabase(common.DatabaseTypeClickHouse) { + return LOG_DB.AutoMigrate(&AuditLog{}) + } + return LOG_DB.Exec(`CREATE TABLE IF NOT EXISTS audit_logs ( + id Int64 DEFAULT 0, event_id String, user_id Int64, username String, actor_role Int32, + created_at Int64, category String, action String, token_ref String, + auth_method String, ip String, user_agent String, method String, route String, + status Int32, success UInt8, request_id String, content String, other JSON + ) ENGINE = MergeTree() + PARTITION BY toYYYYMM(toDateTime(created_at)) + ORDER BY (created_at, event_id)`).Error +} + +func ValidAuditCategory(category string) bool { + return category == "" || category == AuditCategoryLogin || category == AuditCategorySecurity || category == AuditCategoryOperation || category == AuditCategoryAccessToken +} + +func ValidTokenFingerprint(value string) bool { + if value == "" { + return true + } + if len(value) != 64 { + return false + } + return strings.Trim(value, "0123456789abcdef") == "" +} diff --git a/model/audit_other.go b/model/audit_other.go new file mode 100644 index 0000000000..19d3f5cd25 --- /dev/null +++ b/model/audit_other.go @@ -0,0 +1,95 @@ +package model + +import ( + "database/sql/driver" + "encoding/json" + "fmt" + + "github.com/QuantumNous/new-api/common" +) + +// AuditOther is the structured metadata stored with an audit event. Privileged +// fields are separate so API projections can remove them without re-encoding JSON. +type AuditOther struct { + Op *AuditOperation `json:"op,omitempty"` + AdminInfo *AuditAdminInfo `json:"admin_info,omitempty"` + AuditInfo *AuditRequestInfo `json:"audit_info,omitempty"` + RootInfo AuditFields `json:"root_info,omitempty"` + LoginMethod string `json:"login_method,omitempty"` + UserAgent string `json:"user_agent,omitempty"` +} + +type AuditOperation struct { + Action string `json:"action"` + Params AuditFields `json:"params,omitempty"` +} + +type AuditAdminInfo struct { + AdminID int `json:"admin_id,omitempty"` + AdminUsername string `json:"admin_username,omitempty"` + AdminRole int `json:"admin_role,omitempty"` + AuthMethod string `json:"auth_method,omitempty"` +} + +type AuditRequestInfo struct { + Method string `json:"method"` + Route string `json:"route"` + Path string `json:"path"` + Status int `json:"status"` + Success bool `json:"success"` + Params map[string]string `json:"params,omitempty"` +} + +// AuditFields holds action-specific parameters and root-only extensions. +// Retain their encoded values when reading so arbitrary nested integers do not +// round-trip through float64 and lose precision before the API returns them. +type AuditFields map[string]any + +func (fields *AuditFields) UnmarshalJSON(data []byte) error { + var values map[string]json.RawMessage + if err := common.Unmarshal(data, &values); err != nil { + return err + } + if values == nil { + *fields = nil + return nil + } + decoded := make(AuditFields, len(values)) + for key, value := range values { + decoded[key] = value + } + *fields = decoded + return nil +} + +func (other AuditOther) Value() (driver.Value, error) { + data, err := common.Marshal(other) + if err != nil { + return nil, err + } + // PostgreSQL's simple protocol requires string, not a bytea parameter. + return string(data), nil +} + +func (other *AuditOther) Scan(value any) error { + var data []byte + switch value := value.(type) { + case nil: + *other = AuditOther{} + return nil + case string: + data = []byte(value) + case []byte: + data = value + default: + return fmt.Errorf("unsupported audit metadata database type %T", value) + } + var decoded AuditOther + if len(data) > 0 { + if err := common.Unmarshal(data, &decoded); err != nil { + return err + } + } + *other = decoded + return nil +} diff --git a/model/log.go b/model/log.go index a0407d539c..2afef5b602 100644 --- a/model/log.go +++ b/model/log.go @@ -166,7 +166,7 @@ func RecordLog(userId int, logType int, content string) { } // RecordLogWithAdminInfo 记录操作日志,并将管理员相关信息存入 Other.admin_info, -func RecordLogWithAdminInfo(userId int, logType int, content string, adminInfo map[string]interface{}) { +func RecordLogWithAdminInfo(userId int, logType int, content string, adminInfo *AuditAdminInfo, request ...*gin.Context) { if logType == LogTypeConsume && !common.LogConsumeEnabled { return } @@ -178,75 +178,71 @@ func RecordLogWithAdminInfo(userId int, logType int, content string, adminInfo m Type: logType, Content: content, } - if len(adminInfo) > 0 { - other := NewLogOther() - other.MergeAdmin(adminInfo) - log.Other = other.JSONString() + if logType == LogTypeManage { + var c *gin.Context + if len(request) > 0 { + c = request[0] + } + actorRole := 0 + if c != nil { + actorRole = c.GetInt("role") + } + RecordAuditLog(c, AuditLog{UserId: userId, Username: username, ActorRole: actorRole, Category: AuditCategoryOperation, Content: content, Other: AuditOther{AdminInfo: adminInfo}, Success: true}) + return + } + if adminInfo != nil { + data, err := common.Marshal(AuditOther{AdminInfo: adminInfo}) + if err != nil { + common.SysError("failed to encode log admin info: " + err.Error()) + return + } + log.Other = string(data) } if err := createLog(log); err != nil { common.SysLog("failed to record log: " + err.Error()) } } -// buildOpField 构建语言无关的操作描述(写入 Other.op)。 -// 前端依据 action(稳定操作标识) + params(结构化参数) 在渲染期用 i18n 本地化展示, -// 因此不在数据库中存储自然语言句子。 -func buildOpField(action string, params map[string]interface{}) map[string]interface{} { - op := map[string]interface{}{ - "action": action, - } - if len(params) > 0 { - op["params"] = params - } - return op -} - -// RecordLoginLog 记录用户登录成功的审计日志(type=LogTypeLogin)。 +// RecordLoginLog writes new login events to the independent audit table. // username 由调用方传入(登录流程已持有用户对象),避免额外的数据库查询。 // content 为英文兜底文本(用于导出);action+params 供前端本地化渲染。 -// extra 可携带 login_method、user_agent 等附加信息(普通用户可见)。 -func RecordLoginLog(userId int, username string, content string, ip string, action string, params map[string]interface{}, extra map[string]interface{}) { - other := NewLogOther() - other.MergePublic(extra) - other.SetPublic("op", buildOpField(action, params)) - log := &Log{ - UserId: userId, - Username: username, - CreatedAt: common.GetTimestamp(), - Type: LogTypeLogin, - Content: content, - Ip: ip, - Other: other.JSONString(), - } - if err := createLog(log); err != nil { - common.SysLog("failed to record login log: " + err.Error()) +// other 包含 login_method、user_agent 等结构化信息。 +func RecordLoginLog(userId, actorRole int, username string, content string, ip string, action string, params map[string]interface{}, other AuditOther, request ...*gin.Context) { + other.Op = &AuditOperation{Action: action, Params: params} + var c *gin.Context + if len(request) > 0 { + c = request[0] } + RecordAuditLog(c, AuditLog{UserId: userId, Username: username, ActorRole: actorRole, Category: AuditCategoryLogin, Action: action, Content: content, Ip: ip, Other: other, Success: true}) } -// RecordOperationAuditLog 记录管理/高危操作审计日志(type=LogTypeManage)。 +// RecordOperationAuditLog writes new operation/security events to the audit table. // logUserId 为日志归属者,管理审计日志应归属实际操作者;目标资源/用户放入 // action params。username 内部按 logUserId 查询。content 为英文兜底文本(供导出使用)。 // action+params 写入 Other.op,供前端本地化渲染(普通用户可见,不含敏感信息)。 // adminInfo 存放操作者身份(写入 Other.admin_info,普通用户查询时剥离); // auditInfo 存放路由/方法/结果等中间件兜底信息(写入 Other.audit_info,普通用户查询时剥离)。 -func RecordOperationAuditLog(logUserId int, content string, ip string, action string, params map[string]interface{}, adminInfo map[string]interface{}, auditInfo map[string]interface{}) { +func RecordOperationAuditLog(logUserId, actorRole int, content string, ip string, action string, params map[string]interface{}, adminInfo *AuditAdminInfo, auditInfo *AuditRequestInfo, request ...*gin.Context) { username, _ := GetUsernameById(logUserId, false) - other := NewLogOther() - other.SetPublic("op", buildOpField(action, params)) - other.MergeAdmin(adminInfo) - other.MergeAudit(auditInfo) - log := &Log{ - UserId: logUserId, - Username: username, - CreatedAt: common.GetTimestamp(), - Type: LogTypeManage, - Content: content, - Ip: ip, - Other: other.JSONString(), + other := AuditOther{ + Op: &AuditOperation{Action: action, Params: params}, + AdminInfo: adminInfo, + AuditInfo: auditInfo, } - if err := createLog(log); err != nil { - common.SysLog("failed to record operation audit log: " + err.Error()) + var c *gin.Context + if len(request) > 0 { + c = request[0] } + category := AuditCategoryOperation + if adminInfo == nil { + category = AuditCategorySecurity + } + status, success := 200, true + if auditInfo != nil { + status = auditInfo.Status + success = auditInfo.Success + } + RecordAuditLog(c, AuditLog{UserId: logUserId, Username: username, ActorRole: actorRole, Category: category, Action: action, Content: content, Ip: ip, Status: status, Success: success, Other: other}) } func RecordTopupLog(userId int, content string, callerIp string, paymentMethod string, callbackPaymentMethod string) { diff --git a/model/main.go b/model/main.go index 3a70622b21..fda3234755 100644 --- a/model/main.go +++ b/model/main.go @@ -232,6 +232,9 @@ func InitLogDB() (err error) { LOG_DB = DB common.SetLogDatabaseType(common.MainDatabaseType()) initCol() + if common.IsMasterNode { + return MigrateAuditLogs() + } return } db, dbType, err := chooseDB("LOG_SQL_DSN", true) @@ -387,6 +390,9 @@ func migrateDB() error { } func migrateLOGDB() error { + if err := MigrateAuditLogs(); err != nil { + return err + } if common.UsingLogDatabase(common.DatabaseTypeClickHouse) { return migrateClickHouseLogDB() } diff --git a/model/user.go b/model/user.go index 1fbaa34ce1..00aa24fbb8 100644 --- a/model/user.go +++ b/model/user.go @@ -77,39 +77,40 @@ func resolveUserSortOptions(sortOptions []UserSortOptions) UserSortOptions { // User if you add sensitive fields, don't forget to clean them in setupLogin function. // Otherwise, the sensitive information will be saved on local storage in plain text! type User struct { - Id int `json:"id"` - Username string `json:"username" gorm:"unique;index" validate:"max=20"` - Password string `json:"password" gorm:"not null;" validate:"min=8,max=20"` - OriginalPassword string `json:"original_password" gorm:"-:all"` // this field is only for Password change verification, don't save it to database! - DisplayName string `json:"display_name" gorm:"index" validate:"max=20"` - Role int `json:"role" gorm:"type:int;default:1"` // admin, common - Status int `json:"status" gorm:"type:int;default:1"` // enabled, disabled - Email string `json:"email" gorm:"index" validate:"max=50"` - GitHubId string `json:"github_id" gorm:"column:github_id;index"` - DiscordId string `json:"discord_id" gorm:"column:discord_id;index"` - OidcId string `json:"oidc_id" gorm:"column:oidc_id;index"` - WeChatId string `json:"wechat_id" gorm:"column:wechat_id;index"` - TelegramId string `json:"telegram_id" gorm:"column:telegram_id;index"` - VerificationCode string `json:"verification_code" gorm:"-:all"` // this field is only for Email verification, don't save it to database! - AccessToken *string `json:"-" gorm:"type:char(32);column:access_token;uniqueIndex"` // this token is for system management - Quota int `json:"quota" gorm:"type:int;default:0"` - UsedQuota int `json:"used_quota" gorm:"type:int;default:0;column:used_quota"` // used quota - RequestCount int `json:"request_count" gorm:"type:int;default:0;"` // request number - Group string `json:"group" gorm:"type:varchar(64);default:'default'"` - AffCode string `json:"aff_code" gorm:"type:varchar(32);column:aff_code;uniqueIndex"` - AffCount int `json:"aff_count" gorm:"type:int;default:0;column:aff_count"` - AffQuota int `json:"aff_quota" gorm:"type:int;default:0;column:aff_quota"` // 邀请剩余额度 - AffHistoryQuota int `json:"aff_history_quota" gorm:"type:int;default:0;column:aff_history"` // 邀请历史额度 - InviterId int `json:"inviter_id" gorm:"type:int;column:inviter_id;index"` - DeletedAt gorm.DeletedAt `gorm:"index"` - LinuxDOId string `json:"linux_do_id" gorm:"column:linux_do_id;index"` - Setting string `json:"setting" gorm:"type:text;column:setting"` - Remark string `json:"remark,omitempty" gorm:"type:varchar(255)" validate:"max=255"` - StripeCustomer string `json:"stripe_customer" gorm:"type:varchar(64);column:stripe_customer;index"` - CreatedAt int64 `json:"created_at" gorm:"autoCreateTime;column:created_at"` - LastLoginAt int64 `json:"last_login_at" gorm:"default:0;column:last_login_at"` - AuthVersion int64 `json:"-" gorm:"type:bigint;not null;default:1;column:auth_version"` - AdminPermissions map[string]map[string]bool `json:"admin_permissions,omitempty" gorm:"-:all"` + Id int `json:"id"` + Username string `json:"username" gorm:"unique;index" validate:"max=20"` + Password string `json:"password" gorm:"not null;" validate:"min=8,max=20"` + OriginalPassword string `json:"original_password" gorm:"-:all"` // this field is only for Password change verification, don't save it to database! + DisplayName string `json:"display_name" gorm:"index" validate:"max=20"` + Role int `json:"role" gorm:"type:int;default:1"` // admin, common + Status int `json:"status" gorm:"type:int;default:1"` // enabled, disabled + Email string `json:"email" gorm:"index" validate:"max=50"` + GitHubId string `json:"github_id" gorm:"column:github_id;index"` + DiscordId string `json:"discord_id" gorm:"column:discord_id;index"` + OidcId string `json:"oidc_id" gorm:"column:oidc_id;index"` + WeChatId string `json:"wechat_id" gorm:"column:wechat_id;index"` + TelegramId string `json:"telegram_id" gorm:"column:telegram_id;index"` + VerificationCode string `json:"verification_code" gorm:"-:all"` // this field is only for Email verification, don't save it to database! + AccessToken *string `json:"-" gorm:"type:char(32);column:access_token;uniqueIndex"` // this token is for system management + AccessTokenCreatedAt *int64 `json:"-" gorm:"type:bigint;column:access_token_created_at"` + Quota int `json:"quota" gorm:"type:int;default:0"` + UsedQuota int `json:"used_quota" gorm:"type:int;default:0;column:used_quota"` // used quota + RequestCount int `json:"request_count" gorm:"type:int;default:0;"` // request number + Group string `json:"group" gorm:"type:varchar(64);default:'default'"` + AffCode string `json:"aff_code" gorm:"type:varchar(32);column:aff_code;uniqueIndex"` + AffCount int `json:"aff_count" gorm:"type:int;default:0;column:aff_count"` + AffQuota int `json:"aff_quota" gorm:"type:int;default:0;column:aff_quota"` // 邀请剩余额度 + AffHistoryQuota int `json:"aff_history_quota" gorm:"type:int;default:0;column:aff_history"` // 邀请历史额度 + InviterId int `json:"inviter_id" gorm:"type:int;column:inviter_id;index"` + DeletedAt gorm.DeletedAt `gorm:"index"` + LinuxDOId string `json:"linux_do_id" gorm:"column:linux_do_id;index"` + Setting string `json:"setting" gorm:"type:text;column:setting"` + Remark string `json:"remark,omitempty" gorm:"type:varchar(255)" validate:"max=255"` + StripeCustomer string `json:"stripe_customer" gorm:"type:varchar(64);column:stripe_customer;index"` + CreatedAt int64 `json:"created_at" gorm:"autoCreateTime;column:created_at"` + LastLoginAt int64 `json:"last_login_at" gorm:"default:0;column:last_login_at"` + AuthVersion int64 `json:"-" gorm:"type:bigint;not null;default:1;column:auth_version"` + AdminPermissions map[string]map[string]bool `json:"admin_permissions,omitempty" gorm:"-:all"` } func (user *User) ToBaseUser() *UserBase { @@ -145,7 +146,9 @@ func UpdateUserAccessToken(id int, token string) error { if id == 0 { return errors.New("id 为空!") } - result := DB.Model(&User{}).Where("id = ?", id).Update("access_token", token) + result := DB.Model(&User{}).Where("id = ?", id).Updates(map[string]interface{}{ + "access_token": token, "access_token_created_at": common.GetTimestamp(), + }) if result.Error != nil { return result.Error } @@ -155,6 +158,23 @@ func UpdateUserAccessToken(id int, token string) error { return nil } +// RevokeUserAccessToken returns the generation actually revoked under the row lock. +func RevokeUserAccessToken(id int) (string, error) { + var tokenRef string + err := DB.Transaction(func(tx *gorm.DB) error { + var user User + if err := lockForUpdate(tx).Select("id", "access_token").First(&user, id).Error; err != nil { + return err + } + tokenRef = AccessTokenFingerprint(user.GetAccessToken()) + if tokenRef == "" { + return nil + } + return tx.Model(&User{}).Where("id = ?", id).Updates(map[string]interface{}{"access_token": nil, "access_token_created_at": nil}).Error + }) + return tokenRef, err +} + func (user *User) GetSetting() dto.UserSetting { setting := dto.UserSetting{} if user.Setting != "" { diff --git a/router/api-router.go b/router/api-router.go index 18074a9325..f8ff56902c 100644 --- a/router/api-router.go +++ b/router/api-router.go @@ -16,6 +16,7 @@ func SetApiRouter(router *gin.Engine) { apiRouter := router.Group("/api") apiRouter.Use(middleware.RouteTag("api")) apiRouter.Use(gzip.Gzip(gzip.DefaultCompression)) + apiRouter.Use(middleware.AccessTokenAudit()) apiRouter.Use(middleware.BodyStorageCleanup()) // 清理请求体存储 apiRouter.Use(middleware.GlobalAPIRateLimit()) anonymousRequestBodyLimit := middleware.AnonymousRequestBodyLimit() @@ -82,7 +83,7 @@ func SetApiRouter(router *gin.Engine) { userRoute.GET("/groups", controller.GetUserGroups) selfRoute := userRoute.Group("/") - selfRoute.Use(middleware.UserAuth()) + selfRoute.Use(middleware.DisableCache(), middleware.UserAuth()) { selfRoute.GET("/sessions", middleware.DisableCache(), controller.GetLoginSessions) selfRoute.DELETE("/sessions/:sid", middleware.DisableCache(), controller.DeleteLoginSession) @@ -93,6 +94,9 @@ func SetApiRouter(router *gin.Engine) { selfRoute.PUT("/self", middleware.CriticalRateLimit(), middleware.DisableCache(), controller.UpdateSelf) selfRoute.DELETE("/self", controller.DeleteSelf) selfRoute.GET("/token", middleware.CriticalRateLimit(), middleware.UserCriticalRateLimit("access-token"), middleware.DisableCache(), controller.GenerateAccessToken) + selfRoute.GET("/token/status", middleware.DisableCache(), controller.GetAccessTokenStatus) + selfRoute.POST("/token", middleware.CriticalRateLimit(), middleware.UserCriticalRateLimit("access-token"), middleware.DisableCache(), controller.GenerateAccessToken) + selfRoute.DELETE("/token", middleware.CriticalRateLimit(), middleware.DisableCache(), controller.RevokeAccessToken) selfRoute.GET("/passkey", controller.PasskeyStatus) selfRoute.POST("/passkey/register/begin", middleware.DisableCache(), controller.PasskeyRegisterBegin) selfRoute.POST("/passkey/register/finish", middleware.DisableCache(), controller.PasskeyRegisterFinish) @@ -288,6 +292,8 @@ func SetApiRouter(router *gin.Engine) { redemptionRoute.DELETE("/invalid", controller.DeleteInvalidRedemption) redemptionRoute.DELETE("/:id", controller.DeleteRedemption) } + apiRouter.GET("/audit", middleware.DisableCache(), middleware.AdminAuth(), middleware.RequirePermission(authz.AuditRead), controller.GetAuditLogs) + apiRouter.GET("/audit/self", middleware.DisableCache(), middleware.UserAuth(), controller.GetAuditLogs) logRoute := apiRouter.Group("/log") logRoute.GET("/", middleware.AdminAuth(), controller.GetAllLogs) logRoute.GET("/stat", middleware.AdminAuth(), controller.GetLogsStat) diff --git a/router/main.go b/router/main.go index f3e81035ff..d605206b1b 100644 --- a/router/main.go +++ b/router/main.go @@ -32,6 +32,7 @@ func SetRouter(router *gin.Engine, assets WebAssets) { router.NoRoute( pluginDispatcher, middleware.RouteTag("web"), + middleware.AccessTokenAudit(), func(c *gin.Context) { c.Redirect(http.StatusMovedPermanently, fmt.Sprintf("%s%s", frontendBaseUrl, c.Request.RequestURI)) }, diff --git a/router/plugin_router_test.go b/router/plugin_router_test.go index 5e8618504d..9ec3c538c8 100644 --- a/router/plugin_router_test.go +++ b/router/plugin_router_test.go @@ -882,3 +882,33 @@ func performPluginRequest(handler http.Handler, method, path string) *httptest.R handler.ServeHTTP(recorder, request) return recorder } + +func TestWebFallbackDoesNotCacheMissingAPIOrAssets(t *testing.T) { + outer := gin.New() + SetWebRouter(outer, WebAssets{IndexPage: []byte("dashboard")}, func(c *gin.Context) { c.Next() }) + for _, path := range []string{"/api/user/token/status", "/api/audit/self?p=1", "/v1/missing", "/assets/missing.js"} { + t.Run(path, func(t *testing.T) { + response := performPluginRequest(outer, http.MethodGet, path) + assert.Equal(t, http.StatusNotFound, response.Code) + assert.Contains(t, response.Body.String(), "Invalid URL") + assert.Contains(t, response.Header().Get("Cache-Control"), "no-store") + assert.NotContains(t, response.Header().Get("Cache-Control"), "604800") + }) + } + page := performPluginRequest(outer, http.MethodGet, "/security") + assert.Equal(t, http.StatusOK, page.Code) + assert.Equal(t, "dashboard", page.Body.String()) + assert.Equal(t, "no-cache", page.Header().Get("Cache-Control")) +} + +func TestSecurityRoutesDisableCachingBeforeAuthentication(t *testing.T) { + outer := gin.New() + SetApiRouter(outer) + for _, path := range []string{"/api/user/token/status", "/api/user/token", "/api/audit/self", "/api/audit"} { + t.Run(path, func(t *testing.T) { + response := performPluginRequest(outer, http.MethodGet, path) + assert.Equal(t, http.StatusUnauthorized, response.Code) + assert.Contains(t, response.Header().Get("Cache-Control"), "no-store") + }) + } +} diff --git a/router/web-router.go b/router/web-router.go index dbfadf2152..7f814da70d 100644 --- a/router/web-router.go +++ b/router/web-router.go @@ -26,6 +26,7 @@ func SetWebRouter(router *gin.Engine, assets WebAssets, pluginDispatcher gin.Han pluginDispatcher, middleware.RouteTag("web"), gzip.Gzip(gzip.DefaultCompression), + middleware.AccessTokenAudit(), middleware.GlobalWebRateLimit(), middleware.Cache(), static.Serve("/", frontendFS), diff --git a/service/authz/authz_test.go b/service/authz/authz_test.go index 1c4b8cdafa..4cf1f9b717 100644 --- a/service/authz/authz_test.go +++ b/service/authz/authz_test.go @@ -108,6 +108,7 @@ func TestSetUserPermissionsStoresOnlyOverrides(t *testing.T) { ResourceTaskPlugin: { ActionBind: false, }, + ResourceAudit: {ActionRead: false}, }, ExplicitUserPermissions(42)) assert.Equal(t, PermissionsMap{ ResourceChannel: { @@ -139,6 +140,7 @@ func TestSetUserPermissionsStoresOnlyOverrides(t *testing.T) { ResourceTaskPlugin: { ActionBind: false, }, + ResourceAudit: {ActionRead: false}, }, ExplicitUserPermissions(42)) assert.Empty(t, ExplicitUserOverrides(42)) } diff --git a/service/authz/resources_audit.go b/service/authz/resources_audit.go new file mode 100644 index 0000000000..2dbdd08e74 --- /dev/null +++ b/service/authz/resources_audit.go @@ -0,0 +1,17 @@ +package authz + +const ResourceAudit = "audit" + +var AuditRead = Permission{Resource: ResourceAudit, Action: ActionRead} + +func init() { + RegisterResource(ResourceDefinition{ + Resource: ResourceAudit, + LabelKey: "Audit Logs", + Actions: []ActionDefinition{{ + Action: ActionRead, + LabelKey: "View other accounts' audit logs", + DescriptionKey: "View audit records from user and admin roles. Root records are always excluded.", + }}, + }) +} diff --git a/web/src/components/layout/components/mobile-drawer.tsx b/web/src/components/layout/components/mobile-drawer.tsx index 9e09df7719..c287a3110a 100644 --- a/web/src/components/layout/components/mobile-drawer.tsx +++ b/web/src/components/layout/components/mobile-drawer.tsx @@ -17,7 +17,7 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ import { Link } from '@tanstack/react-router' -import { X, User, Wallet, LogOut } from 'lucide-react' +import { X, User, Wallet, LogOut, ShieldCheck } from 'lucide-react' import { AnimatePresence, motion, type Variants } from 'motion/react' import { useTranslation } from 'react-i18next' @@ -26,6 +26,7 @@ import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar' import { Button } from '@/components/ui/button' import { Skeleton } from '@/components/ui/skeleton' import useDialogState from '@/hooks/use-dialog' +import { useIsSidebarModuleVisible } from '@/hooks/use-sidebar-config' import { useUserDisplay } from '@/hooks/use-user-display' import type { AuthUser } from '@/stores/auth-store' @@ -81,6 +82,7 @@ function MobileUserProfile({ user, onNavigate }: MobileUserProfileProps) { const { t } = useTranslation() const [signOutOpen, setSignOutOpen] = useDialogState() const { displayName, initials, roleLabel } = useUserDisplay(user) + const isSecurityVisible = useIsSidebarModuleVisible('/security') if (!user) return null @@ -122,6 +124,17 @@ function MobileUserProfile({ user, onNavigate }: MobileUserProfileProps) { {t('Profile')} + {isSecurityVisible && ( + + + {t('Security & Access')} + + )} + ) : ( - {mobileLinksList.map((link, index) => ( + {mobileLinksList.map((link) => ( diff --git a/web/src/components/profile-dropdown.tsx b/web/src/components/profile-dropdown.tsx index f34c755682..1e9f22c95f 100644 --- a/web/src/components/profile-dropdown.tsx +++ b/web/src/components/profile-dropdown.tsx @@ -17,7 +17,7 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ import { useNavigate } from '@tanstack/react-router' -import { User, Wallet, LogOut, Settings } from 'lucide-react' +import { User, Wallet, LogOut, Settings, ShieldCheck } from 'lucide-react' import { useMemo } from 'react' import { useTranslation } from 'react-i18next' @@ -48,6 +48,7 @@ export function ProfileDropdown() { const { displayName, roleLabel } = useUserDisplay(user) const isSuperAdmin = user?.role === ROLE.SUPER_ADMIN const isWalletVisible = useIsSidebarModuleVisible('/wallet') + const isSecurityVisible = useIsSidebarModuleVisible('/security') const avatarName = user?.username || displayName const avatarFallback = getUserAvatarFallback(avatarName) const avatarFallbackStyle = useMemo( @@ -107,6 +108,13 @@ export function ProfileDropdown() { {t('Profile')} + {isSecurityVisible && ( + navigate({ to: '/security' })}> + + {t('Security & Access')} + + )} + {isWalletVisible && ( navigate({ to: '/wallet' })}> diff --git a/web/src/features/auth/secure-verification/components/secure-verification-dialog.tsx b/web/src/features/auth/secure-verification/components/secure-verification-dialog.tsx index dcced4cf4b..7d40010c38 100644 --- a/web/src/features/auth/secure-verification/components/secure-verification-dialog.tsx +++ b/web/src/features/auth/secure-verification/components/secure-verification-dialog.tsx @@ -73,7 +73,9 @@ export function SecureVerificationDialog({ state.description ?? (availableTabs.length ? 'Confirm your identity before accessing this sensitive action.' - : 'Enable Two-factor Authentication or Passkey in your profile settings to continue.') + : t( + 'Enable Two-factor Authentication or Passkey in Security & Access to continue.' + )) const handleVerify = () => { if (!activeMethod) return @@ -132,7 +134,7 @@ export function SecureVerificationDialog({

{t( - 'Enable Two-factor Authentication or Passkey in your profile to unlock sensitive operations.' + 'Enable Two-factor Authentication or Passkey in Security & Access to unlock sensitive operations.' )}

diff --git a/web/src/features/profile/__tests__/settings.test.tsx b/web/src/features/profile/__tests__/settings.test.tsx new file mode 100644 index 0000000000..ac4a2a22d4 --- /dev/null +++ b/web/src/features/profile/__tests__/settings.test.tsx @@ -0,0 +1,194 @@ +/* +Copyright (C) 2023-2026 QuantumNous + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +For commercial licensing, please contact support@quantumnous.com +*/ +import { fireEvent, render, screen, waitFor } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { api } from '@/lib/api' + +import { updateUserSettings } from '../api' +import { NotificationTab } from '../components/tabs/notification-tab' +import type { UserProfile } from '../types' + +const profile: UserProfile = { + id: 1, + username: 'alice', + display_name: 'Alice', + role: 1, + group: 'default', + quota: 1000000, + used_quota: 0, + request_count: 0, + status: 1, + aff_count: 0, + aff_quota: 0, + aff_history_quota: 0, + created_time: 0, +} +const settings = { + notify_type: 'webhook', + quota_warning_threshold: 1200, + notification_email: '', + webhook_url: 'https://example.com/notify', + webhook_secret: 'webhook-secret', + bark_url: '', + gotify_url: '', + gotify_token: '', + gotify_priority: 5, + accept_unset_model_ratio_model: true, + record_ip_log: true, + upstream_model_update_notify_enabled: true, +} + +afterEach(() => vi.restoreAllMocks()) + +describe('user settings saves across profile and security', () => { + it('disabling IP recording sends the latest complete notification settings', async () => { + const get = vi.spyOn(api, 'get').mockResolvedValue({ + data: { + success: true, + data: { ...profile, setting: JSON.stringify(settings) }, + }, + }) + const put = vi + .spyOn(api, 'put') + .mockResolvedValue({ data: { success: true } }) + await updateUserSettings({ record_ip_log: false }) + expect(get).toHaveBeenCalledWith('/api/user/self') + expect(put).toHaveBeenCalledWith('/api/user/setting', { + ...settings, + record_ip_log: false, + }) + }) + + it('saving IP recording for a user with no settings supplies the existing defaults', async () => { + vi.spyOn(api, 'get').mockResolvedValue({ + data: { success: true, data: profile }, + }) + const put = vi + .spyOn(api, 'put') + .mockResolvedValue({ data: { success: true } }) + await updateUserSettings({ record_ip_log: true }) + expect(put).toHaveBeenCalledWith('/api/user/setting', { + notify_type: 'email', + quota_warning_threshold: 500000, + notification_email: '', + webhook_url: '', + webhook_secret: '', + bark_url: '', + gotify_url: '', + gotify_token: '', + gotify_priority: 5, + accept_unset_model_ratio_model: false, + record_ip_log: true, + upstream_model_update_notify_enabled: false, + }) + }) + + it('alternating notification and IP saves retains the latest values from each page', async () => { + let saved = { ...settings } + vi.spyOn(api, 'get').mockImplementation(async () => ({ + data: { + success: true, + data: { ...profile, setting: JSON.stringify(saved) }, + }, + })) + vi.spyOn(api, 'put').mockImplementation(async (_url, body) => { + saved = body as typeof settings + return { data: { success: true } } + }) + await updateUserSettings({ record_ip_log: false }) + await updateUserSettings({ quota_warning_threshold: 2500 }) + await updateUserSettings({ record_ip_log: true }) + expect(saved).toEqual({ + ...settings, + quota_warning_threshold: 2500, + record_ip_log: true, + }) + }) + + it('a rejected profile read prevents the settings write', async () => { + vi.spyOn(api, 'get').mockRejectedValue(new Error('offline')) + const put = vi.spyOn(api, 'put') + await expect(updateUserSettings({ record_ip_log: false })).rejects.toThrow( + 'offline' + ) + expect(put).not.toHaveBeenCalled() + }) + + it('an unsuccessful profile response prevents the settings write', async () => { + vi.spyOn(api, 'get').mockResolvedValue({ + data: { success: false, message: 'Unavailable' }, + }) + const put = vi.spyOn(api, 'put') + expect(await updateUserSettings({ record_ip_log: false })).toEqual({ + success: false, + message: 'Unavailable', + }) + expect(put).not.toHaveBeenCalled() + }) + + it('an unsuccessful settings write is returned to the caller', async () => { + vi.spyOn(api, 'get').mockResolvedValue({ + data: { success: true, data: profile }, + }) + vi.spyOn(api, 'put').mockResolvedValue({ + data: { success: false, message: 'Save failed' }, + }) + expect(await updateUserSettings({ record_ip_log: true })).toEqual({ + success: false, + message: 'Save failed', + }) + }) + + it('saving a stale notification form keeps the current IP setting and the notification edits', async () => { + const onUpdate = vi.fn() + vi.spyOn(api, 'get').mockResolvedValue({ + data: { + success: true, + data: { + ...profile, + setting: JSON.stringify({ ...settings, record_ip_log: false }), + }, + }, + }) + const put = vi + .spyOn(api, 'put') + .mockResolvedValue({ data: { success: true } }) + render( + + ) + expect( + screen.queryByRole('switch', { name: 'Record IP Address' }) + ).not.toBeInTheDocument() + fireEvent.change( + screen.getByRole('spinbutton', { name: 'Quota Warning Threshold' }), + { target: { value: '2700' } } + ) + fireEvent.click(screen.getByRole('button', { name: 'Save Settings' })) + await waitFor(() => expect(onUpdate).toHaveBeenCalled()) + expect(put).toHaveBeenCalledWith('/api/user/setting', { + ...settings, + quota_warning_threshold: 2700, + record_ip_log: false, + }) + }) +}) diff --git a/web/src/features/profile/api.ts b/web/src/features/profile/api.ts index 1d112ab4a9..7544837bb4 100644 --- a/web/src/features/profile/api.ts +++ b/web/src/features/profile/api.ts @@ -20,6 +20,7 @@ import { api } from '@/lib/api' import type { CustomOAuthBinding } from '@/lib/oauth' import type { LoginSession } from '@/stores/auth-store' +import { normalizeUserSettings } from './lib/user-settings' import type { ApiResponse, UserProfile, @@ -60,7 +61,12 @@ export async function updateUserProfile( export async function updateUserSettings( data: UpdateUserSettingsRequest ): Promise { - const res = await api.put('/api/user/setting', data) + const profile = await getUserProfile() + if (!profile.success || !profile.data) { + return { success: false, message: profile.message } + } + const settings = normalizeUserSettings(profile.data.setting) + const res = await api.put('/api/user/setting', { ...settings, ...data }) return res.data } @@ -84,14 +90,6 @@ export async function deleteUserAccount( return res.data } -/** - * Generate/regenerate system access token - */ -export async function generateAccessToken(): Promise> { - const res = await api.get('/api/user/token') - return res.data -} - // ============================================================================ // Account Binding APIs // ============================================================================ diff --git a/web/src/features/profile/components/dialogs/access-token-dialog.tsx b/web/src/features/profile/components/dialogs/access-token-dialog.tsx deleted file mode 100644 index c506cc95f1..0000000000 --- a/web/src/features/profile/components/dialogs/access-token-dialog.tsx +++ /dev/null @@ -1,198 +0,0 @@ -/* -Copyright (C) 2023-2026 QuantumNous - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as -published by the Free Software Foundation, either version 3 of the -License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Affero General Public License for more details. - -You should have received a copy of the GNU Affero General Public License -along with this program. If not, see . - -For commercial licensing, please contact support@quantumnous.com -*/ -import { KeyRound, Loader2, RefreshCw } from 'lucide-react' -import { useState } from 'react' -import { useTranslation } from 'react-i18next' - -import { ConfirmDialog } from '@/components/confirm-dialog' -import { CopyButton } from '@/components/copy-button' -import { Dialog } from '@/components/dialog' -import { Button } from '@/components/ui/button' -import { - Empty, - EmptyDescription, - EmptyHeader, - EmptyMedia, - EmptyTitle, -} from '@/components/ui/empty' -import { Input } from '@/components/ui/input' -import { Label } from '@/components/ui/label' - -import { useAccessToken } from '../../hooks' - -// ============================================================================ -// Access Token Dialog Component -// ============================================================================ - -interface AccessTokenDialogProps { - open: boolean - onOpenChange: (open: boolean) => void -} - -export function AccessTokenDialog({ - open, - onOpenChange, -}: AccessTokenDialogProps) { - const { t } = useTranslation() - const { token, generating, generate, clearToken } = useAccessToken() - const [confirmOpen, setConfirmOpen] = useState(false) - - const handleOpenChange = (nextOpen: boolean) => { - if (generating) return - - if (!nextOpen) { - setConfirmOpen(false) - clearToken() - } - onOpenChange(nextOpen) - } - - const handleGenerate = async () => { - if (await generate()) { - setConfirmOpen(false) - } - } - - return ( - <> - - - - - } - > -
- {token ? ( -
- -
- - -
-

- {t( - "Save this token now. You won't be able to view it again after closing this dialog." - )} -

-
- ) : ( - - - - - - {t('Access tokens are shown only once')} - - - {t( - 'For security, existing access tokens cannot be displayed. Regenerate only when you need a new token.' - )} - - - {t( - 'Regenerating immediately invalidates any existing token.' - )} - - - - )} -
-
- - { - if (!generating) setConfirmOpen(nextOpen) - }} - title={t('Regenerate access token?')} - desc={ -
-

- {t( - 'This will immediately invalidate your existing access token. Any applications or scripts using it will stop working.' - )} -

-

- {t( - 'The new token will only be shown once. Copy it and store it securely.' - )} -

-
- } - confirmText={ - generating ? ( - <> -