google / google/adk-python

Support plugin hooks for session-related HTTP endpoints to enable authentication validation

Ouverte
#3,445 1 commentaire 0 réactions 1 personne assignée Réclamée par @wyf7107 Voir sur GitHub
needs review web
Langage dominant
Python
Étoiles
21.5k
Forks
4k
Merge moyen
1 j 14 h
PR mergées (30 j)
37

Description

### Is your feature request related to a problem? Please describe.

Currently, ADK's plugin system provides callbacks like `on_user_message_callback` and `before_run_callback`, but these are all invoked within the `Runner.run_async()` execution flow.

However, session management HTTP endpoints (`GET/POST/PATCH/DELETE /apps/{app_name}/users/{user_id}/sessions/*`) execute **before** `Runner.run_async()` is called, making them inaccessible to existing plugin hooks.

**Specific problems:**
- No way to validate JWT token `sub` claim against `user_id` parameter at the session endpoint level
- Cannot implement authentication/authorization checks for session create/get/update/delete operations uniformly via plugins
- While FastAPI middleware is possible, accessing endpoint-specific parameters (`user_id`, `session_id`, etc.) is cumbersome and breaks consistency with ADK's plugin system

### Describe the solution you'd like

Add plugin hooks for session-related HTTP endpoints by extending the existing `BasePlugin` class with new callback methods.

**Proposed new callback:**

```python
async def before_session_endpoint_callback(
self,
*,
endpoint_type: Literal["get", "create", "update", "delete", "list"],
app_name: str,
user_id: str,
session_id: Optional[str],
request_headers: dict[str, str],
request_body: Optional[dict[str, Any]],
) -> Optional[HTTPException]:
"""
Called before session-related endpoint execution.

Returns:
HTTPException to skip endpoint execution and return that error.
None to continue normal execution.
"""
pass
```

**Implementation location:**
In the `AdkWebServer` class, invoke this callback in each session endpoint (`get_session`, `create_session`, `update_session`, `delete_session`, `list_sessions`) before calling `session_service`.

**Usage example:**

```python
class JWTValidationPlugin(BasePlugin):
async def before_session_endpoint_callback(
self, *, endpoint_type, app_name, user_id, session_id,
request_headers, request_body
):
auth_header = request_headers.get("authorization", "")
if not auth_header.startswith("Bearer "):
return HTTPException(status_code=401, detail="Missing JWT token")

token = auth_header[7:]
claims = parse_jwt(token) # Implementation omitted

if claims.get("sub") != user_id:
return HTTPException(
status_code=403,
detail="JWT sub does not match user_id"
)

return None # Validation passed, continue
```

### Describe alternatives you've considered

1. **FastAPI middleware implementation**: Possible but makes accessing endpoint-specific parameters complex and loses consistency with ADK's plugin system

2. **Custom `SessionService` implementation**: While you can extend `BaseSessionService`, this operates at the service layer rather than HTTP layer, preventing access to HTTP headers

3. **Using `on_user_message_callback`**: This callback is invoked within `Runner.run_async()`, so it cannot intercept session get/create endpoints themselves

### Additional context

- To maintain consistency with the existing plugin system, adding to the `BasePlugin` class is preferred
- Will need to add a new callback execution method (`run_before_session_endpoint_callback`) to `PluginManager`
- Error responses should use standard FastAPI `HTTPException` format
- JWT parsing should be implemented in plugins, not in ADK core (for security and maintainability)

Guide de contribution

Ouvrir le guide de contribution

Évaluation

Cette issue n'a pas encore été évaluée.

Recevez les nouvelles issues par e-mail

Un résumé court des issues GitHub adaptées aux débutants.