|
13 | 13 | from pydantic.json import pydantic_encoder |
14 | 14 |
|
15 | 15 | from codeflash.cli_cmds.console import console, logger |
| 16 | +from codeflash.code_utils.code_utils import exit_with_message |
16 | 17 | from codeflash.code_utils.env_utils import ensure_codeflash_api_key, get_codeflash_api_key, get_pr_number |
17 | 18 | from codeflash.code_utils.git_utils import get_current_branch, get_repo_owner_and_name |
18 | 19 | from codeflash.github.PrComment import FileDiffContent, PrComment |
@@ -120,6 +121,49 @@ def get_user_id(api_key: Optional[str] = None) -> Optional[str]: |
120 | 121 | return None |
121 | 122 |
|
122 | 123 |
|
| 124 | +def validate_api_key() -> None: |
| 125 | + """Validate the API key by making a request to the /cfapi/cli-get-user endpoint. |
| 126 | + |
| 127 | + Raises SystemExit if the API key is invalid (403) or missing. |
| 128 | + This should be called early in the CLI flow before starting optimization. |
| 129 | + """ |
| 130 | + logger.debug("validate_api_key: Starting API key validation") |
| 131 | + api_key = get_codeflash_api_key() |
| 132 | + |
| 133 | + response = make_cfapi_request( |
| 134 | + endpoint="/cli-get-user", method="GET", extra_headers={"cli_version": __version__}, api_key=api_key, suppress_errors=True |
| 135 | + ) |
| 136 | + |
| 137 | + if response.status_code == 403: |
| 138 | + error_message = "Invalid API key" |
| 139 | + try: |
| 140 | + json_response = response.json() |
| 141 | + if "error" in json_response: |
| 142 | + error_message = json_response["error"] |
| 143 | + elif "message" in json_response: |
| 144 | + error_message = json_response["message"] |
| 145 | + except (ValueError, TypeError): |
| 146 | + error_message = response.text or "Invalid API key" |
| 147 | + |
| 148 | + msg = ( |
| 149 | + f"Invalid Codeflash API key. {error_message}\n" |
| 150 | + "You can generate a valid API key at https://app.codeflash.ai/app/apikeys,\n" |
| 151 | + "then set it as a CODEFLASH_API_KEY environment variable." |
| 152 | + ) |
| 153 | + logger.error(f"validate_api_key: API key validation failed with 403 - {error_message}") |
| 154 | + exit_with_message(msg, error_on_exit=True) |
| 155 | + |
| 156 | + if response.status_code != 200: |
| 157 | + msg = ( |
| 158 | + f"Failed to validate API key (status {response.status_code}: {response.reason})\n" |
| 159 | + "Please check your API key at https://app.codeflash.ai/app/apikeys" |
| 160 | + ) |
| 161 | + logger.error(f"validate_api_key: API key validation failed with status {response.status_code}") |
| 162 | + exit_with_message(msg, error_on_exit=True) |
| 163 | + |
| 164 | + logger.debug("validate_api_key: API key validation successful") |
| 165 | + |
| 166 | + |
123 | 167 | def suggest_changes( |
124 | 168 | owner: str, |
125 | 169 | repo: str, |
|
0 commit comments