google / google/adk-python

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

Aperta
#3,445 1 commento 0 reazioni 1 assegnatario Rivendicata da @wyf7107 Vedi su GitHub
needs review web
Lingua principale
Python
Stelle
21.5k
Fork
4k
Merge medio
1g 14h
PR unite (30g)
37

Descrizione

### 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)

Guida per i contributori

Apri la guida per i contributori

Valutazione

Questa issue non è ancora stata valutata.

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.