Repository navigation
feat[Go] implement check connection by using apikey and region - #15475
Conversation
📝 WalkthroughWalkthroughAdds a provider-scoped CheckConnection API, service entrypoint, and wiring. Introduces a CheckConnectionRequest DTO and DAO lookup by api_key for local providers; service dispatches by provider class and handlers/router are updated to call the new flow. ChangesProvider Connection Checking
Sequence DiagramsequenceDiagram
participant Client
participant ProviderHandler
participant ModelProviderService
participant TenantModelInstanceDAO
participant ModelDriver
Client->>ProviderHandler: GET /providers/:provider_name/connection {api_key, region, base_url}
ProviderHandler->>ModelProviderService: CheckConnection(providerName, apiKey, region, baseURL, userID)
alt provider class == "local"
ModelProviderService->>TenantModelInstanceDAO: GetInstanceByApiKey(apiKey, providerID)
TenantModelInstanceDAO->>ModelProviderService: TenantModelInstance
ModelProviderService->>ModelDriver: CheckConnection(APIConfig with instance data)
else non-local
ModelProviderService->>ModelDriver: CheckConnection(APIConfig(apiKey, region, baseURL))
end
ModelDriver->>ModelProviderService: result
ModelProviderService->>ProviderHandler: result
ProviderHandler->>Client: JSON response
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Poem
🚥 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: 3
🤖 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/dao/tenant_model_instance.go`:
- Around line 44-50: The GetInstanceByApiKey lookup in TenantModelInstanceDAO
(function GetInstanceByApiKey) currently queries only api_key and provider_id
via DB.Where and can return the wrong local instance when multiple instances
share a key or keys are empty; update this function to also include region in
the DB filter when region is available, or if region is not provided, fetch all
rows matching api_key and provider_id (e.g., use Find into a slice) and
disambiguate in code by selecting the instance whose region/base_url matches the
incoming request before returning (so that whatever calls CheckConnection
receives the correct resolved instance). Ensure you update callers accordingly
if the function signature needs a region parameter or returns multiple
candidates for caller-side disambiguation.
In `@internal/handler/providers.go`:
- Around line 400-407: The handler currently requires a JSON body via
c.ShouldBindJSON(&req) for service.CheckConnectionRequest while the route is a
GET; update the handler to not require a GET body by replacing the JSON binding
with query binding (e.g., use c.ShouldBindQuery(&req) or read
c.Query("api_key")/c.Query("region") and populate a
service.CheckConnectionRequest) and perform the same validation/error response;
alternatively, if you prefer keeping JSON, change the route to POST and keep
c.ShouldBindJSON(&req) — ensure the chosen change is reflected wherever the
route is registered so the HTTP verb and binding method are consistent.
In `@internal/service/model_service.go`:
- Around line 439-447: Normalize request fields before branching: trim
whitespace from req.APIKey and req.Region (set default region "default" if
empty) at the start of the provider handling code so both the local path
(checkLocalProviderConnection(providerName, req, userID)) and the non-local path
use the same normalized values; move the apiKey/region normalization above the
strings.EqualFold(providerInfo.Class, "local") check and ensure the trimmed API
key is passed through in req for DAO lookups.
🪄 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: 02b79248-c7e0-4da5-b0f3-c745dc0a5c1c
📒 Files selected for processing (4)
internal/dao/tenant_model_instance.gointernal/handler/providers.gointernal/router/router.gointernal/service/model_service.go
| func (dao *TenantModelInstanceDAO) GetInstanceByApiKey(apiKey, providerID string) (*entity.TenantModelInstance, error) { | ||
| var instance entity.TenantModelInstance | ||
| err := DB.Where("api_key = ? && provider_id = ?", apiKey, providerID).First(&instance).Error | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| return &instance, nil |
There was a problem hiding this comment.
Lookup by API key alone can select the wrong local instance.
This query ignores region and returns the first (provider_id, api_key) match. With multiple local instances sharing a key—or empty keys—the new provider-level check can validate the wrong base_url/region and report a false result. Please resolve the instance with both request inputs, or fetch all key matches and disambiguate before calling CheckConnection.
🤖 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/dao/tenant_model_instance.go` around lines 44 - 50, The
GetInstanceByApiKey lookup in TenantModelInstanceDAO (function
GetInstanceByApiKey) currently queries only api_key and provider_id via DB.Where
and can return the wrong local instance when multiple instances share a key or
keys are empty; update this function to also include region in the DB filter
when region is available, or if region is not provided, fetch all rows matching
api_key and provider_id (e.g., use Find into a slice) and disambiguate in code
by selecting the instance whose region/base_url matches the incoming request
before returning (so that whatever calls CheckConnection receives the correct
resolved instance). Ensure you update callers accordingly if the function
signature needs a region parameter or returns multiple candidates for
caller-side disambiguation.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15475 +/- ##
=======================================
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 Sentry. 🚀 New features to boost your workflow:
|
Haruko386
left a comment
There was a problem hiding this comment.
body:
{}
resp:
{
"code": 0,
"message": "success"
}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/service/model_service.go`:
- Around line 478-480: The current lookup using
modelInstanceDAO.GetInstanceByApiKey(provider.ID, apiKey) is ambiguous for local
providers with blank/reused api_key and can pick the wrong instance; instead,
preserve and use the already-loaded instance when performing instance-level
checks (e.g., in CheckInstanceConnection) or change the DAO contract to accept
an unambiguous selector (such as instance_name or region) and use that selector
in place of GetInstanceByApiKey; specifically, update places calling
modelInstanceDAO.GetInstanceByApiKey (and the CheckInstanceConnection flow) to
either pass the existing instance object/ID already loaded earlier or modify the
lookup signature to include region/instance_name and use that to fetch the
correct instance.
🪄 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: a54e9e4a-d3a4-4d18-9318-83e0c7307dab
📒 Files selected for processing (3)
internal/handler/providers.gointernal/router/router.gointernal/service/model_service.go
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/service/model_service.go (1)
369-376:⚠️ Potential issue | 🟠 Major | ⚡ Quick winDo not return the raw API key in the instance detail response.
This now exposes the stored credential verbatim through
ShowProviderInstance, which unnecessarily broadens secret access to every caller of the instance-detail API. Return a masked value or a boolean instead.Suggested change
result := map[string]interface{}{ "id": instance.ID, "instanceName": instance.InstanceName, "providerID": instance.ProviderID, "status": instance.Status, - "apikey": instance.APIKey, + "hasApiKey": strings.TrimSpace(instance.APIKey) != "", "region": extra["region"], }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/service/model_service.go` around lines 369 - 376, The instance detail response currently returns the raw API key via instance.APIKey in the result map inside ShowProviderInstance (or the function that constructs the instance response); change this to avoid exposing secrets by replacing the "apikey" value with either a masked string (e.g., "****...") or a boolean like "hasApiKey": true/false, and ensure any callers expecting the full key are updated accordingly; locate the result map construction (referencing instance.ID, instance.InstanceName, instance.ProviderID, instance.Status, instance.APIKey, extra["region"]) and remove or replace the use of instance.APIKey with the chosen masked/boolean representation and update tests/consumers as needed.
🤖 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/handler/providers.go`:
- Around line 446-455: The handler calls
h.modelProviderService.ShowProviderInstance and writes a JSON error response but
doesn't return, so execution continues and unguarded type assertions on
instanceInfo (apikey/region) can panic; fix by returning immediately after
sending the error JSON, and add defensive checks before using instanceInfo
(ensure instanceInfo != nil and use safe type assertions like v, ok :=
instanceInfo["apikey"].(string) and v, ok := instanceInfo["region"].(string)),
and if missing send a clear error JSON and return; update the block around
ShowProviderInstance, instanceInfo, apikey and region accordingly.
---
Outside diff comments:
In `@internal/service/model_service.go`:
- Around line 369-376: The instance detail response currently returns the raw
API key via instance.APIKey in the result map inside ShowProviderInstance (or
the function that constructs the instance response); change this to avoid
exposing secrets by replacing the "apikey" value with either a masked string
(e.g., "****...") or a boolean like "hasApiKey": true/false, and ensure any
callers expecting the full key are updated accordingly; locate the result map
construction (referencing instance.ID, instance.InstanceName,
instance.ProviderID, instance.Status, instance.APIKey, extra["region"]) and
remove or replace the use of instance.APIKey with the chosen masked/boolean
representation and update tests/consumers as needed.
🪄 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: 981f3b6a-4d32-4711-a263-58ea111e2609
📒 Files selected for processing (2)
internal/handler/providers.gointernal/service/model_service.go
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
internal/handler/providers.go (1)
400-401:⚠️ Potential issue | 🟠 Major | ⚡ Quick winUse POST here if this endpoint requires JSON credentials.
internal/router/router.gostill exposes/providers/:provider_name/connectionasGET, but this handler only acceptsShouldBindJSON. GET bodies are unreliable across clients and proxies, and movingapi_keyinto the query string would leak credentials into URLs. Keep JSON binding and switch the route toPOST.#!/bin/bash # Verify that the handler expects a JSON body while the router registers GET. sed -n '390,407p' internal/handler/providers.go sed -n '297,311p' internal/router/router.go🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/handler/providers.go` around lines 400 - 401, The handler for CheckConnectionRequest uses ShouldBindJSON to parse JSON credentials (see service.CheckConnectionRequest and the call to c.ShouldBindJSON), but the route /providers/:provider_name/connection is still registered as GET in internal/router/router.go; change the route registration from GET to POST so the handler receives a JSON body (do not move api_key into query params), update any router registration that references "/providers/:provider_name/connection" to use POST, and keep the JSON binding in the provider connection handler unchanged.
🤖 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/service/model_service.go`:
- Around line 449-459: The CheckConnection path currently rejects local
providers when baseURL is empty; remove the explicit guard that returns an error
for `if baseURL == ""` inside the block that checks
`strings.EqualFold(providerInfo.Class, "local")` so that
`newModelDriverForBaseURL(driver, providerName, region, baseURL)` is always
called (it already handles empty `baseURL` by using the existing driver). In
short: delete the `base_url is required` error branch and let
`newModelDriverForBaseURL` decide behavior for empty `baseURL`, keeping the rest
of the `providerInfo.ModelDriver`/`driver` logic intact.
---
Duplicate comments:
In `@internal/handler/providers.go`:
- Around line 400-401: The handler for CheckConnectionRequest uses
ShouldBindJSON to parse JSON credentials (see service.CheckConnectionRequest and
the call to c.ShouldBindJSON), but the route
/providers/:provider_name/connection is still registered as GET in
internal/router/router.go; change the route registration from GET to POST so the
handler receives a JSON body (do not move api_key into query params), update any
router registration that references "/providers/:provider_name/connection" to
use POST, and keep the JSON binding in the provider connection handler
unchanged.
🪄 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: 811a60ca-8856-4acb-a2ae-a2694e679d58
📒 Files selected for processing (2)
internal/handler/providers.gointernal/service/model_service.go
| driver := providerInfo.ModelDriver | ||
| if strings.EqualFold(providerInfo.Class, "local") { | ||
| if baseURL == "" { | ||
| return common.CodeDataError, fmt.Errorf("base_url is required for local provider %s", providerName) | ||
| } | ||
|
|
||
| var err error | ||
| driver, err = newModelDriverForBaseURL(driver, providerName, region, baseURL) | ||
| if err != nil { | ||
| return common.CodeServerError, err | ||
| } |
There was a problem hiding this comment.
Keep base_url optional for local connection checks.
newModelDriverForBaseURL already treats an empty baseURL as "use the existing driver". This guard makes CheckConnection stricter than the rest of the service, and the instance connection path in internal/handler/providers.go now inherits that failure for local instances that have no stored extra["base_url"].
Suggested fix
driver := providerInfo.ModelDriver
if strings.EqualFold(providerInfo.Class, "local") {
- if baseURL == "" {
- return common.CodeDataError, fmt.Errorf("base_url is required for local provider %s", providerName)
- }
-
var err error
driver, err = newModelDriverForBaseURL(driver, providerName, region, baseURL)
if err != nil {
return common.CodeServerError, err
}
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| driver := providerInfo.ModelDriver | |
| if strings.EqualFold(providerInfo.Class, "local") { | |
| if baseURL == "" { | |
| return common.CodeDataError, fmt.Errorf("base_url is required for local provider %s", providerName) | |
| } | |
| var err error | |
| driver, err = newModelDriverForBaseURL(driver, providerName, region, baseURL) | |
| if err != nil { | |
| return common.CodeServerError, err | |
| } | |
| driver := providerInfo.ModelDriver | |
| if strings.EqualFold(providerInfo.Class, "local") { | |
| var err error | |
| driver, err = newModelDriverForBaseURL(driver, providerName, region, baseURL) | |
| if err != nil { | |
| return common.CodeServerError, err | |
| } | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/service/model_service.go` around lines 449 - 459, The
CheckConnection path currently rejects local providers when baseURL is empty;
remove the explicit guard that returns an error for `if baseURL == ""` inside
the block that checks `strings.EqualFold(providerInfo.Class, "local")` so that
`newModelDriverForBaseURL(driver, providerName, region, baseURL)` is always
called (it already handles empty `baseURL` by using the existing driver). In
short: delete the `base_url is required` error branch and let
`newModelDriverForBaseURL` decide behavior for empty `baseURL`, keeping the rest
of the `providerInfo.ModelDriver`/`driver` logic intact.
What problem does this PR solve?
Verified from PostMan
GET http://127.0.0.1:9384/api/v1/providers/gitee/connection
GET http://127.0.0.1:9384/api/v1/providers/gitee/connection
GET http://127.0.0.1:9384/api/v1/providers/gitee/connection
GET http://127.0.0.1:9384/api/v1/providers/lmstudio/connection
Type of change