Skip to content

Conversation

@DavidsonGomes
Copy link
Contributor

@DavidsonGomes DavidsonGomes commented May 13, 2025

Summary by Sourcery

Add API key sharing endpoints and extend chat routes to support flexible authentication (JWT or API key), refactor streaming chunk processing, and update the changelog

New Features:

  • Add flexible authentication dependency to support JWT or API key auth for chat and WebSocket routes
  • Expose POST /{agent_id}/share endpoint to retrieve an agent’s API key for sharing
  • Expose GET /{agent_id}/shared endpoint to fetch agent details using only API key authentication

Enhancements:

  • Streamline chat handler by replacing direct JWT dependency with the new flexible auth dependency
  • Enhance WebSocket handshake to accept and validate either JWT tokens or API keys
  • Refactor a2a_task_manager streaming logic to parse the updated chunk structure and improve error handling

Documentation:

  • Update CHANGELOG.md with entry for API key sharing and flexible authentication in version 0.0.9

@sourcery-ai
Copy link

sourcery-ai bot commented May 13, 2025

Reviewer's Guide

This PR implements flexible JWT/API key authentication for chat routes, adds endpoints to share and retrieve agents via API keys, refactors the streaming task processor to handle content-based chunks, and updates the CHANGELOG for version 0.0.9.

File-Level Changes

Change Details Files
Flexible authentication for chat routes
  • Imported Optional and Dict for header typing
  • Implemented get_agent_by_api_key to handle JWT or API key
  • Enhanced websocket_chat to process auth_data with token or api_key
  • Replaced JWT-only dependency in chat endpoint with get_agent_by_api_key
  • Updated authentication logging messages
src/api/chat_routes.py
API key sharing endpoints
  • Added share_agent endpoint to validate client and return API key
  • Added get_shared_agent endpoint for API key–based agent retrieval with card URL fallback
src/api/agent_routes.py
Refactor streaming task processing
  • Removed legacy type checks for chunks
  • Parsed content.role and parts to construct Message objects
  • Streamlined error handling and full_response accumulation
src/services/a2a_task_manager.py
Changelog update for version 0.0.9
  • Added entry for API key sharing and flexible authentication under 'Added'
CHANGELOG.md

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@DavidsonGomes DavidsonGomes merged commit 6cfff4c into main May 13, 2025
2 checks passed
Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @DavidsonGomes - I've reviewed your changes and found some issues that need to be addressed.

Blocking issues:

  • Avoid logging raw auth_data to prevent leaking credentials (link)

  • The flexible JWT/API key authentication logic is duplicated in both get_agent_by_api_key and websocket_chat—consider extracting it into a shared dependency or helper to reduce duplication and improve maintainability.

  • In _stream_task_process you now skip any chunk without a 'content' key silently; consider adding a debug log or fallback handling for unexpected chunk formats to make debugging easier.

Here's what I looked at during the review
  • 🟡 General issues: 4 issues found
  • 🔴 Security: 1 blocking issue
  • 🟢 Testing: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines +75 to +76
api_key: Optional[str] = Header(None, alias="x-api-key"),
authorization: Optional[str] = Header(None),
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (bug_risk): Use explicit alias for the Authorization header

FastAPI’s Header defaults to lowercase 'authorization', but clients send 'Authorization'. Add alias='Authorization' so it's recognized.

Suggested change
api_key: Optional[str] = Header(None, alias="x-api-key"),
authorization: Optional[str] = Header(None),
api_key: Optional[str] = Header(None, alias="x-api-key"),
authorization: Optional[str] = Header(None, alias="Authorization"),

# Verify if the user has access to the agent's client
await verify_user_client(payload, db, agent.client_id)
return agent
except Exception as e:
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (bug_risk): Avoid catching generic Exception in JWT flow

Don't catch Exception; it hides HTTPExceptions (e.g., 404). Only catch token-validation errors and re-raise others.

try:
auth_data = await websocket.receive_json()
logger.info(f"Received authentication data: {auth_data}")
logger.info(f"Authentication data received: {auth_data}")
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 issue (security): Avoid logging raw auth_data to prevent leaking credentials

auth_data can include tokens or API keys, so cleartext logging may expose secrets. Log only non-sensitive fields (e.g. auth_data['type']).

)
async def chat(
request: ChatRequest,
_=Depends(get_agent_by_api_key),
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Capture the authenticated agent instead of discarding it

Rename _ to agent so the handler can use the validated agent directly and skip extra lookups.

Suggested change
_=Depends(get_agent_by_api_key),
agent=Depends(get_agent_by_api_key),

logger.error(
f"Error processing chunk: {e}, chunk: {chunk_data}"
)
for part in parts:
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue: Guard against non-dict parts before calling part.get()

Check isinstance(part, dict) before using part.get(), or enforce that all parts are dicts to avoid errors when parts include raw strings.



@router.websocket("/ws/{agent_id}/{external_id}")
async def websocket_chat(
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (code-quality): Low code quality found in websocket_chat - 21% (low-code-quality)


ExplanationThe quality score for this function is below the quality threshold of 25%.
This score is a combination of the method length, cognitive complexity and working memory.

How can you solve this?

It might be worth refactoring this function to make it shorter and more readable.

  • Reduce the function length by extracting pieces of functionality out into
    their own functions. This is the most important thing you can do - ideally a
    function should be less than 10 lines.
  • Reduce nesting, perhaps by introducing guard clauses to return early.
  • Ensure that variables are tightly scoped, so that code using related concepts
    sits together within the function rather than being scattered.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants