Skip to content

Go CLI: refactor some commands - #16204

Merged
JinHai-CN merged 7 commits into
infiniflow:mainfrom
JinHai-CN:fix473
Jun 19, 2026
Merged

JinHai-CN merged 7 commits into
infiniflow:mainfrom
JinHai-CN:fix473

Conversation

@JinHai-CN

Copy link
Copy Markdown
Member

What problem does this PR solve?

  • list resources

Type of change

  • New Feature (non-breaking change which adds functionality)
  • Refactoring

Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
@coderabbitai

coderabbitai Bot commented Jun 19, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Introduces 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 Admin*Command naming conventions and email-encoded URL parameter handling for all user-scoped admin operations.

Changes

Admin API and CLI refactor

Layer / File(s) Summary
Email encoding utility foundation
internal/common/format.go
Adds base64-based EncodeEmail(email string) string and DecodeEmail(encoded string) (string, error) helpers to safely encode/decode email addresses for use in URL path parameters throughout the admin API and CLI.
Enterprise service: structured payloads and new methods
internal/admin/enterprise_service.go
Replaces role management (ListRoles, CreateRole, GetRole, UpdateRole, DeleteRole, all permission methods) and system TODOs with structured map[string]interface{} payloads containing command and enterprise-edition error messages. Changes DeleteRole signature from (error) to (map[string]interface{}, error). Adds ListResources() method. Implements three API key methods: CreateUserAPIKey, DeleteUserAPIKey, ListUserAPIKeys that fetch users via userDAO.GetByEmail, wrap user-not-found errors, and return structured payloads with command, user email/nickname, and method-specific data.
Handler parameter decoding and user-scoped endpoints
internal/admin/handler.go, internal/admin/enterprise_handler.go
Extended nine existing handlers (GetUser, DeleteUser, ChangePassword, UpdateUserActivateStatus, GrantAdmin, RevokeAdmin, ListUserAPITokens, GenerateUserAPIToken, DeleteUserAPIToken) and fourteen user-scoped handlers (ShowUserDatasetSummary, ShowUserSummary, ShowUserStorage, ShowUserQuota, ShowUserIndex, UpdateUserRole, ShowUserPermission, ListUserDatasets, ListUserAgents, ListUserChats, ListUserSearches, ListUserModels, ListUserFiles, PurgeUserData) to decode username path parameter via DecodeEmail with HTTP 400 on decode failure.
New HTTP endpoints: roles, resources, system, and API keys
internal/admin/enterprise_handler.go
Modified ListRoles to return raw roles array; updated DeleteRole to return HTTP 404 with role payload on service error. Added ListResources handler with error-to-404 mapping. Added system handlers: GetSystemFingerprint, SetSystemLicense, ShowSystemLicense, UpdateSystemLicenseConfig. Added user API key handlers: CreateUserAPIKey, DeleteUserAPIKey, ListUserAPIKeys with parameter validation, service error responses, and success payloads.
Router: protected route consolidation and endpoint wiring
internal/admin/router.go
Consolidated protected admin route blocks for services, variables, configs, environments, version, log level, provider/queue/ingestor subroutes. Registered GET /roles/resource for ListResources. Rewired /users/:username/keys from token handlers to API key handlers (POST→CreateUserAPIKey, GET→ListUserAPIKeys, DELETE→DeleteUserAPIKey with :key param). Kept /users/:username/tokens on token handlers. Repositioned fingerprint, license, and ingestion endpoints.
CLI token types, lexer, and parser dispatcher
internal/cli/types.go, internal/cli/lexer.go, internal/cli/parser.go
Added TokenFingerprint and TokenLicense token type constants. Extended lexer to recognize FINGERPRINT and LICENSE keywords. Added TokenCheck case in parser's admin command dispatcher routing to parseAdminCheckCommand().
CLI parser: LIST, CREATE, DROP, and LIST USER KEYS
internal/cli/admin_parser.go, internal/cli/user_parser.go
Implemented parseAdminListRoles and parseAdminListResources helpers. Introduced parseAdminCreateUserCommand with password/KEY branching and parseAdminCreateRoleCommand with optional DESCRIPTION. Added parseAdminDropUserCommand and parseAdminDropUserAPIKeyCommand variants. Extended parseAdminListUserCommand for KEYS syntax. Rerouted user parser CREATE USER to admin create parsing and removed old parseCreateUser() method.
CLI parser: SHOW, CHECK, SET license and fingerprint commands
internal/cli/admin_parser.go
Extended parseAdminShowCommand to recognize FINGERPRINT and LICENSE targets. Implemented parseAdminCheckCommand for CHECK LICENSE parsing. Introduced parseAdminSetLicense supporting SET LICENSE <quoted> and SET LICENSE CONFIG <number> <number> forms. Updated parseAdminShowVersionCommand to emit admin-specific command type. Implemented parseAdminShowFingerprintCommand and parseAdminShowLicenseCommand.
CLI commands: core admin command handlers
internal/cli/admin_command.go
Added common import for email encoding. Renamed ShowAdminVersion → AdminShowVersionCommand, ListRoles → AdminListRolesCommand, CreateRole → AdminCreateRoleCommand, CreateUser → AdminCreateUserCommand, DropUser → AdminDropUserCommand. Added AdminListResourcesCommand. Updated AdminCreateRoleCommand validation (require role_name, optional description) and response unmarshalling from SimpleResponse to CommonDataResponse. Removed DropAdminToken handler.
CLI commands: user/role operations and API key management
internal/cli/admin_command.go
Updated GrantAdmin/RevokeAdmin to encode user_name via common.EncodeEmail. Added AdminCreateUserAPIKeyCommand (POST /admin/users/{encoded_user}/keys), AdminDropUserAPIKeyCommand (DELETE /admin/users/{encoded_user}/keys/{api_key}). Updated user activation, password change, and drop operations to use email encoding. Updated ListUserDatasets, ListAgents, AlterUserRole, ShowUserPermission, GenerateAdminToken, ListAdminTokens to encode usernames in URLs.
CLI commands: system license and fingerprint operations
internal/cli/admin_command.go
Added AdminSetLicenseCommand (POST /admin/system/license) and AdminSetLicenseConfigCommand (PUT /admin/system/license/config). Added AdminCheckLicenseCommand (GET /admin/system/license?check=true), AdminShowFingerprintCommand (GET /admin/system/fingerprint), AdminShowLicenseCommand (GET /admin/system/license). All use CommonDataResponse unmarshalling with result validation and duration tracking.
CLI commands: user information endpoints with email encoding
internal/cli/admin_command.go
Updated all admin user "show" endpoints (ShowUser*) to encode user_name via common.EncodeEmail when constructing /admin/users/{...}/... URLs. Updated AdminPurgeUserCommand with email encoding. Updated user dataset/agent/chat/search/model/file listing commands with email encoding. Added AdminListUserKeysCommand (GET /admin/users/{encoded_user}/keys).
CLI dispatcher: ExecuteAdminCommand routing
internal/cli/cli_http.go
Extended ExecuteAdminCommand switch dispatcher to route all new admin command types (admin_list_resources_command, admin_list_roles_command, admin_create_user_command, admin_create_user_api_key_command, admin_create_role_command, admin_drop_user_command, admin_drop_user_api_key_command, admin_set_license_command, admin_set_license_config_command, admin_check_license_command, admin_show_fingerprint_command, admin_show_license_command, admin_show_version_command, admin_list_user_keys_command) to corresponding handlers. Removes prior non-admin command cases.
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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

  • infiniflow/ragflow#16201: Updates username parameter decoding in per-user dataset/agent/chat/search/model/file listing handlers, overlapping with this PR's comprehensive email decoding infrastructure for user-scoped admin endpoints.

Poem

🐇 Resources listed, keys created with care,
Email encoded in paths everywhere!
Handlers refactored, the CLI commands gleam,
Admin ops standardized—a well-oiled team.
From service to dispatcher, each layer aligned,
The refactor is done, and the paths are defined! ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 3

❌ Failed checks (2 warnings, 1 inconclusive)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is largely incomplete, providing minimal context. It states 'list resources' as the problem but omits details about API key management, email encoding, license handling, and other significant features introduced in the PR. Expand the description to cover all major changes: resource listing, user API key management, system license/fingerprint endpoints, email encoding for route parameters, role response payload restructuring, and CLI command renaming. Add context explaining why these changes were made.
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title is vague and generic, using non-descriptive phrasing ('refactor some commands') that doesn't convey meaningful information about the substantial changeset. Consider a more specific title that captures the main changes, such as 'Add resource listing and API key management endpoints with email encoding' or 'Refactor admin CLI commands and add enterprise resource/license handlers'.
✅ Passed checks (2 passed)
Check name Status Explanation
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.

✏️ 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.

❤️ Share

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

@JinHai-CN JinHai-CN added the ci Continue Integration label Jun 19, 2026
@JinHai-CN
JinHai-CN marked this pull request as ready for review June 19, 2026 08:42
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. ☯️ refactor Pull request that refactor/refine code 💞 feature Feature request, pull request that fullfill a new feature. labels Jun 19, 2026

@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: 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

📥 Commits

Reviewing files that changed from the base of the PR and between 11499f7 and fc29987.

📒 Files selected for processing (6)
  • internal/admin/enterprise_handler.go
  • internal/admin/enterprise_service.go
  • internal/admin/router.go
  • internal/cli/admin_command.go
  • internal/cli/admin_parser.go
  • internal/cli/cli_http.go

"roles": roles,
"total": len(roles),
}, "")
success(c, roles, "")

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.

⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

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.

Comment on lines +119 to 123
role, err := h.service.DeleteRole(roleName)
if err != nil {
errorResponse(c, "Role not found", 404)
return
}

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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.

Comment thread internal/admin/enterprise_service.go Resolved
Comment thread internal/admin/router.go Resolved
Signed-off-by: Jin Hai <[email protected]>
@coderabbitai

coderabbitai Bot commented Jun 19, 2026

Copy link
Copy Markdown
Contributor

Caution

Failed to replace (edit) comment. This is likely due to insufficient permissions or the comment being deleted.

Error details
{}

@codecov

codecov Bot commented Jun 19, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (b409cfc) to head (6fffbfc).
⚠️ Report is 2 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Signed-off-by: Jin Hai <[email protected]>

@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: 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 | 🔴 Critical

API mode CREATE USER fails due to incorrect command type routing.

parseCreateCommand (used in non-admin/API parsing context) routes TokenUser to parseAdminCreateUserCommand(), which produces admin_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 issues CREATE 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 | 🔴 Critical

Inconsistent role name parsing in parseAdminCreateRoleCommand.

parseAdminCreateRoleCommand uses parseQuotedString() for role names (line 700), while parseAdminShowRoleCommand, parseAdminDropRole, and parseAdminAlterRole all use parseIdentifier(). The user parser's role operations (parseCreateRole, parseDropRole, parseAlterRole) also use parseIdentifier(). This inconsistency within the admin parser and divergence from the user parser pattern suggests parseAdminCreateRoleCommand is 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 value

Copy-paste comment is misleading.

The comments on lines 675 and 687 say "Semicolon is optional for UNSET TOKEN" but these are CREATE USER commands, not UNSET TOKEN commands. 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 value

Grammatically 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

📥 Commits

Reviewing files that changed from the base of the PR and between fc29987 and ede12da.

📒 Files selected for processing (7)
  • internal/admin/enterprise_handler.go
  • internal/admin/enterprise_service.go
  • internal/admin/router.go
  • internal/cli/admin_command.go
  • internal/cli/admin_parser.go
  • internal/cli/cli_http.go
  • internal/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

Comment thread internal/cli/admin_command.go Resolved
@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jun 19, 2026

@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: 5

♻️ Duplicate comments (1)
internal/cli/admin_command.go (1)

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

Path-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 apiKey can 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

📥 Commits

Reviewing files that changed from the base of the PR and between ede12da and 673c877.

📒 Files selected for processing (6)
  • internal/admin/enterprise_handler.go
  • internal/admin/enterprise_service.go
  • internal/admin/router.go
  • internal/cli/admin_command.go
  • internal/cli/admin_parser.go
  • internal/cli/cli_http.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/admin/router.go

Comment on lines +1005 to +1008
result, err := h.service.DeleteUserAPIKey(username, key)
if err != nil {
errorResponse(c, err.Error(), 500)
return

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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

Comment on lines +711 to +714
user, err := s.userDAO.GetByEmail(username)
if err != nil {
return nil, fmt.Errorf("user not found: %w", err)
}

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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.

Comment thread internal/cli/admin_command.go Resolved
Comment on lines +858 to 863
switch p.curToken.Type {
case TokenKey:
return p.parseAdminDropUserAPIKeyCommand(userName)
default:
p.nextToken()
}

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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.

Comment thread internal/cli/cli_http.go
Comment on lines +64 to +67
case "admin_drop_user_command":
return c.AdminDropUserCommand(cmd)
case "admin_drop_user_api_key_command":
return c.AdminDropUserAPIKeyCommand(cmd)

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.

⚠️ Potential issue | 🟠 Major

🧩 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 -C2

Repository: 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 -C5

Repository: 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.go

Repository: 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.go

Repository: 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 -B2

Repository: 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/ -A10

Repository: 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]>
@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels Jun 19, 2026

@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 `@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

📥 Commits

Reviewing files that changed from the base of the PR and between 673c877 and d7af773.

📒 Files selected for processing (9)
  • internal/admin/enterprise_handler.go
  • internal/admin/enterprise_service.go
  • internal/admin/router.go
  • internal/cli/admin_command.go
  • internal/cli/admin_parser.go
  • internal/cli/cli_http.go
  • internal/cli/lexer.go
  • internal/cli/parser.go
  • internal/cli/types.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/admin/router.go
  • internal/admin/enterprise_service.go

Comment on lines +236 to +241
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(),
})

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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.

Comment on lines +1316 to +1332
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

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

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]>

@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: 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

📥 Commits

Reviewing files that changed from the base of the PR and between d7af773 and 6fffbfc.

📒 Files selected for processing (6)
  • internal/admin/enterprise_handler.go
  • internal/admin/enterprise_service.go
  • internal/admin/handler.go
  • internal/admin/router.go
  • internal/cli/admin_command.go
  • internal/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

Comment on lines +1980 to +1981
encodedUserName := common.EncodeEmail(email)
apiURL := fmt.Sprintf("/admin/users/%s/admin", encodedUserName)

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.

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

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.

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

@JinHai-CN
JinHai-CN merged commit 1b712be into infiniflow:main Jun 19, 2026
3 checks passed
This was referenced Jun 22, 2026
@coderabbitai coderabbitai Bot mentioned this pull request Jul 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. ☯️ refactor Pull request that refactor/refine code size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant