Skip to content

feat(go-api): migrate searchbot share detail endpoint to go - #16124

Merged
JinHai-CN merged 3 commits into
infiniflow:mainfrom
Harry-Hz-Zhang:go-bot-endpoints
Jun 22, 2026
Merged

JinHai-CN merged 3 commits into
infiniflow:mainfrom
Harry-Hz-Zhang:go-bot-endpoints

Conversation

@Harry-Hz-Zhang

Copy link
Copy Markdown
Contributor

Summary

This PR migrates GET /api/v1/searchbots/detail from Python to Go.

Changes

  • add public Go route for /api/v1/searchbots/detail
  • implement beta-token auth flow for shared search access
  • add tenant-based access check for shared search apps
  • add joined search detail query for the share response
  • align Go response shape with the current Python runtime behavior
  • add DAO / service / handler tests for the new endpoint

Verification

Compared Python and Go responses with real requests:

  • Python: http://127.0.0.1:9380/api/v1/searchbots/detail
  • Go: http://127.0.0.1:9384/api/v1/searchbots/detail

Verified:

  • same HTTP status
  • same response code/message
  • same response fields and values
  • same beta-token access behavior

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. 💞 feature Feature request, pull request that fullfill a new feature. labels Jun 17, 2026
@Harry-Hz-Zhang Harry-Hz-Zhang added the ci Continue Integration label Jun 17, 2026
@Harry-Hz-Zhang
Harry-Hz-Zhang marked this pull request as draft June 17, 2026 05:53
@Harry-Hz-Zhang
Harry-Hz-Zhang marked this pull request as ready for review June 17, 2026 05:53
@coderabbitai

coderabbitai Bot commented Jun 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 9fc91c02-0b4f-4320-a30b-af7a64b67092

📥 Commits

Reviewing files that changed from the base of the PR and between 55f6f1f and 6900583.

📒 Files selected for processing (1)
  • internal/router/router.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/router/router.go

📝 Walkthrough

Walkthrough

Adds a new unauthenticated GET /api/v1/searchbots/detail endpoint that authenticates via a beta API token from the Authorization header. The implementation spans a new DAO method for beta token lookup, a joined search+user DAO query, service-layer access control and response mapping, a new SearchBotHandler.SearchbotDetail handler, and router registration. Tests are included at every layer.

Changes

Searchbot Share-Detail Endpoint

Layer / File(s) Summary
Beta token DAO and search detail DAO
internal/dao/api_token.go, internal/dao/search.go, internal/dao/api_token_beta_test.go, internal/dao/search_detail_test.go
APITokenDAO.GetByBeta queries the beta column via GORM. SearchDetailRow struct and SearchDAO.GetDetailByID perform a joined search+user query with status filtering. DAO tests cover successful lookup, joined field values, and inactive-user nil return.
Beta auth service and search share-detail service
internal/service/user.go, internal/service/search.go, internal/service/user_beta_test.go, internal/service/search_share_detail_test.go
UserService.GetUserByBetaAPIToken parses the Authorization header, calls GetByBeta, fetches the user by tenant ID, and validates the stored access_token. SearchService.GetSearchShareDetail enforces access control via GetSearchDetail, fetches via SearchDAO.GetDetailByID, and maps results into SearchShareDetail. Service tests cover success, invalid token, empty access token, and permission denial.
Handler, router, and integration tests
internal/handler/searchbot.go, internal/router/router.go, internal/handler/searchbot_detail_test.go
SearchBotHandler.SearchbotDetail validates search_id, authenticates via beta token, calls the service, and maps error strings to API error codes. GET /api/v1/searchbots/detail is registered on the no-auth route group. Commit-alias routes are repositioned in the router. Handler tests cover the success path, missing search_id, invalid beta token, unauthorized search access, and error response hardening. Formatting-only changes are applied to existing DTOs and helpers.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant SearchBotHandler
  participant UserService
  participant APITokenDAO
  participant SearchService
  participant SearchDAO

  rect rgba(100, 149, 237, 0.5)
    note over Client,APITokenDAO: Beta Token Authentication
    Client->>SearchBotHandler: GET /searchbots/detail?search_id=X (Authorization: Bearer <beta>)
    SearchBotHandler->>UserService: GetUserByBetaAPIToken(authorization)
    UserService->>APITokenDAO: GetByBeta(token)
    APITokenDAO-->>UserService: *APIToken (TenantID)
    UserService->>UserService: fetch user by TenantID, validate access_token
    UserService-->>SearchBotHandler: *User or CodeUnauthorized
  end

  rect rgba(60, 179, 113, 0.5)
    note over SearchBotHandler,SearchDAO: Share-Detail Retrieval
    SearchBotHandler->>SearchService: GetSearchShareDetail(user.ID, searchID)
    SearchService->>SearchService: GetSearchDetail (access control check)
    SearchService->>SearchDAO: GetDetailByID(searchID)
    SearchDAO-->>SearchService: *SearchDetailRow (joined user fields)
    SearchService-->>SearchBotHandler: *SearchShareDetail
    SearchBotHandler-->>Client: CodeSuccess + detail payload
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested labels

💞 feature

🐇 A new door in the bot's den,
A beta key unlocks it then —
The search detail hops through the join,
User and avatar align in line.
No auth required, just the token bright,
The rabbit wired it up just right! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 8.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main change: migrating the searchbot share detail endpoint from Python to Go.
Description check ✅ Passed The description provides clear problem context (endpoint migration), comprehensive change summary, and verification methodology, but omits the required 'Type of change' checkbox section from the template.
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.

@Harry-Hz-Zhang Harry-Hz-Zhang changed the title migrate searchbot share detail endpoint to go feat(go-api): migrate searchbot share detail endpoint to go Jun 17, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
internal/service/user_beta_test.go (1)

78-88: ⚡ Quick win

Add coverage for empty/whitespace Authorization headers.

Please add assertions for cases like "Bearer " and " " returning common.CodeUnauthorized. This locks in the auth-parser boundary behavior and guards regressions.

🤖 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/user_beta_test.go` around lines 78 - 88, The test
TestUserServiceGetUserByBetaAPITokenRejectsInvalidToken only validates the
"Bearer missing" case but lacks coverage for edge cases where the Authorization
header contains only whitespace or empty values. Add additional assertions in
this test function to verify that calling GetUserByBetaAPIToken with inputs like
"Bearer " (Bearer followed by only spaces) and "   " (only whitespace) both
properly reject the request and return common.CodeUnauthorized, ensuring the
auth-parser correctly handles these boundary conditions.
🤖 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/searchbot.go`:
- Around line 424-433: The default case in the error handling for the
GetSearchShareDetail call in the searchbot.go handler is exposing internal error
details directly to clients by passing err.Error() to the jsonError function.
Replace the default case to return a generic public error message (such as "An
error occurred" or similar) to the client, and instead log the actual error
details server-side using an appropriate logger to maintain debuggability while
preventing information disclosure of backend internals.

In `@internal/service/user.go`:
- Around line 1076-1089: The token extraction logic can accept empty or
whitespace-only tokens, which then gets passed to apiTokenDAO.GetByBeta(). After
extracting the token from the authorization string split, add validation to
check that the token is not empty or contains only whitespace before calling
apiTokenDAO.GetByBeta(). If the token is empty or blank, return an unauthorized
error without making the DAO call to avoid unnecessary database lookups.

---

Nitpick comments:
In `@internal/service/user_beta_test.go`:
- Around line 78-88: The test
TestUserServiceGetUserByBetaAPITokenRejectsInvalidToken only validates the
"Bearer missing" case but lacks coverage for edge cases where the Authorization
header contains only whitespace or empty values. Add additional assertions in
this test function to verify that calling GetUserByBetaAPIToken with inputs like
"Bearer " (Bearer followed by only spaces) and "   " (only whitespace) both
properly reject the request and return common.CodeUnauthorized, ensuring the
auth-parser correctly handles these boundary conditions.
🪄 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: 6a86e76f-b8bc-42e0-a3c6-78e55f356bd4

📥 Commits

Reviewing files that changed from the base of the PR and between e456598 and 0534e37.

📒 Files selected for processing (11)
  • internal/dao/api_token.go
  • internal/dao/api_token_beta_test.go
  • internal/dao/search.go
  • internal/dao/search_detail_test.go
  • internal/handler/searchbot.go
  • internal/handler/searchbot_detail_test.go
  • internal/router/router.go
  • internal/service/search.go
  • internal/service/search_share_detail_test.go
  • internal/service/user.go
  • internal/service/user_beta_test.go

Comment on lines +424 to +433
detail, err := h.searchSvc.GetSearchShareDetail(user.ID, searchID)
if err != nil {
switch err.Error() {
case "has no permission for this operation":
jsonError(c, common.CodeOperatingError, "Has no permission for this operation.")
case "can't find this Search App!":
jsonError(c, common.CodeDataError, "Can't find this Search App!")
default:
jsonError(c, common.CodeServerError, err.Error())
}

@coderabbitai coderabbitai Bot Jun 17, 2026 •

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

Do not expose internal error text in public responses.

The default branch returns err.Error() directly to clients, which can leak backend internals from DAO/service failures. Return a fixed public message and log the internal error server-side.

🔧 Suggested patch
 	detail, err := h.searchSvc.GetSearchShareDetail(user.ID, searchID)
 	if err != nil {
 		switch err.Error() {
 		case "has no permission for this operation":
 			jsonError(c, common.CodeOperatingError, "Has no permission for this operation.")
 		case "can't find this Search App!":
 			jsonError(c, common.CodeDataError, "Can't find this Search App!")
 		default:
-			jsonError(c, common.CodeServerError, err.Error())
+			common.Warn("searchbot detail failed", zap.Error(err))
+			jsonError(c, common.CodeServerError, "Internal server error")
 		}
 		return
 	}
📝 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
detail, err := h.searchSvc.GetSearchShareDetail(user.ID, searchID)
if err != nil {
switch err.Error() {
case "has no permission for this operation":
jsonError(c, common.CodeOperatingError, "Has no permission for this operation.")
case "can't find this Search App!":
jsonError(c, common.CodeDataError, "Can't find this Search App!")
default:
jsonError(c, common.CodeServerError, err.Error())
}
detail, err := h.searchSvc.GetSearchShareDetail(user.ID, searchID)
if err != nil {
switch err.Error() {
case "has no permission for this operation":
jsonError(c, common.CodeOperatingError, "Has no permission for this operation.")
case "can't find this Search App!":
jsonError(c, common.CodeDataError, "Can't find this Search App!")
default:
common.Warn("searchbot detail failed", zap.Error(err))
jsonError(c, common.CodeServerError, "Internal server error")
}
return
}
🤖 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/searchbot.go` around lines 424 - 433, The default case in
the error handling for the GetSearchShareDetail call in the searchbot.go handler
is exposing internal error details directly to clients by passing err.Error() to
the jsonError function. Replace the default case to return a generic public
error message (such as "An error occurred" or similar) to the client, and
instead log the actual error details server-side using an appropriate logger to
maintain debuggability while preventing information disclosure of backend
internals.

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.

@Hz-186 Please check this.

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.

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

Copy link
Copy Markdown
Contributor Author

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

Do not expose internal error text in public responses.

The default branch returns err.Error() directly to clients, which can leak backend internals from DAO/service failures. Return a fixed public message and log the internal error server-side.
🔧 Suggested patch

📝 Committable suggestion

🤖 Prompt for AI Agents

fixed

Comment thread internal/service/user.go Outdated
Comment on lines +1076 to +1089
parts := strings.Split(authorization, " ")
var token string
if len(parts) == 2 {
token = parts[1]
} else if len(parts) == 1 {
token = parts[0]
} else {
return nil, common.CodeUnauthorized, fmt.Errorf("invalid authorization format")
}

apiTokenDAO := dao.NewAPITokenDAO()
userToken, err := apiTokenDAO.GetByBeta(token)
if err != nil {
return nil, common.CodeUnauthorized, fmt.Errorf("invalid beta access token")

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

Reject empty/whitespace beta tokens before DAO lookup.

The current parser can pass an empty token (for example, "Bearer "), then query GetByBeta(""). Enforce non-empty token extraction and robust splitting before the DB call.

🔧 Suggested fix
-	parts := strings.Split(authorization, " ")
+	parts := strings.Fields(authorization)
 	var token string
-	if len(parts) == 2 {
-		token = parts[1]
+	if len(parts) == 2 {
+		if !strings.EqualFold(parts[0], "Bearer") {
+			return nil, common.CodeUnauthorized, fmt.Errorf("invalid authorization format")
+		}
+		token = parts[1]
 	} else if len(parts) == 1 {
 		token = parts[0]
 	} else {
 		return nil, common.CodeUnauthorized, fmt.Errorf("invalid authorization format")
 	}
+	if strings.TrimSpace(token) == "" {
+		return nil, common.CodeUnauthorized, fmt.Errorf("authorization token is empty")
+	}
📝 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
parts := strings.Split(authorization, " ")
var token string
if len(parts) == 2 {
token = parts[1]
} else if len(parts) == 1 {
token = parts[0]
} else {
return nil, common.CodeUnauthorized, fmt.Errorf("invalid authorization format")
}
apiTokenDAO := dao.NewAPITokenDAO()
userToken, err := apiTokenDAO.GetByBeta(token)
if err != nil {
return nil, common.CodeUnauthorized, fmt.Errorf("invalid beta access token")
parts := strings.Fields(authorization)
var token string
if len(parts) == 2 {
if !strings.EqualFold(parts[0], "Bearer") {
return nil, common.CodeUnauthorized, fmt.Errorf("invalid authorization format")
}
token = parts[1]
} else if len(parts) == 1 {
token = parts[0]
} else {
return nil, common.CodeUnauthorized, fmt.Errorf("invalid authorization format")
}
if strings.TrimSpace(token) == "" {
return nil, common.CodeUnauthorized, fmt.Errorf("authorization token is empty")
}
apiTokenDAO := dao.NewAPITokenDAO()
userToken, err := apiTokenDAO.GetByBeta(token)
if err != nil {
return nil, common.CodeUnauthorized, fmt.Errorf("invalid beta access token")
🤖 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/user.go` around lines 1076 - 1089, The token extraction
logic can accept empty or whitespace-only tokens, which then gets passed to
apiTokenDAO.GetByBeta(). After extracting the token from the authorization
string split, add validation to check that the token is not empty or contains
only whitespace before calling apiTokenDAO.GetByBeta(). If the token is empty or
blank, return an unauthorized error without making the DAO call to avoid
unnecessary database lookups.

@codecov

codecov Bot commented Jun 18, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (a70c7e8) to head (6900583).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #16124   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  Misses         29       29           
  Partials       20       20           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@xugangqiang

Copy link
Copy Markdown
Contributor

LGTM

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

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants