-
-
Notifications
You must be signed in to change notification settings - Fork 627
feat: harden oauth flows and providers #662
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
Summary of ChangesHello @jroth1111, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request significantly enhances the system's OAuth capabilities by introducing a standardized and robust framework for authentication flows. It unifies the implementation details for existing providers like Claude, Codex, Gemini, iFlow, and Qwen under new shared Highlights
🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console. Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Code Review
This pull request introduces a significant and well-executed refactoring of the OAuth authentication flows. By creating shared oauthflow and oauthhttp helpers, you've unified the authentication logic for various providers, which greatly improves maintainability and robustness. The addition of new providers like Copilot and Kiro is well-integrated into this new framework. The change from log.Fatalf to log.Errorf in handlers is a critical improvement for server stability. The introduction of a dedicated proxy path for OAuth requests and thread-safe handling of global state are also excellent hardening measures. My review includes one suggestion to improve a polling loop for efficiency, but overall, this is a high-quality contribution.
| for { | ||
| if time.Now().After(deadline) { | ||
| log.Error("oauth flow timed out") | ||
| setOAuthStatus(state, "OAuth flow timed out") | ||
| return | ||
| } | ||
| if data, errR := os.ReadFile(waitFile); errR == nil { | ||
| var m map[string]string | ||
| _ = json.Unmarshal(data, &m) | ||
| _ = os.Remove(waitFile) | ||
| if errStr := m["error"]; errStr != "" { | ||
| log.Errorf("Authentication failed: %s", errStr) | ||
| setOAuthStatus(state, "Authentication failed") | ||
| return | ||
| } | ||
| if m["state"] != state { | ||
| log.Errorf("State mismatch") | ||
| setOAuthStatus(state, "State mismatch") | ||
| return | ||
| } | ||
| code := m["code"] | ||
| if code == "" { | ||
| log.Error("No authorization code received") | ||
| setOAuthStatus(state, "No authorization code received") | ||
| return | ||
| } | ||
|
|
||
| // Exchange code for tokens | ||
| tokenReq := &kiroauth.CreateTokenRequest{ | ||
| Code: code, | ||
| CodeVerifier: codeVerifier, | ||
| RedirectURI: kiroauth.KiroRedirectURI, | ||
| } | ||
|
|
||
| tokenResp, errToken := socialClient.CreateToken(ctx, tokenReq) | ||
| if errToken != nil { | ||
| log.Errorf("Failed to exchange code for tokens: %v", errToken) | ||
| setOAuthStatus(state, "Failed to exchange code for tokens") | ||
| return | ||
| } | ||
|
|
||
| // Save the token | ||
| expiresIn := tokenResp.ExpiresIn | ||
| if expiresIn <= 0 { | ||
| expiresIn = 3600 | ||
| } | ||
| expiresAt := time.Now().Add(time.Duration(expiresIn) * time.Second) | ||
| email := kiroauth.ExtractEmailFromJWT(tokenResp.AccessToken) | ||
|
|
||
| idPart := kiroauth.SanitizeEmailForFilename(email) | ||
| if idPart == "" { | ||
| idPart = fmt.Sprintf("%d", time.Now().UnixNano()%100000) | ||
| } | ||
|
|
||
| now := time.Now() | ||
| fileName := fmt.Sprintf("kiro-%s-%s.json", strings.ToLower(provider), idPart) | ||
|
|
||
| record := &coreauth.Auth{ | ||
| ID: fileName, | ||
| Provider: "kiro", | ||
| FileName: fileName, | ||
| Metadata: map[string]any{ | ||
| "type": "kiro", | ||
| "access_token": tokenResp.AccessToken, | ||
| "refresh_token": tokenResp.RefreshToken, | ||
| "profile_arn": tokenResp.ProfileArn, | ||
| "expires_at": expiresAt.Format(time.RFC3339), | ||
| "auth_method": "social", | ||
| "provider": provider, | ||
| "email": email, | ||
| "last_refresh": now.Format(time.RFC3339), | ||
| }, | ||
| } | ||
|
|
||
| savedPath, errSave := h.saveTokenRecord(ctx, record) | ||
| if errSave != nil { | ||
| log.Errorf("Failed to save authentication tokens: %v", errSave) | ||
| setOAuthStatus(state, "Failed to save authentication tokens") | ||
| return | ||
| } | ||
|
|
||
| fmt.Printf("Authentication successful! Token saved to %s\n", savedPath) | ||
| if email != "" { | ||
| fmt.Printf("Authenticated as: %s\n", email) | ||
| } | ||
| deleteOAuthStatus(state) | ||
| return | ||
| } | ||
| time.Sleep(500 * time.Millisecond) | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This polling loop uses time.Sleep, which can be inefficient as it blocks the goroutine. For better resource usage and responsiveness to context cancellation, consider refactoring this to use a time.Ticker within a select block. This pattern is already used in the device code polling loop in the aws/builder-id case within this same function.
ticker := time.NewTicker(500 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
log.Error("oauth flow cancelled")
setOAuthStatus(state, "OAuth flow cancelled")
return
case <-ticker.C:
if time.Now().After(deadline) {
log.Error("oauth flow timed out")
setOAuthStatus(state, "OAuth flow timed out")
return
}
if data, errR := os.ReadFile(waitFile); errR == nil {
var m map[string]string
_ = json.Unmarshal(data, &m)
_ = os.Remove(waitFile)
if errStr := m["error"]; errStr != "" {
log.Errorf("Authentication failed: %s", errStr)
setOAuthStatus(state, "Authentication failed")
return
}
if m["state"] != state {
log.Errorf("State mismatch")
setOAuthStatus(state, "State mismatch")
return
}
code := m["code"]
if code == "" {
log.Error("No authorization code received")
setOAuthStatus(state, "No authorization code received")
return
}
// Exchange code for tokens
tokenReq := &kiroauth.CreateTokenRequest{
Code: code,
CodeVerifier: codeVerifier,
RedirectURI: kiroauth.KiroRedirectURI,
}
tokenResp, errToken := socialClient.CreateToken(ctx, tokenReq)
if errToken != nil {
log.Errorf("Failed to exchange code for tokens: %v", errToken)
setOAuthStatus(state, "Failed to exchange code for tokens")
return
}
// Save the token
expiresIn := tokenResp.ExpiresIn
if expiresIn <= 0 {
expiresIn = 3600
}
expiresAt := time.Now().Add(time.Duration(expiresIn) * time.Second)
email := kiroauth.ExtractEmailFromJWT(tokenResp.AccessToken)
idPart := kiroauth.SanitizeEmailForFilename(email)
if idPart == "" {
idPart = fmt.Sprintf("%d", time.Now().UnixNano()%100000)
}
now := time.Now()
fileName := fmt.Sprintf("kiro-%s-%s.json", strings.ToLower(provider), idPart)
record := &coreauth.Auth{
ID: fileName,
Provider: "kiro",
FileName: fileName,
Metadata: map[string]any{
"type": "kiro",
"access_token": tokenResp.AccessToken,
"refresh_token": tokenResp.RefreshToken,
"profile_arn": tokenResp.ProfileArn,
"expires_at": expiresAt.Format(time.RFC3339),
"auth_method": "social",
"provider": provider,
"email": email,
"last_refresh": now.Format(time.RFC3339),
},
}
savedPath, errSave := h.saveTokenRecord(ctx, record)
if errSave != nil {
log.Errorf("Failed to save authentication tokens: %v", errSave)
setOAuthStatus(state, "Failed to save authentication tokens")
return
}
fmt.Printf("Authentication successful! Token saved to %s\n", savedPath)
if email != "" {
fmt.Printf("Authenticated as: %s\n", email)
}
deleteOAuthStatus(state)
return
}
}
}|
Please clear the conflicts. |
53f0c6e to
bb1098a
Compare
|
Rebased on upstream/main and resolved conflicts. OAuth hardening changes are now on top of latest main. @luispater would you mind re-reviewing? |
|
Updated polling loops per review: switched OAuth callback waits to ticker+select (ctx cancel/timeout) across providers and made Gemini onboarding sleep ctx-aware. Ready for re-review. @luispater |
This project is not the Plus version. This project does not accept any pull requests related to third-party provider support. You should clean up the code pertaining to After that, please wait for this PR to be merged into |
|
Per your feedback, removed GitHub Copilot + Kiro provider support from CLIProxyAPI (auth packages, SDK auth, and management handler paths). Tests: ? github.com/router-for-me/CLIProxyAPI/v6/cmd/server [no test files] |
|
Follow-up ping: Copilot/Kiro removals are in; tests green. Ready for re-review when you have time. @luispater |
|
Also removed the last Copilot mention (comment in OpenAI->Claude stream handling). returns no matches now. @luispater |
|
Removed the internal/translator change to satisfy the translator-path-guard; opened issue #677 for maintainers to update that comment. OAuth hardening PR now avoids translator changes. All Gemini feedback (ticker+ctx cancellation) was already applied. Ready for re-review. |
5b1d4ff to
19cb819
Compare
|
@luispater rebase/conflict cleanup done; removed GitHub Copilot + Kiro support and avoided translator-path-guard changes. Ready for re-review. |
Summary
Motivation
Testing