Skip to content

Commit 48b4e6b

Browse files
committed
fix(api-tokens): Don't hide errors related to api-tokens
Issue: APPAI-173
1 parent 88dbc84 commit 48b4e6b

File tree

5 files changed

+52
-74
lines changed

5 files changed

+52
-74
lines changed

packages/gg_api_core/src/gg_api_core/client.py

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1073,22 +1073,18 @@ async def get_current_token_info(self) -> dict[str, Any]:
10731073
"""
10741074
logger.info("Getting current API token information")
10751075

1076-
try:
1077-
# If we already have token info, return it
1078-
if self._token_info is not None:
1079-
# Convert Pydantic model to dict if needed
1080-
if hasattr(self._token_info, "model_dump"):
1081-
return dict(self._token_info.model_dump())
1082-
elif isinstance(self._token_info, dict):
1083-
return self._token_info
1084-
else:
1085-
return await self._request_get("/api_tokens/self")
1076+
# If we already have token info, return it
1077+
if self._token_info is not None:
1078+
# Convert Pydantic model to dict if needed
1079+
if hasattr(self._token_info, "model_dump"):
1080+
return dict(self._token_info.model_dump())
1081+
elif isinstance(self._token_info, dict):
1082+
return self._token_info
1083+
else:
1084+
return await self._request_get("/api_tokens/self")
10861085

1087-
# Otherwise fetch from the API
1088-
return await self._request_get("/api_tokens/self")
1089-
except Exception as e:
1090-
logger.error(f"Failed to get current token info: {str(e)}")
1091-
raise
1086+
# Otherwise fetch from the API
1087+
return await self._request_get("/api_tokens/self")
10921088

10931089
async def list_api_tokens(self) -> dict[str, Any]:
10941090
"""List all API tokens for the account.

packages/gg_api_core/src/gg_api_core/mcp_server.py

Lines changed: 11 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from typing import Any
99

1010
from fastmcp import FastMCP
11-
from fastmcp.exceptions import FastMCPError, ValidationError
11+
from fastmcp.exceptions import ValidationError
1212
from fastmcp.server.dependencies import get_http_headers
1313
from fastmcp.server.middleware import Middleware
1414
from fastmcp.tools import Tool
@@ -215,28 +215,21 @@ async def _fetch_token_scopes_from_api(self, client=None) -> set[str]:
215215
Returns:
216216
set: The fetched scopes, or empty set on error
217217
"""
218-
try:
219-
client_to_use = self.get_client()
220-
221-
# Fetch the complete token info
222-
logger.debug("Attempting to fetch token scopes from GitGuardian API")
223-
token_info = await client_to_use.get_current_token_info()
218+
client_to_use = self.get_client()
224219

225-
# Extract scopes
226-
scopes = token_info.get("scopes", [])
227-
logger.debug(f"Retrieved token scopes: {scopes}")
220+
# Fetch the complete token info
221+
logger.debug("Attempting to fetch token scopes from GitGuardian API")
222+
token_info = await client_to_use.get_current_token_info()
228223

229-
return set(scopes)
224+
# Extract scopes
225+
scopes = token_info.get("scopes", [])
226+
logger.debug(f"Retrieved token scopes: {scopes}")
230227

231-
except Exception as e:
232-
raise FastMCPError("Error fetching token scopes from /api_tokens/self endpoint") from e
228+
return set(scopes)
233229

234230
async def _fetch_token_info_from_api(self) -> dict[str, Any]:
235-
try:
236-
client = self.get_client()
237-
return await client.get_current_token_info()
238-
except Exception as e:
239-
raise FastMCPError("Error fetching token info from /api_tokens/self endpoint") from e
231+
client = self.get_client()
232+
return await client.get_current_token_info()
240233

241234
async def get_scopes(self) -> set[str]:
242235
cached_scopes: set[str] | None = getattr(self, "_token_scopes", None)

packages/gg_api_core/src/gg_api_core/tools/assign_incident.py

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -121,18 +121,12 @@ async def assign_incident(params: AssignIncidentParams) -> AssignIncidentResult:
121121

122122
elif params.mine:
123123
# Get current user's ID from token info
124-
try:
125-
token_info = await client.get_current_token_info()
126-
if token_info and "member_id" in token_info:
127-
assignee_id = token_info["member_id"]
128-
logger.debug(f"Using current user ID for assignment: {assignee_id}")
129-
else:
130-
raise ToolError("Could not determine current user ID from token info")
131-
except ToolError:
132-
raise
133-
except Exception as e:
134-
logger.error(f"Failed to get current user info: {str(e)}")
135-
raise ToolError(f"Failed to get current user info: {str(e)}")
124+
token_info = await client.get_current_token_info()
125+
if token_info and "member_id" in token_info:
126+
assignee_id = token_info["member_id"]
127+
logger.debug(f"Using current user ID for assignment: {assignee_id}")
128+
else:
129+
raise ToolError("Could not determine current user ID from token info")
136130

137131
# Final validation
138132
if not assignee_id:

packages/gg_api_core/src/gg_api_core/tools/list_honeytokens.py

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -63,18 +63,15 @@ async def list_honeytokens(params: ListHoneytokensParams) -> ListHoneytokensResu
6363
# the current user's info first and set creator_id accordingly
6464
creator_id = params.creator_id
6565
if params.mine:
66-
try:
67-
# Get current token info to identify the user
68-
token_info = await client.get_current_token_info()
69-
logger.debug(f"Token info: {token_info}")
70-
if token_info and "member_id" in token_info:
71-
# If we have member_id, use it as creator_id
72-
creator_id = token_info["member_id"]
73-
logger.debug(f"Setting creator_id to current user: {creator_id}")
74-
else:
75-
logger.warning("Could not determine current user ID for 'mine' filter")
76-
except Exception as e:
77-
logger.warning(f"Failed to get current user info for 'mine' filter: {str(e)}")
66+
# Get current token info to identify the user
67+
token_info = await client.get_current_token_info()
68+
logger.debug(f"Token info: {token_info}")
69+
if token_info and "member_id" in token_info:
70+
# If we have member_id, use it as creator_id
71+
creator_id = token_info["member_id"]
72+
logger.debug(f"Setting creator_id to current user: {creator_id}")
73+
else:
74+
logger.warning("Could not determine current user ID for 'mine' filter")
7875

7976
try:
8077
response = await client.list_honeytokens(

tests/tools/test_list_honey_tokens.py

Lines changed: 15 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -440,7 +440,7 @@ async def test_list_honeytokens_mine_true_token_info_error(self, mock_gitguardia
440440
"""
441441
GIVEN: get_current_token_info raises an exception
442442
WHEN: Listing honeytokens with mine=True
443-
THEN: The function continues without user filtering
443+
THEN: The exception propagates to the caller
444444
"""
445445
# Mock get_current_token_info to raise exception
446446
mock_gitguardian_client.get_current_token_info = AsyncMock(side_effect=Exception("Token info failed"))
@@ -449,23 +449,21 @@ async def test_list_honeytokens_mine_true_token_info_error(self, mock_gitguardia
449449
mock_response = {"data": [], "cursor": None, "has_more": False}
450450
mock_gitguardian_client.list_honeytokens = AsyncMock(return_value=mock_response)
451451

452-
# Call the function with mine=True (should not fail, just log warning)
453-
result = await list_honeytokens(
454-
ListHoneytokensParams(
455-
status=None,
456-
search=None,
457-
ordering=None,
458-
show_token=False,
459-
creator_id=None,
460-
creator_api_token_id=None,
461-
per_page=20,
462-
get_all=False,
463-
mine=True,
452+
# Call the function with mine=True - should raise the exception
453+
with pytest.raises(Exception, match="Token info failed"):
454+
await list_honeytokens(
455+
ListHoneytokensParams(
456+
status=None,
457+
search=None,
458+
ordering=None,
459+
show_token=False,
460+
creator_id=None,
461+
creator_api_token_id=None,
462+
per_page=20,
463+
get_all=False,
464+
mine=True,
465+
)
464466
)
465-
)
466-
467-
# Verify function completes without error
468-
assert result.honeytokens == []
469467

470468
@pytest.mark.asyncio
471469
async def test_list_honeytokens_cursor_pagination(self, mock_gitguardian_client):

0 commit comments

Comments
 (0)