Skip to content

fix: auto 分组令牌请求返回 403#4719

Open
oujuncan wants to merge 4 commits into
QuantumNous:mainfrom
oujuncan:fix/auto-group-permission-and-default
Open

fix: auto 分组令牌请求返回 403#4719
oujuncan wants to merge 4 commits into
QuantumNous:mainfrom
oujuncan:fix/auto-group-permission-and-default

Conversation

@oujuncan
Copy link
Copy Markdown

@oujuncan oujuncan commented May 9, 2026

⚠️ 提交说明 / PR Notice

📝 变更描述 / Description

问题:auto 分组令牌请求返回 403

middleware/auth.goTokenAuth 中间件在校验令牌分组时,会检查 tokenGroup 是否在用户可用分组列表(UserUsableGroups)中。但 "auto" 是一个伪分组(pseudo-group),不会出现在可用分组列表里,导致所有 auto 分组的令牌请求直接被 403 拦截。

后面第 392 行已经有对 "auto" 的特殊处理(跳过"已弃用"检查),但代码在第 386 行就提前返回了,根本执行不到。

修复:"auto" 跳过 UserUsableGroups 校验。这是安全的,因为下游 GetUserAutoGroup() 会根据用户实际可用分组过滤 auto 能解析到的真实分组,权限控制由下游保证。

#4653 是同一类问题(该 PR 修复的是 distributor.go 中的相同逻辑)。

🚀 变更类型 / Type of change

  • 🐛 Bug 修复 (Bug fix)
  • ✨ 新功能 (New feature)
  • ⚡ 性能优化 / 重构 (Refactor)
  • 📝 文档更新 (Documentation)

🔗 关联任务 / Related Issue

✅ 提交前检查项 / Checklist

  • 人工确认: 我已亲自整理并撰写此描述,没有直接粘贴未经处理的 AI 输出。
  • 非重复提交: 我已搜索现有的 IssuesPRs,确认不是重复提交。
  • Bug fix 说明: 若此 PR 标记为 Bug fix,我已提交或关联对应 Issue,且不会将设计取舍、预期不一致或理解偏差直接归类为 bug。
  • 变更理解: 我已理解这些更改的工作原理及可能影响。
  • 范围聚焦: 本 PR 未包含任何与当前任务无关的代码改动。
  • 本地验证: 已在本地运行并通过测试或手动验证,维护者可以据此复核结果。
  • 安全合规: 代码中无敏感凭据,且符合项目代码规范。

📸 运行证明 / Proof of Work

后端编译通过:

$ go build ./...
# 无错误输出

修复前(auto 分组令牌请求 /v1/models):

{
    "error": {
        "code": "",
        "message": "无权访问 auto 分组",
        "type": "new_api_error"
    }
}

修复后: 正常返回模型列表。

Summary by CodeRabbit

Release Notes

  • Bug Fixes
    • Token validation for automatic group assignments now skips unnecessary verification steps while maintaining standard security checks for explicit groups
    • API key creation form now properly initializes default values based on available groups, improving the creation experience
    • Form state is now maintained consistently when reopening the API key creation interface, preventing unintended resets

Review Change Stack

1. middleware/auth.go: TokenAuth 中间件对 "auto" 伪分组跳过
   UserUsableGroups 校验,修复 auto 分组令牌请求返回 403 的问题。
   auto 分组的实际权限控制由下游 GetUserAutoGroup 保证。

2. web/default: 当 DefaultUseAutoGroup 为 false 时,新建 API 密钥
   的分组默认值使用接口返回的第一个可用分组,而非空字符串。

Closes QuantumNous#3189
Related QuantumNous#4653 QuantumNous#4160
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 9, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 6461836c-1f3c-4537-9767-3c9ce3371071

📥 Commits

Reviewing files that changed from the base of the PR and between 4c33c56 and 55e09d7.

📒 Files selected for processing (1)
  • web/default/src/features/keys/components/api-keys-mutate-drawer.tsx
💤 Files with no reviewable changes (1)
  • web/default/src/features/keys/components/api-keys-mutate-drawer.tsx

Walkthrough

The PR enables "auto" group support for API key creation. The backend now exempts "auto" tokens from usable-group membership checks, while the frontend drawer derives the first available group from fetched groups and uses it as the default form value when not in auto mode.

Changes

Auto Group Support for API Keys

Layer / File(s) Summary
Backend Authorization
middleware/auth.go
Token group validation exempts "auto" from usable-groups membership check; non-auto groups continue requiring validation.
Frontend Drawer Integration
web/default/src/features/keys/components/api-keys-mutate-drawer.tsx
Drawer derives firstGroup from groupsRaw and passes it to form initialization and create-mode resets; firstGroup added to effect dependencies.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Suggested reviewers

  • xyfacai

Poem

🐰 A token hops through fields so green,
Where "auto" groups need not convene—
No membership checks for magic strings,
Just fetch the first group that it brings.
Backend and drawer now agree, hooray! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title clearly identifies the main fix: handling auto group tokens returning 403 errors in the TokenAuth middleware.
Linked Issues check ✅ Passed Both code changes directly address the linked issue #3189: TokenAuth middleware fix handles auto group tokens, and API key form fix ensures proper default group initialization when defaultUseAutoGroup is configured.
Out of Scope Changes check ✅ Passed All changes are scoped to the two specific issues: middleware token validation and API key form default values initialization, with no unrelated modifications present.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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 and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
web/default/src/features/keys/components/api-keys-mutate-drawer.tsx (1)

168-184: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Prevent form reset when groups load during create-mode input.

The firstGroup dependency in the useEffect (line 184) causes the form to reset whenever groups are fetched or refetched, wiping any input the user has entered in create mode. On slow networks, opening the create drawer, typing a name, and waiting for the groups query to complete will lose that input.

Guard the reset in create mode with a dirty check:

Suggested fix
     } else if (open && !isUpdate) {
       // For create, reset to defaults
-      form.reset(getApiKeyFormDefaultValues(defaultUseAutoGroup, firstGroup))
+      if (!form.formState.isDirty) {
+        form.reset(getApiKeyFormDefaultValues(defaultUseAutoGroup, firstGroup))
+      }
     }
🤖 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 `@web/default/src/features/keys/components/api-keys-mutate-drawer.tsx` around
lines 168 - 184, The useEffect currently resets the create-mode form whenever
firstGroup (groups) changes, wiping user input; update the create branch so it
only calls form.reset(getApiKeyFormDefaultValues(defaultUseAutoGroup,
firstGroup)) when the form is not dirty (use form.formState.isDirty or
form.getState().isDirty depending on your form API) — keep the existing
fetch/update logic (getApiKey and transformApiKeyToFormDefaults) for isUpdate,
and leave the effect dependencies (open, isUpdate, currentRow, form,
defaultUseAutoGroup, firstGroup) intact.
🤖 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.

Outside diff comments:
In `@web/default/src/features/keys/components/api-keys-mutate-drawer.tsx`:
- Around line 168-184: The useEffect currently resets the create-mode form
whenever firstGroup (groups) changes, wiping user input; update the create
branch so it only calls
form.reset(getApiKeyFormDefaultValues(defaultUseAutoGroup, firstGroup)) when the
form is not dirty (use form.formState.isDirty or form.getState().isDirty
depending on your form API) — keep the existing fetch/update logic (getApiKey
and transformApiKeyToFormDefaults) for isUpdate, and leave the effect
dependencies (open, isUpdate, currentRow, form, defaultUseAutoGroup, firstGroup)
intact.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: af37624e-9f02-4a4f-af90-d4f2ca67a22a

📥 Commits

Reviewing files that changed from the base of the PR and between d146e45 and 882459e.

📒 Files selected for processing (3)
  • middleware/auth.go
  • web/default/src/features/keys/components/api-keys-mutate-drawer.tsx
  • web/default/src/features/keys/lib/api-key-form.ts

mrogers added 2 commits May 9, 2026 20:37
Prevent groups async load from wiping user input when firstGroup
changes after the user has started filling the form.
When defaultUseAutoGroup=false, the group field should remain empty
(showing placeholder) so users explicitly choose a group, rather than
auto-selecting the first available group from the API response.
@oujuncan oujuncan changed the title fix: auto 分组令牌请求 403 及 API 密钥表单默认分组为空 fix: auto 分组令牌请求返回 403 May 9, 2026
Take main's backendHasAuto check for defaultUseAutoGroup,
which correctly guards auto group default based on backend state.
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.

设置了创建令牌默认选择auto分组无效, 依旧是默认用户分组

1 participant