Repository navigation
Conversation
Re-source username/role/status/group from GetUserCache on every session auth so bans and demotions take effect before cookie expiry. UserBase includes Role for admin checks without a dedicated DB hit when Redis is warm. Unit tests without RDB/DB keep session hints.
WalkthroughSession authentication now refreshes user data from Redis or the database, normalizes identity fields, rejects invalid states, and propagates refreshed context. Cached user snapshots include roles, with middleware coverage for disabled, missing, and database-error cases. ChangesSession authentication refresh
Estimated code review effort: 3 (Moderate) | ~25 minutes Sequence Diagram(s)sequenceDiagram
participant Client
participant TokenOrUserAuth
participant getFreshSessionUser
participant Redis
participant modelDB
Client->>TokenOrUserAuth: request with session identity
TokenOrUserAuth->>getFreshSessionUser: refresh session user
getFreshSessionUser->>Redis: read cached user snapshot
getFreshSessionUser->>modelDB: query user on cache miss
getFreshSessionUser-->>TokenOrUserAuth: refreshed user or error
TokenOrUserAuth-->>Client: continue or return auth status
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@middleware/auth.go`:
- Around line 228-239: Propagate the normalized status through the request
context in the shown authentication flow by adding it alongside the existing
username, role, id, and group values in the context setup. Update the
refresh-context test to assert that the context contains the refreshed status.
- Around line 193-196: Update the role selection logic around the cached
snapshot check in the authentication middleware: never fall back to the session
or cookie role when the cached snapshot’s full.Role is zero. Treat that snapshot
as stale by reloading or invalidating it, then derive the role from the
refreshed state so fail-closed demotion is preserved.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 5edc6928-1bee-43e9-b10b-e73a8eb9ba8e
📒 Files selected for processing (4)
middleware/auth.gomiddleware/auth_test.gomodel/user.gomodel/user_cache.go
CodeRabbit #6298: a pre-Role Redis snapshot with Role==0 previously fell back to the cookie role, which could keep a demoted admin elevated. Always take role/status from cache/DB, reload from DB when Role is zero, and propagate status into the request context like TokenOrUserAuth.
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
middleware/auth_test.go (1)
226-239: 🎯 Functional Correctness | 🔵 Trivial | 🏗️ Heavy liftDocstring overstates what this test actually exercises.
The comment says this verifies the "cache snapshot returns Role==0 (pre-Role schema)" reload path, but
setupTokenOrUserAuthTestDBdisables Redis and the DB row'sRoleis non-zero (common.RoleCommonUser). That meansauthHelper'sif full.Role == 0 && model.DB != nil { ... }branch inmiddleware/auth.go— the specific fix this PR's follow-up commit introduces — is never actually reached here; this test only proves DB authority over a stale session role claim, which is a different (still useful) scenario.Either narrow the doc comment to reflect the DB-authority scenario actually tested, or add a case that forces a cached snapshot with
Role == 0(e.g., by enablingcommon.RedisEnabledand pre-seeding a legacy cache entry) to directly exercise the reload branch.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@middleware/auth_test.go` around lines 226 - 239, The test comment overstates coverage of the legacy cache-role reload path. Update the documentation above TestAdminAuthDoesNotTrustSessionRoleWhenCacheLacksRole to describe only the scenario it actually exercises: a demoted database user must override a stale admin role in the session, without claiming coverage of Role==0 cache snapshots.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@middleware/auth_test.go`:
- Around line 305-322: Replace the independent value checks in the /me handler
and the response status check with testify/assert, while retaining require for
setup or fatal conditions. Update the relevant assertions in the test around
UserAuth and router.ServeHTTP so all non-fatal mismatches are reported without
stopping at the first failure.
- Around line 254-277: In the demoted-user test, remove the unused gotRole and
gotStatus variables, their assignments in the registered handler, and the
discard statements. Replace the final independent require checks with assert
checks, and validate the response body by unmarshalling its JSON into the
appropriate response type and asserting Success is false instead of using a
substring match.
---
Nitpick comments:
In `@middleware/auth_test.go`:
- Around line 226-239: The test comment overstates coverage of the legacy
cache-role reload path. Update the documentation above
TestAdminAuthDoesNotTrustSessionRoleWhenCacheLacksRole to describe only the
scenario it actually exercises: a demoted database user must override a stale
admin role in the session, without claiming coverage of Role==0 cache snapshots.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 37ca9146-b4c7-4d7a-a80e-80a5361001e4
📒 Files selected for processing (2)
middleware/auth.gomiddleware/auth_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
- middleware/auth.go
| handlerCalled := false | ||
| var gotRole, gotStatus int | ||
| router.GET("/admin", AdminAuth(), func(c *gin.Context) { | ||
| handlerCalled = true | ||
| gotRole = c.GetInt("role") | ||
| gotStatus = c.GetInt("status") | ||
| c.Status(http.StatusNoContent) | ||
| }) | ||
|
|
||
| cookies := tokenOrUserAuthSessionCookies(t, router, user.Id) | ||
| recorder := httptest.NewRecorder() | ||
| request := httptest.NewRequest(http.MethodGet, "/admin", nil) | ||
| request.Header.Set("New-Api-User", fmt.Sprintf("%d", user.Id)) | ||
| for _, sessionCookie := range cookies { | ||
| request.AddCookie(sessionCookie) | ||
| } | ||
| router.ServeHTTP(recorder, request) | ||
|
|
||
| // Demoted user must not pass AdminAuth. | ||
| require.Equal(t, http.StatusOK, recorder.Code) // authHelper returns 200 + success:false | ||
| require.False(t, handlerCalled) | ||
| require.Contains(t, recorder.Body.String(), "false") | ||
| _ = gotRole | ||
| _ = gotStatus |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win
Tighten assertions and drop dead variables in this test.
Three issues in this final block:
- Lines 273-277 use
requirefor independent, non-fatal value checks (status code,handlerCalled, body content). As per coding guidelines,**/*_test.go: "New or substantially rewritten Go backend tests must usetestify/requirefor setup and fatal assertions andtestify/assertfor non-fatal value checks." None of these three checks gate subsequent logic that could panic, so they should useassert. - Line 275's
require.Contains(t, recorder.Body.String(), "false")is a loose substring match rather than an exact check on the JSON response (e.g. unmarshal and assertSuccess == false), which better matches the guideline's preference for exact outputs. gotRole/gotStatus(255, 258-259) are only ever set inside the handler, which is confirmed never called (274); they're dead and just discarded (276-277) — safe to remove.
🔧 Suggested cleanup
- handlerCalled := false
- var gotRole, gotStatus int
- router.GET("/admin", AdminAuth(), func(c *gin.Context) {
- handlerCalled = true
- gotRole = c.GetInt("role")
- gotStatus = c.GetInt("status")
- c.Status(http.StatusNoContent)
- })
+ handlerCalled := false
+ router.GET("/admin", AdminAuth(), func(c *gin.Context) {
+ handlerCalled = true
+ c.Status(http.StatusNoContent)
+ }) // Demoted user must not pass AdminAuth.
- require.Equal(t, http.StatusOK, recorder.Code) // authHelper returns 200 + success:false
- require.False(t, handlerCalled)
- require.Contains(t, recorder.Body.String(), "false")
- _ = gotRole
- _ = gotStatus
+ assert.Equal(t, http.StatusOK, recorder.Code) // authHelper returns 200 + success:false
+ assert.False(t, handlerCalled)
+ var body map[string]any
+ require.NoError(t, common.Unmarshal(recorder.Body.Bytes(), &body))
+ assert.Equal(t, false, body["success"])📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| handlerCalled := false | |
| var gotRole, gotStatus int | |
| router.GET("/admin", AdminAuth(), func(c *gin.Context) { | |
| handlerCalled = true | |
| gotRole = c.GetInt("role") | |
| gotStatus = c.GetInt("status") | |
| c.Status(http.StatusNoContent) | |
| }) | |
| cookies := tokenOrUserAuthSessionCookies(t, router, user.Id) | |
| recorder := httptest.NewRecorder() | |
| request := httptest.NewRequest(http.MethodGet, "/admin", nil) | |
| request.Header.Set("New-Api-User", fmt.Sprintf("%d", user.Id)) | |
| for _, sessionCookie := range cookies { | |
| request.AddCookie(sessionCookie) | |
| } | |
| router.ServeHTTP(recorder, request) | |
| // Demoted user must not pass AdminAuth. | |
| require.Equal(t, http.StatusOK, recorder.Code) // authHelper returns 200 + success:false | |
| require.False(t, handlerCalled) | |
| require.Contains(t, recorder.Body.String(), "false") | |
| _ = gotRole | |
| _ = gotStatus | |
| handlerCalled := false | |
| router.GET("/admin", AdminAuth(), func(c *gin.Context) { | |
| handlerCalled = true | |
| c.Status(http.StatusNoContent) | |
| }) | |
| cookies := tokenOrUserAuthSessionCookies(t, router, user.Id) | |
| recorder := httptest.NewRecorder() | |
| request := httptest.NewRequest(http.MethodGet, "/admin", nil) | |
| request.Header.Set("New-Api-User", fmt.Sprintf("%d", user.Id)) | |
| for _, sessionCookie := range cookies { | |
| request.AddCookie(sessionCookie) | |
| } | |
| router.ServeHTTP(recorder, request) | |
| // Demoted user must not pass AdminAuth. | |
| assert.Equal(t, http.StatusOK, recorder.Code) // authHelper returns 200 + success:false | |
| assert.False(t, handlerCalled) | |
| var body map[string]any | |
| require.NoError(t, common.Unmarshal(recorder.Body.Bytes(), &body)) | |
| assert.Equal(t, false, body["success"]) |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@middleware/auth_test.go` around lines 254 - 277, In the demoted-user test,
remove the unused gotRole and gotStatus variables, their assignments in the
registered handler, and the discard statements. Replace the final independent
require checks with assert checks, and validate the response body by
unmarshalling its JSON into the appropriate response type and asserting Success
is false instead of using a substring match.
Source: Coding guidelines
| router.GET("/me", UserAuth(), func(c *gin.Context) { | ||
| require.Equal(t, user.Username, c.GetString("username")) | ||
| require.Equal(t, user.Role, c.GetInt("role")) | ||
| require.Equal(t, user.Status, c.GetInt("status")) | ||
| require.Equal(t, user.Group, c.GetString("user_group")) | ||
| c.Status(http.StatusNoContent) | ||
| }) | ||
|
|
||
| cookies := tokenOrUserAuthSessionCookies(t, router, user.Id) | ||
| recorder := httptest.NewRecorder() | ||
| request := httptest.NewRequest(http.MethodGet, "/me", nil) | ||
| request.Header.Set("New-Api-User", fmt.Sprintf("%d", user.Id)) | ||
| for _, sessionCookie := range cookies { | ||
| request.AddCookie(sessionCookie) | ||
| } | ||
| router.ServeHTTP(recorder, request) | ||
|
|
||
| require.Equal(t, http.StatusNoContent, recorder.Code) |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win
Use assert for these non-fatal value checks.
Lines 306-309 (inside the handler) and 322 assert independent values with require, stopping the test at the first mismatch instead of surfacing all of them. As per coding guidelines, **/*_test.go: "New or substantially rewritten Go backend tests must use testify/require for setup and fatal assertions and testify/assert for non-fatal value checks."
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@middleware/auth_test.go` around lines 305 - 322, Replace the independent
value checks in the /me handler and the response status check with
testify/assert, while retaining require for setup or fatal conditions. Update
the relevant assertions in the test around UserAuth and router.ServeHTTP so all
non-fatal mismatches are reported without stopping at the first failure.
Source: Coding guidelines
|
Addressed CodeRabbit review on this PR:
Pushed: |
移植自上游 PR QuantumNous#6298 并与本地 jzlh-fix 合并。此前 authHelper 的 role/status 直接取自 session cookie(30 天有效期),封禁、删除、 降权在 cookie 过期前对已登录会话全部无效;TokenOrUserAuth 同样 只看 cookie status。多租户商用平台(团队/代理/供应商)不可接受。 - session 登录每请求经 GetUserCache 取实时快照(Redis 热路径, miss 回源 DB),username/role/status/group 全部以快照为准; 取快照失败按 fail-closed 中止(404→401,DB 错→500) - 本地原有「group 读实时缓存」的 jzlh-fix 由此升级为全字段版本; access token 路径组改取 ValidateAccessToken 的 DB 全行 - UserBase/ToBaseUser/GetUserCache 补 Role 字段;旧版 Redis 快照 Role 零值视为陈旧,强制回源 DB,绝不回退 cookie 声称的角色 - TokenOrUserAuth 会话分支同样走快照并拒绝非启用状态(403) - 管理接口 disable/promote/demote 已有的 InvalidateUserCache 保证变更即时可见;无持久层的单测环境保留 session 线索 - 新增 7 个中间件回归测试(封禁/删除/降权/DB 故障 fail-closed/ 上下文刷新) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
对抗性 review 发现 abe9f66 的 P2 功能回归:移植 QuantumNous#6298 时 TokenOrUserAuth 对「会话存在但用户被封/删除」改为硬拒,丢掉了本 端点(/v1/videos/:task_id/content 等双鉴权入口)原有的「会话无效则 回落 TokenAuth」行为——携残留封禁会话 cookie + 有效 API 令牌的请求 被误拒。改为:仅当会话用户确为启用态才走会话身份,否则回落 TokenAuth 让令牌独立鉴权(TokenAuth 自身校验用户封禁,安全不放松)。更新 3 个 中间件测试断言回落行为。 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Withdrawing this contribution. No further action needed from maintainers. Closing and deleting the head branch. |
Summary
Second small PR from the withdrawn hardening effort: session auth fail-closed.
UserAuth/AdminAuth/RootAuth/TokenOrUserAuthsession path, reloadusername/role/status/groupviamodel.GetUserCache(Redis first, DB fallback).UserBasegainsRoleso demotion is enforced without a dedicatedGetUserByIdon every dashboard request when cache is warm.RDB == nil).Test plan
go test ./middleware ./modelAdminAuthroutes return insufficient privilegeNotes
Summary by CodeRabbit