Repository navigation
Go CLI: refactor some commands - #16204
Conversation
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughIntroduces email base64 encoding/decoding utilities, refactors enterprise service layer with structured payload responses and new API key methods, extends HTTP handlers with username parameter decoding validation and new endpoints for resource listing and license/fingerprint operations, reorganizes admin routes with API key endpoint rewiring, and comprehensively updates CLI infrastructure (token types, lexer, parsers, command handlers, dispatcher) with standardized ChangesAdmin API and CLI refactor
sequenceDiagram
participant CLIUser
participant CLIParser
participant AdminCmd
participant HTTPHandler
participant Service
rect rgba(100, 149, 237, 0.5)
Note over CLIUser,Service: Resource and Role Listing Flow
CLIUser->>CLIParser: LIST RESOURCES;
CLIParser->>CLIParser: parseAdminListResources()
CLIParser-->>AdminCmd: admin_list_resources_command
AdminCmd->>HTTPHandler: GET /admin/roles/resource
HTTPHandler->>Service: ListResources()
Service-->>HTTPHandler: {command, error}
HTTPHandler-->>AdminCmd: resources payload
AdminCmd-->>CLIUser: Display resources
end
rect rgba(144, 238, 144, 0.5)
Note over CLIUser,Service: User API Key Management Flow
CLIUser->>CLIParser: CREATE USER "[email protected]" KEY;
CLIParser->>CLIParser: parseAdminCreateUserCommand()
CLIParser-->>AdminCmd: admin_create_user_api_key_command
AdminCmd->>AdminCmd: EncodeEmail(user_name)
AdminCmd->>HTTPHandler: POST /admin/users/YWRtaW5AZXhhbXBsZS5jb20=/keys
HTTPHandler->>HTTPHandler: DecodeEmail(username)
HTTPHandler->>Service: CreateUserAPIKey(decoded_email)
Service-->>HTTPHandler: {command, email, api_key}
HTTPHandler-->>AdminCmd: CommonDataResponse
AdminCmd-->>CLIUser: API key created
end
rect rgba(173, 216, 230, 0.5)
Note over CLIUser,Service: System License and Fingerprint Flow
CLIUser->>CLIParser: SET LICENSE "key123";
CLIParser->>CLIParser: parseAdminSetLicense()
CLIParser-->>AdminCmd: admin_set_license_command
AdminCmd->>HTTPHandler: POST /admin/system/license
HTTPHandler->>Service: SetSystemLicense(license_key)
Service-->>HTTPHandler: {command, error}
HTTPHandler-->>AdminCmd: CommonDataResponse
AdminCmd-->>CLIUser: License set
CLIUser->>CLIParser: SHOW FINGERPRINT;
CLIParser->>CLIParser: parseAdminShowFingerprintCommand()
CLIParser-->>AdminCmd: admin_show_fingerprint_command
AdminCmd->>HTTPHandler: GET /admin/system/fingerprint
HTTPHandler->>Service: GetSystemFingerprint()
Service-->>HTTPHandler: {command, fingerprint, error}
HTTPHandler-->>AdminCmd: CommonDataResponse
AdminCmd-->>CLIUser: Display fingerprint
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 3❌ Failed checks (2 warnings, 1 inconclusive)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. 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: 4
🤖 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 40: The success call in the ListRoles function is passing roles directly
as a bare array, but the admin web client expects a structured response with
shape { roles, total }. Modify the success call to construct an object
containing both the roles array and total count (the number of roles) instead of
passing roles directly as the data parameter.
- Around line 119-123: The DeleteRole handler in the deleteRoleHandler method is
currently returning HTTP 404 for all errors from h.service.DeleteRole, which
masks real server failures. Instead, add logic to distinguish between actual
"not found" errors and other backend failures. Only return a 404 status when the
error specifically indicates the role was not found (check the error type or
message), and return a 500 status or other appropriate error code for other
types of failures like database errors or permission issues.
In `@internal/admin/enterprise_service.go`:
- Around line 77-83: The DeleteRole method in the Service struct is returning
inconsistent state in the response map: it sets "deleted" to true while
simultaneously including an error message indicating the feature is unavailable
in enterprise edition, and likely returns nil error. This misleads callers into
treating the operation as successful. Fix this by setting "deleted" to false in
the result map since the role was not actually deleted, and return an
appropriate error (not nil) to clearly indicate the operation failed due to the
enterprise feature limitation.
In `@internal/admin/router.go`:
- Line 171: The ListResources route handler is registered with the DELETE HTTP
method when it should use GET. Change the protected.DELETE("/roles/resource",
r.handler.ListResources) call to use protected.GET instead, so that the GET
requests from both CLI and web clients to the /admin/roles/resource endpoint
will correctly match this route and invoke the ListResources handler.
🪄 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: fe492f5a-7ba9-4c3d-a059-df36a4d2ae9d
📒 Files selected for processing (6)
internal/admin/enterprise_handler.gointernal/admin/enterprise_service.gointernal/admin/router.gointernal/cli/admin_command.gointernal/cli/admin_parser.gointernal/cli/cli_http.go
| "roles": roles, | ||
| "total": len(roles), | ||
| }, "") | ||
| success(c, roles, "") |
There was a problem hiding this comment.
ListRoles response shape no longer matches existing client contract.
This now returns a bare array, while the existing admin web client expects data as { roles, total }. That mismatch will break typed decoding unless all consumers are migrated in lockstep.
🤖 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 40, The success call in the
ListRoles function is passing roles directly as a bare array, but the admin web
client expects a structured response with shape { roles, total }. Modify the
success call to construct an object containing both the roles array and total
count (the number of roles) instead of passing roles directly as the data
parameter.
| role, err := h.service.DeleteRole(roleName) | ||
| if err != nil { | ||
| errorResponse(c, "Role not found", 404) | ||
| return | ||
| } |
There was a problem hiding this comment.
DeleteRole currently converts every backend error into HTTP 404.
Only explicit “not found” errors should return 404; other failures should remain 500 to avoid masking real server faults.
Suggested fix pattern
role, err := h.service.DeleteRole(roleName)
if err != nil {
- errorResponse(c, "Role not found", 404)
+ if errors.Is(err, common.ErrUserNotFound) { // replace with role-not-found sentinel if available
+ errorResponse(c, "Role not found", 404)
+ } else {
+ errorResponse(c, err.Error(), 500)
+ }
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` around lines 119 - 123, The DeleteRole
handler in the deleteRoleHandler method is currently returning HTTP 404 for all
errors from h.service.DeleteRole, which masks real server failures. Instead, add
logic to distinguish between actual "not found" errors and other backend
failures. Only return a 404 status when the error specifically indicates the
role was not found (check the error type or message), and return a 500 status or
other appropriate error code for other types of failures like database errors or
permission issues.
Signed-off-by: Jin Hai <[email protected]>
|
Caution Failed to replace (edit) comment. This is likely due to insufficient permissions or the comment being deleted. Error details |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #16204 +/- ##
==========================================
- Coverage 94.56% 93.16% -1.40%
==========================================
Files 10 10
Lines 717 717
Branches 118 118
==========================================
- Hits 678 668 -10
- Misses 25 29 +4
- Partials 14 20 +6 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
internal/cli/user_parser.go (1)
577-602:⚠️ Potential issue | 🔴 CriticalAPI mode CREATE USER fails due to incorrect command type routing.
parseCreateCommand(used in non-admin/API parsing context) routesTokenUsertoparseAdminCreateUserCommand(), which producesadmin_create_user_command. However,ExecuteUserCommand(which handles API mode commands) does not have a case for this type; it will hit the default case and return an error. When a user in API mode issuesCREATE USER, the command parsing succeeds but execution fails because the command type is not handled in the user execution path.🤖 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/cli/user_parser.go` around lines 577 - 602, The parseCreateCommand method incorrectly routes TokenUser to parseAdminCreateUserCommand, which produces an admin_create_user_command type that ExecuteUserCommand does not handle. In the non-admin/API parsing context, TokenUser should be routed to a different parser method that produces a command type compatible with ExecuteUserCommand instead of the admin-specific parser. Review what command type ExecuteUserCommand expects for user creation and update the parseCreateCommand switch case for TokenUser to call the appropriate non-admin user creation parser method.internal/cli/admin_parser.go (1)
698-725:⚠️ Potential issue | 🔴 CriticalInconsistent role name parsing in
parseAdminCreateRoleCommand.
parseAdminCreateRoleCommandusesparseQuotedString()for role names (line 700), whileparseAdminShowRoleCommand,parseAdminDropRole, andparseAdminAlterRoleall useparseIdentifier(). The user parser's role operations (parseCreateRole,parseDropRole,parseAlterRole) also useparseIdentifier(). This inconsistency within the admin parser and divergence from the user parser pattern suggestsparseAdminCreateRoleCommandis likely using the wrong parsing method.🤖 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/cli/admin_parser.go` around lines 698 - 725, The parseAdminCreateRoleCommand function uses parseQuotedString() to parse the role name, while other similar functions like parseAdminShowRoleCommand, parseAdminDropRole, and parseAdminAlterRole use parseIdentifier() instead. To fix this inconsistency, replace the parseQuotedString() call with parseIdentifier() when parsing the roleName variable in parseAdminCreateRoleCommand to align with the pattern used in other admin role parsing functions and the user parser role operations.
🧹 Nitpick comments (2)
internal/cli/admin_parser.go (1)
647-681: 💤 Low valueCopy-paste comment is misleading.
The comments on lines 675 and 687 say "Semicolon is optional for UNSET TOKEN" but these are
CREATE USERcommands, notUNSET TOKENcommands. Consider updating to a generic comment like "Semicolon is optional".🤖 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/cli/admin_parser.go` around lines 647 - 681, The comment in the parseAdminCreateUserCommand function that states "Semicolon is optional for UNSET TOKEN" is incorrect and misleading, as this function handles CREATE USER commands, not UNSET TOKEN commands. Update the comment to be generic and accurate for the context, such as changing it to "Semicolon is optional" to properly reflect that the semicolon handling applies to the current command type being parsed.internal/cli/admin_command.go (1)
209-248: 💤 Low valueGrammatically awkward error message.
Line 212: "this command is only allowed in ADMIN mode or already login" should be "this command is only allowed in ADMIN mode and requires login" or similar.
Suggested fix
func (c *CLI) AdminCreateRoleCommand(cmd *Command) (ResponseIf, error) { if c.Config.CLIMode != AdminMode || c.AdminServerClient.LoginToken == nil { - return nil, fmt.Errorf("this command is only allowed in ADMIN mode or already login") + return nil, fmt.Errorf("this command requires ADMIN mode and an active login session") }🤖 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/cli/admin_command.go` around lines 209 - 248, The error message in the AdminCreateRoleCommand function uses grammatically incorrect phrasing. Update the error message returned when checking if the command is allowed (when c.Config.CLIMode != AdminMode || c.AdminServerClient.LoginToken == nil) to use proper grammar. Change "this command is only allowed in ADMIN mode or already login" to "this command is only allowed in ADMIN mode and requires login" or similar grammatically correct phrasing that clearly conveys the requirements.
🤖 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/cli/admin_command.go`:
- Around line 440-477: The userName variable is inserted directly into the URL
path without encoding, which can cause issues if the username contains special
characters like forward slashes or percent signs. In the
AdminCreateUserAPIKeyCommand function, when constructing the apiURL using
fmt.Sprintf, wrap the userName parameter with url.PathEscape to safely encode it
for use in the URL path. This should be applied whenever userName (or similar
parameters like email) is used in URL path construction throughout the file.
---
Outside diff comments:
In `@internal/cli/admin_parser.go`:
- Around line 698-725: The parseAdminCreateRoleCommand function uses
parseQuotedString() to parse the role name, while other similar functions like
parseAdminShowRoleCommand, parseAdminDropRole, and parseAdminAlterRole use
parseIdentifier() instead. To fix this inconsistency, replace the
parseQuotedString() call with parseIdentifier() when parsing the roleName
variable in parseAdminCreateRoleCommand to align with the pattern used in other
admin role parsing functions and the user parser role operations.
In `@internal/cli/user_parser.go`:
- Around line 577-602: The parseCreateCommand method incorrectly routes
TokenUser to parseAdminCreateUserCommand, which produces an
admin_create_user_command type that ExecuteUserCommand does not handle. In the
non-admin/API parsing context, TokenUser should be routed to a different parser
method that produces a command type compatible with ExecuteUserCommand instead
of the admin-specific parser. Review what command type ExecuteUserCommand
expects for user creation and update the parseCreateCommand switch case for
TokenUser to call the appropriate non-admin user creation parser method.
---
Nitpick comments:
In `@internal/cli/admin_command.go`:
- Around line 209-248: The error message in the AdminCreateRoleCommand function
uses grammatically incorrect phrasing. Update the error message returned when
checking if the command is allowed (when c.Config.CLIMode != AdminMode ||
c.AdminServerClient.LoginToken == nil) to use proper grammar. Change "this
command is only allowed in ADMIN mode or already login" to "this command is only
allowed in ADMIN mode and requires login" or similar grammatically correct
phrasing that clearly conveys the requirements.
In `@internal/cli/admin_parser.go`:
- Around line 647-681: The comment in the parseAdminCreateUserCommand function
that states "Semicolon is optional for UNSET TOKEN" is incorrect and misleading,
as this function handles CREATE USER commands, not UNSET TOKEN commands. Update
the comment to be generic and accurate for the context, such as changing it to
"Semicolon is optional" to properly reflect that the semicolon handling applies
to the current command type being parsed.
🪄 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: dd732738-0c2f-4461-a97b-00477cc3751d
📒 Files selected for processing (7)
internal/admin/enterprise_handler.gointernal/admin/enterprise_service.gointernal/admin/router.gointernal/cli/admin_command.gointernal/cli/admin_parser.gointernal/cli/cli_http.gointernal/cli/user_parser.go
🚧 Files skipped from review as they are similar to previous changes (2)
- internal/admin/enterprise_handler.go
- internal/admin/enterprise_service.go
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 5
♻️ Duplicate comments (1)
internal/cli/admin_command.go (1)
850-850:⚠️ Potential issue | 🟠 Major | ⚡ Quick winPath-escape the API key before placing it in the route.
API keys can contain reserved path characters, and the Python admin client encodes the key before calling this same DELETE endpoint. A raw
apiKeycan split the route and make deletion fail or hit the wrong path segment. This is the same path-parameter escaping issue previously flagged for this file.Proposed fix
+ "net/url" + - resp, err := c.AdminServerClient.Request("DELETE", fmt.Sprintf("/admin/users/%s/keys/%s", userName, apiKey), "admin", nil, nil) + resp, err := c.AdminServerClient.Request("DELETE", fmt.Sprintf("/admin/users/%s/keys/%s", url.PathEscape(userName), url.PathEscape(apiKey)), "admin", nil, 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/cli/admin_command.go` at line 850, In the Request method call for the DELETE operation, the apiKey parameter is being directly inserted into the route string without path-escaping. API keys can contain reserved path characters that will break the route. Path-escape the apiKey variable before inserting it into the fmt.Sprintf route string to ensure the key is properly encoded, similar to how the Python admin client handles this same DELETE endpoint.
🤖 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`:
- Around line 1005-1008: The DeleteUserAPIKey method error handling at line 1006
and the related error handling at line 1023 currently return HTTP 500 for all
service errors. Instead, these handlers should check if the error is a
user-not-found error and return HTTP 404 in that case, while returning 500 for
other errors. This aligns with the existing behavior in the GetUser handler.
Update both error handling blocks to conditionally check the error type and call
errorResponse with the appropriate status code (404 for user-not-found errors,
500 for others).
In `@internal/admin/enterprise_service.go`:
- Around line 711-714: The error handling in the GetByEmail calls at line 711
and line 730 currently wraps all errors as "user not found", which masks backend
faults and breaks upstream HTTP status mapping. Modify both locations to check
if the error from userDAO.GetByEmail() is a specific not-found sentinel error
(check your DAO implementation for the exact sentinel). Only wrap true not-found
errors with your not-found message; for all other errors, return them unchanged
to preserve error semantics and allow proper HTTP status mapping upstream.
In `@internal/cli/admin_command.go`:
- Around line 2686-2688: The variable `result` is declared as type
`CommonResponse`, but the ListUserAPIKeys API endpoint returns a structured
object payload rather than a JSON array. Change the type of the `result`
variable from `CommonResponse` to `CommonDataResponse` to properly handle the
response structure. This will allow the json.Unmarshal call to correctly parse
the structured object payload before the result.Code is checked.
In `@internal/cli/admin_parser.go`:
- Around line 858-863: The switch statement checking p.curToken.Type currently
handles only the TokenKey case by calling parseAdminDropUserAPIKeyCommand, while
the default case just advances one token without rejecting unexpected suffixes,
allowing the command to return successfully anyway. Fix this by having the
default case return an error to properly reject unexpected tokens after DROP
USER, and ensure that after parseAdminDropUserAPIKeyCommand returns, the parser
advances the token properly before the semicolon validation check runs, since
parseQuotedString() does not advance the token position on its own.
In `@internal/cli/cli_http.go`:
- Around line 64-67: The dispatcher switch statement in cli_http.go is missing a
case handler for the "drop_role" command that the parser emits. Add a new case
statement for "drop_role" that returns a call to c.DropRole(cmd), following the
same pattern as the existing adjacent cases like AdminDropUserCommand and
AdminDropUserAPIKeyCommand. This will route DROP ROLE commands to the existing
DropRole handler method in admin_command.go instead of falling through to the
default error case.
---
Duplicate comments:
In `@internal/cli/admin_command.go`:
- Line 850: In the Request method call for the DELETE operation, the apiKey
parameter is being directly inserted into the route string without
path-escaping. API keys can contain reserved path characters that will break the
route. Path-escape the apiKey variable before inserting it into the fmt.Sprintf
route string to ensure the key is properly encoded, similar to how the Python
admin client handles this same DELETE endpoint.
🪄 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: 7ce6aa32-0fb5-41e7-bdab-ff62a49cff13
📒 Files selected for processing (6)
internal/admin/enterprise_handler.gointernal/admin/enterprise_service.gointernal/admin/router.gointernal/cli/admin_command.gointernal/cli/admin_parser.gointernal/cli/cli_http.go
🚧 Files skipped from review as they are similar to previous changes (1)
- internal/admin/router.go
| result, err := h.service.DeleteUserAPIKey(username, key) | ||
| if err != nil { | ||
| errorResponse(c, err.Error(), 500) | ||
| return |
There was a problem hiding this comment.
Return 404 for user-not-found in API-key handlers instead of always 500.
Line 1006 and Line 1023 treat all service errors as internal errors. This diverges from the existing admin contract (GetUser) and expected API-key behavior for missing users.
Suggested fix
+import "errors"
+import "github.com/infiniflow/ragflow/internal/common"
...
if err != nil {
- errorResponse(c, err.Error(), 500)
+ if errors.Is(err, common.ErrUserNotFound) {
+ errorResponse(c, fmt.Sprintf("User '%s' not found", username), 404)
+ } else {
+ errorResponse(c, err.Error(), 500)
+ }
return
}Also applies to: 1022-1025
🤖 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 1005 - 1008, The
DeleteUserAPIKey method error handling at line 1006 and the related error
handling at line 1023 currently return HTTP 500 for all service errors. Instead,
these handlers should check if the error is a user-not-found error and return
HTTP 404 in that case, while returning 500 for other errors. This aligns with
the existing behavior in the GetUser handler. Update both error handling blocks
to conditionally check the error type and call errorResponse with the
appropriate status code (404 for user-not-found errors, 500 for others).
| user, err := s.userDAO.GetByEmail(username) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("user not found: %w", err) | ||
| } |
There was a problem hiding this comment.
Preserve DAO error semantics instead of rewriting all lookup failures as not-found.
Line 711 and Line 730 currently collapse every GetByEmail failure into "user not found". That masks backend faults and breaks correct HTTP/status mapping upstream. Map only true not-found cases to your not-found sentinel; propagate all other errors unchanged.
Suggested fix
user, err := s.userDAO.GetByEmail(username)
if err != nil {
- return nil, fmt.Errorf("user not found: %w", err)
+ if errors.Is(err, common.ErrUserNotFound) {
+ return nil, fmt.Errorf("user not found: %w", err)
+ }
+ return nil, err
}Also applies to: 730-733
🤖 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 711 - 714, The error
handling in the GetByEmail calls at line 711 and line 730 currently wraps all
errors as "user not found", which masks backend faults and breaks upstream HTTP
status mapping. Modify both locations to check if the error from
userDAO.GetByEmail() is a specific not-found sentinel error (check your DAO
implementation for the exact sentinel). Only wrap true not-found errors with
your not-found message; for all other errors, return them unchanged to preserve
error semantics and allow proper HTTP status mapping upstream.
| switch p.curToken.Type { | ||
| case TokenKey: | ||
| return p.parseAdminDropUserAPIKeyCommand(userName) | ||
| default: | ||
| p.nextToken() | ||
| } |
There was a problem hiding this comment.
Reject unexpected DROP USER suffixes and advance after the API key.
DROP USER "<name>" KEYS currently falls into default, consumes one token, and still returns admin_drop_user_command. For the key form, parseQuotedString() does not advance, so the semicolon check runs while still positioned on the key token.
Proposed parser fix
switch p.curToken.Type {
case TokenKey:
return p.parseAdminDropUserAPIKeyCommand(userName)
- default:
+ case TokenSemicolon:
p.nextToken()
+ case TokenEOF:
+ default:
+ return nil, fmt.Errorf("unexpected token after USER name: %s", p.curToken.Value)
}
cmd := NewCommand("admin_drop_user_command")
@@
apiKey, err := p.parseQuotedString()
if err != nil {
return nil, err
}
+ p.nextToken()
// Semicolon is optional
if p.curToken.Type == TokenSemicolon {Also applies to: 873-880
🤖 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/cli/admin_parser.go` around lines 858 - 863, The switch statement
checking p.curToken.Type currently handles only the TokenKey case by calling
parseAdminDropUserAPIKeyCommand, while the default case just advances one token
without rejecting unexpected suffixes, allowing the command to return
successfully anyway. Fix this by having the default case return an error to
properly reject unexpected tokens after DROP USER, and ensure that after
parseAdminDropUserAPIKeyCommand returns, the parser advances the token properly
before the semicolon validation check runs, since parseQuotedString() does not
advance the token position on its own.
| case "admin_drop_user_command": | ||
| return c.AdminDropUserCommand(cmd) | ||
| case "admin_drop_user_api_key_command": | ||
| return c.AdminDropUserAPIKeyCommand(cmd) |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Verify parser command strings, dispatcher cases, and available role-drop handlers.
rg -nP 'NewCommand\("(drop_role|admin_drop_role_command)"\)|case "(drop_role|admin_drop_role_command)"|func \(c \*CLI\).*DropRole' --type go -C2Repository: infiniflow/ragflow
Length of output: 986
🏁 Script executed:
#!/bin/bash
# Get full dispatcher switch statement from cli_http.go, specifically looking for drop_role case
rg -n 'case "drop_role"' internal/cli/cli_http.go -C5Repository: infiniflow/ragflow
Length of output: 44
🏁 Script executed:
#!/bin/bash
# Get the complete switch statement in cli_http.go to see all cases and the default
sed -n '50,100p' internal/cli/cli_http.goRepository: infiniflow/ragflow
Length of output: 1646
🏁 Script executed:
#!/bin/bash
# Continue looking further in the switch statement for drop_role or default case
sed -n '85,150p' internal/cli/cli_http.goRepository: infiniflow/ragflow
Length of output: 2491
🏁 Script executed:
#!/bin/bash
# Search for drop_role case and the default case in cli_http.go
rg -n 'case "drop_role"|default:' internal/cli/cli_http.go -A2 -B2Repository: infiniflow/ragflow
Length of output: 606
🏁 Script executed:
#!/bin/bash
# Find the parser function that creates the drop_role command
rg -n 'func.*parseAdminDropRoleCommand|func.*parseDropRoleCommand' internal/cli/ -A10Repository: infiniflow/ragflow
Length of output: 682
🏁 Script executed:
#!/bin/bash
# Verify: 1) DropRole handler exists, 2) No drop_role case in dispatcher, 3) Where parseAdminDropRoleCommand is called
echo "=== DropRole handler ==="
rg -n 'func \(c \*CLI\) DropRole' internal/cli/ -A3
echo "=== Search for drop_role in dispatcher ==="
rg -n 'drop_role' internal/cli/cli_http.go
echo "=== Where parseAdminDropRoleCommand is called ==="
rg -n 'parseAdminDropRoleCommand' internal/cli/Repository: infiniflow/ragflow
Length of output: 713
Add missing drop_role case to dispatcher.
The parser emits NewCommand("drop_role") but the dispatcher in cli_http.go (line 213) has no matching case, causing DROP ROLE commands to fall through to the default error. The handler DropRole() exists in admin_command.go:250. Add a case like:
case "drop_role":
return c.DropRole(cmd)
🤖 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/cli/cli_http.go` around lines 64 - 67, The dispatcher switch
statement in cli_http.go is missing a case handler for the "drop_role" command
that the parser emits. Add a new case statement for "drop_role" that returns a
call to c.DropRole(cmd), following the same pattern as the existing adjacent
cases like AdminDropUserCommand and AdminDropUserAPIKeyCommand. This will route
DROP ROLE commands to the existing DropRole handler method in admin_command.go
instead of falling through to the default error case.
Signed-off-by: Jin Hai <[email protected]>
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 `@internal/admin/enterprise_handler.go`:
- Around line 236-241: The JSON binding error handler in the ShouldBindJSON
block is returning HTTP 200 (http.StatusOK) instead of the correct HTTP 400
status code for validation failures, and contains an improperly formatted
println statement. Change the c.JSON call to use http.StatusBadRequest instead
of http.StatusOK, remove the println statement entirely, and refactor to use the
shared error path for consistent error handling across the handler (likely a
common error response function) rather than duplicating the response structure
inline.
In `@internal/cli/admin_parser.go`:
- Around line 1316-1332: The SET LICENSE CONFIG command parsing block leaves the
parser in an inconsistent state by not consuming the optional trailing
semicolon, while the non-CONFIG license branch does consume it. After the second
p.nextToken() call that follows the parseNumber call for number2, add a
conditional check to test if p.curToken.Type equals TokenSemicolon, and if true,
call p.nextToken() one more time to consume the semicolon before setting the
command parameters and returning.
🪄 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: e0885fd7-aa3c-46a6-8227-c9c80cb5901a
📒 Files selected for processing (9)
internal/admin/enterprise_handler.gointernal/admin/enterprise_service.gointernal/admin/router.gointernal/cli/admin_command.gointernal/cli/admin_parser.gointernal/cli/cli_http.gointernal/cli/lexer.gointernal/cli/parser.gointernal/cli/types.go
🚧 Files skipped from review as they are similar to previous changes (2)
- internal/admin/router.go
- internal/admin/enterprise_service.go
| if err := c.ShouldBindJSON(&req); err != nil { | ||
| println("JSON bind error: %v (type: %T)", err, err) | ||
| c.JSON(http.StatusOK, gin.H{ | ||
| "code": common.CodeBadRequest, | ||
| "message": err.Error(), | ||
| }) |
There was a problem hiding this comment.
Return HTTP 400 for JSON binding failures.
These validation failures currently return HTTP 200, so clients can treat malformed license requests as successful. Use the shared error path and drop the non-formatting println calls.
🐛 Proposed fix
if err := c.ShouldBindJSON(&req); err != nil {
- println("JSON bind error: %v (type: %T)", err, err)
- c.JSON(http.StatusOK, gin.H{
- "code": common.CodeBadRequest,
- "message": err.Error(),
- })
+ errorResponse(c, err.Error(), http.StatusBadRequest)
return
} if err := c.ShouldBindJSON(&req); err != nil {
- println("JSON bind error: %v (type: %T)", err, err)
- c.JSON(http.StatusOK, gin.H{
- "code": common.CodeBadRequest,
- "message": err.Error(),
- })
+ errorResponse(c, err.Error(), http.StatusBadRequest)
return
}Also applies to: 280-285
🤖 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 236 - 241, The JSON
binding error handler in the ShouldBindJSON block is returning HTTP 200
(http.StatusOK) instead of the correct HTTP 400 status code for validation
failures, and contains an improperly formatted println statement. Change the
c.JSON call to use http.StatusBadRequest instead of http.StatusOK, remove the
println statement entirely, and refactor to use the shared error path for
consistent error handling across the handler (likely a common error response
function) rather than duplicating the response structure inline.
| if p.curToken.Type == TokenConfig { | ||
| p.nextToken() // consume CONFIG | ||
| // SET LICENSE CONFIG <number1> <number2> | ||
| cmd := NewCommand("admin_set_license_config_command") | ||
| number1, err := p.parseNumber() | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| p.nextToken() | ||
| number2, err := p.parseNumber() | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| p.nextToken() | ||
| cmd.Params["number1"] = number1 | ||
| cmd.Params["number2"] = number2 | ||
| return cmd, nil |
There was a problem hiding this comment.
Consume the optional semicolon in SET LICENSE CONFIG.
After Line 1329, SET LICENSE CONFIG 1 2; leaves p.curToken on TokenSemicolon, while the non-CONFIG license branch consumes it. Keep parser state consistent before returning.
Suggested fix
cmd.Params["number1"] = number1
cmd.Params["number2"] = number2
+
+ // Semicolon is optional
+ if p.curToken.Type == TokenSemicolon {
+ p.nextToken()
+ }
return cmd, 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/cli/admin_parser.go` around lines 1316 - 1332, The SET LICENSE
CONFIG command parsing block leaves the parser in an inconsistent state by not
consuming the optional trailing semicolon, while the non-CONFIG license branch
does consume it. After the second p.nextToken() call that follows the
parseNumber call for number2, add a conditional check to test if p.curToken.Type
equals TokenSemicolon, and if true, call p.nextToken() one more time to consume
the semicolon before setting the command parameters and returning.
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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/cli/admin_command.go`:
- Around line 1980-1981: The apiURL construction in the admin command is using
an incorrect endpoint path that ends with `/admin` instead of `/storage`. Locate
the apiURL variable assignment where it constructs the endpoint with fmt.Sprintf
and the encodedUserName parameter, and change the path suffix from `/admin` to
`/storage` to match the router definition for the ShowUserStorage endpoint,
ensuring the correct URL `/admin/users/{username}/storage` is used.
🪄 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: cc09d8bd-a941-4e7e-9ce3-6a19b3a758a9
📒 Files selected for processing (6)
internal/admin/enterprise_handler.gointernal/admin/enterprise_service.gointernal/admin/handler.gointernal/admin/router.gointernal/cli/admin_command.gointernal/common/format.go
💤 Files with no reviewable changes (1)
- internal/admin/enterprise_service.go
🚧 Files skipped from review as they are similar to previous changes (1)
- internal/admin/router.go
| encodedUserName := common.EncodeEmail(email) | ||
| apiURL := fmt.Sprintf("/admin/users/%s/admin", encodedUserName) |
There was a problem hiding this comment.
Incorrect endpoint path: /admin should be /storage.
The URL path uses /admin/users/%s/admin but this command shows user storage. The router defines GET /users/:username/storage for ShowUserStorage. This will result in 404 errors or unexpected behavior.
🐛 Proposed fix
encodedUserName := common.EncodeEmail(email)
- apiURL := fmt.Sprintf("/admin/users/%s/admin", encodedUserName)
+ apiURL := fmt.Sprintf("/admin/users/%s/storage", encodedUserName)📝 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.
| encodedUserName := common.EncodeEmail(email) | |
| apiURL := fmt.Sprintf("/admin/users/%s/admin", encodedUserName) | |
| encodedUserName := common.EncodeEmail(email) | |
| apiURL := fmt.Sprintf("/admin/users/%s/storage", encodedUserName) |
🤖 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/cli/admin_command.go` around lines 1980 - 1981, The apiURL
construction in the admin command is using an incorrect endpoint path that ends
with `/admin` instead of `/storage`. Locate the apiURL variable assignment where
it constructs the endpoint with fmt.Sprintf and the encodedUserName parameter,
and change the path suffix from `/admin` to `/storage` to match the router
definition for the ShowUserStorage endpoint, ensuring the correct URL
`/admin/users/{username}/storage` is used.
What problem does this PR solve?
Type of change