Skip to content

Commit 376ca0d

Browse files
FIX: Codeflash does not exit on invalid api key (#863)
* early validation for API key * fix lint errors * avoid duplicated calls while validating API key * avoid error throwing duplication during 403 respoinse for invalid API key * enhance the GitHub App is not installed error message * fix formatting --------- Co-authored-by: Mohamed Ashraf <[email protected]>
1 parent b9d5f16 commit 376ca0d

File tree

2 files changed

+37
-10
lines changed

2 files changed

+37
-10
lines changed

codeflash/api/cfapi.py

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
"""Module for interacting with the Codeflash API."""
2+
13
from __future__ import annotations
24

35
import json
@@ -13,6 +15,7 @@
1315
from pydantic.json import pydantic_encoder
1416

1517
from codeflash.cli_cmds.console import console, logger
18+
from codeflash.code_utils.code_utils import exit_with_message
1619
from codeflash.code_utils.env_utils import ensure_codeflash_api_key, get_codeflash_api_key, get_pr_number
1720
from codeflash.code_utils.git_utils import get_current_branch, get_repo_owner_and_name
1821
from codeflash.github.PrComment import FileDiffContent, PrComment
@@ -89,13 +92,18 @@ def make_cfapi_request(
8992
def get_user_id(api_key: Optional[str] = None) -> Optional[str]:
9093
"""Retrieve the user's userid by making a request to the /cfapi/cli-get-user endpoint.
9194
95+
:param api_key: The API key to use. If None, uses get_codeflash_api_key().
9296
:return: The userid or None if the request fails.
9397
"""
9498
if not api_key and not ensure_codeflash_api_key():
9599
return None
96100

97101
response = make_cfapi_request(
98-
endpoint="/cli-get-user", method="GET", extra_headers={"cli_version": __version__}, api_key=api_key
102+
endpoint="/cli-get-user",
103+
method="GET",
104+
extra_headers={"cli_version": __version__},
105+
api_key=api_key,
106+
suppress_errors=True,
99107
)
100108
if response.status_code == 200:
101109
if "min_version" not in response.text:
@@ -116,6 +124,20 @@ def get_user_id(api_key: Optional[str] = None) -> Optional[str]:
116124
logger.error("Failed to retrieve userid from the response.")
117125
return None
118126

127+
# Handle 403 (Invalid API key) - exit with error message
128+
if response.status_code == 403:
129+
msg = (
130+
"Invalid Codeflash API key. The API key you provided is not valid.\n"
131+
"Please generate a new one at https://app.codeflash.ai/app/apikeys ,\n"
132+
"then set it as a CODEFLASH_API_KEY environment variable.\n"
133+
"For more information, refer to the documentation at \n"
134+
"https://docs.codeflash.ai/optimizing-with-codeflash/codeflash-github-actions#manual-setup\n"
135+
"or\n"
136+
"https://docs.codeflash.ai/optimizing-with-codeflash/codeflash-github-actions#automated-setup-recommended"
137+
)
138+
exit_with_message(msg, error_on_exit=True)
139+
140+
# For other errors, log and return None (backward compatibility)
119141
logger.error(f"Failed to look up your userid; is your CF API key valid? ({response.reason})")
120142
return None
121143

codeflash/code_utils/github_utils.py

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
from codeflash.api.cfapi import is_github_app_installed_on_repo
66
from codeflash.cli_cmds.cli_common import apologize_and_exit
7-
from codeflash.cli_cmds.console import logger
7+
from codeflash.cli_cmds.console import paneled_text
88
from codeflash.code_utils.compat import LF
99
from codeflash.code_utils.git_utils import get_repo_owner_and_name
1010

@@ -18,15 +18,20 @@ def get_github_secrets_page_url(repo: Optional[Repo] = None) -> str:
1818

1919

2020
def require_github_app_or_exit(owner: str, repo: str) -> None:
21-
if not is_github_app_installed_on_repo(owner, repo):
22-
logger.error(
23-
f"It looks like the Codeflash GitHub App is not installed on the repository {owner}/{repo} or the GitHub"
24-
f" account linked to your CODEFLASH_API_KEY does not have access to the repository {owner}/{repo}.{LF}"
25-
"Before continuing, please install the Codeflash GitHub App on your repository by visiting "
26-
f"https://github.com/apps/codeflash-ai/installations/select_target{LF}"
21+
# Suppress low-level HTTP error logging to avoid duplicate logs; we present a friendly panel instead
22+
if not is_github_app_installed_on_repo(owner, repo, suppress_errors=True):
23+
# Show a clear, user-friendly panel instead of raw error logs
24+
message = (
25+
f"It looks like the Codeflash GitHub App is not installed on the repository {owner}/{repo} "
26+
f"or the GitHub account linked to your CODEFLASH_API_KEY does not have access to the repository {owner}/{repo}.{LF}{LF}"
27+
"To continue, install the Codeflash GitHub App on your repository:"
28+
f"{LF}https://github.com/apps/codeflash-ai/installations/select_target{LF}{LF}"
29+
"Tip: If you want to find optimizations without opening PRs, run Codeflash with the --no-pr flag."
2730
)
28-
logger.error(
29-
f"Note: if you want to find optimizations without opening PRs, you can run Codeflash with the --no-pr flag.{LF}"
31+
paneled_text(
32+
message,
33+
panel_args={"title": "GitHub App Required", "border_style": "red", "expand": False},
34+
text_args={"style": "bold red"},
3035
)
3136
apologize_and_exit()
3237

0 commit comments

Comments
 (0)