Repository navigation
Go: add dummy admin functions - #16830
Conversation
Signed-off-by: Jin Hai <[email protected]>
📝 WalkthroughWalkthroughAdds protected enterprise admin routes and handlers for role permissions, sensitive words, verification email, whitelist management, and ingestion tasks. Adds corresponding service stubs and changes selected not-found error responses to server errors. ChangesEnterprise admin API
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant AdminRouter
participant EnterpriseHandler
participant EnterpriseService
AdminRouter->>EnterpriseHandler: Enterprise admin request
EnterpriseHandler->>EnterpriseService: Validate and invoke operation
EnterpriseService-->>EnterpriseHandler: Command payload or error
EnterpriseHandler-->>AdminRouter: Success or error response
Possibly related PRs
Suggested labels: Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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: 5
🧹 Nitpick comments (2)
internal/admin/enterprise_service.go (1)
136-145: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winStub methods return
nilerror with "not supported" in the data, so handlers always respond with success.Every stub embeds an
"error"key in the result map but returnsnilfor the error value. Handlers checkif err != niland, since it is always nil, callcommon.SuccessWithData. Clients receive a success code with an error message buried in the data. Consider returning an actualerrors.New("... is not supported")so handlers map it toCodeServerErrorconsistently.♻️ Example fix for one stub
func (s *Service) ListRolesWithPermission() ([]map[string]interface{}, error) { - return []map[string]interface{}{ - { - "command": "list_roles_with_permission", - "error": "'list roles with permission' is not supported", - }, - }, nil + return nil, errors.New("'list roles with permission' is not supported") }Also applies to: 1187-1296
🤖 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 `@internal/admin/enterprise_service.go` around lines 136 - 145, Update ListRolesWithPermission and the other stub methods in the affected range to return an actual errors.New(...) error for unsupported operations instead of embedding an "error" field in successful result data and returning nil. Preserve each method’s existing unsupported message, and ensure handlers receive the non-nil error so they produce CodeServerError responses.internal/admin/enterprise_handler.go (1)
1800-1809: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueCheck file count before iterating all files in multipart handlers.
Both
UploadSensitiveWordsandBatchAddWhiteListvalidate every file in a loop, then reject iflen(files) != 1. If a client uploads 10 files, all 10 are validated before the count rejection. Move the count check before the loop.♻️ Proposed fix for UploadSensitiveWords (apply same pattern to BatchAddWhiteList)
files := form.File["file"] + if len(files) != 1 { + common.ResponseWithCodeData(c, common.CodeArgumentError, nil, "Only one file is allowed") + return + } for _, fh := range files { if fh == nil || fh.Filename == "" { common.ResponseWithCodeData(c, common.CodeArgumentError, nil, "No file or filename is empty") return } } - if len(files) != 1 { - common.ResponseWithCodeData(c, common.CodeArgumentError, nil, "Only one file is allowed") - return - } file := files[0]Also applies to: 1907-1916
🤖 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 `@internal/admin/enterprise_handler.go` around lines 1800 - 1809, In both UploadSensitiveWords and BatchAddWhiteList, move the len(files) != 1 rejection before the loop that validates file entries, so multipart requests with an invalid file count return immediately without iterating. Preserve the existing nil-file or empty-filename validation for the single allowed file.
🤖 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 `@internal/admin/enterprise_handler.go`:
- Line 1834: Remove the println debug statement from the JSON binding error path
in the surrounding enterprise handler, leaving the existing error handling
behavior unchanged.
- Line 1965: Update the success message in DeleteWhiteList to return “White list
deleted successfully” instead of the copied update message, while preserving the
existing result and response flow.
In `@internal/admin/enterprise_service.go`:
- Around line 1212-1224: Update BindVerificationEmail to remove the password
field from the result map, ensuring the API response returned by
common.SuccessWithData does not echo the SMTP credential; preserve the remaining
response fields and unsupported-operation error.
In `@internal/admin/router.go`:
- Around line 224-225: Align the :id handling in UpdateWhiteList and
DeleteWhiteList so both endpoints enforce the same identifier type, preferably
validating/parsing the path parameter consistently before invoking their
services. Preserve the existing behavior for valid numeric identifiers and
reject non-numeric values uniformly.
- Line 179: Align the admin whitelist route registrations in the router with the
paths and HTTP methods used by the client API definitions: update the
roles-with-permission endpoint, whitelist add endpoint, and whitelist deletion
endpoint (including its identifier parameter) consistently across
`internal/admin/router.go` and the corresponding API helpers in
`web/src/utils/api.ts`, preserving the intended delete method.
---
Nitpick comments:
In `@internal/admin/enterprise_handler.go`:
- Around line 1800-1809: In both UploadSensitiveWords and BatchAddWhiteList,
move the len(files) != 1 rejection before the loop that validates file entries,
so multipart requests with an invalid file count return immediately without
iterating. Preserve the existing nil-file or empty-filename validation for the
single allowed file.
In `@internal/admin/enterprise_service.go`:
- Around line 136-145: Update ListRolesWithPermission and the other stub methods
in the affected range to return an actual errors.New(...) error for unsupported
operations instead of embedding an "error" field in successful result data and
returning nil. Preserve each method’s existing unsupported message, and ensure
handlers receive the non-nil error so they produce CodeServerError responses.
🪄 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: 30f713d7-198d-486d-bfad-952f794b0c23
📒 Files selected for processing (3)
internal/admin/enterprise_handler.gointernal/admin/enterprise_service.gointernal/admin/router.go
| func (h *Handler) BindVerificationEmail(c *gin.Context) { | ||
| var request BindVerificationEmailRequest | ||
| if err := c.ShouldBindJSON(&request); err != nil { | ||
| println("JSON bind error: %v (type: %T)", err, err) |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Remove the println debug artifact.
Go's built-in println does not support format verbs — %v and %T are printed literally to stderr. This is a debug artifact that should not be in production code.
🧹 Proposed fix
if err := c.ShouldBindJSON(&request); err != nil {
- println("JSON bind error: %v (type: %T)", err, err)
common.ErrorWithCode(c, common.CodeBadRequest, err.Error())
return
}📝 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.
| println("JSON bind error: %v (type: %T)", err, err) | |
| if err := c.ShouldBindJSON(&request); err != nil { | |
| common.ErrorWithCode(c, common.CodeBadRequest, err.Error()) | |
| return | |
| } |
🤖 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 `@internal/admin/enterprise_handler.go` at line 1834, Remove the println debug
statement from the JSON binding error path in the surrounding enterprise
handler, leaving the existing error handling behavior unchanged.
| return | ||
| } | ||
|
|
||
| common.SuccessWithData(c, result, "White list updated successfully") |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Fix the copy-pasted success message in DeleteWhiteList.
The handler returns "White list updated successfully" but should say "White list deleted successfully".
💚 Proposed fix
- common.SuccessWithData(c, result, "White list updated successfully")
+ common.SuccessWithData(c, result, "White list deleted successfully")📝 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.
| common.SuccessWithData(c, result, "White list updated successfully") | |
| common.SuccessWithData(c, result, "White list deleted successfully") |
🤖 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 `@internal/admin/enterprise_handler.go` at line 1965, Update the success
message in DeleteWhiteList to return “White list deleted successfully” instead
of the copied update message, while preserving the existing result and response
flow.
| func (s *Service) BindVerificationEmail(email, host string, port int, username, password string, useTLS, useSSL bool) (map[string]interface{}, error) { | ||
| result := map[string]interface{}{ | ||
| "command": "bind_verification_email", | ||
| "email": email, | ||
| "host": host, | ||
| "port": port, | ||
| "username": username, | ||
| "password": password, | ||
| "use_tls": useTLS, | ||
| "use_ssl": useSSL, | ||
| "error": "'Bind verification email' is not supported", | ||
| } | ||
| return result, nil |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟠 Major | ⚡ Quick win
BindVerificationEmail leaks the SMTP password in the API response.
The service includes "password": password in the result map, and the handler returns it to the client via common.SuccessWithData. Even as a stub, this echoes the credential back. Remove password from the response map.
🔒 Proposed fix
func (s *Service) BindVerificationEmail(email, host string, port int, username, password string, useTLS, useSSL bool) (map[string]interface{}, error) {
result := map[string]interface{}{
"command": "bind_verification_email",
"email": email,
"host": host,
"port": port,
"username": username,
- "password": password,
"use_tls": useTLS,
"use_ssl": useSSL,
"error": "'Bind verification email' is not supported",
}
return result, nil
}📝 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.
| func (s *Service) BindVerificationEmail(email, host string, port int, username, password string, useTLS, useSSL bool) (map[string]interface{}, error) { | |
| result := map[string]interface{}{ | |
| "command": "bind_verification_email", | |
| "email": email, | |
| "host": host, | |
| "port": port, | |
| "username": username, | |
| "password": password, | |
| "use_tls": useTLS, | |
| "use_ssl": useSSL, | |
| "error": "'Bind verification email' is not supported", | |
| } | |
| return result, nil | |
| func (s *Service) BindVerificationEmail(email, host string, port int, username, password string, useTLS, useSSL bool) (map[string]interface{}, error) { | |
| result := map[string]interface{}{ | |
| "command": "bind_verification_email", | |
| "email": email, | |
| "host": host, | |
| "port": port, | |
| "username": username, | |
| "use_tls": useTLS, | |
| "use_ssl": useSSL, | |
| "error": "'Bind verification email' is not supported", | |
| } | |
| return result, nil | |
| } |
🤖 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 `@internal/admin/enterprise_service.go` around lines 1212 - 1224, Update
BindVerificationEmail to remove the password field from the result map, ensuring
the API response returned by common.SuccessWithData does not echo the SMTP
credential; preserve the remaining response fields and unsupported-operation
error.
| protected.POST("/roles/:role_name/permission", r.handler.GrantRolePermission) | ||
| protected.DELETE("/roles/:role_name/permission", r.handler.RevokeRolePermission) | ||
| protected.GET("/roles/resource", r.handler.ListResources) | ||
| protected.GET("/roles/permission", r.handler.ListRolesWithPermission) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Description: Check web client API URL definitions against server routes.
# Check roles_with_permission vs roles/permission
rg -n 'roles_with_permission' web/src/utils/api.ts
# Check whitelist vs white-list
rg -n 'whitelist' web/src/utils/api.ts
# Check server route definitions
rg -n 'white-list\|roles/permission' internal/admin/router.goRepository: infiniflow/ragflow
Length of output: 524
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect the relevant server routes and nearby context.
sed -n '150,240p' internal/admin/router.go
# Inspect the client API definitions around the reported endpoints.
sed -n '425,470p' web/src/utils/api.ts
# Find any alternate route aliases or related admin whitelist handlers.
rg -n 'white-list|whitelist|roles_with_permission|roles/permission' internal web/src -g '!**/node_modules/**'Repository: infiniflow/ragflow
Length of output: 16137
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Show the whitelist page's API call sites and surrounding logic.
sed -n '1,320p' web/src/pages/admin/whitelist.tsx
# Show all usages of the whitelist API helpers.
rg -n 'adminListWhitelist|adminCreateWhitelistEntry|adminUpdateWhitelistEntry|adminDeleteWhitelistEntry|adminImportWhitelist' web/src -g '!**/node_modules/**'Repository: infiniflow/ragflow
Length of output: 11469
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect the whitelist handlers and their path-param handling.
rg -n 'func .*DeleteWhiteList|func .*AddWhiteList|func .*UpdateWhiteList|func .*ShowWhiteList|Param\("id"\)|Atoi|strconv' internal -g '!**/node_modules/**'
# Show the handler implementation if it exists in a single file.
sed -n '1,260p' internal/admin/handler.go 2>/dev/null || true
sed -n '1,260p' internal/admin/white_list.go 2>/dev/null || true
sed -n '1,260p' internal/admin/whitelist.go 2>/dev/null || trueRepository: infiniflow/ragflow
Length of output: 40233
Align the admin whitelist routes with the client
web/src/utils/api.ts still targets /admin/roles_with_permission, /admin/whitelist/add, and /admin/whitelist/:email, while internal/admin/router.go exposes /admin/roles/permission, /admin/white-list, and DELETE /white-list/:id. These calls will 404 or pass the wrong identifier unless both sides are updated together.
🤖 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 `@internal/admin/router.go` at line 179, Align the admin whitelist route
registrations in the router with the paths and HTTP methods used by the client
API definitions: update the roles-with-permission endpoint, whitelist add
endpoint, and whitelist deletion endpoint (including its identifier parameter)
consistently across `internal/admin/router.go` and the corresponding API helpers
in `web/src/utils/api.ts`, preserving the intended delete method.
| protected.PUT("/white-list/:id", r.handler.UpdateWhiteList) | ||
| protected.DELETE("/white-list/:id", r.handler.DeleteWhiteList) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
UpdateWhiteList and DeleteWhiteList expect different :id types.
Both routes use :id as a path parameter, but UpdateWhiteList passes the raw string to the service while DeleteWhiteList parses it as an int via strconv.Atoi. A non-numeric id would succeed on PUT but fail on DELETE. Align the type expectations.
🤖 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 `@internal/admin/router.go` around lines 224 - 225, Align the :id handling in
UpdateWhiteList and DeleteWhiteList so both endpoints enforce the same
identifier type, preferably validating/parsing the path parameter consistently
before invoking their services. Preserve the existing behavior for valid numeric
identifiers and reject non-numeric values uniformly.
As title.