Repository navigation
Go CLI: admin model framework - #16252
Conversation
Signed-off-by: Jin Hai <[email protected]>
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds four new admin REST endpoints for listing provider instances, showing instance details, showing instance balance, and listing models within an instance. Introduces six shared CLI handlers that route to correct endpoints by CLIMode. Extends the CLI parser to dispatch LIST PROVIDER, SHOW PROVIDER, and CHECK PROVIDER subcommands. Unifies HTTP command dispatch for both admin and user modes by routing to shared Common handlers instead of user-only implementations. ChangesAdmin provider instance management
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Sequence Diagram(s)sequenceDiagram
participant Client
participant Router
participant Handler
participant Service
Client->>Router: GET /api/v1/admin/providers/:provider_name/instances
Router->>Handler: ListModelInstances(c)
Handler->>Service: ListModelInstances(userID, providerName)
Service-->>Handler: []map[string]interface{}, error
Handler-->>Client: success or 500 response
Client->>Router: GET /api/v1/admin/providers/:provider_name/instances/:instance_name
Router->>Handler: ShowProviderInstance(c)
Handler->>Service: ShowProviderInstance(userID, providerName, instanceName)
Service-->>Handler: map[string]interface{}, error
Handler-->>Client: success or 500 response
Client->>Router: GET /api/v1/admin/providers/:provider_name/instances/:instance_name/balance
Router->>Handler: ShowProviderInstanceBalance(c)
Handler->>Service: ShowProviderInstanceBalance(userID, providerName, instanceName)
Service-->>Handler: map[string]interface{}, error
Handler-->>Client: success or 500 response
Client->>Router: GET /api/v1/admin/providers/:provider_name/instances/:instance_name/models
Router->>Handler: ListInstanceModels(c)
Handler->>Service: ListInstanceModels(userID, providerName, instanceName)
Service-->>Handler: []map[string]interface{}, error
Handler-->>Client: success or 500 response
Possibly related PRs
Suggested labels
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/cli/common_command.go`:
- Around line 340-343: The providerName variable is being inserted directly into
URL paths in the fmt.Sprintf calls without proper escaping, which can cause
issues if the name contains reserved URL characters. Add the import for net/url
at the top of the file, then modify both the AdminServerClient path at line 340
and the APIMode path at line 343 to use url.PathEscape(providerName) instead of
interpolating providerName directly into the path strings.
🪄 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: 6a83b78f-9630-4769-ac26-3fa501c0900f
📒 Files selected for processing (7)
internal/admin/enterprise_handler.gointernal/admin/enterprise_service.gointernal/admin/router.gointernal/cli/admin_parser.gointernal/cli/cli_http.gointernal/cli/common_command.gointernal/cli/user_command.go
💤 Files with no reviewable changes (1)
- internal/cli/user_command.go
| endPoint = fmt.Sprintf("/admin/providers/%s/instances", providerName) | ||
| resp, err = c.AdminServerClient.Request("GET", endPoint, "web", nil, nil) | ||
| case APIMode: | ||
| endPoint = fmt.Sprintf("/providers/%s/instances", providerName) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Escape provider_name before interpolating it into URL paths.
At Line 340 and Line 343, providerName is inserted raw into the path. Names with reserved URL chars can hit the wrong endpoint or fail routing.
Suggested fix
func (c *CLI) CommonListProviderInstances(cmd *Command) (ResponseIf, error) {
providerName, ok := cmd.Params["provider_name"].(string)
if !ok {
return nil, fmt.Errorf("provider_name not provided")
}
+ escapedProviderName := url.PathEscape(providerName)
var resp *Response
var err error
var endPoint string
switch c.Config.CLIMode {
case AdminMode:
- endPoint = fmt.Sprintf("/admin/providers/%s/instances", providerName)
+ endPoint = fmt.Sprintf("/admin/providers/%s/instances", escapedProviderName)
resp, err = c.AdminServerClient.Request("GET", endPoint, "web", nil, nil)
case APIMode:
- endPoint = fmt.Sprintf("/providers/%s/instances", providerName)
+ endPoint = fmt.Sprintf("/providers/%s/instances", escapedProviderName)
resp, err = c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].Request("GET", endPoint, "web", nil, nil)
default:
return nil, fmt.Errorf("invalid server type")
}Also add:
import "net/url"🤖 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 340 - 343, The providerName
variable is being inserted directly into URL paths in the fmt.Sprintf calls
without proper escaping, which can cause issues if the name contains reserved
URL characters. Add the import for net/url at the top of the file, then modify
both the AdminServerClient path at line 340 and the APIMode path at line 343 to
use url.PathEscape(providerName) instead of interpolating providerName directly
into the path strings.
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
internal/cli/common_command.go (1)
343-347: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winEscape path parameters before building endpoint URLs.
At Line 343 and Line 346,
providerName/instanceNameare interpolated raw into path segments. Reserved characters can break routing or hit a different endpoint.Suggested fix
+import "net/url" ... func (c *CLI) CommonShowProviderInstanceCommand(cmd *Command) (ResponseIf, error) { instanceName, ok := cmd.Params["instance_name"].(string) if !ok { return nil, fmt.Errorf("instance name not provided") } @@ providerName, ok := cmd.Params["provider_name"].(string) if !ok { return nil, fmt.Errorf("provider name not provided") } + escapedProviderName := url.PathEscape(providerName) + escapedInstanceName := url.PathEscape(instanceName) @@ switch c.Config.CLIMode { case AdminMode: - endPoint = fmt.Sprintf("/admin/providers/%s/instances/%s", providerName, instanceName) + endPoint = fmt.Sprintf("/admin/providers/%s/instances/%s", escapedProviderName, escapedInstanceName) resp, err = c.AdminServerClient.Request("GET", endPoint, "web", nil, nil) case APIMode: - endPoint = fmt.Sprintf("/providers/%s/instances/%s", providerName, instanceName) + endPoint = fmt.Sprintf("/providers/%s/instances/%s", escapedProviderName, escapedInstanceName) resp, err = c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].Request("GET", endPoint, "web", nil, nil)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/cli/common_command.go` around lines 343 - 347, The path parameters providerName and instanceName are being directly interpolated into endpoint URLs in the AdminMode and APIMode cases without proper URL escaping, which can cause routing issues or security vulnerabilities if these parameters contain reserved characters. Escape both providerName and instanceName using url.PathEscape from the net/url package before passing them to the fmt.Sprintf calls in both the AdminMode case (the endPoint assignment at line 343) and the APIMode case (the endPoint assignment at line 346). Ensure the net/url package is imported in this file.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/cli/admin_parser.go`:
- Around line 709-720: The default case in the switch statement checking
p.curToken.Type (which handles TokenInstance and TokenModel cases) silently
consumes unexpected tokens by calling p.nextToken() and then continues to create
and return a valid admin_show_provider command. This accepts invalid syntax
instead of rejecting it. Replace the default case logic to properly reject
unexpected tokens by returning an error instead of silently consuming the token
and proceeding with command creation. The default case should indicate that an
unexpected token was encountered after the provider name, rather than allowing
the parse to succeed.
---
Duplicate comments:
In `@internal/cli/common_command.go`:
- Around line 343-347: The path parameters providerName and instanceName are
being directly interpolated into endpoint URLs in the AdminMode and APIMode
cases without proper URL escaping, which can cause routing issues or security
vulnerabilities if these parameters contain reserved characters. Escape both
providerName and instanceName using url.PathEscape from the net/url package
before passing them to the fmt.Sprintf calls in both the AdminMode case (the
endPoint assignment at line 343) and the APIMode case (the endPoint assignment
at line 346). Ensure the net/url package is imported in this file.
🪄 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: 883b4e82-95e3-4a07-9ab1-b784a00e6a2c
📒 Files selected for processing (7)
internal/admin/enterprise_handler.gointernal/admin/enterprise_service.gointernal/admin/router.gointernal/cli/admin_parser.gointernal/cli/cli_http.gointernal/cli/common_command.gointernal/cli/user_command.go
💤 Files with no reviewable changes (1)
- internal/cli/user_command.go
🚧 Files skipped from review as they are similar to previous changes (2)
- internal/admin/enterprise_service.go
- internal/cli/cli_http.go
| switch p.curToken.Type { | ||
| case TokenInstance: | ||
| return p.parseAdminShowProviderInstance(providerName) | ||
| case TokenModel: | ||
| return p.parseAdminShowProviderModel(providerName) | ||
| default: | ||
| p.nextToken() | ||
| } | ||
|
|
||
| cmd := NewCommand("admin_show_provider") | ||
| cmd.Params["provider_name"] = providerName | ||
| return cmd, nil |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Reject unexpected tokens after provider name in SHOW PROVIDER parsing.
The default branch (Line 714–Line 716) silently consumes any token and still emits admin_show_provider. This accepts invalid syntax instead of failing fast.
Suggested fix
switch p.curToken.Type {
case TokenInstance:
return p.parseAdminShowProviderInstance(providerName)
case TokenModel:
return p.parseAdminShowProviderModel(providerName)
default:
- p.nextToken()
+ if p.curToken.Type != TokenSemicolon && p.curToken.Type != TokenEOF {
+ return nil, fmt.Errorf("unexpected token after provider name: %s", p.curToken.Literal)
+ }
+ if p.curToken.Type == TokenSemicolon {
+ p.nextToken()
+ }
}🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/cli/admin_parser.go` around lines 709 - 720, The default case in the
switch statement checking p.curToken.Type (which handles TokenInstance and
TokenModel cases) silently consumes unexpected tokens by calling p.nextToken()
and then continues to create and return a valid admin_show_provider command.
This accepts invalid syntax instead of rejecting it. Replace the default case
logic to properly reject unexpected tokens by returning an error instead of
silently consuming the token and proceeding with command creation. The default
case should indicate that an unexpected token was encountered after the provider
name, rather than allowing the parse to succeed.
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 6
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/admin/enterprise_handler.go`:
- Line 587: The success message in the connection check response is incorrectly
labeled as "Model instance connection checked successfully" when this is
actually a provider-level connection check. Locate the success function call
around line 587 in the enterprise_handler.go file and update the message string
to correctly indicate this is a provider connection check rather than a model
instance check, changing the terminology from "Model instance" to "Provider" to
avoid misleading output in CLI and API responses.
In `@internal/admin/enterprise_service.go`:
- Around line 251-252: Remove the "api_key" field from the response map that is
being returned by the enterprise service. The line containing "api_key": apiKey,
should be deleted entirely, leaving only non-sensitive fields like "base_url":
baseURL, in the response to prevent API key secrets from being exposed through
logs, telemetry, or client-side persistence.
- Around line 246-254: The `CheckProviderConnection` method in the return
statement is missing the enterprise "not implemented" marker that other sibling
enterprise stub methods include. Add the appropriate enterprise "not
implemented" marker to the return map or method to maintain consistency with
other stub methods and prevent false success reporting for this unimplemented
feature.
In `@internal/admin/router.go`:
- Line 189: The route registration at line 189 uses HTTP GET method for the
CheckProviderConnection handler, but GET requests do not reliably support
request bodies. Change the route from GET to POST for the
/:provider_name/connection endpoint (provider.GET should become provider.POST),
which matches the handler's expectation of receiving JSON body data via
ShouldBindJSON.
In `@internal/cli/admin_parser.go`:
- Around line 892-894: The parseAdminCheckProviderInstance function returns
early and bypasses the end-of-command validation checks (semicolon/EOF
validation) that are performed for the REGION and KEY variants of the CHECK
PROVIDER command. After the early return statement in the TokenInstance
condition, ensure that parseAdminCheckProviderInstance is followed by the same
end-of-command validation logic that occurs in the REGION and KEY parsing paths
to maintain consistent validation across all command variants.
In `@internal/cli/common_command.go`:
- Around line 677-679: In the APIMode case within the provider connection check
logic, the HTTP method used for the API request is incorrect. Change the Request
method call on c.APIServerClientMap to use "POST" instead of "GET" when calling
the /providers/{provider_name}/connection endpoint. This aligns the client code
with the actual API endpoint definition which expects a POST request for
provider key connection checks.
🪄 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: 8f880c80-2fc6-4275-a1aa-28ca91447641
📒 Files selected for processing (7)
internal/admin/enterprise_handler.gointernal/admin/enterprise_service.gointernal/admin/router.gointernal/cli/admin_parser.gointernal/cli/cli_http.gointernal/cli/common_command.gointernal/cli/user_command.go
💤 Files with no reviewable changes (1)
- internal/cli/user_command.go
| return | ||
| } | ||
|
|
||
| success(c, result, "Model instance connection checked successfully") |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Fix provider check success message text.
Line 587 currently says model instance for a provider-level connection check, which is misleading in CLI/API output.
Proposed patch
- success(c, result, "Model instance connection checked successfully")
+ success(c, result, "Provider connection checked successfully")📝 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.
| success(c, result, "Model instance connection checked successfully") | |
| success(c, result, "Provider connection checked successfully") |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/admin/enterprise_handler.go` at line 587, The success message in the
connection check response is incorrectly labeled as "Model instance connection
checked successfully" when this is actually a provider-level connection check.
Locate the success function call around line 587 in the enterprise_handler.go
file and update the message string to correctly indicate this is a provider
connection check rather than a model instance check, changing the terminology
from "Model instance" to "Provider" to avoid misleading output in CLI and API
responses.
| return map[string]interface{}{ | ||
| "command": "check_provider_connection", | ||
| "user_id": userID, | ||
| "provider_id": providerName, | ||
| "region": region, | ||
| "api_key": apiKey, | ||
| "base_url": baseURL, | ||
| }, nil | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Keep enterprise stub contract consistent for provider checks.
CheckProviderConnection is the only new enterprise stub that omits the enterprise “not implemented” marker, while sibling methods include it. This can report a false success path for an unimplemented feature.
Proposed patch
func (s *Service) CheckProviderConnection(userID, providerName, region, apiKey, baseURL string) (map[string]interface{}, error) {
return map[string]interface{}{
"command": "check_provider_connection",
"user_id": userID,
"provider_id": providerName,
"region": region,
"api_key": apiKey,
"base_url": baseURL,
+ "error": "'check provider connection' is implemented in enterprise edition",
}, 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.
| return map[string]interface{}{ | |
| "command": "check_provider_connection", | |
| "user_id": userID, | |
| "provider_id": providerName, | |
| "region": region, | |
| "api_key": apiKey, | |
| "base_url": baseURL, | |
| }, nil | |
| } | |
| func (s *Service) CheckProviderConnection(userID, providerName, region, apiKey, baseURL string) (map[string]interface{}, error) { | |
| return map[string]interface{}{ | |
| "command": "check_provider_connection", | |
| "user_id": userID, | |
| "provider_id": providerName, | |
| "region": region, | |
| "api_key": apiKey, | |
| "base_url": baseURL, | |
| "error": "'check provider connection' is implemented in enterprise edition", | |
| }, 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/admin/enterprise_service.go` around lines 246 - 254, The
`CheckProviderConnection` method in the return statement is missing the
enterprise "not implemented" marker that other sibling enterprise stub methods
include. Add the appropriate enterprise "not implemented" marker to the return
map or method to maintain consistency with other stub methods and prevent false
success reporting for this unimplemented feature.
| "api_key": apiKey, | ||
| "base_url": baseURL, |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟠 Major | ⚡ Quick win
Do not return raw API keys in service responses.
Line 251 includes api_key in the response map. Even in stub mode, echoing secrets increases leakage risk via logs, telemetry, or client-side persistence.
Proposed patch
- "api_key": apiKey,
+ "api_key": "",(Or omit api_key entirely and return only non-sensitive fields.)
📝 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.
| "api_key": apiKey, | |
| "base_url": baseURL, | |
| "api_key": "", | |
| "base_url": baseURL, |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/admin/enterprise_service.go` around lines 251 - 252, Remove the
"api_key" field from the response map that is being returned by the enterprise
service. The line containing "api_key": apiKey, should be deleted entirely,
leaving only non-sensitive fields like "base_url": baseURL, in the response to
prevent API key secrets from being exposed through logs, telemetry, or
client-side persistence.
| if p.curToken.Type == TokenInstance { | ||
| return p.parseAdminCheckProviderInstance(providerName) | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
CHECK PROVIDER ... INSTANCE ... bypasses end-of-command validation.
At Line 893, the early return skips the semicolon/EOF checks at Lines 928-933, so the INSTANCE variant is not validated as strictly as the REGION/KEY variant.
Suggested fix
if p.curToken.Type == TokenInstance {
- return p.parseAdminCheckProviderInstance(providerName)
+ cmd, err := p.parseAdminCheckProviderInstance(providerName)
+ if err != nil {
+ return nil, err
+ }
+ if p.curToken.Type == TokenSemicolon {
+ p.nextToken()
+ }
+ if p.curToken.Type != TokenEOF {
+ return nil, fmt.Errorf("unexpected token: %s", p.curToken.Value)
+ }
+ return cmd, nil
}Also applies to: 928-933, 946-959
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/cli/admin_parser.go` around lines 892 - 894, The
parseAdminCheckProviderInstance function returns early and bypasses the
end-of-command validation checks (semicolon/EOF validation) that are performed
for the REGION and KEY variants of the CHECK PROVIDER command. After the early
return statement in the TokenInstance condition, ensure that
parseAdminCheckProviderInstance is followed by the same end-of-command
validation logic that occurs in the REGION and KEY parsing paths to maintain
consistent validation across all command variants.
Signed-off-by: Jin Hai <[email protected]>
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #16252 +/- ##
==========================================
- Coverage 94.56% 93.16% -1.40%
==========================================
Files 10 10
Lines 717 717
Branches 118 118
==========================================
- Hits 678 668 -10
- Misses 25 29 +4
- Partials 14 20 +6 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Signed-off-by: Jin Hai <[email protected]>
What problem does this PR solve?
Type of change