Skip to content

fix(auth): fail-closed session refresh via user cache - #6298

Closed
xvyimu wants to merge 2 commits into
QuantumNous:mainfrom
xvyimu:pr/b2-session-fail-closed
Closed

xvyimu wants to merge 2 commits into
QuantumNous:mainfrom
xvyimu:pr/b2-session-fail-closed

Conversation

@xvyimu

@xvyimu xvyimu commented Jul 18, 2026 •

Copy link
Copy Markdown

Summary

Second small PR from the withdrawn hardening effort: session auth fail-closed.

  • Session cookies are treated as identity hints only.
  • On each UserAuth / AdminAuth / RootAuth / TokenOrUserAuth session path, reload username / role / status / group via model.GetUserCache (Redis first, DB fallback).
  • UserBase gains Role so demotion is enforced without a dedicated GetUserById on every dashboard request when cache is warm.
  • Ban / missing user → unauthorized/forbidden before the 30-day cookie would expire.
  • Unit tests without Redis/DB keep session-only behavior (no panic on RDB == nil).

Test plan

  • go test ./middleware ./model
  • Manual: disable user in admin → existing browser session loses access on next API call
  • Manual: demote admin → AdminAuth routes return insufficient privilege

Notes

Summary by CodeRabbit

  • Bug Fixes
    • Session authentication now normalizes session user IDs and refreshes the user’s identity, role, status, and group before granting access.
    • Sessions for disabled/deleted/missing users are rejected; refresh failures now fail securely when persistence is available.
    • Authorization now validates refreshed status and minimum role requirements rather than relying on stale claims.
    • Cached user snapshots now retain role to keep authorization decisions consistent.
  • Tests
    • Added coverage for session refresh, fail-closed behavior, admin checks, and context propagation (including status).
  • Documentation
    • Clarified disabled-vs-other token states for read-only token authentication.

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.
@coderabbitai

coderabbitai Bot commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

Session 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.

Changes

Session authentication refresh

Layer / File(s) Summary
User snapshot role propagation
model/user.go, model/user_cache.go
User role values are now included in converted and cached UserBase snapshots.
Middleware session refresh flow
middleware/auth.go
Session IDs and context values are normalized; session users are refreshed from cache or database, with explicit 401, 403, and 500 handling.
Authentication regression coverage
middleware/auth_test.go
Gin and SQLite tests cover refreshed context, disabled or missing users, database failures, deleted or demoted admin users, and status propagation.

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
Loading

Poem

I’m a rabbit with a cookie in tow,
Refreshing the user before we go.
Roles bloom in the cache,
Stale sessions get a splash,
And tests guard each auth flow.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: making session auth fail closed by refreshing identity from the user cache.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5a6c53d and 77614af.

📒 Files selected for processing (4)
  • middleware/auth.go
  • middleware/auth_test.go
  • model/user.go
  • model/user_cache.go

Comment thread middleware/auth.go Resolved
Comment thread middleware/auth.go Resolved
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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
middleware/auth_test.go (1)

226-239: 🎯 Functional Correctness | 🔵 Trivial | 🏗️ Heavy lift

Docstring overstates what this test actually exercises.

The comment says this verifies the "cache snapshot returns Role==0 (pre-Role schema)" reload path, but setupTokenOrUserAuthTestDB disables Redis and the DB row's Role is non-zero (common.RoleCommonUser). That means authHelper's if full.Role == 0 && model.DB != nil { ... } branch in middleware/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 enabling common.RedisEnabled and 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

📥 Commits

Reviewing files that changed from the base of the PR and between 77614af and 7f01eee.

📒 Files selected for processing (2)
  • middleware/auth.go
  • middleware/auth_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • middleware/auth.go

Comment thread middleware/auth_test.go
Comment on lines +254 to +277
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 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 require for independent, non-fatal value checks (status code, handlerCalled, body content). 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." None of these three checks gate subsequent logic that could panic, so they should use assert.
  • 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 assert Success == 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.

Suggested change
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

Comment thread middleware/auth_test.go
Comment on lines +305 to +322
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 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

@xvyimu

xvyimu commented Jul 19, 2026

Copy link
Copy Markdown
Author

Addressed CodeRabbit review on this PR:

  1. Role fail-closed: never fall back to session/cookie role when cache snapshot has Role==0. Invalidate cache and reload from DB; always take role/status from cache/DB.
  2. Context: c.Set("status", status) is now set on the session auth path (same as TokenOrUserAuth).

Pushed: 7f01eeec on pr/b2-session-fail-closed.
Tests: go test ./middleware green.

JacksonsY added a commit to JacksonsY/new-api that referenced this pull request Jul 19, 2026
移植自上游 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]>
JacksonsY added a commit to JacksonsY/new-api that referenced this pull request Jul 19, 2026
对抗性 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]>
@xvyimu

xvyimu commented Jul 23, 2026

Copy link
Copy Markdown
Author

Withdrawing this contribution. No further action needed from maintainers. Closing and deleting the head branch.

@xvyimu xvyimu closed this Jul 23, 2026
@xvyimu
xvyimu deleted the pr/b2-session-fail-closed branch July 23, 2026 05:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants