Repository navigation
feat[Go] implement /connectors/google/oauth - #15584
Conversation
📝 WalkthroughWalkthroughThis 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. ChangesGoogle Web OAuth Feature
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 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: 2
🧹 Nitpick comments (2)
internal/router/router_test.go (1)
14-28: ⚡ Quick winExercise
Router.Setuphere 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 ifSetupregistered 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 winAdd 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 intypequery propagation, JSON binding, and thetext/htmlcallback 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
📒 Files selected for processing (5)
internal/handler/connector.gointernal/handler/connector_test.gointernal/router/router.gointernal/router/router_test.gointernal/service/connector.go
| 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.") |
There was a problem hiding this comment.
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.
| 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") |
There was a problem hiding this comment.
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.
| 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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
What problem does this PR solve?
The following API is available in go
Verified from Ragflow Page
Type of change