Skip to content

Go CLI: fix key commands - #16306

Merged
JinHai-CN merged 4 commits into
infiniflow:mainfrom
JinHai-CN:fix489
Jun 24, 2026
Merged

JinHai-CN merged 4 commits into
infiniflow:mainfrom
JinHai-CN:fix489

Conversation

@JinHai-CN

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

Copy link
Copy Markdown
Member

What problem does this PR solve?

RAGFlow(api/default)> set key 'ragflow-JgnarFSCUiV99oOvvMDei7ZzZg1cVlqGd1AMHrHeKE4';
SUCCESS
RAGFlow(api/default)> unset key;
SUCCESS

RAGFlow(api/default)> list provider 'zhipu-ai' instances;

RAGFlow(api/default)> list providers;

RAGFlow(api/default)> list available providers;

RAGFlow(api/default)> list provider 'zhipu-ai' instance 'test' models;

Type of change

  • Bug Fix (non-breaking change which fixes an issue)

@coderabbitai

coderabbitai Bot commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Renames the CLI authentication credential from APIToken/api_token to APIKey/api_key across all layers: struct fields, YAML config, HTTP client auth headers, command parsers (SET KEY/UNSET KEY), command dispatch routing, and credential guards in every user-facing command. Also renames provider-listing parser functions to use API-prefixed names.

Changes

API Token → API Key Rename

Layer / File(s) Summary
Core credential struct fields and config types
internal/cli/http_client.go, internal/cli/cli.go
HTTPClient renames APIToken/useAPIToken to APIKey/useAPIKey; APIServerConfig and ConfigFile rename the YAML field from api_token to api_key.
HTTP client auth header and auto-detection
internal/cli/http_client.go
Headers, UploadMultipart, and httpClientAdapter.Request all switch from APIToken/useAPIToken to APIKey/useAPIKey when constructing Authorization: Bearer headers and selecting authKind.
CLI config loading, flag parsing, and initialization
internal/cli/cli.go
The -t/--token flag, rf.yml loading, NewCLIWithConfig HTTP client wiring, and Run password-prompt condition all switch to APIKey.
Parser: SET KEY / UNSET KEY / provider listing
internal/cli/user_parser.go, internal/cli/admin_parser.go, internal/cli/parser.go
Introduces parseAPISetCommands/parseAPISetAPIKey (SET KEY → api_set_api_key), changes parseUnsetCommand to UNSET KEY → api_unset_api_key, adds API-specific provider listing helpers (parseAPIListProviders, parseAPIListProviderCommands, parseAPIListAvailableProviders), and renames parseListAvailableProviders to parseAdminListAvailableProviders in the admin parser.
Command dispatch routing
internal/cli/cli_http.go
ExecuteUserCommand replaces set_token/unset_token with api_set_api_key/api_unset_api_key, and renames available-providers and provider-instance command strings to API-prefixed names.
APISetAPIKey / APIUnsetAPIKey / ShowToken implementation
internal/cli/user_command.go
Removes SetToken/UnsetToken; adds APISetAPIKey (validates key via GET /system/tokens, rolls back on failure) and APIUnsetAPIKey; ShowToken reads from APIKey.
Common command auth-label and save-config gating
internal/cli/common_command.go
ListAPIServer, SaveServerConfig, and GetAPIServerInfo switch ApiToken checks to APIKey, emitting "api key" auth labels.
Per-command APIKey credential gating
internal/cli/user_command.go
All user-mode commands (embed, rerank, TTS, ASR, OCR, parse, tasks, models, ingest, OpenaiChat, and listing commands) switch their credential guards from APIToken to APIKey.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • infiniflow/ragflow#16221: Modifies the same LIST AVAILABLE PROVIDERS dispatch path in admin_parser.go that this PR renames.
  • infiniflow/ragflow#16299: Overlaps directly with the API-key command/handler renames and dispatch changes in user_command.go, parser.go, and cli_http.go.
  • infiniflow/ragflow#16119: Updates admin_parser.go admin LIST command dispatch logic at the same parsing paths affected by this PR.

Poem

🐇 Hop, hop, the token's gone away,
A shiny new API key has come to stay!
APIToken retired, APIKey takes flight,
Bearer headers gleam with api-key light.
The parser now says SET KEY, not SET TOKEN —
All the auth guards hop along in unison! 🗝️

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
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.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and relevant to the main change: fixing Go CLI key-related commands.
Description check ✅ Passed The PR description follows the template and states the problem and change type, with useful command examples.
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.

@JinHai-CN JinHai-CN added the ci Continue Integration label Jun 24, 2026
@JinHai-CN
JinHai-CN marked this pull request as ready for review June 24, 2026 10:03
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Jun 24, 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: 6

Caution

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

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

83-97: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Preserve API-key auth for callers that still pass web.

Several API-key-gated commands still call Request(..., "web", ...). With LoginToken == nil, this branch emits no Authorization, so API-key-only sessions pass the guard but fail the request. Either update those callers to select "api"/"auto" or add a web-mode API-key fallback here.

🐛 Proposed central fallback
 	case "web", "admin":
 		if c.LoginToken != nil {
 			headers["Authorization"] = *c.LoginToken
+		} else if authKind == "web" && c.useAPIKey && c.APIKey != nil {
+			headers["Authorization"] = fmt.Sprintf("Bearer %s", *c.APIKey)
 		}
 	}
🤖 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/http_client.go` around lines 83 - 97, The Headers method in
HTTPClient drops Authorization for callers that still pass "web" when LoginToken
is nil, which breaks API-key-only sessions. Update the relevant Request callers
to use "api" or "auto" where appropriate, or add a fallback in
HTTPClient.Headers for the "web" branch to emit the API key when LoginToken is
absent. Keep the fix centered on HTTPClient.Headers and any Request call sites
that still pass "web".
internal/cli/cli.go (1)

40-49: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Keep accepting legacy api_token config keys.

This PR is marked non-breaking, but existing rf.yml files using top-level or per-server api_token are now silently ignored, leaving APIKey nil and API-key-only users unauthenticated.

🐛 Proposed compatibility fallback
 type APIServerConfig struct {
 	Name         string  `yaml:"name"`
 	Host         string  `yaml:"host"`
 	UserName     *string `yaml:"user_name"`
 	UserPassword *string `yaml:"password"`
 	APIKey       *string `yaml:"api_key"`
+	LegacyAPIToken *string `yaml:"api_token,omitempty"`
 	KeyFile      *string `yaml:"key_file"`
 	IP           string
 	Port         int
 }
 
 type ConfigFile struct {
 	Host         string                      `yaml:"host"`      // default API server host
 	APIKey       string                      `yaml:"api_key"`   // default API server api key
+	LegacyAPIToken string                   `yaml:"api_token,omitempty"`
 	UserName     string                      `yaml:"user_name"` // default API server user name
 	Password     string                      `yaml:"password"`  // default API server password
 	APIServerMap map[string]*APIServerConfig `yaml:"api_servers"`
 }
-			if config.APIKey != "" {
+			if config.APIKey == "" {
+				config.APIKey = config.LegacyAPIToken
+			}
+			if config.APIKey != "" {
 				if defaultApiServerConfig.APIKey == nil {
 					defaultApiServerConfig.APIKey = &config.APIKey
 				}
 			}
+			for _, serverConfig := range config.APIServerMap {
+				if serverConfig.APIKey == nil && serverConfig.LegacyAPIToken != nil {
+					serverConfig.APIKey = serverConfig.LegacyAPIToken
+					serverConfig.LegacyAPIToken = nil
+				}
+			}

Also applies to: 266-268

🤖 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.go` around lines 40 - 49, The config parsing in ConfigFile
and the server config fields is dropping legacy api_token values, which leaves
APIKey unset for older rf.yml files. Update the config handling in cli.go so
both top-level and per-server api_token are still accepted as a fallback,
mapping them into APIKey when api_key is absent. Check the ConfigFile struct and
the server/config types around the referenced fields to preserve backwards
compatibility without changing current api_key behavior.
internal/cli/user_command.go (1)

395-412: 🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Use api auth when an API key is the only credential.

These guards now allow API-key-only users, but the requests still pass authKind: "web". HTTPClient.Headers("web") only sends LoginToken, so SET KEY users hit these endpoints without an Authorization header.

Prefer centralizing this to avoid missing call sites:

func userAuthKind(httpClient *HTTPClient) (string, error) {
	if httpClient.useAPIKey && httpClient.APIKey != nil {
		return "api", nil
	}
	if httpClient.LoginToken != nil {
		return "web", nil
	}
	return "", fmt.Errorf("no authorization")
}

Then pass that authKind instead of hard-coded "web" in the affected requests.

Also applies to: 582-604, 1876-1877, 1940-1940, 1959-1960, 2029-2029, 2048-2049, 2157-2157, 2256-2257, 2328-2328, 2360-2361, 2436-2436, 2456-2457, 2538-2538, 2558-2559, 2582-2582, 2601-2602, 2630-2630, 2690-2691, 2721-2721, 3173-3174, 3198-3198, 3298-3299, 3315-3315, 3338-3339, 3363-3363, 3386-3387, 3402-3402, 3425-3426, 3442-3442

🤖 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 395 - 412, The affected requests
are still using hard-coded "web" auth even when an API key is the only
credential, so update the request auth selection in the relevant handlers to use
API auth when useAPIKey/APIKey is present. Add and use a shared helper like
userAuthKind on HTTPClient to return "api" for API-key-only callers and "web"
for LoginToken callers, then pass that returned authKind into HTTPClient.Request
instead of "web" at the affected call sites such as the documents listing flow
in user_command.go.
🤖 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/common_command.go`:
- Around line 1313-1315: The authentication check in the CLI command now
validates APIKey and LoginToken, but the returned message still refers only to
an “API token.” Update the user-facing error in the same conditional path in the
common command logic to use wording that matches the current auth fields and
login flow, so the message is accurate and consistent with c.APIServerClientMap
and c.Config.APIClientConfig.CurrentAPIServer.
- Around line 1137-1140: Protect the server listing logic in the
APIServerClientMap loop from nil dereference by not accessing fields on
c.APIServerClientMap[serverName] unless the entry exists; in the code path that
builds each element for configured servers, check whether the map entry for
serverName is present before reading LoginToken or APIKey, and fall back
gracefully for non-current servers that have no client object.
- Around line 1366-1369: The auth field in GetAPIServerInfo is being read from
CurrentAPIServer instead of the requested serverName, which can produce
incorrect results for show api server on a different server. Update the auth
lookup in GetAPIServerInfo to use the APIServerClientMap entry for serverName
consistently when checking LoginToken and APIKey, so the reported auth reflects
the requested API server.

In `@internal/cli/user_command.go`:
- Around line 1020-1059: Update the validation error messages in the API key
flow inside the token-validation block of user_command.go to use API key
terminology instead of token terminology. In the code around the
Request("/system/tokens") validation and the JSON/status checks, rename the
returned errors from “failed to validate token” and “token validation failed” to
consistent API key wording, while keeping the same restore-on-failure behavior
for APIKey and useAPIKey.

In `@internal/cli/user_parser.go`:
- Around line 3694-3696: The UNSET KEY parser error message is stale and still
says TOKEN even though the check in user_parser.go’s UNSET KEY branch expects
TokenKey. Update the error text in the relevant parse path to mention
KEY/TokenKey consistently so failures from the UNSET handling are accurate and
easier to understand.
- Around line 390-398: The parseAPIListAvailableProviders branch validates
TokenProviders but returns without consuming it, so the parser state is left
behind and the optional semicolon/trailing input handling diverges from the
other LIST parsers. Update parseAPIListAvailableProviders in Parser to advance
past PROVIDERS before returning the NewCommand("api_list_available_providers"),
matching the token consumption pattern used by the other list parsing methods.

---

Outside diff comments:
In `@internal/cli/cli.go`:
- Around line 40-49: The config parsing in ConfigFile and the server config
fields is dropping legacy api_token values, which leaves APIKey unset for older
rf.yml files. Update the config handling in cli.go so both top-level and
per-server api_token are still accepted as a fallback, mapping them into APIKey
when api_key is absent. Check the ConfigFile struct and the server/config types
around the referenced fields to preserve backwards compatibility without
changing current api_key behavior.

In `@internal/cli/http_client.go`:
- Around line 83-97: The Headers method in HTTPClient drops Authorization for
callers that still pass "web" when LoginToken is nil, which breaks API-key-only
sessions. Update the relevant Request callers to use "api" or "auto" where
appropriate, or add a fallback in HTTPClient.Headers for the "web" branch to
emit the API key when LoginToken is absent. Keep the fix centered on
HTTPClient.Headers and any Request call sites that still pass "web".

In `@internal/cli/user_command.go`:
- Around line 395-412: The affected requests are still using hard-coded "web"
auth even when an API key is the only credential, so update the request auth
selection in the relevant handlers to use API auth when useAPIKey/APIKey is
present. Add and use a shared helper like userAuthKind on HTTPClient to return
"api" for API-key-only callers and "web" for LoginToken callers, then pass that
returned authKind into HTTPClient.Request instead of "web" at the affected call
sites such as the documents listing flow in user_command.go.
🪄 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: 717932d2-84d0-4602-9f82-1b83044313f2

📥 Commits

Reviewing files that changed from the base of the PR and between 9a91564 and 81c5f47.

📒 Files selected for processing (8)
  • internal/cli/admin_parser.go
  • internal/cli/cli.go
  • internal/cli/cli_http.go
  • internal/cli/common_command.go
  • internal/cli/http_client.go
  • internal/cli/parser.go
  • internal/cli/user_command.go
  • internal/cli/user_parser.go

Comment on lines 1137 to +1140
if c.APIServerClientMap[serverName].LoginToken != nil {
element["auth"] = "login"
} else if apiServerConfig.ApiToken != nil {
element["auth"] = "api token"
} else if c.APIServerClientMap[serverName].APIKey != nil {
element["auth"] = "api key"

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.

🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win

Avoid nil dereference when listing non-current API servers.

APIServerClientMap is only initialized for the current API server, but this loop visits every configured server. For non-current entries, c.APIServerClientMap[serverName] can be nil and panic.

Proposed fix
-		if c.APIServerClientMap[serverName].LoginToken != nil {
+		httpClient := c.APIServerClientMap[serverName]
+		if httpClient != nil && httpClient.LoginToken != nil {
 			element["auth"] = "login"
-		} else if c.APIServerClientMap[serverName].APIKey != nil {
+		} else if (httpClient != nil && httpClient.APIKey != nil) || apiServerConfig.APIKey != nil {
 			element["auth"] = "api key"
 		} else {
 			element["auth"] = "no auth"
📝 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 c.APIServerClientMap[serverName].LoginToken != nil {
element["auth"] = "login"
} else if apiServerConfig.ApiToken != nil {
element["auth"] = "api token"
} else if c.APIServerClientMap[serverName].APIKey != nil {
element["auth"] = "api key"
httpClient := c.APIServerClientMap[serverName]
if httpClient != nil && httpClient.LoginToken != nil {
element["auth"] = "login"
} else if (httpClient != nil && httpClient.APIKey != nil) || apiServerConfig.APIKey != nil {
element["auth"] = "api key"
🤖 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/common_command.go` around lines 1137 - 1140, Protect the server
listing logic in the APIServerClientMap loop from nil dereference by not
accessing fields on c.APIServerClientMap[serverName] unless the entry exists; in
the code path that builds each element for configured servers, check whether the
map entry for serverName is present before reading LoginToken or APIKey, and
fall back gracefully for non-current servers that have no client object.

Comment on lines +1313 to 1315
if c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].APIKey == nil && c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].LoginToken == nil {
return nil, fmt.Errorf("API token not set. Please login first")
}

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

Update the stale “API token” error text.

The condition now checks APIKey, but the user-facing error still says “API token”.

Proposed fix
-			return nil, fmt.Errorf("API token not set. Please login first")
+			return nil, fmt.Errorf("API key not set. Please login first")
📝 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 c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].APIKey == nil && c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].LoginToken == nil {
return nil, fmt.Errorf("API token not set. Please login first")
}
if c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].APIKey == nil && c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].LoginToken == nil {
return nil, fmt.Errorf("API key not set. Please login first")
}
🤖 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/common_command.go` around lines 1313 - 1315, The authentication
check in the CLI command now validates APIKey and LoginToken, but the returned
message still refers only to an “API token.” Update the user-facing error in the
same conditional path in the common command logic to use wording that matches
the current auth fields and login flow, so the message is accurate and
consistent with c.APIServerClientMap and
c.Config.APIClientConfig.CurrentAPIServer.

Comment on lines 1366 to +1369
if c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].LoginToken != nil {
result.Data["auth"] = "login"
} else if apiServerConfig.ApiToken != nil {
result.Data["auth"] = "api token"
} else if c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].APIKey != nil {
result.Data["auth"] = "api key"

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

Report auth for the requested API server, not the current one.

GetAPIServerInfo(serverName) displays details for serverName, but these lines read auth from CurrentAPIServer, so show api server <other> can report the wrong auth state.

Proposed fix
-		if c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].LoginToken != nil {
+		httpClient := c.APIServerClientMap[serverName]
+		if httpClient != nil && httpClient.LoginToken != nil {
 			result.Data["auth"] = "login"
-		} else if c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].APIKey != nil {
+		} else if (httpClient != nil && httpClient.APIKey != nil) || apiServerConfig.APIKey != nil {
 			result.Data["auth"] = "api key"
 		} else {
 			result.Data["auth"] = "no auth"
📝 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 c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].LoginToken != nil {
result.Data["auth"] = "login"
} else if apiServerConfig.ApiToken != nil {
result.Data["auth"] = "api token"
} else if c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].APIKey != nil {
result.Data["auth"] = "api key"
httpClient := c.APIServerClientMap[serverName]
if httpClient != nil && httpClient.LoginToken != nil {
result.Data["auth"] = "login"
} else if (httpClient != nil && httpClient.APIKey != nil) || apiServerConfig.APIKey != nil {
result.Data["auth"] = "api key"
🤖 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/common_command.go` around lines 1366 - 1369, The auth field in
GetAPIServerInfo is being read from CurrentAPIServer instead of the requested
serverName, which can produce incorrect results for show api server on a
different server. Update the auth lookup in GetAPIServerInfo to use the
APIServerClientMap entry for serverName consistently when checking LoginToken
and APIKey, so the reported auth reflects the requested API server.

Comment on lines 1020 to 1059
// Save current token to restore if validation fails
savedToken := c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].APIToken
savedUseAPIToken := c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].useAPIToken
savedToken := c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].APIKey
savedUseAPIToken := c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].useAPIKey

// Set the new token temporarily for validation
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].APIToken = &token
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].useAPIToken = true
// Set the new key temporarily for validation
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].APIKey = &apiKey
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].useAPIKey = true

// Validate token by calling list tokens API
resp, err := c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].Request("GET", "/tokens", "api", nil, nil)
resp, err := c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].Request("GET", "/system/tokens", "api", nil, nil)
if err != nil {
// Restore original token on error
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].APIToken = savedToken
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].useAPIToken = savedUseAPIToken
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].APIKey = savedToken
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].useAPIKey = savedUseAPIToken
return nil, fmt.Errorf("failed to validate token: %w", err)
}

if resp.StatusCode != 200 {
// Restore original token on error
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].APIToken = savedToken
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].useAPIToken = savedUseAPIToken
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].APIKey = savedToken
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].useAPIKey = savedUseAPIToken
return nil, fmt.Errorf("token validation failed: HTTP %d, body: %s", resp.StatusCode, string(resp.Body))
}

var result CommonResponse
if err = json.Unmarshal(resp.Body, &result); err != nil {
// Restore original token on error
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].APIToken = savedToken
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].useAPIToken = savedUseAPIToken
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].APIKey = savedToken
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].useAPIKey = savedUseAPIToken
return nil, fmt.Errorf("token validation failed: invalid JSON (%w)", err)
}

if result.Code != 0 {
// Restore original token on error
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].APIToken = savedToken
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].useAPIToken = savedUseAPIToken
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].APIKey = savedToken
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].useAPIKey = savedUseAPIToken
return nil, fmt.Errorf("token validation failed: %s", result.Message)
}

// Token is valid, keep it set

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

Finish renaming token terminology in API key validation errors.

SET KEY failures still return “token validation failed” / “failed to validate token”, which leaks the old command language into the new API key flow.

Proposed wording cleanup
-	return nil, fmt.Errorf("failed to validate token: %w", err)
+	return nil, fmt.Errorf("failed to validate API key: %w", err)
...
-	return nil, fmt.Errorf("token validation failed: HTTP %d, body: %s", resp.StatusCode, string(resp.Body))
+	return nil, fmt.Errorf("API key validation failed: HTTP %d, body: %s", resp.StatusCode, string(resp.Body))
...
-	return nil, fmt.Errorf("token validation failed: invalid JSON (%w)", err)
+	return nil, fmt.Errorf("API key validation failed: invalid JSON (%w)", err)
...
-	return nil, fmt.Errorf("token validation failed: %s", result.Message)
+	return nil, fmt.Errorf("API key validation failed: %s", result.Message)
📝 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
// Save current token to restore if validation fails
savedToken := c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].APIToken
savedUseAPIToken := c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].useAPIToken
savedToken := c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].APIKey
savedUseAPIToken := c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].useAPIKey
// Set the new token temporarily for validation
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].APIToken = &token
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].useAPIToken = true
// Set the new key temporarily for validation
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].APIKey = &apiKey
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].useAPIKey = true
// Validate token by calling list tokens API
resp, err := c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].Request("GET", "/tokens", "api", nil, nil)
resp, err := c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].Request("GET", "/system/tokens", "api", nil, nil)
if err != nil {
// Restore original token on error
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].APIToken = savedToken
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].useAPIToken = savedUseAPIToken
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].APIKey = savedToken
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].useAPIKey = savedUseAPIToken
return nil, fmt.Errorf("failed to validate token: %w", err)
}
if resp.StatusCode != 200 {
// Restore original token on error
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].APIToken = savedToken
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].useAPIToken = savedUseAPIToken
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].APIKey = savedToken
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].useAPIKey = savedUseAPIToken
return nil, fmt.Errorf("token validation failed: HTTP %d, body: %s", resp.StatusCode, string(resp.Body))
}
var result CommonResponse
if err = json.Unmarshal(resp.Body, &result); err != nil {
// Restore original token on error
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].APIToken = savedToken
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].useAPIToken = savedUseAPIToken
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].APIKey = savedToken
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].useAPIKey = savedUseAPIToken
return nil, fmt.Errorf("token validation failed: invalid JSON (%w)", err)
}
if result.Code != 0 {
// Restore original token on error
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].APIToken = savedToken
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].useAPIToken = savedUseAPIToken
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].APIKey = savedToken
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].useAPIKey = savedUseAPIToken
return nil, fmt.Errorf("token validation failed: %s", result.Message)
}
// Token is valid, keep it set
// Save current token to restore if validation fails
savedToken := c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].APIKey
savedUseAPIToken := c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].useAPIKey
// Set the new key temporarily for validation
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].APIKey = &apiKey
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].useAPIKey = true
// Validate token by calling list tokens API
resp, err := c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].Request("GET", "/system/tokens", "api", nil, nil)
if err != nil {
// Restore original token on error
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].APIKey = savedToken
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].useAPIKey = savedUseAPIToken
return nil, fmt.Errorf("failed to validate API key: %w", err)
}
if resp.StatusCode != 200 {
// Restore original token on error
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].APIKey = savedToken
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].useAPIKey = savedUseAPIToken
return nil, fmt.Errorf("API key validation failed: HTTP %d, body: %s", resp.StatusCode, string(resp.Body))
}
var result CommonResponse
if err = json.Unmarshal(resp.Body, &result); err != nil {
// Restore original token on error
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].APIKey = savedToken
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].useAPIKey = savedUseAPIToken
return nil, fmt.Errorf("API key validation failed: invalid JSON (%w)", err)
}
if result.Code != 0 {
// Restore original token on error
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].APIKey = savedToken
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].useAPIKey = savedUseAPIToken
return nil, fmt.Errorf("API key validation failed: %s", result.Message)
}
// Token is valid, keep it set
🤖 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 1020 - 1059, Update the validation
error messages in the API key flow inside the token-validation block of
user_command.go to use API key terminology instead of token terminology. In the
code around the Request("/system/tokens") validation and the JSON/status checks,
rename the returned errors from “failed to validate token” and “token validation
failed” to consistent API key wording, while keeping the same restore-on-failure
behavior for APIKey and useAPIKey.

Comment on lines +390 to +398
func (p *Parser) parseAPIListAvailableProviders() (*Command, error) {
p.nextToken() // consume AVAILABLE

if p.curToken.Type != TokenProviders {
return nil, fmt.Errorf("expected PROVIDERS")
}

return NewCommand("api_list_available_providers"), 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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Consume PROVIDERS before returning from LIST AVAILABLE PROVIDERS.

This branch validates PROVIDERS but leaves it as curToken, so the advertised optional semicolon is never consumed and trailing input handling diverges from the other LIST parsers.

Proposed fix
 func (p *Parser) parseAPIListAvailableProviders() (*Command, error) {
 	p.nextToken() // consume AVAILABLE
 
 	if p.curToken.Type != TokenProviders {
 		return nil, fmt.Errorf("expected PROVIDERS")
 	}
+	p.nextToken() // consume PROVIDERS
+
+	// Semicolon is optional
+	if p.curToken.Type == TokenSemicolon {
+		p.nextToken()
+	}
 
 	return NewCommand("api_list_available_providers"), nil
 }
📝 Committable suggestion

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

Suggested change
func (p *Parser) parseAPIListAvailableProviders() (*Command, error) {
p.nextToken() // consume AVAILABLE
if p.curToken.Type != TokenProviders {
return nil, fmt.Errorf("expected PROVIDERS")
}
return NewCommand("api_list_available_providers"), nil
}
func (p *Parser) parseAPIListAvailableProviders() (*Command, error) {
p.nextToken() // consume AVAILABLE
if p.curToken.Type != TokenProviders {
return nil, fmt.Errorf("expected PROVIDERS")
}
p.nextToken() // consume PROVIDERS
// Semicolon is optional
if p.curToken.Type == TokenSemicolon {
p.nextToken()
}
return NewCommand("api_list_available_providers"), 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/user_parser.go` around lines 390 - 398, The
parseAPIListAvailableProviders branch validates TokenProviders but returns
without consuming it, so the parser state is left behind and the optional
semicolon/trailing input handling diverges from the other LIST parsers. Update
parseAPIListAvailableProviders in Parser to advance past PROVIDERS before
returning the NewCommand("api_list_available_providers"), matching the token
consumption pattern used by the other list parsing methods.

Comment on lines +3694 to 3696
if p.curToken.Type != TokenKey {
return nil, fmt.Errorf("expected TOKEN after UNSET")
}

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

Update the UNSET KEY parse error.

Line 3694 now expects TokenKey, but Line 3695 still says TOKEN, which makes failed UNSET KEY input confusing.

Proposed fix
 	if p.curToken.Type != TokenKey {
-		return nil, fmt.Errorf("expected TOKEN after UNSET")
+		return nil, fmt.Errorf("expected KEY after UNSET")
 	}
📝 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 p.curToken.Type != TokenKey {
return nil, fmt.Errorf("expected TOKEN after UNSET")
}
if p.curToken.Type != TokenKey {
return nil, fmt.Errorf("expected KEY after UNSET")
}
🤖 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 3694 - 3696, The UNSET KEY parser
error message is stale and still says TOKEN even though the check in
user_parser.go’s UNSET KEY branch expects TokenKey. Update the error text in the
relevant parse path to mention KEY/TokenKey consistently so failures from the
UNSET handling are accurate and easier to understand.

@codecov

codecov Bot commented Jun 24, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (9a91564) to head (81c5f47).

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #16306   +/-   ##
=======================================
  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.

@JinHai-CN
JinHai-CN merged commit 1fc0260 into infiniflow:main Jun 24, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant