Skip to content

Go CLI: refactor - #16355

Merged
JinHai-CN merged 9 commits into
infiniflow:mainfrom
JinHai-CN:fix494
Jun 25, 2026
Merged

JinHai-CN merged 9 commits into
infiniflow:mainfrom
JinHai-CN:fix494

Conversation

@JinHai-CN

@JinHai-CN JinHai-CN commented Jun 25, 2026 •

Copy link
Copy Markdown
Member

What problem does this PR solve?

# ADMIN MODE
RAGFlow(admin)> show log level;
+-------+-------+
| field | value |
+-------+-------+
| level | info  |
+-------+-------+
RAGFlow(admin)> set log level debug;
SUCCESS
RAGFlow(admin)> show log level;
+-------+-------+
| field | value |
+-------+-------+
| level | debug |
+-------+-------+

# API MODE
RAGFlow(api/default)> reset key;
SUCCESS

RAGFlow(api/default)> list vars;
+-----------+----------------------------------+--------------+-----------------------------------------------------------------------------------------+
| data_type | name                             | setting_type | value                                                                                   |
+-----------+----------------------------------+--------------+-----------------------------------------------------------------------------------------+
| string    | default_role                     | config       |                                                                                         |
| bool      | enable_whitelist                 | config       | true                                                                                    |
| string    | feishu|sso.app_access_token_url  | config       | https://open.feishu.cn/open-apis/auth/v3/app_access_token/internal                      |
| string    | feishu|sso.app_id                | config       |                                                                                         |
| string    | feishu|sso.app_secret            | config       |                                                                                         |
| bool      | feishu|sso.enabled               | config       | false                                                                                   |
| string    | feishu|sso.user_access_token_url | config       | https://open.feishu.cn/open-apis/authen/v1/oidc/access_token                            |
| string    | github|sso.client_id             | config       |                                                                                         |
| bool      | github|sso.enabled               | config       | false                                                                                   |
| string    | github|sso.secret_key            | config       |                                                                                         |
| string    | google|sso.client_id             | config       |                                                                                         |
| string    | google|sso.client_secret         | config       |                                                                                         |
| bool      | google|sso.enabled               | config       | false                                                                                   |
| string    | google|sso.redirect_uri          | config       |                                                                                         |
| string    | ldap|default.attribute_list      | config       | cn,mail,uid,givenName,sn,jpegPhoto,sAMAccountName,userPrincipalName                     |
| string    | ldap|default.dn                  | config       |                                                                                         |
| bool      | ldap|default.enabled             | config       | false                                                                                   |
| string    | ldap|default.name                | config       |                                                                                         |
| string    | ldap|default.password            | config       |                                                                                         |
| string    | ldap|default.search_filter       | config       | (|(userPrincipalName={username})(mail={username}))                                      |
| string    | ldap|default.url                 | config       |                                                                                         |
| string    | mail.default_sender              | config       |                                                                                         |
| string    | mail.frontend_url                | config       |                                                                                         |
| string    | mail.password                    | config       |                                                                                         |
| integer   | mail.port                        | config       | 10                                                                                      |
| string    | mail.server                      | config       |                                                                                         |
| integer   | mail.timeout                     | config       | 10                                                                                      |
| bool      | mail.use_ssl                     | config       | false                                                                                   |
| bool      | mail.use_tls                     | config       | false                                                                                   |
| string    | mail.username                    | config       | test_user                                                                               |
| json      | sandbox.aliyun_codeinterpreter   | config       | {}                                                                                      |
| json      | sandbox.e2b                      | config       | {}                                                                                      |
| string    | sandbox.provider_type            | config       | self_managed                                                                            |
| json      | sandbox.self_managed             | config       | {"endpoint": "http://localhost:9385", "timeout": 30, "max_retries": 3, "pool_size": 10} |
+-----------+----------------------------------+--------------+-----------------------------------------------------------------------------------------+
RAGFlow(api/default)> list envs;
+-------------------------+------------------+
| env                     | value            |
+-------------------------+------------------+
| DOC_ENGINE              | elasticsearch    |
| DEFAULT_SUPERUSER_EMAIL | [email protected] |
| DB_TYPE                 | mysql            |
| DEVICE                  | cpu              |
| STORAGE_IMPL            | MINIO            |
+-------------------------+------------------+

RAGFlow(api/default)> show log level;
+-------+-------+
| field | value |
+-------+-------+
| level | info  |
+-------+-------+
RAGFlow(api/default)> set log level debug;
SUCCESS
RAGFlow(api/default)> show log level;
+-------+-------+
| field | value |
+-------+-------+
| level | debug |

Signed-off-by: Jin Hai <[email protected]>
@JinHai-CN JinHai-CN added the ci Continue Integration label Jun 25, 2026
@JinHai-CN
JinHai-CN marked this pull request as ready for review June 25, 2026 08:20
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jun 25, 2026
@JinHai-CN
JinHai-CN marked this pull request as draft June 25, 2026 08:20
@JinHai-CN
JinHai-CN marked this pull request as ready for review June 25, 2026 08:20
@coderabbitai

coderabbitai Bot commented Jun 25, 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

API-specific CLI commands now cover reset, show-log, list, and variable operations. System handlers, services, and routes add variable management and environment listing endpoints, with shared system-setting helpers used across admin and service code.

Changes

CLI command parsing and routing

Layer / File(s) Summary
API parser updates
internal/cli/admin_parser.go, internal/cli/parser.go, internal/cli/user_parser.go
API list, show, set, and reset parsing now includes environments, variables, and log-level commands, API reset is split into default-model and API-key paths, and parser comments were standardized across many helpers.
API command routing
internal/cli/admin_command.go, internal/cli/cli_http.go, internal/cli/user_command.go
ExecuteAdminCommand and ExecuteUserCommand now use API-specific command labels for license, variable, reset, current, show-log, environment, and list operations, and the CLI command methods include the new API variable and environment handlers.

System settings API

Layer / File(s) Summary
System service and shared helpers
internal/admin/service.go, internal/service/system.go, internal/common/system.go, internal/common/status_message.go, internal/admin/service_variables_test.go
System-setting formatting, validation, and type inference now use shared helpers; SystemService now includes variable, config, and environment methods backed by a settings DAO.
System handlers and routes
internal/handler/system.go, internal/router/router.go
System endpoints now include list and update handlers for variables and a list handler for environments, and the router registers the new protected /api/v1/system routes.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested labels

☯️ refactor

Poem

A rabbit tapped the console keys,
For logs and vars and windy seas.
The routes grew fresh, the parsers hummed,
New system paths were neatly plumbed.
🐇✨

🚥 Pre-merge checks | ✅ 2 | ❌ 3

❌ Failed checks (2 warnings, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The PR includes examples of the behavior change, but it omits the required Type of change section and lacks a brief plain-English problem summary. Add the Type of change checklist and a short background summary explaining what problem the CLI and system-setting changes solve.
Title check ❓ Inconclusive The title is generic and doesn’t clearly describe the main CLI behavior changes. Use a specific one-line title that names the main change, such as adding/refactoring CLI commands for variables, envs, and log level.
✅ 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.

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

Caution

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

⚠️ Outside diff range comments (1)
internal/cli/user_parser.go (1)

2072-2121: 🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

Emit the API reset command type from the reset parser.

parseAPIResetCommands now routes API user resets here, but parseAPIResetDefaultModel still creates reset_default_model while ExecuteUserCommand only handles api_reset_default_model. RESET DEFAULT ... MODEL will fall through as an unknown API command.

🐛 Proposed fix
-	cmd := NewCommand("reset_default_model")
+	cmd := NewCommand("api_reset_default_model")
🤖 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 2072 - 2121, The reset parser is
emitting a command name that does not match what execution handles, so API reset
default model commands are treated as unknown. Update parseAPIResetDefaultModel
(and any related reset command construction in parseAPIResetCommands) to create
the same command type that ExecuteUserCommand expects, namely
api_reset_default_model. Keep the existing token parsing for DEFAULT, model
type, and MODEL unchanged, and ensure the returned Command.Params["model_type"]
still carries the parsed type.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@internal/cli/user_parser.go`:
- Around line 2072-2121: The reset parser is emitting a command name that does
not match what execution handles, so API reset default model commands are
treated as unknown. Update parseAPIResetDefaultModel (and any related reset
command construction in parseAPIResetCommands) to create the same command type
that ExecuteUserCommand expects, namely api_reset_default_model. Keep the
existing token parsing for DEFAULT, model type, and MODEL unchanged, and ensure
the returned Command.Params["model_type"] still carries the parsed type.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 5f7de70d-1b3e-4071-b324-fb8745492887

📥 Commits

Reviewing files that changed from the base of the PR and between edfa9be and 4232b3e.

📒 Files selected for processing (4)
  • internal/cli/admin_parser.go
  • internal/cli/cli_http.go
  • internal/cli/parser.go
  • internal/cli/user_parser.go

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.

Caution

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

⚠️ Outside diff range comments (1)
internal/cli/user_parser.go (1)

3593-3624: 🎯 Functional Correctness | 🔴 Critical

UNSET KEY syntax is broken due to missing case in parseUserStatement

While RESET KEY is correctly routed via TokenReset in parser.go to api_unset_api_key, the legacy UNSET keyword falls through to the default error case. TokenUnset is missing from the user statement switch in internal/cli/user_parser.go, causing UNSET KEY to fail with "invalid user statement".

Add case TokenUnset: return p.parseAPIResetKey() to maintain backward compatibility with the legacy syntax.

🤖 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 3593 - 3624, The user statement
dispatcher in parseUserStatement is missing support for the legacy UNSET
keyword, so UNSET KEY falls into the default invalid user statement path. Add a
TokenUnset branch in Parser.parseUserStatement that routes to the same API key
reset handler used by RESET KEY, reusing parseAPIResetKey to preserve backward
compatibility while keeping the existing token-based dispatch structure intact.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@internal/cli/user_parser.go`:
- Around line 3593-3624: The user statement dispatcher in parseUserStatement is
missing support for the legacy UNSET keyword, so UNSET KEY falls into the
default invalid user statement path. Add a TokenUnset branch in
Parser.parseUserStatement that routes to the same API key reset handler used by
RESET KEY, reusing parseAPIResetKey to preserve backward compatibility while
keeping the existing token-based dispatch structure intact.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 0bea5f6f-e55a-4da6-a1d9-f5436dfa227d

📥 Commits

Reviewing files that changed from the base of the PR and between 4232b3e and 3fe600a.

📒 Files selected for processing (1)
  • internal/cli/user_parser.go

@codecov

codecov Bot commented Jun 25, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (1dfc240) to head (d39e9ec).
⚠️ Report is 12 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #16355   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  Misses         29       29           
  Partials       20       20           

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

@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 25, 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: 3

🧹 Nitpick comments (2)
internal/handler/system.go (1)

230-233: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use the shared response-code constants instead of magic numbers.

The sibling handler SetLogLevel (Line 201) uses common.CodeDataError, but these new handlers hardcode 500 and 400. Align with the existing common.Code* constants for consistency across the API surface.

Also applies to: 256-257, 280-281, 296-298

🤖 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/handler/system.go` around lines 230 - 233, The new handler responses
are hardcoding numeric codes instead of using the shared common.Code* constants,
which makes them inconsistent with SetLogLevel and the rest of the API. Update
the JSON payloads in the affected handler methods in system.go to use the
appropriate shared response-code constants from common (for example, the same
pattern used by SetLogLevel) rather than literal 500 or 400 values, and apply
the same change to all listed response sites.
internal/service/system.go (1)

395-423: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚖️ Poor tradeoff

SystemService.SetVariable duplicates admin.Service.SetVariable verbatim.

This method (and ListAllVariables/ListEnvironments below) are near-identical copies of the implementations in internal/admin/service.go. The only deltas are the error constructor (fmt.Errorf vs NewAdminException). Since both now delegate to the same common.* helpers, consider extracting the shared body into a common helper that takes the DAO + an error formatter, to avoid the two copies drifting over time.

🤖 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/service/system.go` around lines 395 - 423, SystemService.SetVariable
is a near-verbatim copy of admin.Service.SetVariable, so the logic can drift
between the two implementations. Extract the shared variable-update flow into a
common helper that takes the DAO and an error-construction callback, then have
both SystemService.SetVariable and admin.Service.SetVariable delegate to it
while preserving their different error types. Keep the common
validation/create/update path in one place and reuse the existing
common.ValidateSystemSettingValue and common.InferSystemSettingDataType calls.
🤖 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/user_command.go`:
- Around line 3415-3417: The JSON unmarshal error message in
APIListVariablesCommand is using the wrong operation name, which makes
troubleshooting confusing. Update the fmt.Errorf text in the variables command
path so it refers to listing variables rather than listing environments, keeping
the existing unmarshal failure context and err wrapping intact. Use the
APIListVariablesCommand and json.Unmarshal flow to locate the message.

In `@internal/handler/system.go`:
- Around line 252-276: In SystemHandler.SetVariable, the explicit empty-string
validation for req.VarName and req.VarValue is redundant because
binding:"required" already makes ShouldBindJSON reject missing/empty values;
remove those unreachable branches and keep validation in one place. Also update
the ShouldBindJSON error response so it reports a bind/validation failure
generically or with the correct field context, instead of always returning "Var
name is required".

In `@internal/service/system.go`:
- Around line 437-491: ListEnvironments is duplicating config defaults instead
of using the resolved values, which can drift from the real application
settings. Update SystemService.ListEnvironments to read from the central config
source or resolved config accessor for DOC_ENGINE, DEFAULT_SUPERUSER_EMAIL,
DB_TYPE, DEVICE, and STORAGE_IMPL rather than hardcoding fallbacks. Also review
the route exposure for ListEnvironments in the authorized group and, if
DEFAULT_SUPERUSER_EMAIL should not be visible to all authenticated users,
restrict that field or move the endpoint behind admin-only access.

---

Nitpick comments:
In `@internal/handler/system.go`:
- Around line 230-233: The new handler responses are hardcoding numeric codes
instead of using the shared common.Code* constants, which makes them
inconsistent with SetLogLevel and the rest of the API. Update the JSON payloads
in the affected handler methods in system.go to use the appropriate shared
response-code constants from common (for example, the same pattern used by
SetLogLevel) rather than literal 500 or 400 values, and apply the same change to
all listed response sites.

In `@internal/service/system.go`:
- Around line 395-423: SystemService.SetVariable is a near-verbatim copy of
admin.Service.SetVariable, so the logic can drift between the two
implementations. Extract the shared variable-update flow into a common helper
that takes the DAO and an error-construction callback, then have both
SystemService.SetVariable and admin.Service.SetVariable delegate to it while
preserving their different error types. Keep the common validation/create/update
path in one place and reuse the existing common.ValidateSystemSettingValue and
common.InferSystemSettingDataType calls.
🪄 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: 99792ad4-8140-4464-b4f1-13a21904f7b7

📥 Commits

Reviewing files that changed from the base of the PR and between 3fe600a and ffbb662.

📒 Files selected for processing (8)
  • internal/admin/service.go
  • internal/cli/cli_http.go
  • internal/cli/user_command.go
  • internal/cli/user_parser.go
  • internal/common/status_message.go
  • internal/handler/system.go
  • internal/router/router.go
  • internal/service/system.go
✅ Files skipped from review due to trivial changes (1)
  • internal/common/status_message.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/cli/user_parser.go

Comment on lines +3415 to +3417
if err = json.Unmarshal(resp.Body, &result); err != nil {
return nil, fmt.Errorf("list environments failed: invalid JSON (%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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Fix mismatched error text in variables command.

The unmarshal error message says “list environments failed” inside APIListVariablesCommand, which is misleading during troubleshooting.

Suggested patch
-	return nil, fmt.Errorf("list environments failed: invalid JSON (%w)", err)
+	return nil, fmt.Errorf("list variables failed: invalid JSON (%w)", err)
📝 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
if err = json.Unmarshal(resp.Body, &result); err != nil {
return nil, fmt.Errorf("list environments failed: invalid JSON (%w)", err)
}
if err = json.Unmarshal(resp.Body, &result); err != nil {
return nil, fmt.Errorf("list variables failed: invalid JSON (%w)", err)
}
🤖 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_command.go` around lines 3415 - 3417, The JSON unmarshal
error message in APIListVariablesCommand is using the wrong operation name,
which makes troubleshooting confusing. Update the fmt.Errorf text in the
variables command path so it refers to listing variables rather than listing
environments, keeping the existing unmarshal failure context and err wrapping
intact. Use the APIListVariablesCommand and json.Unmarshal flow to locate the
message.

Comment on lines +252 to +276
func (h *SystemHandler) SetVariable(c *gin.Context) {
var req SetVariableHTTPRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusOK, gin.H{
"code": 400,
"message": "Var name is required",
})
return
}

if req.VarName == "" {
c.JSON(http.StatusOK, gin.H{
"code": 400,
"message": "Var name is required",
})
return
}

if req.VarValue == "" {
c.JSON(http.StatusOK, gin.H{
"code": 400,
"message": "Var value is required",
})
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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

binding:"required" makes the explicit empty-string checks unreachable, and the bind-error message is misleading.

With binding:"required" on both fields, ShouldBindJSON already fails for empty/missing var_name or var_value, so the req.VarName == "" / req.VarValue == "" branches at Lines 262-276 can never trigger. Additionally, any bind failure (malformed JSON, or a missing var_value) returns "Var name is required", which is incorrect for those cases.

♻️ Suggested simplification
 	var req SetVariableHTTPRequest
 	if err := c.ShouldBindJSON(&req); err != nil {
 		c.JSON(http.StatusOK, gin.H{
 			"code":    400,
-			"message": "Var name is required",
+			"message": "var_name and var_value are required",
 		})
 		return
 	}
-
-	if req.VarName == "" {
-		c.JSON(http.StatusOK, gin.H{
-			"code":    400,
-			"message": "Var name is required",
-		})
-		return
-	}
-
-	if req.VarValue == "" {
-		c.JSON(http.StatusOK, gin.H{
-			"code":    400,
-			"message": "Var value is required",
-		})
-		return
-	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func (h *SystemHandler) SetVariable(c *gin.Context) {
var req SetVariableHTTPRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusOK, gin.H{
"code": 400,
"message": "Var name is required",
})
return
}
if req.VarName == "" {
c.JSON(http.StatusOK, gin.H{
"code": 400,
"message": "Var name is required",
})
return
}
if req.VarValue == "" {
c.JSON(http.StatusOK, gin.H{
"code": 400,
"message": "Var value is required",
})
return
}
func (h *SystemHandler) SetVariable(c *gin.Context) {
var req SetVariableHTTPRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusOK, gin.H{
"code": 400,
"message": "var_name and var_value are required",
})
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/handler/system.go` around lines 252 - 276, In
SystemHandler.SetVariable, the explicit empty-string validation for req.VarName
and req.VarValue is redundant because binding:"required" already makes
ShouldBindJSON reject missing/empty values; remove those unreachable branches
and keep validation in one place. Also update the ShouldBindJSON error response
so it reports a bind/validation failure generically or with the correct field
context, instead of always returning "Var name is required".

Comment on lines +437 to +491
func (s *SystemService) ListEnvironments() ([]map[string]interface{}, error) {
result := make([]map[string]interface{}, 0)

// DOC_ENGINE
docEngine := os.Getenv("DOC_ENGINE")
if docEngine == "" {
docEngine = "elasticsearch"
}
result = append(result, map[string]interface{}{
"env": "DOC_ENGINE",
"value": docEngine,
})

// DEFAULT_SUPERUSER_EMAIL
defaultSuperuserEmail := os.Getenv("DEFAULT_SUPERUSER_EMAIL")
if defaultSuperuserEmail == "" {
defaultSuperuserEmail = "[email protected]"
}
result = append(result, map[string]interface{}{
"env": "DEFAULT_SUPERUSER_EMAIL",
"value": defaultSuperuserEmail,
})

// DB_TYPE
dbType := os.Getenv("DB_TYPE")
if dbType == "" {
dbType = "mysql"
}
result = append(result, map[string]interface{}{
"env": "DB_TYPE",
"value": dbType,
})

// DEVICE
device := os.Getenv("DEVICE")
if device == "" {
device = "cpu"
}
result = append(result, map[string]interface{}{
"env": "DEVICE",
"value": device,
})

// STORAGE_IMPL
storageImpl := os.Getenv("STORAGE_IMPL")
if storageImpl == "" {
storageImpl = "MINIO"
}
result = append(result, map[string]interface{}{
"env": "STORAGE_IMPL",
"value": storageImpl,
})

return result, 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.

🔒 Security & Privacy | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Find where these env vars' real defaults are defined to compare against the literals here.
rg -nP '\b(DOC_ENGINE|DEFAULT_SUPERUSER_EMAIL|DB_TYPE|DEVICE|STORAGE_IMPL)\b' -g '!**/*_test.go' -C2

Repository: infiniflow/ragflow

Length of output: 156


🏁 Script executed:

#!/bin/bash
# Find the route registration for ListEnvironments to verify the authentication group
grep -rn "ListEnvironments" internal/server/ --include="*.go" | head -20

Repository: infiniflow/ragflow

Length of output: 156


🏁 Script executed:

#!/bin/bash
# Find route definitions in server routers
find internal/server -name "router.go" -o -name "*router*.go" | xargs grep -n "environments" -i 2>/dev/null | head -20

Repository: infiniflow/ragflow

Length of output: 156


🏁 Script executed:

#!/bin/bash
# Search for the API handler path registration using the function name as a hint
# Try to find where the handler is wired up, likely in a route definition file or method chaining
grep -rn "GET.*Environments" internal/ --include="*.go" 2>/dev/null || grep -rn "r\.GET.*Environment" internal/ --include="*.go" 2>/dev/null | head -10

Repository: infiniflow/ragflow

Length of output: 342


🏁 Script executed:

#!/bin/bash
# Find the route registration for ListEnvironments to verify the authentication group
grep -rn "ListEnvironments" internal/server/ --include="*.go" | head -20

Repository: infiniflow/ragflow

Length of output: 156


🏁 Script executed:

#!/bin/bash
# Check the router.go file around line 562 to verify the auth middleware used for the environments route
sed -n '550,575p' internal/router/router.go

Repository: infiniflow/ragflow

Length of output: 898


🏁 Script executed:

#!/bin/bash
# Check the router.go file context to determine which group 'system' belongs to (public, authorized, or admin)
sed -n '520,565p' internal/router/router.go

Repository: infiniflow/ragflow

Length of output: 2101


🏁 Script executed:

#!/bin/bash
# Determine which group 'v1' is and what middleware it has (public vs auth)
# Also check if there's specific logic guarding the environments endpoint elsewhere
sed -n '1,100p' internal/router/router.go | grep -A 5 -B 5 'v1.Group'
# Check the function definition where this routing happens to see if 'v1' is inside an auth check
grep -n "func.*HandleRoutes" internal/router/router.go | head -5

Repository: infiniflow/ragflow

Length of output: 156


🏁 Script executed:

#!/bin/bash
# Find where the routes are registered to see the middleware stack for the /system endpoint
grep -n 'SetupRouter\|Serve\|ListenAndServe' internal/router/router.go | head -5

Repository: infiniflow/ragflow

Length of output: 470


🏁 Script executed:

#!/bin/bash
# Scan the beginning of the file to find how 'v1' is constructed (middleware)
head -150 internal/router/router.go | grep -A 3 -B 3 'api_v1\|v1.Group'

Repository: infiniflow/ragflow

Length of output: 156


🏁 Script executed:

#!/bin/bash
# Read the full file structure to understand the Router setup
wc -l internal/router/router.go
sed -n '1,50p' internal/router/router.go

Repository: infiniflow/ragflow

Length of output: 2066


🏁 Script executed:

#!/bin/bash
# Search for where the 'v1' router group is instantiated with authentication middleware
grep -rn 'v1 :=\|api_v1 :=' internal/router/router.go | head -5
grep -rn "Use.*auth" internal/router/router.go | head -10

Repository: infiniflow/ragflow

Length of output: 248


Align default values with the config source and verify if superuser email disclosure is intended for all authenticated users.

ListEnvironments hardcodes fallback values (e.g., "mysql", "elasticsearch", "[email protected]") that currently match the application defaults, but this duplication creates a risk of drift. If the default logic changes in the config module, this endpoint will report outdated values. It should ideally read the resolved configuration directly.

Additionally, the endpoint is registered under the authorized group, meaning any authenticated user can view the DEFAULT_SUPERUSER_EMAIL. Given this sensitivity, please confirm if exposure to all authenticated users is intended or if it requires admin-only restriction.

Code Snippet
func (s *SystemService) ListEnvironments() ([]map[string]interface{}, error) {
	result := make([]map[string]interface{}, 0)

	// DOC_ENGINE
	docEngine := os.Getenv("DOC_ENGINE")
	if docEngine == "" {
		docEngine = "elasticsearch"
	}
	// ... similar logic for DB_TYPE, DEVICE, and STORAGE_IMPL
	// DEFAULT_SUPERUSER_EMAIL reporting immediately follows
}
🤖 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/service/system.go` around lines 437 - 491, ListEnvironments is
duplicating config defaults instead of using the resolved values, which can
drift from the real application settings. Update SystemService.ListEnvironments
to read from the central config source or resolved config accessor for
DOC_ENGINE, DEFAULT_SUPERUSER_EMAIL, DB_TYPE, DEVICE, and STORAGE_IMPL rather
than hardcoding fallbacks. Also review the route exposure for ListEnvironments
in the authorized group and, if DEFAULT_SUPERUSER_EMAIL should not be visible to
all authenticated users, restrict that field or move the endpoint behind
admin-only access.

Signed-off-by: Jin Hai <[email protected]>
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: 2

Caution

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

⚠️ Outside diff range comments (1)
internal/cli/user_parser.go (1)

2044-2081: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Align parsed log levels with the API contract.

/system/config/log documents DEBUG, INFO, WARNING, and ERROR; accepting fatal/panic and sending warn can create commands the API rejects.

Proposed fix
 	case TokenDebug:
-		cmd.Params["level"] = "debug"
+		cmd.Params["level"] = "DEBUG"
 	case TokenInfo:
-		cmd.Params["level"] = "info"
+		cmd.Params["level"] = "INFO"
 	case TokenWarn:
-		cmd.Params["level"] = "warn"
+		cmd.Params["level"] = "WARNING"
 	case TokenError:
-		cmd.Params["level"] = "error"
-	case TokenFatal:
-		cmd.Params["level"] = "fatal"
-	case TokenPanic:
-		cmd.Params["level"] = "panic"
+		cmd.Params["level"] = "ERROR"
🤖 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 2044 - 2081, The log-level parsing
in Parser.parseAPISetLogLevel is accepting values that do not match the
/system/config/log API contract. Update the
TokenDebug/TokenInfo/TokenWarn/TokenError handling to emit the documented levels
only, map the warning token to the API’s expected WARNING value instead of warn,
and remove the unsupported fatal/panic cases so the generated api_set_log_level
command stays contract-compliant.
🤖 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/user_command.go`:
- Around line 244-245: The log config update in user_command.go is using admin
auth for a login-protected endpoint, which can break normal API-mode sessions.
Update the request in the SetLogLevel flow to use web auth consistently with the
matching GET path, specifically in the code that calls httpClient.Request for
"/system/config/log". Keep the change localized to the existing client/request
logic so the endpoint is accessed with the same auth mode as the read path.
- Around line 250-259: The user registration response handling in
`RegisterUser`/`SimpleResponse` is forcing failures to look successful by
overwriting the response code with 0. Remove the unconditional `result.Code = 0`
assignment after `json.Unmarshal`, and preserve the application-level code
returned by the API so `resp.StatusCode == 200` responses can still surface an
error when the payload indicates failure.

---

Outside diff comments:
In `@internal/cli/user_parser.go`:
- Around line 2044-2081: The log-level parsing in Parser.parseAPISetLogLevel is
accepting values that do not match the /system/config/log API contract. Update
the TokenDebug/TokenInfo/TokenWarn/TokenError handling to emit the documented
levels only, map the warning token to the API’s expected WARNING value instead
of warn, and remove the unsupported fatal/panic cases so the generated
api_set_log_level command stays contract-compliant.
🪄 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: 89cd142e-8028-4cbe-8a76-c606077be2eb

📥 Commits

Reviewing files that changed from the base of the PR and between d0ef21b and d0a9f4d.

📒 Files selected for processing (4)
  • internal/admin/service_variables_test.go
  • internal/cli/cli_http.go
  • internal/cli/user_command.go
  • internal/cli/user_parser.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/cli/cli_http.go

Comment on lines +244 to +245
httpClient := c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer]
resp, err := httpClient.Request("PUT", "/system/config/log", "admin", nil, payload)

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Use web auth for the log config endpoint.

The matching GET path uses "web", and /system/config/log is login-protected; "admin" can make set log level fail for normal API-mode sessions.

Proposed fix
-	resp, err := httpClient.Request("PUT", "/system/config/log", "admin", nil, payload)
+	resp, err := httpClient.Request("PUT", "/system/config/log", "web", nil, payload)
📝 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
httpClient := c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer]
resp, err := httpClient.Request("PUT", "/system/config/log", "admin", nil, payload)
httpClient := c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer]
resp, err := httpClient.Request("PUT", "/system/config/log", "web", nil, payload)
🤖 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_command.go` around lines 244 - 245, The log config update
in user_command.go is using admin auth for a login-protected endpoint, which can
break normal API-mode sessions. Update the request in the SetLogLevel flow to
use web auth consistently with the matching GET path, specifically in the code
that calls httpClient.Request for "/system/config/log". Keep the change
localized to the existing client/request logic so the endpoint is accessed with
the same auth mode as the read path.

Comment on lines +250 to +259
if resp.StatusCode != 200 {
return nil, fmt.Errorf("failed to register user: HTTP %d, body: %s", resp.StatusCode, string(resp.Body))
}

return nil, fmt.Errorf("no log level")
var result SimpleResponse
if err = json.Unmarshal(resp.Body, &result); err != nil {
return nil, fmt.Errorf("change log level failed: invalid JSON (%w)", err)
}
result.Code = 0
result.Duration = resp.Duration

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Do not force log-level updates to success.

Line 258 overwrites any application-level error code with 0, so an HTTP 200 error response can be reported as success.

Proposed fix
 	if resp.StatusCode != 200 {
-		return nil, fmt.Errorf("failed to register user: HTTP %d, body: %s", resp.StatusCode, string(resp.Body))
+		return nil, fmt.Errorf("failed to change log level: HTTP %d, body: %s", resp.StatusCode, string(resp.Body))
 	}
 
 	var result SimpleResponse
 	if err = json.Unmarshal(resp.Body, &result); err != nil {
 		return nil, fmt.Errorf("change log level failed: invalid JSON (%w)", err)
 	}
-	result.Code = 0
+	if result.Code != 0 {
+		return nil, fmt.Errorf("%s", result.Message)
+	}
 	result.Duration = resp.Duration
📝 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
if resp.StatusCode != 200 {
return nil, fmt.Errorf("failed to register user: HTTP %d, body: %s", resp.StatusCode, string(resp.Body))
}
return nil, fmt.Errorf("no log level")
var result SimpleResponse
if err = json.Unmarshal(resp.Body, &result); err != nil {
return nil, fmt.Errorf("change log level failed: invalid JSON (%w)", err)
}
result.Code = 0
result.Duration = resp.Duration
if resp.StatusCode != 200 {
return nil, fmt.Errorf("failed to change log level: HTTP %d, body: %s", resp.StatusCode, string(resp.Body))
}
var result SimpleResponse
if err = json.Unmarshal(resp.Body, &result); err != nil {
return nil, fmt.Errorf("change log level failed: invalid JSON (%w)", err)
}
if result.Code != 0 {
return nil, fmt.Errorf("%s", result.Message)
}
result.Duration = resp.Duration
🤖 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_command.go` around lines 250 - 259, The user registration
response handling in `RegisterUser`/`SimpleResponse` is forcing failures to look
successful by overwriting the response code with 0. Remove the unconditional
`result.Code = 0` assignment after `json.Unmarshal`, and preserve the
application-level code returned by the API so `resp.StatusCode == 200` responses
can still surface an error when the payload indicates failure.

@JinHai-CN
JinHai-CN merged commit dbefadd into infiniflow:main Jun 25, 2026
5 of 6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant