fix: make Kiro auth fallback safe and document Claude limits

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
RCD
2026-05-11 07:51:59 +00:00
co-authored by Copilot
parent 18d9369ce4
commit 3636be31d6
12 changed files with 127 additions and 167 deletions
+2 -2
View File
@@ -1,6 +1,6 @@
# Binaries
cli-proxy-api
cliproxy
/cli-proxy-api
/cliproxy
proxypilot-linux
proxypilot-darwin
proxypilot-windows
+4 -2
View File
@@ -107,8 +107,8 @@ Run OAuth login for your provider:
./proxypilot --claude-login # Claude
./proxypilot --codex-login # OpenAI/Codex
./proxypilot --login # Gemini
./proxypilot --kiro-login # Kiro (Google OAuth)
./proxypilot --kiro-aws-login # Kiro (AWS Builder ID)
./proxypilot --kiro-login # Kiro (AWS Builder ID)
./proxypilot --kiro-aws-login # Kiro (AWS Builder ID device code)
./proxypilot --qwen-login # Qwen
./proxypilot --antigravity-login # Antigravity
@@ -122,6 +122,8 @@ Run OAuth login for your provider:
OAuth tokens are stored locally and auto-refreshed before expiry.
Kiro Google/GitHub OAuth is not currently supported because AWS Cognito rejects third-party localhost callbacks. Use AWS Builder ID (`--kiro-login` / `--kiro-aws-login`) or import from the official Kiro IDE.
### Security Defaults (Auth + CORS)
- Proxy requests require API keys by default. To allow unauthenticated access (not recommended), set `allow-unauthenticated: true` in `config.yaml`.
+2 -2
View File
@@ -163,8 +163,8 @@ func main() {
flag.BoolVar(&noIncognito, "no-incognito", false, "Force disable incognito mode (uses existing browser session)")
flag.IntVar(&oauthCallbackPort, "oauth-callback-port", 0, "Override OAuth callback port (defaults to provider-specific port)")
flag.BoolVar(&antigravityLogin, "antigravity-login", false, "Login to Antigravity using OAuth")
flag.BoolVar(&kiroLogin, "kiro-login", false, "Login to Kiro using Google OAuth")
flag.BoolVar(&kiroGoogleLogin, "kiro-google-login", false, "Login to Kiro using Google OAuth (same as --kiro-login)")
flag.BoolVar(&kiroLogin, "kiro-login", false, "Login to Kiro using AWS Builder ID")
flag.BoolVar(&kiroGoogleLogin, "kiro-google-login", false, "Show Kiro Google OAuth limitation and supported alternatives")
flag.BoolVar(&kiroAWSLogin, "kiro-aws-login", false, "Login to Kiro using AWS Builder ID (device code flow)")
flag.BoolVar(&kiroAWSAuthCode, "kiro-aws-authcode", false, "Login to Kiro using AWS Builder ID (authorization code flow, better UX)")
flag.BoolVar(&kiroImport, "kiro-import", false, "Import Kiro token from Kiro IDE (~/.aws/sso/cache/kiro-auth-token.json)")
+13
View File
@@ -32,6 +32,19 @@ Important:
- Avoid Claude Code “Auth conflict”: do **not** set both `ANTHROPIC_AUTH_TOKEN` and `ANTHROPIC_API_KEY` at the same time.
- Restart Claude Code after editing settings so the new env vars take effect.
## Claude OAuth quota limitation
Anthropic currently treats third-party app traffic differently from regular Claude.ai or Claude Code subscription usage. If a Claude OAuth request fails with:
```text
Third-party apps now draw from your extra usage, not your plan limits.
Add more at claude.ai/settings/usage and keep going.
```
that response is coming from Anthropic, not ProxyPilot. It means the OAuth credential is valid, but Anthropic is requiring paid extra usage for this third-party API path. ProxyPilot cannot make those requests draw from normal Claude.ai subscription quota.
For Claude through ProxyPilot, either add extra usage in Anthropic settings, use a supported API-key billing path, or route the client to another provider/model alias such as Antigravity, Codex, Gemini, or Kiro.
## Server-side model aliasing (Claude handler)
CLIProxyAPI rewrites common Claude Code model aliases to locally-available models before routing:
+6 -4
View File
@@ -57,12 +57,14 @@ proxypilot --codex-login # Login to Codex using OAuth
proxypilot --claude-login # Login to Claude using OAuth
proxypilot --qwen-login # Login to Qwen using OAuth
proxypilot --antigravity-login # Login to Antigravity using OAuth
proxypilot --kiro-login # Login to Kiro using Google OAuth
proxypilot --kiro-aws-login # Login to Kiro using AWS Builder ID
proxypilot --kiro-login # Login to Kiro using AWS Builder ID
proxypilot --kiro-aws-login # Login to Kiro using AWS Builder ID device code
proxypilot --minimax-login # Add MiniMax API key
proxypilot --zhipu-login # Add Zhipu AI API key
```
Kiro Google/GitHub OAuth is not currently supported because AWS Cognito rejects third-party localhost callbacks. Use AWS Builder ID or import a token from the official Kiro IDE instead.
### Login Options
```bash
@@ -309,8 +311,8 @@ proxypilot --codex-login # Codex OAuth
proxypilot --claude-login # Claude OAuth
proxypilot --qwen-login # Qwen OAuth
proxypilot --antigravity-login # Antigravity OAuth
proxypilot --kiro-login # Kiro Google OAuth
proxypilot --kiro-aws-login # Kiro AWS Builder ID
proxypilot --kiro-login # Kiro AWS Builder ID
proxypilot --kiro-aws-login # Kiro AWS Builder ID device code
# Agent Detection & Setup
proxypilot --detect-agents # Detect installed agents
+9 -44
View File
@@ -9,63 +9,28 @@ import (
log "github.com/sirupsen/logrus"
)
// DoKiroLogin triggers the Kiro authentication flow with Google OAuth.
// This is the default login method (same as --kiro-google-login).
// DoKiroLogin triggers the Kiro authentication flow with AWS Builder ID.
//
// Parameters:
// - cfg: The application configuration
// - options: Login options including Prompt field
func DoKiroLogin(cfg *config.Config, options *LoginOptions) {
// Use Google login as default
DoKiroGoogleLogin(cfg, options)
DoKiroAWSLogin(cfg, options)
}
// DoKiroGoogleLogin triggers Kiro authentication with Google OAuth.
// This uses a custom protocol handler (kiro://) to receive the callback.
//
// Parameters:
// - cfg: The application configuration
// - options: Login options including prompts
func DoKiroGoogleLogin(cfg *config.Config, options *LoginOptions) {
if options == nil {
options = &LoginOptions{}
}
// Note: Kiro defaults to incognito mode for multi-account support.
// Users can override with --no-incognito if they want to use existing browser sessions.
manager := newAuthManager()
// Use KiroAuthenticator with Google login
authenticator := sdkAuth.NewKiroAuthenticator()
record, err := authenticator.LoginWithGoogle(context.Background(), cfg, &sdkAuth.LoginOptions{
NoBrowser: options.NoBrowser,
Metadata: map[string]string{},
Prompt: options.Prompt,
})
if err != nil {
log.Errorf("Kiro Google authentication failed: %v", err)
fmt.Println("\nTroubleshooting:")
fmt.Println("1. Make sure the protocol handler is installed")
fmt.Println("2. Complete the Google login in the browser")
fmt.Println("3. If callback fails, try: --kiro-import (after logging in via Kiro IDE)")
return
}
// Save the auth record
savedPath, err := manager.SaveAuth(record, cfg)
if err != nil {
log.Errorf("Failed to save auth: %v", err)
return
}
if savedPath != "" {
fmt.Printf("Authentication saved to %s\n", savedPath)
}
if record != nil && record.Label != "" {
fmt.Printf("Authenticated as %s\n", record.Label)
}
fmt.Println("Kiro Google authentication successful!")
log.Warn("Kiro Google OAuth is disabled because AWS Cognito rejects third-party localhost callbacks")
fmt.Println("\nKiro Google login is not currently supported by ProxyPilot.")
fmt.Println("AWS Cognito rejects ProxyPilot's localhost redirect URI with redirect_mismatch.")
fmt.Println("\nUse one of these supported alternatives:")
fmt.Println("1. --kiro-aws-login for AWS Builder ID device authorization")
fmt.Println("2. --kiro-aws-authcode for AWS Builder ID browser callback")
fmt.Println("3. --kiro-import after signing in with the official Kiro IDE")
}
// DoKiroAWSLogin triggers Kiro authentication with AWS Builder ID.
+13
View File
@@ -179,6 +179,7 @@ func fetchModelsFromRemote(ctx context.Context) (*staticModelsJSON, string) {
log.Warnf("models parse failed from %s: %v", url, err)
continue
}
mergeMissingForkModelSections(&parsed, getModels())
if err := validateModelsCatalog(&parsed); err != nil {
log.Warnf("models validate failed from %s: %v", url, err)
continue
@@ -349,6 +350,18 @@ func validateModelsCatalog(data *staticModelsJSON) error {
return nil
}
func mergeMissingForkModelSections(data, fallback *staticModelsJSON) {
if data == nil || fallback == nil {
return
}
if len(data.Qwen) == 0 {
data.Qwen = cloneModelInfos(fallback.Qwen)
}
if len(data.IFlow) == 0 {
data.IFlow = cloneModelInfos(fallback.IFlow)
}
}
func validateModelSection(section string, models []*ModelInfo) error {
if len(models) == 0 {
return fmt.Errorf("%s section is empty", section)
+35
View File
@@ -0,0 +1,35 @@
package registry
import "testing"
func TestMergeMissingForkModelSectionsPreservesQwenAndIFlow(t *testing.T) {
data := &staticModelsJSON{
Claude: []*ModelInfo{{ID: "claude-1"}},
Gemini: []*ModelInfo{{ID: "gemini-1"}},
Vertex: []*ModelInfo{{ID: "vertex-1"}},
GeminiCLI: []*ModelInfo{{ID: "gemini-cli-1"}},
AIStudio: []*ModelInfo{{ID: "aistudio-1"}},
CodexFree: []*ModelInfo{{ID: "codex-free-1"}},
CodexTeam: []*ModelInfo{{ID: "codex-team-1"}},
CodexPlus: []*ModelInfo{{ID: "codex-plus-1"}},
CodexPro: []*ModelInfo{{ID: "codex-pro-1"}},
Kimi: []*ModelInfo{{ID: "kimi-1"}},
Antigravity: []*ModelInfo{{ID: "antigravity-1"}},
}
fallback := &staticModelsJSON{
Qwen: []*ModelInfo{{ID: "qwen-fallback"}},
IFlow: []*ModelInfo{{ID: "iflow-fallback"}},
}
mergeMissingForkModelSections(data, fallback)
if err := validateModelsCatalog(data); err != nil {
t.Fatalf("expected merged catalog to validate: %v", err)
}
if got := data.Qwen[0].ID; got != "qwen-fallback" {
t.Fatalf("expected qwen fallback model, got %q", got)
}
if got := data.IFlow[0].ID; got != "iflow-fallback" {
t.Fatalf("expected iflow fallback model, got %q", got)
}
}
+6 -3
View File
@@ -519,7 +519,7 @@ func (e *KiroExecutor) executeWithRetry(ctx context.Context, auth *cliproxyauth.
// ExecuteStream handles streaming requests to Kiro API.
// Supports automatic token refresh on 401/403 errors and quota fallback on 429.
func (e *KiroExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (stream <-chan cliproxyexecutor.StreamChunk, err error) {
func (e *KiroExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (_ *cliproxyexecutor.StreamResult, err error) {
accessToken, profileArn := kiroCredentials(auth)
if accessToken == "" {
return nil, fmt.Errorf("kiro: access token not found in auth")
@@ -586,7 +586,7 @@ func (e *KiroExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Aut
}
// executeStreamWithRetry performs the streaming HTTP request with automatic retry on auth errors.
func (e *KiroExecutor) executeStreamWithRetry(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options, accessToken, profileArn string, kiroPayload, body []byte, from sdktranslator.Format, reporter *usageReporter, currentOrigin, kiroModelID string, isAgentic, isChatOnly bool, tokenKey string) (<-chan cliproxyexecutor.StreamChunk, error) {
func (e *KiroExecutor) executeStreamWithRetry(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options, accessToken, profileArn string, kiroPayload, body []byte, from sdktranslator.Format, reporter *usageReporter, currentOrigin, kiroModelID string, isAgentic, isChatOnly bool, tokenKey string) (*cliproxyexecutor.StreamResult, error) {
maxRetries := 2
rateLimiter := kiroauth.GetGlobalRateLimiter()
cooldownMgr := kiroauth.GetGlobalCooldownManager()
@@ -831,7 +831,10 @@ func (e *KiroExecutor) executeStreamWithRetry(ctx context.Context, auth *cliprox
e.streamToChannel(ctx, resp.Body, out, from, req.Model, opts.OriginalRequest, body, reporter, thinkingEnabled)
}(httpResp, thinkingEnabled)
return out, nil
return &cliproxyexecutor.StreamResult{
Headers: httpResp.Header.Clone(),
Chunks: out,
}, nil
}
}
+2 -110
View File
@@ -222,61 +222,7 @@ func (a *KiroAuthenticator) LoginWithGoogle(ctx context.Context, cfg *config.Con
if cfg == nil {
return nil, fmt.Errorf("kiro auth: configuration is required")
}
oauth := kiroauth.NewKiroOAuth(cfg)
// Use Google OAuth flow with protocol handler
tokenData, err := oauth.LoginWithGoogle(ctx)
if err != nil {
return nil, fmt.Errorf("google login failed: %w", err)
}
// Parse expires_at
expiresAt, err := time.Parse(time.RFC3339, tokenData.ExpiresAt)
if err != nil {
expiresAt = time.Now().Add(1 * time.Hour)
}
// Extract identifier for file naming
idPart := extractKiroIdentifier(tokenData.Email, tokenData.ProfileArn)
now := time.Now()
fileName := fmt.Sprintf("kiro-google-%s.json", idPart)
record := &coreauth.Auth{
ID: fileName,
Provider: "kiro",
FileName: fileName,
Label: "kiro-google",
Status: coreauth.StatusActive,
CreatedAt: now,
UpdatedAt: now,
Metadata: map[string]any{
"type": "kiro",
"access_token": tokenData.AccessToken,
"refresh_token": tokenData.RefreshToken,
"profile_arn": tokenData.ProfileArn,
"expires_at": tokenData.ExpiresAt,
"auth_method": tokenData.AuthMethod,
"provider": tokenData.Provider,
"email": tokenData.Email,
},
Attributes: map[string]string{
"profile_arn": tokenData.ProfileArn,
"source": "google-oauth",
"email": tokenData.Email,
},
// NextRefreshAfter is aligned with RefreshLead (5min)
NextRefreshAfter: expiresAt.Add(-5 * time.Minute),
}
if tokenData.Email != "" {
fmt.Printf("\n✓ Kiro Google authentication completed successfully! (Account: %s)\n", tokenData.Email)
} else {
fmt.Println("\n✓ Kiro Google authentication completed successfully!")
}
return record, nil
return nil, fmt.Errorf("kiro google login is not supported: AWS Cognito rejects third-party localhost callbacks; use AWS Builder ID or import from Kiro IDE")
}
// LoginWithGitHub performs OAuth login for Kiro with GitHub.
@@ -285,61 +231,7 @@ func (a *KiroAuthenticator) LoginWithGitHub(ctx context.Context, cfg *config.Con
if cfg == nil {
return nil, fmt.Errorf("kiro auth: configuration is required")
}
oauth := kiroauth.NewKiroOAuth(cfg)
// Use GitHub OAuth flow with protocol handler
tokenData, err := oauth.LoginWithGitHub(ctx)
if err != nil {
return nil, fmt.Errorf("github login failed: %w", err)
}
// Parse expires_at
expiresAt, err := time.Parse(time.RFC3339, tokenData.ExpiresAt)
if err != nil {
expiresAt = time.Now().Add(1 * time.Hour)
}
// Extract identifier for file naming
idPart := extractKiroIdentifier(tokenData.Email, tokenData.ProfileArn)
now := time.Now()
fileName := fmt.Sprintf("kiro-github-%s.json", idPart)
record := &coreauth.Auth{
ID: fileName,
Provider: "kiro",
FileName: fileName,
Label: "kiro-github",
Status: coreauth.StatusActive,
CreatedAt: now,
UpdatedAt: now,
Metadata: map[string]any{
"type": "kiro",
"access_token": tokenData.AccessToken,
"refresh_token": tokenData.RefreshToken,
"profile_arn": tokenData.ProfileArn,
"expires_at": tokenData.ExpiresAt,
"auth_method": tokenData.AuthMethod,
"provider": tokenData.Provider,
"email": tokenData.Email,
},
Attributes: map[string]string{
"profile_arn": tokenData.ProfileArn,
"source": "github-oauth",
"email": tokenData.Email,
},
// NextRefreshAfter is aligned with RefreshLead (5min)
NextRefreshAfter: expiresAt.Add(-5 * time.Minute),
}
if tokenData.Email != "" {
fmt.Printf("\n✓ Kiro GitHub authentication completed successfully! (Account: %s)\n", tokenData.Email)
} else {
fmt.Println("\n✓ Kiro GitHub authentication completed successfully!")
}
return record, nil
return nil, fmt.Errorf("kiro github login is not supported: AWS Cognito rejects third-party localhost callbacks; use AWS Builder ID or import from Kiro IDE")
}
// ImportFromKiroIDE imports token from Kiro IDE's token file.
+5
View File
@@ -429,6 +429,8 @@ func (s *Service) ensureExecutorsForAuthWithMode(a *coreauth.Auth, forceReplace
s.coreManager.RegisterExecutor(executor.NewAntigravityExecutor(s.cfg))
case "claude":
s.coreManager.RegisterExecutor(executor.NewClaudeExecutor(s.cfg))
case "kiro":
s.coreManager.RegisterExecutor(executor.NewKiroExecutor(s.cfg))
case "kimi":
s.coreManager.RegisterExecutor(executor.NewKimiExecutor(s.cfg))
default:
@@ -1101,6 +1103,9 @@ func (s *Service) registerModelsForAuth(a *coreauth.Auth) {
}
}
models = applyExcludedModels(models, excluded)
case "kiro":
models = registry.GetKiroModels()
models = applyExcludedModels(models, excluded)
case "codex":
codexPlanType := ""
if a.Attributes != nil {
+30
View File
@@ -0,0 +1,30 @@
package cliproxy
import (
"testing"
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
"github.com/router-for-me/CLIProxyAPI/v7/sdk/config"
)
func TestRegisterModelsForAuth_KiroRegistersStaticModels(t *testing.T) {
service := &Service{cfg: &config.Config{}}
auth := &coreauth.Auth{
ID: "auth-kiro",
Provider: "kiro",
Status: coreauth.StatusActive,
}
registry := GlobalModelRegistry()
registry.UnregisterClient(auth.ID)
t.Cleanup(func() {
registry.UnregisterClient(auth.ID)
})
service.registerModelsForAuth(auth)
models := registry.GetAvailableModelsByProvider("kiro")
if len(models) == 0 {
t.Fatal("expected kiro models to be registered")
}
}