Repository navigation
Go CLI: fix key commands - #16306
Go CLI: fix key commands#16306
Conversation
Signed-off-by: Jin Hai <[email protected]>
📝 WalkthroughWalkthroughRenames the CLI authentication credential from ChangesAPI Token → API Key Rename
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
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 winPreserve API-key auth for callers that still pass
web.Several API-key-gated commands still call
Request(..., "web", ...). WithLoginToken == nil, this branch emits noAuthorization, 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 winKeep accepting legacy
api_tokenconfig keys.This PR is marked non-breaking, but existing
rf.ymlfiles using top-level or per-serverapi_tokenare now silently ignored, leavingAPIKeynil 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 liftUse
apiauth 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 sendsLoginToken, soSET KEYusers 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
authKindinstead 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
📒 Files selected for processing (8)
internal/cli/admin_parser.gointernal/cli/cli.gointernal/cli/cli_http.gointernal/cli/common_command.gointernal/cli/http_client.gointernal/cli/parser.gointernal/cli/user_command.gointernal/cli/user_parser.go
| 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" |
There was a problem hiding this comment.
🩺 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.
| 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.
| 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") | ||
| } |
There was a problem hiding this comment.
🎯 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.
| 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.
| 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" |
There was a problem hiding this comment.
🎯 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.
| 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.
| // 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 |
There was a problem hiding this comment.
📐 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.
| // 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.
| 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 | ||
| } |
There was a problem hiding this comment.
🎯 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.
| 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.
| if p.curToken.Type != TokenKey { | ||
| return nil, fmt.Errorf("expected TOKEN after UNSET") | ||
| } |
There was a problem hiding this comment.
🎯 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.
| 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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
What problem does this PR solve?
Type of change