Skip to content

Commit 2f001bb

Browse files
early validation for API key
1 parent de9837a commit 2f001bb

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

codeflash/api/cfapi.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
from pydantic.json import pydantic_encoder
1414

1515
from codeflash.cli_cmds.console import console, logger
16+
from codeflash.code_utils.code_utils import exit_with_message
1617
from codeflash.code_utils.env_utils import ensure_codeflash_api_key, get_codeflash_api_key, get_pr_number
1718
from codeflash.code_utils.git_utils import get_current_branch, get_repo_owner_and_name
1819
from codeflash.github.PrComment import FileDiffContent, PrComment
@@ -120,6 +121,49 @@ def get_user_id(api_key: Optional[str] = None) -> Optional[str]:
120121
return None
121122

122123

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+
123167
def suggest_changes(
124168
owner: str,
125169
repo: str,

codeflash/main.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
from pathlib import Path
88

9+
from codeflash.api.cfapi import validate_api_key
910
from codeflash.cli_cmds.cli import parse_args, process_pyproject_config
1011
from codeflash.cli_cmds.cmd_init import CODEFLASH_LOGO, ask_run_end_to_end_test
1112
from codeflash.cli_cmds.console import paneled_text
@@ -42,6 +43,8 @@ def main() -> None:
4243
args = process_pyproject_config(args)
4344
if not env_utils.check_formatter_installed(args.formatter_cmds):
4445
return
46+
# Validate API key early before starting optimization
47+
validate_api_key()
4548
args.previous_checkpoint_functions = ask_should_use_checkpoint_get_functions(args)
4649
init_sentry(not args.disable_telemetry, exclude_errors=True)
4750
posthog_cf.initialize_posthog(not args.disable_telemetry)

0 commit comments

Comments
 (0)