Skip to content

将helm纳入统一的权限管理 #261

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Jul 18, 2025
Merged

将helm纳入统一的权限管理 #261

merged 9 commits into from
Jul 18, 2025

Conversation

weibaohui
Copy link
Owner

将helm纳入统一的权限管理

实现CheckPermissionLogic函数用于检查用户对集群资源的操作权限
包括平台管理员、集群管理员、只读权限和Exec权限的校验
支持命名空间黑白名单机制进行细粒度权限控制
重构权限检查逻辑,将其从cb包移动到comm包以提升代码组织性
移除cb.go中未使用的导入和重复的权限检查代码
将helm仓库相关路由移至admin分组并重构为控制器结构
统一权限检查逻辑,简化重复代码
新增无集群的helm命令构造函数
更新前端api路径匹配新的路由结构
将helm chart相关路由从主路由移至单独控制器
更新前端api路径以匹配新的路由结构
将分散的helm路由注册逻辑集中到HelmReleaseController中
通过RegisterHelmReleaseRoutes方法统一注册路由
在helm release相关接口中添加权限检查逻辑
移除getHelmWithNoCluster函数中未使用的context参数
Copy link
Contributor

coderabbitai bot commented Jul 18, 2025

📝 Walkthrough

Summary by CodeRabbit

  • 新功能

    • Helm Chart、Release、Repo 管理接口重构为更清晰的分组和控制器结构,提升可维护性。
    • 新增统一的权限校验逻辑,提升操作安全性。
  • 优化/重构

    • Helm 相关 API 路由分组调整,更符合功能模块划分。
    • Helm 客户端初始化方式优化,部分操作不再依赖集群或命名空间参数。
    • 权限校验逻辑集中管理,简化各处实现。
  • 界面与接口变更

    • Helm Chart 相关 UI 配置的 API 路径由 /k8s/helm/ 前缀调整为 /mgm/helm/。
    • Helm Repo 相关 UI 配置的 API 路径由 /k8s/helm/repo/ 调整为 /admin/helm/repo/。
  • 修复与一致性

    • 所有 Helm Release 操作统一增加权限校验,提升操作一致性和安全性。

Walkthrough

本次变更对 Helm 相关的控制器、路由注册和权限校验逻辑进行了结构化重构。Helm 的发布、Chart、仓库相关 HTTP 路由注册被集中到各自的注册函数中,控制器方法由函数改为结构体方法。权限校验逻辑从内联实现迁移到 comm 包的统一入口,并新增了无集群上下文的 Helm 客户端构造器。同时,前端 UI 的 Helm 相关 API 路径同步调整。

Changes

文件/路径分组 变更简述
main.go Helm 路由注册由内联分散变为调用 helm 包集中注册函数
pkg/cb/cb.go handleCommonLogic 权限校验逻辑全部移除,改为调用 comm.CheckPermissionLogic
pkg/comm/permission.go 新增 CheckPermissionLogic 统一权限校验函数
pkg/controller/helm/helm.go getHelm 移除 namespace 参数,增加 getHelmWithNoCluster,权限检查改为 check 函数
pkg/controller/helm/helm_chart.go Chart 相关 handler 封装为 HelmChartController 结构体方法,集中路由注册,Helm 客户端初始化改为无集群上下文
pkg/controller/helm/helm_release.go Release 相关 handler 封装为 HelmReleaseController 结构体方法,集中路由注册,统一权限校验,getHelm 调用方式调整
pkg/controller/helm/helm_repo.go Repo 相关 handler 封装为 HelmRepoController 结构体方法,集中路由注册,Helm 客户端初始化改为无集群上下文,移除权限校验
pkg/helm/helm_cmd.go 新增 NewHelmCmdWithNoCluster 构造函数,支持无集群上下文 Helm 客户端
ui/public/pages/helm/chart.json 前端 Chart 相关 API 路径从 /k8s/helm/ 调整为 /mgm/helm/
ui/public/pages/helm/repo.json 前端 Repo 相关 API 路径从 /k8s/helm/repo 调整为 /admin/helm/repo

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant UI
    participant GinRouter
    participant HelmController
    participant comm

    User->>UI: 发起 Helm 相关请求
    UI->>GinRouter: 请求 /mgm/helm/... 或 /admin/helm/...
    GinRouter->>HelmController: 分发到对应 Controller 方法
    HelmController->>comm: CheckPermissionLogic 权限校验
    comm-->>HelmController: 返回校验结果
    HelmController->>HelmController: 业务处理
    HelmController-->>UI: 返回响应
Loading

Possibly related PRs

  • weibaohui/k8m#188: 修复并增强 namespace 级别的权限校验,涉及与本 PR 权限逻辑重构相关的前置修正。
  • weibaohui/k8m#235: 将 Helm 客户端从 SDK 升级为二进制命令模式,涉及 Helm 控制器与客户端结构调整,与本次 Helm 路由和控制器重构直接相关。

Poem

🐰
路由集中新生辉,
权限校验一处归。
Helm 控制分三类,
结构清晰不怕累。
前端路径也齐飞,
代码如画更整齐!

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch callback

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@weibaohui weibaohui merged commit 00e4495 into main Jul 18, 2025
5 of 6 checks passed
@weibaohui weibaohui deleted the callback branch July 18, 2025 15:06
Copy link
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.

Actionable comments posted: 1

🔭 Outside diff range comments (4)
pkg/controller/helm/helm_repo.go (3)

86-113: DeleteRepo 方法缺少权限检查

AddOrUpdateRepo 类似,这个方法允许任何用户删除 Helm 仓库,存在严重的安全风险。

建议在删除操作前添加权限检查:

 func (r *HelmRepoController) DeleteRepo(c *gin.Context) {
     ids := c.Param("ids")
+
+    // 检查权限
+    _, _, err := handleCommonLogic(c, "delete", "", "", "helm-repo")
+    if err != nil {
+        amis.WriteJsonError(c, err)
+        return
+    }

     h, err := getHelmWithNoCluster()

114-130: UpdateReposIndex 方法缺少权限检查

更新仓库索引操作同样需要权限控制。

建议添加权限检查:

 func (r *HelmRepoController) UpdateReposIndex(c *gin.Context) {
     var req struct {
         IDs string `json:"ids"`
     }
     if err := c.ShouldBindJSON(&req); err != nil {
         amis.WriteJsonError(c, err)
         return
     }
+
+    // 检查权限
+    _, _, err := handleCommonLogic(c, "update", "", "", "helm-repo")
+    if err != nil {
+        amis.WriteJsonError(c, err)
+        return
+    }

     h, err := getHelmWithNoCluster()

39-57: 在 AddOrUpdateRepo 方法中添加权限校验

当前 pkg/controller/helm/helm_repo.go 的 AddOrUpdateRepo 无权限校验,与 helm_release.go 中对其他 Helm 操作均调用 handleCommonLogic 不一致,请在调用 getHelmWithNoCluster() 之前加入如下校验:

diff --git a/pkg/controller/helm/helm_repo.go b/pkg/controller/helm/helm_repo.go
index  abcdef1..1234567 100644
--- a/pkg/controller/helm/helm_repo.go
+++ b/pkg/controller/helm/helm_repo.go
@@ -39,6 +39,12 @@ func (r *HelmRepoController) AddOrUpdateRepo(c *gin.Context) {
     if err := c.ShouldBindJSON(&repo); err != nil {
         amis.WriteJsonError(c, err)
         return
     }
+
+    // 权限校验:创建或更新 Helm 仓库
+    _, _, err := handleCommonLogic(c, "create", repo.Name, "", "helm-repo")
+    if err != nil {
+        amis.WriteJsonError(c, err)
+        return
+    }
 
     h, err := getHelmWithNoCluster()
     if err != nil {
         amis.WriteJsonError(c, err)
         return
     }
pkg/controller/helm/helm_chart.go (1)

37-56: GetChartValue 方法缺少权限检查

获取 Chart 值的操作应该有权限控制,确保只有授权用户才能访问。

建议添加权限检查:

 func (hc *HelmChartController) GetChartValue(c *gin.Context) {
     repoName := c.Param("repo")
     chartName := c.Param("chart")
     version := c.Param("version")
+
+    // 检查权限
+    _, _, err := handleCommonLogic(c, "get", chartName, "", repoName)
+    if err != nil {
+        amis.WriteJsonError(c, err)
+        return
+    }
+
     h, err := getHelmWithNoCluster()
🧹 Nitpick comments (5)
pkg/cb/cb.go (1)

70-73: 可能存在命名空间重复的问题

如果 ns 已经存在于 nsList 中,这里的追加操作会导致重复。建议在追加前检查是否已存在。

 ns := stmt.Namespace
 if ns != "" {
-    nsList = append(nsList, ns)
+    if !slice.Contain(nsList, ns) {
+        nsList = append(nsList, ns)
+    }
 }
pkg/comm/permission.go (2)

184-186: 日志格式可能有误

日志中 roleString=%v 但实际记录的是 roles,变量名不一致可能造成混淆。

-    klog.V(6).Infof("cb: cluster= %s,user= %s, role= %s,roleString=%v, operation=%s,  resource=[%s/%s] ",
-        cluster, username, roleString, roles, action, ns, name)
+    klog.V(6).Infof("cb: cluster=%s, user=%s, platformRole=%s, clusterRoles=%v, operation=%s, resource=[%s/%s]",
+        cluster, username, roleString, roles, action, ns, name)

18-187: 权限检查逻辑实现完善

新的集中式权限检查函数很好地实现了:

  • 平台管理员的特殊处理
  • 基于角色的访问控制
  • 命名空间白名单和黑名单机制
  • 详细的错误信息

建议考虑将来进一步模块化,将不同 action 的处理逻辑抽取为独立函数以提高可维护性。

pkg/controller/helm/helm_release.go (2)

222-254: 批量卸载操作可以优化

在循环内创建 Helm 客户端(第 234 行)效率较低,建议在循环外创建一次。

 func (hr *HelmReleaseController) BatchUninstallRelease(c *gin.Context) {
     var req struct {
         Names      []string `json:"name_list"`
         Namespaces []string `json:"ns_list"`
     }
     if err := c.ShouldBindJSON(&req); err != nil {
         amis.WriteJsonError(c, err)
         return
     }
+    
+    h, err := getHelm(c)
+    if err != nil {
+        amis.WriteJsonError(c, err)
+        return
+    }
+    
     for i := 0; i < len(req.Names); i++ {
         name := req.Names[i]
         ns := req.Namespaces[i]
-        h, err := getHelm(c)
-        if err != nil {
-            amis.WriteJsonError(c, err)
-            return
-        }

         // 检查权限
         _, _, err = handleCommonLogic(c, "delete", name, ns, "")

38-43: 错误变量重复声明可能造成混淆

多处使用 := 重新声明 err 变量,虽然语法正确,但可能影响代码可读性。

考虑在需要时使用不同的变量名或显式赋值以提高代码清晰度。

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between addaebe and b3041ff.

📒 Files selected for processing (10)
  • main.go (3 hunks)
  • pkg/cb/cb.go (2 hunks)
  • pkg/comm/permission.go (1 hunks)
  • pkg/controller/helm/helm.go (3 hunks)
  • pkg/controller/helm/helm_chart.go (3 hunks)
  • pkg/controller/helm/helm_release.go (11 hunks)
  • pkg/controller/helm/helm_repo.go (5 hunks)
  • pkg/helm/helm_cmd.go (1 hunks)
  • ui/public/pages/helm/chart.json (3 hunks)
  • ui/public/pages/helm/repo.json (4 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
main.go (3)
pkg/controller/helm/helm_release.go (1)
  • RegisterHelmReleaseRoutes (18-30)
pkg/controller/helm/helm_chart.go (1)
  • RegisterHelmChartRoutes (16-22)
pkg/controller/helm/helm_repo.go (1)
  • RegisterHelmRepoRoutes (17-24)
pkg/comm/permission.go (5)
pkg/constants/role.go (4)
  • RolePlatformAdmin (9-9)
  • RoleClusterAdmin (12-12)
  • RoleClusterReadonly (13-13)
  • RoleClusterPodExec (14-14)
pkg/constants/jwt_user.go (1)
  • JwtUserName (4-4)
pkg/service/service.go (1)
  • UserService (67-69)
pkg/models/cluster_user_role.go (1)
  • ClusterUserRole (15-25)
pkg/comm/utils/slice.go (2)
  • AnyIn (44-56)
  • AllIn (22-34)
pkg/controller/helm/helm_repo.go (1)
pkg/models/helm_repository.go (1)
  • HelmRepository (11-30)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Analyze (go)
🔇 Additional comments (12)
pkg/helm/helm_cmd.go (1)

92-111: 新增的无集群上下文构造函数实现良好

这个新的构造函数 NewHelmCmdWithNoCluster 设计合理:

  • 遵循了现有构造函数的模式
  • 正确验证了 helmBin 参数
  • 确保缓存目录存在
  • 适当地排除了集群相关配置,符合其设计目的

这个函数为需要在无集群上下文环境中使用 Helm 功能的场景提供了良好的支持。

ui/public/pages/helm/repo.json (1)

25-25: API 端点更新与后端重构保持一致

所有 Helm 仓库相关的 API 端点已正确更新到 /admin/helm/repo 命名空间:

  • 保存仓库:/admin/helm/repo/save
  • 删除仓库:/admin/helm/repo/delete/${ids}
  • 更新索引:/admin/helm/repo/update_index
  • 列表查询:/admin/helm/repo/list

这些更改与后端的路由重构完全一致,确保前端能够正确调用新的管理员权限 API。

Also applies to: 323-323, 330-330, 356-356, 374-374

main.go (3)

470-471: Helm 发布路由注册重构良好

将 Helm 发布相关的路由注册集中到 helm.RegisterHelmReleaseRoutes(api) 函数中,这是一个很好的重构:

  • 提高了代码的组织性和可维护性
  • 减少了 main.go 中的重复代码
  • 遵循了单一职责原则

508-509: Helm Chart 路由注册重构一致

Chart 路由注册采用了与发布路由相同的集中化方法,通过 helm.RegisterHelmChartRoutes(mgm) 统一管理,保持了代码风格的一致性。


554-555: Helm 仓库路由注册完成整体重构

仓库路由注册通过 helm.RegisterHelmRepoRoutes(admin) 完成了整个 Helm 模块的路由重构,将所有 Helm 相关路由都采用了统一的注册方式。

ui/public/pages/helm/chart.json (1)

95-95: Chart API 端点更新与后端路由重构一致

所有 Helm Chart 相关的 API 端点已正确更新到 /mgm/helm/ 命名空间:

  • Chart 列表:/mgm/helm/chart/list
  • Chart 版本列表:/mgm/helm/repo/${repository_name}/chart/${name}/versions
  • Chart 值配置:/mgm/helm/repo/${repository_name}/chart/${name}/version/${install_version}/values

这些更改与后端控制器重构完全同步,确保前端能够正确调用新的管理组 API。

Also applies to: 142-142, 225-225

pkg/controller/helm/helm.go (3)

15-27: 简化 getHelm 函数提高代码清晰度

移除了 namespace 参数及其默认值逻辑,使函数职责更加单一明确。这个简化很好地反映了新的 Helm 客户端初始化方法。


28-32: 新增无集群上下文函数支持更多场景

getHelmWithNoCluster 函数为不需要集群上下文的 Helm 操作提供了良好的支持,如仓库管理等场景。实现简洁且目的明确。


52-64: 权限检查逻辑集中化改进

将权限检查逻辑委托给新的 comm.CheckPermissionLogic 函数是一个很好的重构:

  • 统一了权限验证逻辑
  • 提高了代码的可维护性
  • 移除了重复的权限检查代码

同时移除了日志记录前的延迟,提高了响应性能。

pkg/cb/cb.go (1)

65-76: 权限检查逻辑集中化重构良好

将权限检查逻辑从内联实现迁移到 comm.CheckPermissionLogic 是一个很好的架构改进,提高了代码的可维护性和一致性。

pkg/controller/helm/helm_repo.go (1)

17-24: 路由注册位置需要确认

路由注册在 /admin 路径下,这通常表示管理员功能。请确认这是否符合设计意图,因为如果没有权限检查,任何能访问这些路由的用户都可以执行敏感操作。

pkg/controller/helm/helm_release.go (1)

18-30: Helm Release 控制器权限管理实现良好

与其他 Helm 控制器相比,HelmReleaseController 正确实现了所有方法的权限检查,这是很好的安全实践。

Comment on lines +16 to +22
func RegisterHelmChartRoutes(mgm *gin.RouterGroup) {
ctrl := &HelmChartController{}
mgm.GET("/helm/repo/:repo/chart/:chart/versions", ctrl.ChartVersionOptionList)
mgm.GET("/helm/repo/:repo/chart/:chart/version/:version/values", ctrl.GetChartValue)
mgm.GET("/helm/chart/list", ctrl.ListChart)

}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Helm Chart 控制器权限管理不一致

HelmReleaseController 相比,HelmChartController 完全没有权限检查,这种不一致性可能导致安全漏洞。建议统一所有 Helm 相关控制器的权限管理策略。

🤖 Prompt for AI Agents
In pkg/controller/helm/helm_chart.go around lines 16 to 22, the
RegisterHelmChartRoutes function registers routes for HelmChartController
without any permission checks, unlike HelmReleaseController which has
authorization. To fix this, add appropriate middleware or permission checks to
these routes to enforce consistent access control across all Helm-related
controllers, ensuring security policies are uniformly applied.

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.

1 participant