Skip to content

feat[Go] implement check connection by using apikey and region - #15475

Merged
JinHai-CN merged 4 commits into
infiniflow:mainfrom
Haruko386:main
Jun 2, 2026
Merged

JinHai-CN merged 4 commits into
infiniflow:mainfrom
Haruko386:main

Conversation

@Haruko386

Copy link
Copy Markdown
Member

What problem does this PR solve?

Verified from PostMan

GET http://127.0.0.1:9384/api/v1/providers/gitee/connection

body: 

{
    "api_key": "XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    "region": "default"

}

resp: 
{
    "code": 0,
    "message": "success"
}

GET http://127.0.0.1:9384/api/v1/providers/gitee/connection

body: 

{
    "api_key": "XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    "region": "deprecated"

}

resp: 
{
    "code": 0,
    "message": "success"
}

GET http://127.0.0.1:9384/api/v1/providers/gitee/connection

body: 

{
    "api_key": "XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    "region": "china"

}

resp: 
{
    "code": 0,
    "message": "success"
}

GET http://127.0.0.1:9384/api/v1/providers/lmstudio/connection

body: 

{
    "api_key": "",
    "region": "test"

}

resp: 
{
    "code": 0,
    "message": "success"
}

Type of change

  • New Feature (non-breaking change which adds functionality)

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jun 1, 2026
@coderabbitai

coderabbitai Bot commented Jun 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

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

Changes

Provider Connection Checking

Layer / File(s) Summary
Connection request DTO and instance lookup
internal/service/model_service.go, internal/dao/tenant_model_instance.go
Adds CheckConnectionRequest{APIKey, Region, BaseURL} and TenantModelInstanceDAO.GetInstanceByApiKey(apiKey, providerID) which queries by api_key and provider_id.
Service: CheckConnection and instance-resolution
internal/service/model_service.go
Adds ModelProviderService.CheckConnection(providerName, apiKey, region, baseURL, userID), updates ShowProviderInstance to include apikey, and replaces the previous provider-check entrypoint with CheckInstanceConnection that delegates into the new flow and rebuilds drivers for base_url when needed.
HTTP handler and routing
internal/handler/providers.go, internal/router/router.go
Adds ProviderHandler.CheckConnection binding CheckConnectionRequest; updates CheckInstanceConnection to fetch instance info and call modelProviderService.CheckConnection(providerName, apikey, region, baseURL, userID); router adds GET /providers/:provider_name/connection.

Sequence Diagram

sequenceDiagram
  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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • infiniflow/ragflow#14296: Modifies the provider-connection check flow and touches handler/router/service areas overlapping this change.

Suggested labels

💞 feature

Poem

🐇 I hopped along the provider trail,
With api_key snug in my small tail—
Local or remote, I checked each door,
Found region and base_url, then hopped some more.
Connection good — I twitched with delight!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main feature added: implementing check connection functionality using apikey and region parameters.
Description check ✅ Passed The description includes the required 'What problem does this PR solve?' section and specifies the type of change as New Feature, but lacks detailed explanation of the problem being solved or implementation details beyond test examples.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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 and usage tips.

@Haruko386
Haruko386 requested a review from JinHai-CN June 1, 2026 07:42
@Haruko386 Haruko386 added the ci Continue Integration label Jun 1, 2026
@Haruko386
Haruko386 marked this pull request as draft June 1, 2026 07:42
@Haruko386
Haruko386 marked this pull request as ready for review June 1, 2026 07:42

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 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

📥 Commits

Reviewing files that changed from the base of the PR and between 82202fa and 6f062a5.

📒 Files selected for processing (4)
  • internal/dao/tenant_model_instance.go
  • internal/handler/providers.go
  • internal/router/router.go
  • internal/service/model_service.go

Comment on lines +44 to +50
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

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.

⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

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.

Comment thread internal/handler/providers.go Resolved
Comment thread internal/service/model_service.go Resolved
@codecov

codecov Bot commented Jun 1, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (12579db) to head (42376df).
⚠️ Report is 37 commits behind head on main.

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

@Haruko386 Haruko386 left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6f062a5 and 3f39bac.

📒 Files selected for processing (3)
  • internal/handler/providers.go
  • internal/router/router.go
  • internal/service/model_service.go

Comment thread internal/service/model_service.go Resolved

@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: 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 win

Do 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

📥 Commits

Reviewing files that changed from the base of the PR and between 3f39bac and 6c62660.

📒 Files selected for processing (2)
  • internal/handler/providers.go
  • internal/service/model_service.go

Comment thread internal/handler/providers.go Resolved

@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: 1

♻️ Duplicate comments (1)
internal/handler/providers.go (1)

400-401: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Use POST here if this endpoint requires JSON credentials.

internal/router/router.go still exposes /providers/:provider_name/connection as GET, but this handler only accepts ShouldBindJSON. GET bodies are unreliable across clients and proxies, and moving api_key into the query string would leak credentials into URLs. Keep JSON binding and switch the route to POST.

#!/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

📥 Commits

Reviewing files that changed from the base of the PR and between 6c62660 and 42376df.

📒 Files selected for processing (2)
  • internal/handler/providers.go
  • internal/service/model_service.go

Comment on lines +449 to +459
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
}

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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.

Suggested change
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.

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

Labels

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.

2 participants