Skip to content

feat[Go] implement /connectors/google/oauth - #15584

Merged
JinHai-CN merged 1 commit into
infiniflow:mainfrom
Haruko386:main
Jun 3, 2026
Merged

JinHai-CN merged 1 commit into
infiniflow:mainfrom
Haruko386:main

Conversation

@Haruko386

Copy link
Copy Markdown
Member

What problem does this PR solve?

The following API is available in go

/api/v1/connectors/google/oauth/web/start POST
/api/v1/connectors/gmail/oauth/web/callback GET
/api/v1/connectors/google-drive/oauth/web/callback GET
/api/v1/connectors/google/oauth/web/result POST

Verified from Ragflow Page

image

Type of change

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

@Haruko386 Haruko386 added the ci Continue Integration label Jun 3, 2026
@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label Jun 3, 2026
@coderabbitai

coderabbitai Bot commented Jun 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds complete Google Web OAuth support to the connector system, enabling browser-based authorization of Google Drive and Gmail connectors. It introduces OAuth service methods, HTTP handlers, route registration, and validation tests to implement a PKCE-based OAuth flow with Redis state management.

Changes

Google Web OAuth Feature

Layer / File(s) Summary
Service OAuth contracts and core flow logic
internal/service/connector.go
New request/response types and service methods for starting OAuth flows with PKCE state storage, handling OAuth callbacks to exchange authorization codes for tokens via Google's endpoint, and polling Redis for stored credentials. Constants and imports support the OAuth flow operations.
Service OAuth helpers and token exchange
internal/service/connector.go
Helper functions for PKCE challenge generation, Google authorization URL construction, HTTP token exchange with error mapping, credential JSON loading, Redis cache key generation, and HTML popup rendering with postMessage integration.
HTTP handler layer and interface contract
internal/handler/connector.go, internal/handler/connector_test.go
Service interface extended with OAuth method signatures; five HTTP handlers bind JSON requests and query parameters, delegate to service methods, and return JSON or HTML responses; test double stubs support handler compilation and testing.
Route registration and conflict validation
internal/router/router.go, internal/router/router_test.go
Register OAuth callback routes (/connectors/{gmail,google-drive}/oauth/web/callback) at top-level and API v1; add authorized POST routes for starting and polling OAuth flows; test validates callback and detail route patterns do not conflict.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • infiniflow/ragflow#15274: Changes to connectorServiceIface and ConnectorHandler integration in the same handler/service files.

Suggested labels

size:XL, 💞 feature

Poem

🐰 A rabbit hops through OAuth flows,
PKCE codes and tokens glows,
Google Drive and Gmail too,
Redis holds the pending queue.
Web-based auth, now clean and bright!

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The description is incomplete. While it lists the implemented API endpoints and includes a screenshot verification, it lacks detailed context about the problem being solved, implementation approach, or technical details needed for code review. Expand the description to explain why these OAuth endpoints are needed, how they integrate with the broader system, and any relevant implementation notes for reviewers.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main feature being implemented: adding Google OAuth endpoints for connectors in Go, which aligns with the changes across handler, router, and service files.
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 marked this pull request as draft June 3, 2026 09:54
@Haruko386
Haruko386 marked this pull request as ready for review June 3, 2026 09:54

@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 (2)
internal/router/router_test.go (1)

14-28: ⚡ Quick win

Exercise Router.Setup here instead of a hand-built mini router.

This test currently proves Gin can disambiguate these patterns, but it does not verify the routes added in internal/router/router.go. It would still pass if Setup registered the callback paths under the wrong group or dropped one of them entirely. Reusing the real setup would make the regression coverage match the production wiring.

🤖 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/router/router_test.go` around lines 14 - 28, Replace the hand-built
Gin routes in router_test.go with the actual router setup by calling
Router.Setup (the production wiring) so the test asserts real route
registration; locate the test's local engine creation and route handlers and
instead instantiate the Router from internal/router/router.go (or call its Setup
method) to register routes onto the test Gin engine, then run the same
requests/assertions against that engine to ensure the callback and connectors
routes are added exactly as in production.
internal/handler/connector_test.go (1)

55-71: ⚡ Quick win

Add handler tests for the new OAuth endpoints, not just fake-service stubs.

These methods make the interface compile, but there is still no coverage for /connectors/google/oauth/web/start, /connectors/google/oauth/web/result, or the callback HTML response. A couple of table-driven tests here would catch regressions in type query propagation, JSON binding, and the text/html callback contract.

🤖 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/connector_test.go` around lines 55 - 71, Add proper handler
tests for the new Google OAuth endpoints instead of only providing
fakeConnectorService stubs: create table-driven tests in
internal/handler/connector_test.go that exercise the HTTP handlers for
/connectors/google/oauth/web/start, /connectors/google/oauth/web/result and the
callback HTML response by wiring the real handler functions (the ones that call
StartGoogleWebOAuth, PollGoogleWebOAuthResult and GoogleWebOAuthCallback) to an
HTTP test server; assert that the "type" query parameter is propagated into the
service request, that JSON request/response binding for the start/result
endpoints succeeds/fails as expected, and that the callback returns Content-Type
text/html with the expected body; use the existing fakeConnectorService (methods
StartGoogleWebOAuth, PollGoogleWebOAuthResult, GoogleWebOAuthCallback) to
simulate success and error cases in the table entries.
🤖 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/connector.go`:
- Around line 376-388: The code currently trusts user-supplied
web.auth_uri/web.token_uri from getGoogleWebClientConfig which enables SSRF;
update the logic in the Google client init (where webConfig, clientID, authURI
are read) to ignore or validate those fields and always use known Google
endpoints (e.g., googleOAuthAuthorizeURL and googleOAuthTokenURL) unless the
provided URIs exactly match a whitelist of official Google OAuth endpoints; also
apply the same check in exchangeGoogleWebOAuthCode where token_uri is used so
the POST is only sent to the whitelisted Google token endpoint. Ensure you
reference webConfig["auth_uri"], webConfig["token_uri"],
getGoogleWebClientConfig and exchangeGoogleWebOAuthCode when making the change
and return a clear error if the uploaded config contains non-whitelisted
endpoints.
- Around line 516-520: The function defaultGoogleWebOAuthRedirectURI currently
falls back to hard-coded localhost values via getenvDefault which causes
incorrect redirect URIs in non-local deployments; change it to require explicit
config by removing the localhost defaults and fetching the env vars without
defaults (e.g., use getenv or getenvOrEmpty) for GMAIL_WEB_OAUTH_REDIRECT_URI
and GOOGLE_DRIVE_WEB_OAUTH_REDIRECT_URI, and update the function signature
(defaultGoogleWebOAuthRedirectURI) to return (string, error) or accept a
request-derived baseURL so callers can fail fast when the env var is missing
(return an error) instead of returning a localhost URI; ensure callers handle
the error and derive the public base URL from the request layer if dynamic
resolution is needed.

---

Nitpick comments:
In `@internal/handler/connector_test.go`:
- Around line 55-71: Add proper handler tests for the new Google OAuth endpoints
instead of only providing fakeConnectorService stubs: create table-driven tests
in internal/handler/connector_test.go that exercise the HTTP handlers for
/connectors/google/oauth/web/start, /connectors/google/oauth/web/result and the
callback HTML response by wiring the real handler functions (the ones that call
StartGoogleWebOAuth, PollGoogleWebOAuthResult and GoogleWebOAuthCallback) to an
HTTP test server; assert that the "type" query parameter is propagated into the
service request, that JSON request/response binding for the start/result
endpoints succeeds/fails as expected, and that the callback returns Content-Type
text/html with the expected body; use the existing fakeConnectorService (methods
StartGoogleWebOAuth, PollGoogleWebOAuthResult, GoogleWebOAuthCallback) to
simulate success and error cases in the table entries.

In `@internal/router/router_test.go`:
- Around line 14-28: Replace the hand-built Gin routes in router_test.go with
the actual router setup by calling Router.Setup (the production wiring) so the
test asserts real route registration; locate the test's local engine creation
and route handlers and instead instantiate the Router from
internal/router/router.go (or call its Setup method) to register routes onto the
test Gin engine, then run the same requests/assertions against that engine to
ensure the callback and connectors routes are added exactly as in production.
🪄 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: 4729b7bd-0d24-433c-91d9-8e33ee3624c6

📥 Commits

Reviewing files that changed from the base of the PR and between 2061edd and a425ce4.

📒 Files selected for processing (5)
  • internal/handler/connector.go
  • internal/handler/connector_test.go
  • internal/router/router.go
  • internal/router/router_test.go
  • internal/service/connector.go

Comment on lines +376 to +388
clientConfig, err := getGoogleWebClientConfig(credentials)
if err != nil {
return nil, common.CodeArgumentError, err
}

webConfig, _ := clientConfig["web"].(map[string]interface{})
clientID := strings.TrimSpace(stringValue(webConfig["client_id"]))
authURI := strings.TrimSpace(stringValue(webConfig["auth_uri"]))
if authURI == "" {
authURI = googleOAuthAuthorizeURL
}
if clientID == "" || authURI == "" {
return nil, common.CodeServerError, fmt.Errorf("Failed to initialize Google OAuth flow. Please verify the uploaded client configuration.")

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 | 🔴 Critical | ⚡ Quick win

Pin the OAuth endpoints to Google instead of trusting uploaded URIs.

web.auth_uri and web.token_uri come from user-supplied JSON here, and exchangeGoogleWebOAuthCode later POSTs to that token_uri. That lets any authenticated user turn this Google-only flow into an SSRF primitive against arbitrary hosts. For this feature, ignore those fields or strictly whitelist Google's OAuth endpoints before storing the config.

🤖 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/connector.go` around lines 376 - 388, The code currently
trusts user-supplied web.auth_uri/web.token_uri from getGoogleWebClientConfig
which enables SSRF; update the logic in the Google client init (where webConfig,
clientID, authURI are read) to ignore or validate those fields and always use
known Google endpoints (e.g., googleOAuthAuthorizeURL and googleOAuthTokenURL)
unless the provided URIs exactly match a whitelist of official Google OAuth
endpoints; also apply the same check in exchangeGoogleWebOAuthCode where
token_uri is used so the POST is only sent to the whitelisted Google token
endpoint. Ensure you reference webConfig["auth_uri"], webConfig["token_uri"],
getGoogleWebClientConfig and exchangeGoogleWebOAuthCode when making the change
and return a clear error if the uploaded config contains non-whitelisted
endpoints.

Comment on lines +516 to +520
func defaultGoogleWebOAuthRedirectURI(source string) string {
if source == "gmail" {
return getenvDefault("GMAIL_WEB_OAUTH_REDIRECT_URI", "http://localhost:9384/api/v1/connectors/gmail/oauth/web/callback")
}
return getenvDefault("GOOGLE_DRIVE_WEB_OAUTH_REDIRECT_URI", "http://localhost:9384/api/v1/connectors/google-drive/oauth/web/callback")

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 silently fall back to localhost for redirect URIs.

If the env vars are missing in any non-local deployment, the start endpoint will hand Google a callback like http://localhost:9384/..., so the user finishes consent but Google redirects to their own machine and the flow never completes. Fail fast when the redirect URI is not configured, or derive the public base URL from the request layer instead of hard-coding localhost.

Suggested fix
 func defaultGoogleWebOAuthRedirectURI(source string) string {
 	if source == "gmail" {
-		return getenvDefault("GMAIL_WEB_OAUTH_REDIRECT_URI", "http://localhost:9384/api/v1/connectors/gmail/oauth/web/callback")
+		return strings.TrimSpace(os.Getenv("GMAIL_WEB_OAUTH_REDIRECT_URI"))
 	}
-	return getenvDefault("GOOGLE_DRIVE_WEB_OAUTH_REDIRECT_URI", "http://localhost:9384/api/v1/connectors/google-drive/oauth/web/callback")
+	return strings.TrimSpace(os.Getenv("GOOGLE_DRIVE_WEB_OAUTH_REDIRECT_URI"))
 }
📝 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
func defaultGoogleWebOAuthRedirectURI(source string) string {
if source == "gmail" {
return getenvDefault("GMAIL_WEB_OAUTH_REDIRECT_URI", "http://localhost:9384/api/v1/connectors/gmail/oauth/web/callback")
}
return getenvDefault("GOOGLE_DRIVE_WEB_OAUTH_REDIRECT_URI", "http://localhost:9384/api/v1/connectors/google-drive/oauth/web/callback")
func defaultGoogleWebOAuthRedirectURI(source string) string {
if source == "gmail" {
return strings.TrimSpace(os.Getenv("GMAIL_WEB_OAUTH_REDIRECT_URI"))
}
return strings.TrimSpace(os.Getenv("GOOGLE_DRIVE_WEB_OAUTH_REDIRECT_URI"))
}
🤖 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/connector.go` around lines 516 - 520, The function
defaultGoogleWebOAuthRedirectURI currently falls back to hard-coded localhost
values via getenvDefault which causes incorrect redirect URIs in non-local
deployments; change it to require explicit config by removing the localhost
defaults and fetching the env vars without defaults (e.g., use getenv or
getenvOrEmpty) for GMAIL_WEB_OAUTH_REDIRECT_URI and
GOOGLE_DRIVE_WEB_OAUTH_REDIRECT_URI, and update the function signature
(defaultGoogleWebOAuthRedirectURI) to return (string, error) or accept a
request-derived baseURL so callers can fail fast when the env var is missing
(return an error) instead of returning a localhost URI; ensure callers handle
the error and derive the public base URL from the request layer if dynamic
resolution is needed.

@codecov

codecov Bot commented Jun 3, 2026

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15584   +/-   ##
=======================================
  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.

@JinHai-CN
JinHai-CN merged commit df55880 into infiniflow:main Jun 3, 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:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants