From 3e4cf30ee39873d12f05bc40fbfa12d3da92ce45 Mon Sep 17 00:00:00 2001 From: Finessse Date: Fri, 26 Dec 2025 00:53:29 +0700 Subject: [PATCH] feat(auth/kiro): add Kiro authentication module MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add complete Kiro authentication with dual OAuth support: - pkce.go: PKCE code generation for secure OAuth - errors.go: custom error types for auth failures - kiro.go: KiroTokenData and KiroAuthBundle structs - kiro_token.go: token storage with SaveTokenToFile - kiro_auth.go: AWS Builder ID device flow + Google OAuth 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- internal/auth/kiro/auth.go | 129 ------- internal/auth/kiro/errors.go | 192 ++++++++++ internal/auth/kiro/kiro.go | 45 +++ internal/auth/kiro/kiro_auth.go | 614 +++++++++++++++++++++++++++++++ internal/auth/kiro/kiro_token.go | 79 ++++ internal/auth/kiro/pkce.go | 52 +++ 6 files changed, 982 insertions(+), 129 deletions(-) delete mode 100644 internal/auth/kiro/auth.go create mode 100644 internal/auth/kiro/errors.go create mode 100644 internal/auth/kiro/kiro.go create mode 100644 internal/auth/kiro/kiro_auth.go create mode 100644 internal/auth/kiro/kiro_token.go create mode 100644 internal/auth/kiro/pkce.go diff --git a/internal/auth/kiro/auth.go b/internal/auth/kiro/auth.go deleted file mode 100644 index 422ad0a4..00000000 --- a/internal/auth/kiro/auth.go +++ /dev/null @@ -1,129 +0,0 @@ -package kiro - -import ( - "context" - "fmt" - "net/http" - "time" - - "github.com/router-for-me/CLIProxyAPI/v6/internal/browser" - "github.com/router-for-me/CLIProxyAPI/v6/internal/config" - "github.com/router-for-me/CLIProxyAPI/v6/internal/util" - "golang.org/x/oauth2" -) - -const ( - // Kiro uses a specific client ID for AWS Builder ID / CodeWhisperer integration (placeholder) - // In a real scenario, this would be the actual Client ID for Kiro. - kiroClientID = "kiro-client-id-placeholder" - kiroClientSecret = "kiro-client-secret-placeholder" - kiroAuthURL = "https://kiro.ai/auth" // Placeholder - kiroTokenURL = "https://kiro.ai/token" // Placeholder -) - -type KiroTokenStorage struct { - AccessToken string `json:"access_token"` - RefreshToken string `json:"refresh_token"` - Expiry string `json:"expiry"` - TokenType string `json:"token_type"` -} - -// SaveTokenToFile persists authentication tokens to the specified file path. -func (ts *KiroTokenStorage) SaveTokenToFile(authFilePath string) error { - // Logic to save token to file would go here if needed, - // but the core auth manager handles persistence via the Storage field - // being marshalled into the Auth struct. - // This method satisfies the TokenStorage interface. - return nil -} - -type KiroAuth struct{} - -func NewKiroAuth() *KiroAuth { - return &KiroAuth{} -} - -func (k *KiroAuth) GetAuthenticatedClient(ctx context.Context, ts *KiroTokenStorage, cfg *config.Config, noBrowser ...bool) (*http.Client, error) { - // Setup OAuth config - conf := &oauth2.Config{ - ClientID: kiroClientID, - ClientSecret: kiroClientSecret, - RedirectURL: "http://localhost:8086/oauth2callback", - Scopes: []string{"openid", "profile", "email"}, - Endpoint: oauth2.Endpoint{ - AuthURL: kiroAuthURL, - TokenURL: kiroTokenURL, - }, - } - - var token *oauth2.Token - var err error - - // If no token, start flow - if ts.AccessToken == "" { - fmt.Printf("Could not load Kiro token, starting OAuth flow.\n") - token, err = k.getTokenFromWeb(ctx, conf, noBrowser...) - if err != nil { - return nil, fmt.Errorf("failed to get token from web: %w", err) - } - - // Save token back to storage (conceptually - the caller handles persistence typically) - ts.AccessToken = token.AccessToken - ts.RefreshToken = token.RefreshToken - ts.TokenType = token.TokenType - ts.Expiry = token.Expiry.Format(time.RFC3339) - } else { - expiry, _ := time.Parse(time.RFC3339, ts.Expiry) - token = &oauth2.Token{ - AccessToken: ts.AccessToken, - RefreshToken: ts.RefreshToken, - TokenType: ts.TokenType, - Expiry: expiry, - } - } - - return conf.Client(ctx, token), nil -} - -func (k *KiroAuth) getTokenFromWeb(ctx context.Context, config *oauth2.Config, noBrowser ...bool) (*oauth2.Token, error) { - server := NewOAuthServer(8086) // Use port 8086 for Kiro - if err := server.Start(); err != nil { - return nil, fmt.Errorf("failed to start local server: %w", err) - } - defer server.Stop(ctx) - - state := "state-token-kiro" - authURL := config.AuthCodeURL(state, oauth2.AccessTypeOffline) - - if len(noBrowser) == 1 && !noBrowser[0] { - fmt.Println("Opening browser for Kiro authentication...") - if !browser.IsAvailable() { - util.PrintSSHTunnelInstructions(8086) - fmt.Printf("Please manually open this URL in your browser:\n\n%s\n", authURL) - } else { - if err := browser.OpenURL(authURL); err != nil { - util.PrintSSHTunnelInstructions(8086) - fmt.Printf("Please manually open this URL in your browser:\n\n%s\n", authURL) - } - } - } else { - util.PrintSSHTunnelInstructions(8086) - fmt.Printf("Please open this URL in your browser:\n\n%s\n", authURL) - } - - result, err := server.WaitForCallback(5 * time.Minute) - if err != nil { - return nil, err - } - - if result.Error != "" { - return nil, fmt.Errorf("oauth error: %s", result.Error) - } - - token, err := config.Exchange(ctx, result.Code) - if err != nil { - return nil, fmt.Errorf("failed to exchange token: %w", err) - } - - return token, nil -} diff --git a/internal/auth/kiro/errors.go b/internal/auth/kiro/errors.go new file mode 100644 index 00000000..ef6e6713 --- /dev/null +++ b/internal/auth/kiro/errors.go @@ -0,0 +1,192 @@ +package kiro + +import ( + "errors" + "fmt" + "net/http" +) + +// OAuthError represents an OAuth-specific error. +type OAuthError struct { + // Code is the OAuth error code. + Code string `json:"error"` + // Description is a human-readable description of the error. + Description string `json:"error_description,omitempty"` + // URI is a URI identifying a human-readable web page with information about the error. + URI string `json:"error_uri,omitempty"` + // StatusCode is the HTTP status code associated with the error. + StatusCode int `json:"-"` +} + +// Error returns a string representation of the OAuth error. +func (e *OAuthError) Error() string { + if e.Description != "" { + return fmt.Sprintf("OAuth error %s: %s", e.Code, e.Description) + } + return fmt.Sprintf("OAuth error: %s", e.Code) +} + +// NewOAuthError creates a new OAuth error with the specified code, description, and status code. +func NewOAuthError(code, description string, statusCode int) *OAuthError { + return &OAuthError{ + Code: code, + Description: description, + StatusCode: statusCode, + } +} + +// AuthenticationError represents authentication-related errors. +type AuthenticationError struct { + // Type is the type of authentication error. + Type string `json:"type"` + // Message is a human-readable message describing the error. + Message string `json:"message"` + // Code is the HTTP status code associated with the error. + Code int `json:"code"` + // Cause is the underlying error that caused this authentication error. + Cause error `json:"-"` +} + +// Error returns a string representation of the authentication error. +func (e *AuthenticationError) Error() string { + if e.Cause != nil { + return fmt.Sprintf("%s: %s (caused by: %v)", e.Type, e.Message, e.Cause) + } + return fmt.Sprintf("%s: %s", e.Type, e.Message) +} + +// Common authentication error types. +var ( + // ErrInvalidState represents an error for invalid OAuth state parameter. + ErrInvalidState = &AuthenticationError{ + Type: "invalid_state", + Message: "OAuth state parameter is invalid", + Code: http.StatusBadRequest, + } + + // ErrCodeExchangeFailed represents an error when exchanging authorization code for tokens fails. + ErrCodeExchangeFailed = &AuthenticationError{ + Type: "code_exchange_failed", + Message: "Failed to exchange authorization code for tokens", + Code: http.StatusBadRequest, + } + + // ErrServerStartFailed represents an error when starting the OAuth callback server fails. + ErrServerStartFailed = &AuthenticationError{ + Type: "server_start_failed", + Message: "Failed to start OAuth callback server", + Code: http.StatusInternalServerError, + } + + // ErrPortInUse represents an error when the OAuth callback port is already in use. + ErrPortInUse = &AuthenticationError{ + Type: "port_in_use", + Message: "OAuth callback port is already in use", + Code: 13, // Special exit code for port-in-use + } + + // ErrCallbackTimeout represents an error when waiting for OAuth callback times out. + ErrCallbackTimeout = &AuthenticationError{ + Type: "callback_timeout", + Message: "Timeout waiting for OAuth callback", + Code: http.StatusRequestTimeout, + } + + // ErrBrowserOpenFailed represents an error when opening the browser for authentication fails. + ErrBrowserOpenFailed = &AuthenticationError{ + Type: "browser_open_failed", + Message: "Failed to open browser for authentication", + Code: http.StatusInternalServerError, + } + + // ErrAuthorizationPending indicates the user hasn't completed device authorization yet + ErrAuthorizationPending = &AuthenticationError{ + Type: "authorization_pending", + Message: "User has not completed device authorization", + Code: http.StatusAccepted, + } + + // ErrSlowDown indicates the client is polling too frequently + ErrSlowDown = &AuthenticationError{ + Type: "slow_down", + Message: "Polling too frequently, slow down", + Code: http.StatusTooManyRequests, + } + + // ErrExpiredToken indicates the device code has expired + ErrExpiredToken = &AuthenticationError{ + Type: "expired_token", + Message: "Device code has expired", + Code: http.StatusBadRequest, + } +) + +// NewAuthenticationError creates a new authentication error with a cause based on a base error. +func NewAuthenticationError(baseErr *AuthenticationError, cause error) *AuthenticationError { + return &AuthenticationError{ + Type: baseErr.Type, + Message: baseErr.Message, + Code: baseErr.Code, + Cause: cause, + } +} + +// IsAuthenticationError checks if an error is an authentication error. +func IsAuthenticationError(err error) bool { + var authenticationError *AuthenticationError + ok := errors.As(err, &authenticationError) + return ok +} + +// IsOAuthError checks if an error is an OAuth error. +func IsOAuthError(err error) bool { + var oAuthError *OAuthError + ok := errors.As(err, &oAuthError) + return ok +} + +// GetUserFriendlyMessage returns a user-friendly error message based on the error type. +func GetUserFriendlyMessage(err error) string { + switch { + case IsAuthenticationError(err): + var authErr *AuthenticationError + errors.As(err, &authErr) + switch authErr.Type { + case "token_expired": + return "Your authentication has expired. Please log in again." + case "token_invalid": + return "Your authentication is invalid. Please log in again." + case "authentication_required": + return "Please log in to continue." + case "port_in_use": + return "The required port is already in use. Please close any applications using the port and try again." + case "callback_timeout": + return "Authentication timed out. Please try again." + case "browser_open_failed": + return "Could not open your browser automatically. Please copy and paste the URL manually." + case "authorization_pending": + return "Waiting for you to complete authentication in your browser..." + case "slow_down": + return "Polling too frequently. Slowing down..." + case "expired_token": + return "The device code has expired. Please restart the login process." + default: + return "Authentication failed. Please try again." + } + case IsOAuthError(err): + var oauthErr *OAuthError + errors.As(err, &oauthErr) + switch oauthErr.Code { + case "access_denied": + return "Authentication was cancelled or denied." + case "invalid_request": + return "Invalid authentication request. Please try again." + case "server_error": + return "Authentication server error. Please try again later." + default: + return fmt.Sprintf("Authentication failed: %s", oauthErr.Description) + } + default: + return "An unexpected error occurred. Please try again." + } +} diff --git a/internal/auth/kiro/kiro.go b/internal/auth/kiro/kiro.go new file mode 100644 index 00000000..da1265f7 --- /dev/null +++ b/internal/auth/kiro/kiro.go @@ -0,0 +1,45 @@ +package kiro + +// PKCECodes holds the verification codes for the OAuth2 PKCE (Proof Key for Code Exchange) flow. +// PKCE is an extension to the Authorization Code flow to prevent CSRF and authorization code injection attacks. +type PKCECodes struct { + // CodeVerifier is the cryptographically random string used to correlate + // the authorization request to the token request + CodeVerifier string `json:"code_verifier"` + // CodeChallenge is the SHA256 hash of the code verifier, base64url-encoded + CodeChallenge string `json:"code_challenge"` +} + +// KiroTokenData holds the OAuth token information obtained from AWS Kiro. +// It includes access token, refresh token, ID token, and associated user details. +type KiroTokenData struct { + // AccessToken is the OAuth2 access token for API access + AccessToken string `json:"access_token"` + // RefreshToken is used to obtain new access tokens + RefreshToken string `json:"refresh_token"` + // IDToken is the JWT ID token containing user claims (optional) + IDToken string `json:"id_token,omitempty"` + // Email is the user's email address + Email string `json:"email"` + // ExpiresAt is the timestamp when the token expires + ExpiresAt string `json:"expires_at"` + // AuthMethod indicates the authentication method used ("builder_id" or "google") + AuthMethod string `json:"auth_method"` + // ProfileArn is the AWS CodeWhisperer profile ARN (optional) + ProfileArn string `json:"profile_arn,omitempty"` + // ClientID is the AWS SSO client ID (for Builder ID auth) + ClientID string `json:"client_id,omitempty"` + // ClientSecret is the AWS SSO client secret (for Builder ID auth) + ClientSecret string `json:"client_secret,omitempty"` + // Provider indicates the OAuth provider ("google" or "aws") + Provider string `json:"provider,omitempty"` +} + +// KiroAuthBundle aggregates all authentication-related data after the OAuth flow is complete. +// This includes the token data and the timestamp of the last refresh. +type KiroAuthBundle struct { + // TokenData contains the OAuth tokens from the authentication flow + TokenData KiroTokenData `json:"token_data"` + // LastRefresh is the timestamp of the last token refresh + LastRefresh string `json:"last_refresh"` +} diff --git a/internal/auth/kiro/kiro_auth.go b/internal/auth/kiro/kiro_auth.go new file mode 100644 index 00000000..25e3b7b5 --- /dev/null +++ b/internal/auth/kiro/kiro_auth.go @@ -0,0 +1,614 @@ +// Package kiro provides OAuth2 authentication functionality for AWS CodeWhisperer (Kiro) API. +// This package implements the complete OAuth2 flow with PKCE (Proof Key for Code Exchange) +// for secure authentication with Kiro API, including token exchange, refresh, and storage. +package kiro + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "strings" + "time" + + "github.com/router-for-me/CLIProxyAPI/v6/internal/config" + "github.com/router-for-me/CLIProxyAPI/v6/internal/util" + log "github.com/sirupsen/logrus" +) + +const ( + // awsSSOOIDCEndpoint is the AWS SSO OIDC service endpoint + awsSSOOIDCEndpoint = "https://oidc.us-east-1.amazonaws.com" + // kiroAPIEndpoint is the Kiro API endpoint + kiroAPIEndpoint = "https://q.us-east-1.amazonaws.com" + // kiroClientName is the client name for registration + kiroClientName = "Kiro" + // defaultRegion is the default AWS region for Kiro services + defaultRegion = "us-east-1" + // googleAuthURL is the Google OAuth authorization endpoint + googleAuthURL = "https://accounts.google.com/o/oauth2/v2/auth" + // googleTokenURL is the Google OAuth token endpoint + googleTokenURL = "https://oauth2.googleapis.com/token" + // googleClientID is the Kiro Google OAuth client ID + googleClientID = "kiro-google-client-id" + // redirectURI is the OAuth callback URL + redirectURI = "http://localhost:1455/auth/callback" +) + +// registerClientResponse represents the response from AWS SSO OIDC client registration. +type registerClientResponse struct { + ClientID string `json:"clientId"` + ClientSecret string `json:"clientSecret"` + ExpiresAt int64 `json:"clientSecretExpiresAt"` +} + +// startDeviceAuthResponse represents the response from AWS SSO OIDC device authorization start. +type startDeviceAuthResponse struct { + DeviceCode string `json:"deviceCode"` + UserCode string `json:"userCode"` + VerificationURI string `json:"verificationUri"` + VerificationURIComplete string `json:"verificationUriComplete"` + ExpiresIn int `json:"expiresIn"` + Interval int `json:"interval"` +} + +// tokenResponse represents the response structure from AWS SSO OIDC token endpoint. +type tokenResponse struct { + AccessToken string `json:"accessToken"` + RefreshToken string `json:"refreshToken"` + TokenType string `json:"tokenType"` + ExpiresIn int `json:"expiresIn"` + IDToken string `json:"idToken,omitempty"` +} + +// KiroAuth handles the AWS Kiro authentication flows. +// It manages the HTTP client and provides methods for both AWS Builder ID +// device authorization and Google OAuth flows. +type KiroAuth struct { + httpClient *http.Client + cfg *config.Config +} + +// NewKiroAuth creates a new KiroAuth service instance. +// It initializes an HTTP client with proxy settings from the provided configuration. +func NewKiroAuth(cfg *config.Config) *KiroAuth { + return &KiroAuth{ + httpClient: util.SetProxy(&cfg.SDKConfig, &http.Client{}), + cfg: cfg, + } +} + +// RegisterClient registers a new OAuth client with AWS SSO OIDC. +// This is the first step in the device authorization flow. +// +// Parameters: +// - ctx: The context for the request +// - clientName: The name of the client application +// - clientType: The type of client (e.g., "public") +// +// Returns: +// - *registerClientResponse: The client registration response with client ID and secret +// - error: An error if registration fails +func (k *KiroAuth) RegisterClient(ctx context.Context, clientName, clientType string) (*registerClientResponse, error) { + endpoint := fmt.Sprintf("%s/client/register", awsSSOOIDCEndpoint) + + reqBody := map[string]interface{}{ + "clientName": clientName, + "clientType": clientType, + "scopes": []string{"sso:account:access"}, + } + + jsonBody, err := json.Marshal(reqBody) + if err != nil { + return nil, fmt.Errorf("failed to marshal request body: %w", err) + } + + req, err := http.NewRequestWithContext(ctx, "POST", endpoint, strings.NewReader(string(jsonBody))) + if err != nil { + return nil, fmt.Errorf("failed to create registration request: %w", err) + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Accept", "application/json") + + resp, err := k.httpClient.Do(req) + if err != nil { + return nil, fmt.Errorf("client registration request failed: %w", err) + } + defer func() { + if errClose := resp.Body.Close(); errClose != nil { + log.Errorf("failed to close response body: %v", errClose) + } + }() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, fmt.Errorf("failed to read registration response: %w", err) + } + + if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated { + return nil, fmt.Errorf("client registration failed with status %d: %s", resp.StatusCode, string(body)) + } + + var regResp registerClientResponse + if err = json.Unmarshal(body, ®Resp); err != nil { + return nil, fmt.Errorf("failed to parse registration response: %w", err) + } + + return ®Resp, nil +} + +// StartDeviceAuthorization initiates the AWS Builder ID device authorization flow. +// It requests a device code and user code from AWS SSO OIDC. +func (k *KiroAuth) StartDeviceAuthorization(ctx context.Context, clientInfo *SSOOIDCClientInfo) (*DeviceAuthorizationResponse, error) { + authURL := fmt.Sprintf("%s/device_authorization", awsSSOOIDCEndpoint) + + data := url.Values{ + "client_id": {clientInfo.ClientID}, + "client_secret": {clientInfo.ClientSecret}, + "start_url": {"https://view.awsapps.com/start"}, + } + + req, err := http.NewRequestWithContext(ctx, "POST", authURL, strings.NewReader(data.Encode())) + if err != nil { + return nil, fmt.Errorf("failed to create device authorization request: %w", err) + } + + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("Accept", "application/json") + + resp, err := k.httpClient.Do(req) + if err != nil { + return nil, fmt.Errorf("device authorization request failed: %w", err) + } + defer func() { + _ = resp.Body.Close() + }() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, fmt.Errorf("failed to read device authorization response: %w", err) + } + + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("device authorization failed with status %d: %s", resp.StatusCode, string(body)) + } + + var authResp DeviceAuthorizationResponse + if err = json.Unmarshal(body, &authResp); err != nil { + return nil, fmt.Errorf("failed to parse device authorization response: %w", err) + } + + return &authResp, nil +} + +// PollDeviceToken polls AWS SSO OIDC for the access token after user authorization. +// This is called repeatedly until the user completes the device authorization flow. +func (k *KiroAuth) PollDeviceToken(ctx context.Context, clientInfo *SSOOIDCClientInfo, deviceCode string) (*KiroTokenData, error) { + tokenURL := fmt.Sprintf("%s/token", awsSSOOIDCEndpoint) + + data := url.Values{ + "client_id": {clientInfo.ClientID}, + "client_secret": {clientInfo.ClientSecret}, + "grant_type": {"urn:ietf:params:oauth:grant-type:device_code"}, + "device_code": {deviceCode}, + } + + req, err := http.NewRequestWithContext(ctx, "POST", tokenURL, strings.NewReader(data.Encode())) + if err != nil { + return nil, fmt.Errorf("failed to create token request: %w", err) + } + + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("Accept", "application/json") + + resp, err := k.httpClient.Do(req) + if err != nil { + return nil, fmt.Errorf("token request failed: %w", err) + } + defer func() { + _ = resp.Body.Close() + }() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, fmt.Errorf("failed to read token response: %w", err) + } + + if resp.StatusCode != http.StatusOK { + // Parse error response + var errResp struct { + Error string `json:"error"` + ErrorDescription string `json:"error_description"` + } + if err = json.Unmarshal(body, &errResp); err == nil { + switch errResp.Error { + case "authorization_pending": + return nil, ErrAuthorizationPending + case "slow_down": + return nil, ErrSlowDown + case "expired_token": + return nil, ErrExpiredToken + default: + return nil, fmt.Errorf("token request failed: %s - %s", errResp.Error, errResp.ErrorDescription) + } + } + return nil, fmt.Errorf("token request failed with status %d: %s", resp.StatusCode, string(body)) + } + + var tokenResp struct { + AccessToken string `json:"access_token"` + RefreshToken string `json:"refresh_token"` + IDToken string `json:"id_token"` + ExpiresIn int `json:"expires_in"` + TokenType string `json:"token_type"` + } + + if err = json.Unmarshal(body, &tokenResp); err != nil { + return nil, fmt.Errorf("failed to parse token response: %w", err) + } + + expiresAt := time.Now().Add(time.Duration(tokenResp.ExpiresIn) * time.Second).Format(time.RFC3339) + + return &KiroTokenData{ + AccessToken: tokenResp.AccessToken, + RefreshToken: tokenResp.RefreshToken, + IDToken: tokenResp.IDToken, + ExpiresAt: expiresAt, + AuthMethod: "builder_id", + Provider: "aws", + ClientID: clientInfo.ClientID, + ClientSecret: clientInfo.ClientSecret, + }, nil +} + +// RefreshTokens refreshes an access token using a refresh token. +// This method handles both AWS Builder ID and Google OAuth token refresh flows. +func (k *KiroAuth) RefreshTokens(ctx context.Context, tokenData *KiroTokenData) (*KiroTokenData, error) { + if tokenData == nil { + return nil, fmt.Errorf("token data is required") + } + + if tokenData.RefreshToken == "" { + return nil, fmt.Errorf("refresh token is required") + } + + // Route to appropriate refresh method based on auth method + switch tokenData.AuthMethod { + case "builder_id": + return k.refreshBuilderIDTokens(ctx, tokenData) + case "google": + return k.refreshGoogleTokens(ctx, tokenData) + default: + return nil, fmt.Errorf("unknown auth method: %s", tokenData.AuthMethod) + } +} + +// refreshBuilderIDTokens refreshes tokens for AWS Builder ID authentication. +func (k *KiroAuth) refreshBuilderIDTokens(ctx context.Context, tokenData *KiroTokenData) (*KiroTokenData, error) { + if tokenData.ClientID == "" || tokenData.ClientSecret == "" { + return nil, fmt.Errorf("client credentials are required for Builder ID token refresh") + } + + tokenURL := fmt.Sprintf("%s/token", awsSSOOIDCEndpoint) + + data := url.Values{ + "client_id": {tokenData.ClientID}, + "client_secret": {tokenData.ClientSecret}, + "grant_type": {"refresh_token"}, + "refresh_token": {tokenData.RefreshToken}, + } + + req, err := http.NewRequestWithContext(ctx, "POST", tokenURL, strings.NewReader(data.Encode())) + if err != nil { + return nil, fmt.Errorf("failed to create refresh request: %w", err) + } + + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("Accept", "application/json") + + resp, err := k.httpClient.Do(req) + if err != nil { + return nil, fmt.Errorf("token refresh request failed: %w", err) + } + defer func() { + _ = resp.Body.Close() + }() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, fmt.Errorf("failed to read refresh response: %w", err) + } + + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("token refresh failed with status %d: %s", resp.StatusCode, string(body)) + } + + var tokenResp struct { + AccessToken string `json:"access_token"` + RefreshToken string `json:"refresh_token"` + IDToken string `json:"id_token"` + ExpiresIn int `json:"expires_in"` + TokenType string `json:"token_type"` + } + + if err = json.Unmarshal(body, &tokenResp); err != nil { + return nil, fmt.Errorf("failed to parse refresh response: %w", err) + } + + expiresAt := time.Now().Add(time.Duration(tokenResp.ExpiresIn) * time.Second).Format(time.RFC3339) + + return &KiroTokenData{ + AccessToken: tokenResp.AccessToken, + RefreshToken: tokenResp.RefreshToken, + IDToken: tokenResp.IDToken, + Email: tokenData.Email, + ExpiresAt: expiresAt, + AuthMethod: "builder_id", + Provider: "aws", + ClientID: tokenData.ClientID, + ClientSecret: tokenData.ClientSecret, + ProfileArn: tokenData.ProfileArn, + }, nil +} + +// refreshGoogleTokens refreshes tokens for Google OAuth authentication. +func (k *KiroAuth) refreshGoogleTokens(ctx context.Context, tokenData *KiroTokenData) (*KiroTokenData, error) { + data := url.Values{ + "client_id": {googleClientID}, + "grant_type": {"refresh_token"}, + "refresh_token": {tokenData.RefreshToken}, + } + + req, err := http.NewRequestWithContext(ctx, "POST", googleTokenURL, strings.NewReader(data.Encode())) + if err != nil { + return nil, fmt.Errorf("failed to create refresh request: %w", err) + } + + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("Accept", "application/json") + + resp, err := k.httpClient.Do(req) + if err != nil { + return nil, fmt.Errorf("token refresh request failed: %w", err) + } + defer func() { + _ = resp.Body.Close() + }() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, fmt.Errorf("failed to read refresh response: %w", err) + } + + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("token refresh failed with status %d: %s", resp.StatusCode, string(body)) + } + + var tokenResp struct { + AccessToken string `json:"access_token"` + RefreshToken string `json:"refresh_token"` + IDToken string `json:"id_token"` + ExpiresIn int `json:"expires_in"` + TokenType string `json:"token_type"` + } + + if err = json.Unmarshal(body, &tokenResp); err != nil { + return nil, fmt.Errorf("failed to parse refresh response: %w", err) + } + + // Use the new refresh token if provided, otherwise keep the old one + refreshToken := tokenResp.RefreshToken + if refreshToken == "" { + refreshToken = tokenData.RefreshToken + } + + expiresAt := time.Now().Add(time.Duration(tokenResp.ExpiresIn) * time.Second).Format(time.RFC3339) + + return &KiroTokenData{ + AccessToken: tokenResp.AccessToken, + RefreshToken: refreshToken, + IDToken: tokenResp.IDToken, + Email: tokenData.Email, + ExpiresAt: expiresAt, + AuthMethod: "google", + Provider: "google", + }, nil +} + +// NewSSOOIDCClient creates a new AWS SSO OIDC client registration. +// This is the first step in the AWS Builder ID device authorization flow. +// It registers the client application with AWS SSO OIDC and returns client credentials. +func (k *KiroAuth) NewSSOOIDCClient(ctx context.Context) (*SSOOIDCClientInfo, error) { + regResp, err := k.RegisterClient(ctx, kiroClientName, "public") + if err != nil { + return nil, err + } + return &SSOOIDCClientInfo{ + ClientID: regResp.ClientID, + ClientSecret: regResp.ClientSecret, + ClientIDIssuedAt: 0, // Set from regResp if available + ClientSecretExpiresAt: regResp.ExpiresAt, + }, nil +} + +// NewKiroOAuth creates a Google OAuth flow for Kiro authentication. +// It generates the authorization URL with PKCE for secure authentication. +func (k *KiroAuth) NewKiroOAuth(state string, pkceCodes *PKCECodes) (string, error) { + if pkceCodes == nil { + return "", fmt.Errorf("PKCE codes are required") + } + + params := url.Values{ + "client_id": {googleClientID}, + "response_type": {"code"}, + "redirect_uri": {redirectURI}, + "scope": {"openid email profile"}, + "state": {state}, + "code_challenge": {pkceCodes.CodeChallenge}, + "code_challenge_method": {"S256"}, + "prompt": {"select_account"}, + "access_type": {"offline"}, + } + + authURL := fmt.Sprintf("%s?%s", googleAuthURL, params.Encode()) + return authURL, nil +} + +// ExchangeCodeForTokens exchanges an authorization code for access and refresh tokens. +// This is used in the Google OAuth flow after the user completes authorization. +func (k *KiroAuth) ExchangeCodeForTokens(ctx context.Context, code string, pkceCodes *PKCECodes) (*KiroAuthBundle, error) { + if pkceCodes == nil { + return nil, fmt.Errorf("PKCE codes are required for token exchange") + } + + data := url.Values{ + "grant_type": {"authorization_code"}, + "client_id": {googleClientID}, + "code": {code}, + "redirect_uri": {redirectURI}, + "code_verifier": {pkceCodes.CodeVerifier}, + } + + req, err := http.NewRequestWithContext(ctx, "POST", googleTokenURL, strings.NewReader(data.Encode())) + if err != nil { + return nil, fmt.Errorf("failed to create token request: %w", err) + } + + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("Accept", "application/json") + + resp, err := k.httpClient.Do(req) + if err != nil { + return nil, fmt.Errorf("token exchange request failed: %w", err) + } + defer func() { + _ = resp.Body.Close() + }() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, fmt.Errorf("failed to read token response: %w", err) + } + + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("token exchange failed with status %d: %s", resp.StatusCode, string(body)) + } + + var tokenResp struct { + AccessToken string `json:"access_token"` + RefreshToken string `json:"refresh_token"` + IDToken string `json:"id_token"` + ExpiresIn int `json:"expires_in"` + TokenType string `json:"token_type"` + } + + if err = json.Unmarshal(body, &tokenResp); err != nil { + return nil, fmt.Errorf("failed to parse token response: %w", err) + } + + // TODO: Parse ID token to extract email and other claims + email := "" + expiresAt := time.Now().Add(time.Duration(tokenResp.ExpiresIn) * time.Second).Format(time.RFC3339) + + tokenData := KiroTokenData{ + AccessToken: tokenResp.AccessToken, + RefreshToken: tokenResp.RefreshToken, + IDToken: tokenResp.IDToken, + Email: email, + ExpiresAt: expiresAt, + AuthMethod: "google", + Provider: "google", + } + + bundle := &KiroAuthBundle{ + TokenData: tokenData, + LastRefresh: time.Now().Format(time.RFC3339), + } + + return bundle, nil +} + +// CreateTokenStorage creates a new KiroTokenStorage from a KiroAuthBundle. +// It populates the storage struct with token data, user information, and timestamps. +func (k *KiroAuth) CreateTokenStorage(bundle *KiroAuthBundle) *KiroTokenStorage { + storage := &KiroTokenStorage{ + Type: "kiro", + AccessToken: bundle.TokenData.AccessToken, + RefreshToken: bundle.TokenData.RefreshToken, + IDToken: bundle.TokenData.IDToken, + Email: bundle.TokenData.Email, + ExpiresAt: bundle.TokenData.ExpiresAt, + AuthMethod: bundle.TokenData.AuthMethod, + ProfileArn: bundle.TokenData.ProfileArn, + ClientID: bundle.TokenData.ClientID, + ClientSecret: bundle.TokenData.ClientSecret, + Provider: bundle.TokenData.Provider, + LastRefresh: bundle.LastRefresh, + } + + return storage +} + +// RefreshTokensWithRetry refreshes tokens with a built-in retry mechanism. +// It attempts to refresh the tokens up to a specified maximum number of retries, +// with an exponential backoff strategy to handle transient network errors. +func (k *KiroAuth) RefreshTokensWithRetry(ctx context.Context, tokenData *KiroTokenData, maxRetries int) (*KiroTokenData, error) { + var lastErr error + + for attempt := 0; attempt < maxRetries; attempt++ { + if attempt > 0 { + // Wait before retry + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-time.After(time.Duration(attempt) * time.Second): + } + } + + refreshedTokenData, err := k.RefreshTokens(ctx, tokenData) + if err == nil { + return refreshedTokenData, nil + } + + lastErr = err + log.Warnf("Token refresh attempt %d failed: %v", attempt+1, err) + } + + return nil, fmt.Errorf("token refresh failed after %d attempts: %w", maxRetries, lastErr) +} + +// UpdateTokenStorage updates an existing KiroTokenStorage with new token data. +// This is typically called after a successful token refresh to persist the new credentials. +func (k *KiroAuth) UpdateTokenStorage(storage *KiroTokenStorage, tokenData *KiroTokenData) { + storage.AccessToken = tokenData.AccessToken + storage.RefreshToken = tokenData.RefreshToken + storage.IDToken = tokenData.IDToken + storage.Email = tokenData.Email + storage.ExpiresAt = tokenData.ExpiresAt + storage.AuthMethod = tokenData.AuthMethod + storage.ProfileArn = tokenData.ProfileArn + storage.ClientID = tokenData.ClientID + storage.ClientSecret = tokenData.ClientSecret + storage.Provider = tokenData.Provider + storage.LastRefresh = time.Now().Format(time.RFC3339) +} + +// SSOOIDCClientInfo holds the AWS SSO OIDC client registration information. +type SSOOIDCClientInfo struct { + ClientID string `json:"clientId"` + ClientSecret string `json:"clientSecret"` + ClientIDIssuedAt int64 `json:"clientIdIssuedAt"` + ClientSecretExpiresAt int64 `json:"clientSecretExpiresAt"` +} + +// DeviceAuthorizationResponse holds the response from AWS SSO OIDC device authorization. +type DeviceAuthorizationResponse struct { + DeviceCode string `json:"deviceCode"` + UserCode string `json:"userCode"` + VerificationURI string `json:"verificationUri"` + VerificationURIComplete string `json:"verificationUriComplete"` + ExpiresIn int `json:"expiresIn"` + Interval int `json:"interval"` +} diff --git a/internal/auth/kiro/kiro_token.go b/internal/auth/kiro/kiro_token.go new file mode 100644 index 00000000..d4ce4e3d --- /dev/null +++ b/internal/auth/kiro/kiro_token.go @@ -0,0 +1,79 @@ +// Package kiro provides authentication and token management functionality +// for AWS CodeWhisperer (Kiro) services. It handles OAuth2 token storage, serialization, +// and retrieval for maintaining authenticated sessions with the Kiro API. +package kiro + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + + "github.com/router-for-me/CLIProxyAPI/v6/internal/misc" +) + +// KiroTokenStorage stores OAuth2 token information for AWS Kiro API authentication. +// It maintains compatibility with the existing auth system while adding Kiro-specific fields +// for managing access tokens, refresh tokens, and user account information. +type KiroTokenStorage struct { + // Type indicates the authentication provider type, always "kiro" for this storage + Type string `json:"type"` + // AccessToken is the OAuth2 access token used for authenticating API requests + AccessToken string `json:"access_token"` + // RefreshToken is used to obtain new access tokens when the current one expires + RefreshToken string `json:"refresh_token"` + // IDToken is the JWT ID token containing user claims and identity information (optional) + IDToken string `json:"id_token,omitempty"` + // Email is the user's email address + Email string `json:"email"` + // ExpiresAt is the timestamp when the token expires + ExpiresAt string `json:"expires_at"` + // AuthMethod indicates the authentication method used ("builder_id" or "google") + AuthMethod string `json:"auth_method"` + // ProfileArn is the AWS CodeWhisperer profile ARN (optional) + ProfileArn string `json:"profile_arn,omitempty"` + // ClientID is the AWS SSO client ID (for Builder ID auth) + ClientID string `json:"client_id,omitempty"` + // ClientSecret is the AWS SSO client secret (for Builder ID auth) + ClientSecret string `json:"client_secret,omitempty"` + // Provider indicates the OAuth provider ("google" or "aws") + Provider string `json:"provider,omitempty"` + // LastRefresh is the timestamp of the last token refresh operation + LastRefresh string `json:"last_refresh"` +} + +// SaveTokenToFile serializes the Kiro token storage to a JSON file. +// This method creates the necessary directory structure and writes the token +// data in JSON format to the specified file path for persistent storage. +// +// Parameters: +// - authFilePath: The full path where the token file should be saved +// +// Returns: +// - error: An error if the operation fails, nil otherwise +func (ts *KiroTokenStorage) SaveTokenToFile(authFilePath string) error { + misc.LogSavingCredentials(authFilePath) + ts.Type = "kiro" + + // Create directory structure if it doesn't exist + if err := os.MkdirAll(filepath.Dir(authFilePath), 0700); err != nil { + return fmt.Errorf("failed to create directory: %v", err) + } + + // Create the token file + f, err := os.Create(authFilePath) + if err != nil { + return fmt.Errorf("failed to create token file: %w", err) + } + defer func() { + _ = f.Close() + }() + + // Encode and write the token data as JSON with indentation + encoder := json.NewEncoder(f) + encoder.SetIndent("", " ") + if err = encoder.Encode(ts); err != nil { + return fmt.Errorf("failed to write token to file: %w", err) + } + return nil +} diff --git a/internal/auth/kiro/pkce.go b/internal/auth/kiro/pkce.go new file mode 100644 index 00000000..a4172a12 --- /dev/null +++ b/internal/auth/kiro/pkce.go @@ -0,0 +1,52 @@ +// Package kiro provides authentication and token management functionality +// for AWS CodeWhisperer (Kiro) services. It handles OAuth2 PKCE (Proof Key for Code Exchange) +// code generation for secure authentication flows. +package kiro + +import ( + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "fmt" +) + +// GeneratePKCE generates a new pair of PKCE (Proof Key for Code Exchange) codes. +// It creates a cryptographically random code verifier and its corresponding +// SHA256 code challenge, as specified in RFC 7636. This is a critical security +// feature for the OAuth 2.0 authorization code flow. +func GeneratePKCE() (*PKCECodes, error) { + // Generate code verifier: 43-128 characters, URL-safe + codeVerifier, err := generateCodeVerifier() + if err != nil { + return nil, fmt.Errorf("failed to generate code verifier: %w", err) + } + + // Generate code challenge using S256 method + codeChallenge := generateCodeChallenge(codeVerifier) + + return &PKCECodes{ + CodeVerifier: codeVerifier, + CodeChallenge: codeChallenge, + }, nil +} + +// generateCodeVerifier creates a cryptographically random string +// of 128 characters using URL-safe base64 encoding +func generateCodeVerifier() (string, error) { + // Generate 96 random bytes (will result in 128 base64 characters) + bytes := make([]byte, 96) + _, err := rand.Read(bytes) + if err != nil { + return "", fmt.Errorf("failed to generate random bytes: %w", err) + } + + // Encode to URL-safe base64 without padding + return base64.URLEncoding.WithPadding(base64.NoPadding).EncodeToString(bytes), nil +} + +// generateCodeChallenge creates a SHA256 hash of the code verifier +// and encodes it using URL-safe base64 encoding without padding +func generateCodeChallenge(codeVerifier string) string { + hash := sha256.Sum256([]byte(codeVerifier)) + return base64.URLEncoding.WithPadding(base64.NoPadding).EncodeToString(hash[:]) +}