google-adk-extras 0.2.7__tar.gz → 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. {google_adk_extras-0.2.7/src/google_adk_extras.egg-info → google_adk_extras-0.3.0}/PKG-INFO +74 -2
  2. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/README.md +73 -1
  3. google_adk_extras-0.3.0/docs/auth.md +79 -0
  4. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/docs/index.md +6 -1
  5. google_adk_extras-0.3.0/examples/adk_server_8015.py +43 -0
  6. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/pyproject.toml +1 -1
  7. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/src/google_adk_extras/__init__.py +1 -1
  8. google_adk_extras-0.3.0/src/google_adk_extras/auth/__init__.py +10 -0
  9. google_adk_extras-0.3.0/src/google_adk_extras/auth/attach.py +227 -0
  10. google_adk_extras-0.3.0/src/google_adk_extras/auth/config.py +45 -0
  11. google_adk_extras-0.3.0/src/google_adk_extras/auth/jwt_utils.py +36 -0
  12. google_adk_extras-0.3.0/src/google_adk_extras/auth/sql_store.py +183 -0
  13. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/src/google_adk_extras/enhanced_fastapi.py +6 -0
  14. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0/src/google_adk_extras.egg-info}/PKG-INFO +74 -2
  15. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/src/google_adk_extras.egg-info/SOURCES.txt +7 -0
  16. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/LICENSE +0 -0
  17. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/MANIFEST.in +0 -0
  18. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/docs/agent-loading.md +0 -0
  19. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/docs/examples.md +0 -0
  20. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/docs/fastapi.md +0 -0
  21. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/docs/getting-started.md +0 -0
  22. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/docs/quickstarts.md +0 -0
  23. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/docs/services.md +0 -0
  24. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/docs/streaming.md +0 -0
  25. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/docs/troubleshooting.md +0 -0
  26. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/docs/uris.md +0 -0
  27. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/examples/README.md +0 -0
  28. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/examples/consume_remote_a2a.py +0 -0
  29. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/examples/custom_loader.py +0 -0
  30. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/examples/fastapi_app.py +0 -0
  31. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/examples/programmatic_a2a_expose.py +0 -0
  32. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/examples/runner_basic.py +0 -0
  33. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/examples/services/artifacts_local.py +0 -0
  34. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/examples/services/memory_yaml.py +0 -0
  35. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/examples/services/sessions_sql.py +0 -0
  36. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/examples/streaming_sse_ws.py +0 -0
  37. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/mkdocs.yml +0 -0
  38. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/setup.cfg +0 -0
  39. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/setup.py +0 -0
  40. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/src/google_adk_extras/adk_builder.py +0 -0
  41. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/src/google_adk_extras/artifacts/__init__.py +0 -0
  42. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/src/google_adk_extras/artifacts/base_custom_artifact_service.py +0 -0
  43. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/src/google_adk_extras/artifacts/local_folder_artifact_service.py +0 -0
  44. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/src/google_adk_extras/artifacts/mongo_artifact_service.py +0 -0
  45. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/src/google_adk_extras/artifacts/s3_artifact_service.py +0 -0
  46. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/src/google_adk_extras/artifacts/sql_artifact_service.py +0 -0
  47. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/src/google_adk_extras/credentials/base_custom_credential_service.py +0 -0
  48. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/src/google_adk_extras/custom_agent_loader.py +0 -0
  49. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/src/google_adk_extras/enhanced_adk_web_server.py +0 -0
  50. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/src/google_adk_extras/enhanced_runner.py +0 -0
  51. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/src/google_adk_extras/memory/__init__.py +0 -0
  52. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/src/google_adk_extras/memory/base_custom_memory_service.py +0 -0
  53. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/src/google_adk_extras/memory/mongo_memory_service.py +0 -0
  54. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/src/google_adk_extras/memory/redis_memory_service.py +0 -0
  55. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/src/google_adk_extras/memory/sql_memory_service.py +0 -0
  56. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/src/google_adk_extras/memory/yaml_file_memory_service.py +0 -0
  57. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/src/google_adk_extras/sessions/__init__.py +0 -0
  58. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/src/google_adk_extras/sessions/base_custom_session_service.py +0 -0
  59. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/src/google_adk_extras/sessions/mongo_session_service.py +0 -0
  60. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/src/google_adk_extras/sessions/redis_session_service.py +0 -0
  61. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/src/google_adk_extras/sessions/sql_session_service.py +0 -0
  62. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/src/google_adk_extras/sessions/yaml_file_session_service.py +0 -0
  63. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/src/google_adk_extras/streaming/__init__.py +0 -0
  64. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/src/google_adk_extras/streaming/streaming_controller.py +0 -0
  65. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/src/google_adk_extras.egg-info/dependency_links.txt +0 -0
  66. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/src/google_adk_extras.egg-info/requires.txt +0 -0
  67. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/src/google_adk_extras.egg-info/top_level.txt +0 -0
  68. {google_adk_extras-0.2.7 → google_adk_extras-0.3.0}/tests/test_a2a_helpers.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: google-adk-extras
3
- Version: 0.2.7
3
+ Version: 0.3.0
4
4
  Summary: Production-ready services and FastAPI wiring for Google ADK
5
5
  Home-page: https://github.com/DeadMeme5441/google-adk-extras
6
6
  Author: DeadMeme5441
@@ -94,7 +94,7 @@ If you plan to use specific backends, also install their clients (examples):
94
94
  - Redis: `uv pip install redis`
95
95
  - S3: `uv pip install boto3`
96
96
 
97
- Note on credentials (0.2.7): This release removes custom credential services and URI helpers from this package. For outbound credentials used by tools, rely on ADK’s experimental BaseCredentialService (e.g., InMemory/SessionState) or your own ADK-compatible implementation. Inbound API authentication (protecting /run and streaming routes) will be provided as an optional FastAPI layer separately.
97
+ Note on credentials (0.3.0): Outbound credentials for tools remain ADK’s concern (use ADK’s BaseCredentialService). Inbound API authentication is now available as an optional FastAPI layer in this package (see Auth below). You can run fully open (no auth) or enable API Key, Basic, or JWT (including first‑party issuance backed by SQL).
98
98
 
99
99
 
100
100
  ## Quickstart (FastAPI)
@@ -104,6 +104,7 @@ Use the fluent builder to wire services. Then run with uvicorn.
104
104
  ```python
105
105
  # app.py
106
106
  from google_adk_extras import AdkBuilder
107
+ from google_adk_extras.auth import AuthConfig, JwtIssuerConfig, JwtValidatorConfig
107
108
 
108
109
  app = (
109
110
  AdkBuilder()
@@ -127,6 +128,77 @@ uvicorn app:app --reload
127
128
  If you don’t keep agents on disk, register them programmatically and use a custom loader (see below).
128
129
 
129
130
 
131
+ ## Auth (optional)
132
+
133
+ Auth is entirely optional. By default, all endpoints are open (no auth). To enable protection, pass `auth_config` into `get_enhanced_fast_api_app` via the builder or directly.
134
+
135
+ Supported inbound methods:
136
+ - API Key: `X-API-Key: <key>` header (or `?api_key=` query). Keys can be static via config, or issued/rotated via SQL‑backed endpoints.
137
+ - HTTP Basic: `Authorization: Basic base64(user:pass)` for quick human/internal testing. Can validate against in‑memory map or the SQL users table.
138
+ - Bearer JWT (validate): Accept JWTs from Google/Auth0/Okta/etc. via JWKS, or HS256 secret in dev. Enforces iss/aud/exp/nbf.
139
+ - Bearer JWT (issue): First‑party issuer with HS256, tokens minted from `/auth/token`, users stored in SQL (SQLite/Postgres/MySQL).
140
+
141
+ Minimal enablement (JWT validate only):
142
+
143
+ ```python
144
+ from google_adk_extras.auth import AuthConfig, JwtValidatorConfig
145
+
146
+ auth = AuthConfig(
147
+ enabled=True,
148
+ jwt_validator=JwtValidatorConfig(
149
+ jwks_url="https://accounts.google.com/.well-known/openid-configuration", # example
150
+ issuer="https://accounts.google.com",
151
+ audience="your-api-audience",
152
+ ),
153
+ )
154
+
155
+ app = (
156
+ AdkBuilder()
157
+ .with_agents_dir("./agents")
158
+ .build_fastapi_app()
159
+ )
160
+ ```
161
+
162
+ First‑party issuer + validate (single shared HS256 secret) with SQL connector:
163
+
164
+ ```python
165
+ from google_adk_extras.auth import AuthConfig, JwtIssuerConfig, JwtValidatorConfig
166
+
167
+ issuer = JwtIssuerConfig(
168
+ enabled=True,
169
+ issuer="https://local-issuer",
170
+ audience="adk-api",
171
+ algorithm="HS256",
172
+ hs256_secret="topsecret",
173
+ database_url="sqlite:///./auth.db", # also supports Postgres/MySQL
174
+ )
175
+ validator = JwtValidatorConfig(
176
+ issuer=issuer.issuer,
177
+ audience=issuer.audience,
178
+ hs256_secret=issuer.hs256_secret,
179
+ )
180
+
181
+ auth = AuthConfig(enabled=True, jwt_issuer=issuer, jwt_validator=validator)
182
+
183
+ app = (
184
+ AdkBuilder()
185
+ .with_agents_dir("./agents")
186
+ .build_fastapi_app()
187
+ )
188
+ ```
189
+
190
+ Issuing and using tokens/keys at runtime:
191
+ - Register user: `POST /auth/register?username=alice&password=wonder`
192
+ - Token (password): `POST /auth/token?grant_type=password&username=alice&password=wonder`
193
+ - Refresh: `POST /auth/refresh?user_id=<uid>&refresh_token=<jti>`
194
+ - Create API key: `POST /auth/api-keys` (auth required) → returns `{ id, api_key }` (plaintext shown once)
195
+ - List keys: `GET /auth/api-keys` (auth required)
196
+ - Revoke key: `DELETE /auth/api-keys/{id}` (auth required)
197
+ - Use API key: add `X-API-Key: <api_key>` to any protected route (keys currently allow full access)
198
+
199
+ Protected routes include `/run`, `/run_sse`, all `/apps/...` session/artifact/eval endpoints, `/debug/*`, `/builder/*`, and optionally `/list-apps` and `/apps/{app}/metrics-info`.
200
+
201
+
130
202
  ## Quickstart (Runner)
131
203
 
132
204
  Create a Runner wired with your chosen backends. Use agent name (filesystem loader) or pass an agent instance.
@@ -51,7 +51,7 @@ If you plan to use specific backends, also install their clients (examples):
51
51
  - Redis: `uv pip install redis`
52
52
  - S3: `uv pip install boto3`
53
53
 
54
- Note on credentials (0.2.7): This release removes custom credential services and URI helpers from this package. For outbound credentials used by tools, rely on ADK’s experimental BaseCredentialService (e.g., InMemory/SessionState) or your own ADK-compatible implementation. Inbound API authentication (protecting /run and streaming routes) will be provided as an optional FastAPI layer separately.
54
+ Note on credentials (0.3.0): Outbound credentials for tools remain ADK’s concern (use ADK’s BaseCredentialService). Inbound API authentication is now available as an optional FastAPI layer in this package (see Auth below). You can run fully open (no auth) or enable API Key, Basic, or JWT (including first‑party issuance backed by SQL).
55
55
 
56
56
 
57
57
  ## Quickstart (FastAPI)
@@ -61,6 +61,7 @@ Use the fluent builder to wire services. Then run with uvicorn.
61
61
  ```python
62
62
  # app.py
63
63
  from google_adk_extras import AdkBuilder
64
+ from google_adk_extras.auth import AuthConfig, JwtIssuerConfig, JwtValidatorConfig
64
65
 
65
66
  app = (
66
67
  AdkBuilder()
@@ -84,6 +85,77 @@ uvicorn app:app --reload
84
85
  If you don’t keep agents on disk, register them programmatically and use a custom loader (see below).
85
86
 
86
87
 
88
+ ## Auth (optional)
89
+
90
+ Auth is entirely optional. By default, all endpoints are open (no auth). To enable protection, pass `auth_config` into `get_enhanced_fast_api_app` via the builder or directly.
91
+
92
+ Supported inbound methods:
93
+ - API Key: `X-API-Key: <key>` header (or `?api_key=` query). Keys can be static via config, or issued/rotated via SQL‑backed endpoints.
94
+ - HTTP Basic: `Authorization: Basic base64(user:pass)` for quick human/internal testing. Can validate against in‑memory map or the SQL users table.
95
+ - Bearer JWT (validate): Accept JWTs from Google/Auth0/Okta/etc. via JWKS, or HS256 secret in dev. Enforces iss/aud/exp/nbf.
96
+ - Bearer JWT (issue): First‑party issuer with HS256, tokens minted from `/auth/token`, users stored in SQL (SQLite/Postgres/MySQL).
97
+
98
+ Minimal enablement (JWT validate only):
99
+
100
+ ```python
101
+ from google_adk_extras.auth import AuthConfig, JwtValidatorConfig
102
+
103
+ auth = AuthConfig(
104
+ enabled=True,
105
+ jwt_validator=JwtValidatorConfig(
106
+ jwks_url="https://accounts.google.com/.well-known/openid-configuration", # example
107
+ issuer="https://accounts.google.com",
108
+ audience="your-api-audience",
109
+ ),
110
+ )
111
+
112
+ app = (
113
+ AdkBuilder()
114
+ .with_agents_dir("./agents")
115
+ .build_fastapi_app()
116
+ )
117
+ ```
118
+
119
+ First‑party issuer + validate (single shared HS256 secret) with SQL connector:
120
+
121
+ ```python
122
+ from google_adk_extras.auth import AuthConfig, JwtIssuerConfig, JwtValidatorConfig
123
+
124
+ issuer = JwtIssuerConfig(
125
+ enabled=True,
126
+ issuer="https://local-issuer",
127
+ audience="adk-api",
128
+ algorithm="HS256",
129
+ hs256_secret="topsecret",
130
+ database_url="sqlite:///./auth.db", # also supports Postgres/MySQL
131
+ )
132
+ validator = JwtValidatorConfig(
133
+ issuer=issuer.issuer,
134
+ audience=issuer.audience,
135
+ hs256_secret=issuer.hs256_secret,
136
+ )
137
+
138
+ auth = AuthConfig(enabled=True, jwt_issuer=issuer, jwt_validator=validator)
139
+
140
+ app = (
141
+ AdkBuilder()
142
+ .with_agents_dir("./agents")
143
+ .build_fastapi_app()
144
+ )
145
+ ```
146
+
147
+ Issuing and using tokens/keys at runtime:
148
+ - Register user: `POST /auth/register?username=alice&password=wonder`
149
+ - Token (password): `POST /auth/token?grant_type=password&username=alice&password=wonder`
150
+ - Refresh: `POST /auth/refresh?user_id=<uid>&refresh_token=<jti>`
151
+ - Create API key: `POST /auth/api-keys` (auth required) → returns `{ id, api_key }` (plaintext shown once)
152
+ - List keys: `GET /auth/api-keys` (auth required)
153
+ - Revoke key: `DELETE /auth/api-keys/{id}` (auth required)
154
+ - Use API key: add `X-API-Key: <api_key>` to any protected route (keys currently allow full access)
155
+
156
+ Protected routes include `/run`, `/run_sse`, all `/apps/...` session/artifact/eval endpoints, `/debug/*`, `/builder/*`, and optionally `/list-apps` and `/apps/{app}/metrics-info`.
157
+
158
+
87
159
  ## Quickstart (Runner)
88
160
 
89
161
  Create a Runner wired with your chosen backends. Use agent name (filesystem loader) or pass an agent instance.
@@ -0,0 +1,79 @@
1
+ # Auth (Optional)
2
+
3
+ Inbound API authentication is optional. If you don’t pass an `auth_config`, all routes are open (useful for local dev). When enabled, the middleware protects sensitive routes and enforces identity where appropriate.
4
+
5
+ Supported methods:
6
+ - API Key
7
+ - Send `X-API-Key: <token>` header or `?api_key=<token>` query.
8
+ - Keys can be static via config or issued/rotated via SQL‑backed endpoints.
9
+ - HTTP Basic
10
+ - `Authorization: Basic base64(user:pass)`.
11
+ - Checks an in‑memory map or the SQL users table when configured.
12
+ - Bearer JWT (validate)
13
+ - Validate JWTs from OIDC providers (Google, Auth0, Okta, etc.) via JWKS.
14
+ - Or use HS256 with a shared secret in dev.
15
+ - Bearer JWT (issue)
16
+ - First‑party issuer backed by SQL; exposes `/auth/register`, `/auth/token`, `/auth/refresh`.
17
+
18
+ ## Quick examples
19
+
20
+ ### Enable JWT validate only
21
+ ```python
22
+ from google_adk_extras import AdkBuilder
23
+ from google_adk_extras.auth import AuthConfig, JwtValidatorConfig
24
+
25
+ auth = AuthConfig(
26
+ enabled=True,
27
+ jwt_validator=JwtValidatorConfig(
28
+ jwks_url="https://YOUR_ISSUER/.well-known/jwks.json",
29
+ issuer="https://YOUR_ISSUER",
30
+ audience="your-api-audience",
31
+ ),
32
+ )
33
+
34
+ app = AdkBuilder().with_agents_dir("./agents").build_fastapi_app()
35
+ ```
36
+
37
+ ### First‑party issuer + validate (HS256) and SQL store
38
+ ```python
39
+ from google_adk_extras import AdkBuilder
40
+ from google_adk_extras.auth import AuthConfig, JwtIssuerConfig, JwtValidatorConfig
41
+
42
+ issuer = JwtIssuerConfig(
43
+ enabled=True,
44
+ issuer="https://local-issuer",
45
+ audience="adk-api",
46
+ algorithm="HS256",
47
+ hs256_secret="topsecret",
48
+ database_url="sqlite:///./auth.db",
49
+ )
50
+ validator = JwtValidatorConfig(issuer=issuer.issuer, audience=issuer.audience, hs256_secret=issuer.hs256_secret)
51
+
52
+ auth = AuthConfig(enabled=True, jwt_issuer=issuer, jwt_validator=validator)
53
+
54
+ app = AdkBuilder().with_agents_dir("./agents").build_fastapi_app()
55
+ ```
56
+
57
+ ### API key management endpoints (SQL store)
58
+ - `POST /auth/api-keys` → `{ id, api_key }` (plaintext shown once)
59
+ - `GET /auth/api-keys` → list metadata
60
+ - `DELETE /auth/api-keys/{id}` → revoke
61
+
62
+ Use `X-API-Key: <api_key>` (or `?api_key=`) to access protected routes.
63
+
64
+ ## What’s protected
65
+ - Always: `POST /run`, `POST /run_sse`, `GET/POST/DELETE /apps/...`, `/debug/*`, `/builder/*`.
66
+ - Optional: `/list-apps` and `/apps/{app}/metrics-info` (toggled in `AuthConfig`).
67
+ - Ownership: when the URL contains `/users/{user_id}/...`, the `sub` from the token must match `user_id` (API key bypass permitted).
68
+
69
+ ## Optional by design
70
+ - No‑auth is the default. Enable auth only when you’re ready.
71
+ - You can mix modes: e.g., JWT for users and API keys for automation.
72
+
73
+ ```python
74
+ # Direct call if not using the builder
75
+ from google_adk_extras.enhanced_fastapi import get_enhanced_fast_api_app
76
+ from google_adk_extras.auth import AuthConfig
77
+ app = get_enhanced_fast_api_app(..., auth_config=AuthConfig(enabled=True, api_keys=["test"]))
78
+ ```
79
+
@@ -14,6 +14,11 @@ What this is not: a fork of ADK. It builds on top of google-adk.
14
14
  - `EnhancedAdkWebServer`
15
15
  - `EnhancedRunner` (thin wrapper)
16
16
  - `CustomAgentLoader` (programmatic agents)
17
- - Services via subpackages: `sessions`, `artifacts`, `memory`, `credentials`
17
+ - Services via subpackages: `sessions`, `artifacts`, `memory` (optional inbound auth lives under `auth/`)
18
18
 
19
19
  See Quickstarts for copy‑paste examples.
20
+
21
+ Additional guides:
22
+ - [FastAPI Integration](fastapi.md)
23
+ - [Streaming](streaming.md)
24
+ - [Auth (Optional)](auth.md)
@@ -0,0 +1,43 @@
1
+ """Spin up an ADK FastAPI server on 127.0.0.1:8015 with in-memory services.
2
+
3
+ This script uses google_adk_extras.get_enhanced_fast_api_app with a simple
4
+ programmatic agent loader. It is intended only to inspect the OpenAPI schema
5
+ and enumerate endpoints exposed by the ADK web server.
6
+ """
7
+
8
+ from typing import AsyncGenerator, Optional
9
+
10
+ from fastapi import FastAPI
11
+
12
+ from google.genai import types
13
+ from google.adk.events.event import Event
14
+ from google.adk.agents.base_agent import BaseAgent
15
+
16
+ from google_adk_extras.custom_agent_loader import CustomAgentLoader
17
+ from google_adk_extras.enhanced_fastapi import get_enhanced_fast_api_app
18
+
19
+
20
+ class _DummyAgent(BaseAgent):
21
+ """Minimal agent; not used for OpenAPI generation, but loadable if needed."""
22
+
23
+ def __init__(self, name: str = "dummy"):
24
+ super().__init__(name)
25
+
26
+ async def run_async(self, ctx) -> AsyncGenerator[Event, None]:
27
+ # Emit a trivial final event; unlikely to be executed in this script.
28
+ content = types.Content(parts=[types.Part(text="ok")])
29
+ yield Event(author=self.name, content=content)
30
+
31
+
32
+ def build_app() -> FastAPI:
33
+ loader = CustomAgentLoader()
34
+ app = get_enhanced_fast_api_app(
35
+ agent_loader=loader,
36
+ web=False, # no static UI
37
+ enable_streaming=False, # focus on ADK core endpoints
38
+ allow_origins=["*"]
39
+ )
40
+ return app
41
+
42
+
43
+ app = build_app()
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "google-adk-extras"
3
- version = "0.2.7"
3
+ version = "0.3.0"
4
4
  description = "Production-ready services and FastAPI wiring for Google ADK"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.10,<3.13"
@@ -28,4 +28,4 @@ __all__ = [
28
28
  "CustomAgentLoader",
29
29
  ]
30
30
 
31
- __version__ = "0.2.7"
31
+ __version__ = "0.3.0"
@@ -0,0 +1,10 @@
1
+ from .config import AuthConfig, JwtIssuerConfig, JwtValidatorConfig
2
+ from .attach import attach_auth
3
+
4
+ __all__ = [
5
+ "AuthConfig",
6
+ "JwtIssuerConfig",
7
+ "JwtValidatorConfig",
8
+ "attach_auth",
9
+ ]
10
+
@@ -0,0 +1,227 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Optional
4
+
5
+ from fastapi import APIRouter, Depends, FastAPI, HTTPException, Request
6
+ import base64
7
+ from fastapi.security import APIKeyHeader
8
+ from starlette.middleware.base import BaseHTTPMiddleware
9
+
10
+ from .config import AuthConfig, JwtIssuerConfig, JwtValidatorConfig
11
+ from .jwt_utils import decode_jwt, encode_jwt, now_ts
12
+ from .sql_store import AuthStore
13
+
14
+
15
+ def attach_auth(app: FastAPI, cfg: Optional[AuthConfig]) -> None:
16
+ """Attach optional auth to the provided FastAPI app.
17
+
18
+ - Adds middleware that enforces auth on sensitive routes.
19
+ - Optionally registers token issuance endpoints if configured.
20
+ """
21
+ if not cfg or not cfg.enabled or cfg.allow_no_auth:
22
+ return
23
+
24
+ validator = cfg.jwt_validator
25
+ issuer_cfg = cfg.jwt_issuer
26
+ api_keys = set(cfg.api_keys or [])
27
+ basic_users = cfg.basic_users or {}
28
+ auth_store: Optional[AuthStore] = None
29
+ if issuer_cfg and issuer_cfg.database_url:
30
+ auth_store = AuthStore(issuer_cfg.database_url)
31
+
32
+ # Security helpers
33
+ api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)
34
+
35
+ async def _authenticate(request: Request) -> dict:
36
+ # API Key
37
+ api_key = request.query_params.get("api_key") or request.headers.get("x-api-key") or request.headers.get("X-API-Key")
38
+ if not api_key:
39
+ api_key = await api_key_header.__call__(request)
40
+ if api_key and api_key in api_keys:
41
+ return {"method": "api_key", "sub": "api_key_client"}
42
+ if api_key and auth_store and auth_store.verify_api_key(api_key):
43
+ return {"method": "api_key", "sub": "api_key_client"}
44
+
45
+ # Basic
46
+ authz = request.headers.get("authorization") or request.headers.get("Authorization")
47
+ if authz and authz.lower().startswith("basic "):
48
+ try:
49
+ b64 = authz.split(" ", 1)[1]
50
+ raw = base64.b64decode(b64).decode("utf-8")
51
+ username, _, password = raw.partition(":")
52
+ except Exception:
53
+ username, password = "", ""
54
+ # If SQL store present, try it first; else fall back to configured map
55
+ if auth_store:
56
+ uid = auth_store.authenticate_basic(username, password)
57
+ if uid:
58
+ return {"method": "basic", "sub": uid, "username": username}
59
+ stored = basic_users.get(username)
60
+ if stored and (stored == password):
61
+ return {"method": "basic", "sub": username, "username": username}
62
+
63
+ # Bearer JWT
64
+ if authz and authz.lower().startswith("bearer "):
65
+ token = authz.split(" ", 1)[1]
66
+ if validator and (validator.jwks_url or validator.hs256_secret):
67
+ try:
68
+ claims = decode_jwt(
69
+ token,
70
+ issuer=validator.issuer,
71
+ audience=validator.audience,
72
+ jwks_url=validator.jwks_url,
73
+ hs256_secret=validator.hs256_secret,
74
+ )
75
+ sub = str(claims.get("sub"))
76
+ if not sub:
77
+ raise HTTPException(status_code=401, detail="Invalid token: no subject")
78
+ return {"method": "jwt", "sub": sub, "claims": claims}
79
+ except Exception as e:
80
+ raise HTTPException(status_code=401, detail=f"Invalid token: {e}")
81
+
82
+ raise HTTPException(status_code=401, detail="Unauthorized")
83
+
84
+ def _path_requires_auth(path: str, method: str) -> bool:
85
+ method = method.upper()
86
+ # Always protect core run endpoints
87
+ if path == "/run" and method == "POST":
88
+ return True
89
+ if path == "/run_sse" and method == "POST":
90
+ return True
91
+ # Sessions and artifacts under /apps
92
+ if path.startswith("/apps/"):
93
+ # Allow metrics to be toggled
94
+ if path.endswith("/metrics-info") and method == "GET":
95
+ return cfg.protect_metrics
96
+ return True
97
+ # Debug and builder are privileged
98
+ if path.startswith("/debug/") or path.startswith("/builder/"):
99
+ return True
100
+ # API key management endpoints
101
+ if path.startswith("/auth/api-keys"):
102
+ return True
103
+ # Optionally protect list-apps
104
+ if path == "/list-apps" and method == "GET":
105
+ return cfg.protect_list_apps
106
+ return False
107
+
108
+ class _AuthMiddleware(BaseHTTPMiddleware):
109
+ async def dispatch(self, request: Request, call_next):
110
+ path = request.url.path
111
+ if not _path_requires_auth(path, request.method):
112
+ return await call_next(request)
113
+ # Authenticate
114
+ try:
115
+ request.state.identity = await _authenticate(request)
116
+ except HTTPException as e:
117
+ from fastapi.responses import JSONResponse
118
+ return JSONResponse({"detail": e.detail}, status_code=e.status_code)
119
+ # Optional: Enforce user ownership when path has /users/{user_id}/
120
+ try:
121
+ parts = path.strip("/").split("/")
122
+ if "users" in parts:
123
+ idx = parts.index("users")
124
+ claimed = parts[idx + 1]
125
+ sub = str(request.state.identity.get("sub"))
126
+ # Allow api_key method to bypass ownership
127
+ if request.state.identity.get("method") != "api_key" and sub != claimed:
128
+ from fastapi.responses import JSONResponse
129
+ return JSONResponse({"detail": "Forbidden: user mismatch"}, status_code=403)
130
+ except HTTPException:
131
+ raise
132
+ except Exception:
133
+ pass
134
+ return await call_next(request)
135
+
136
+ app.add_middleware(_AuthMiddleware)
137
+
138
+ # Token issuance endpoints (optional)
139
+ if issuer_cfg and issuer_cfg.enabled:
140
+ if issuer_cfg.algorithm == "HS256" and not issuer_cfg.hs256_secret:
141
+ raise RuntimeError("HS256 issuer requires hs256_secret")
142
+ router = APIRouter()
143
+
144
+ @router.post("/auth/register")
145
+ async def register(username: str, password: str):
146
+ if not auth_store:
147
+ raise HTTPException(status_code=400, detail="SQL store not configured")
148
+ uid = auth_store.create_user(username, password)
149
+ return {"user_id": uid}
150
+
151
+ @router.post("/auth/token")
152
+ async def token_grant(grant_type: str = "password", username: Optional[str] = None, password: Optional[str] = None,
153
+ user_id: Optional[str] = None, fingerprint: Optional[str] = None):
154
+ sub: Optional[str] = None
155
+ if grant_type == "password":
156
+ if not auth_store or not username or password is None:
157
+ raise HTTPException(status_code=400, detail="invalid_request")
158
+ uid = auth_store.authenticate_basic(username, password)
159
+ if not uid:
160
+ raise HTTPException(status_code=401, detail="invalid_grant")
161
+ sub = uid
162
+ elif grant_type == "client_credentials":
163
+ # For simplicity map to provided user_id
164
+ if not user_id:
165
+ raise HTTPException(status_code=400, detail="invalid_request")
166
+ sub = user_id
167
+ else:
168
+ raise HTTPException(status_code=400, detail="unsupported_grant_type")
169
+
170
+ now = now_ts()
171
+ access = {
172
+ "iss": issuer_cfg.issuer,
173
+ "aud": issuer_cfg.audience,
174
+ "sub": sub,
175
+ "iat": now,
176
+ "nbf": now,
177
+ "exp": now + issuer_cfg.access_ttl_seconds,
178
+ }
179
+ key = issuer_cfg.hs256_secret if issuer_cfg.algorithm == "HS256" else ""
180
+ access_token = encode_jwt(access, algorithm=issuer_cfg.algorithm, key=key)
181
+
182
+ refresh_token = None
183
+ if auth_store:
184
+ jti = auth_store.issue_refresh(sub, issuer_cfg.refresh_ttl_seconds, fingerprint=fingerprint)
185
+ refresh_token = jti
186
+ return {"access_token": access_token, "token_type": "bearer", "refresh_token": refresh_token}
187
+
188
+ @router.post("/auth/refresh")
189
+ async def refresh(user_id: str, refresh_token: str, fingerprint: Optional[str] = None):
190
+ if not auth_store:
191
+ raise HTTPException(status_code=400, detail="invalid_request")
192
+ if not auth_store.verify_refresh(refresh_token, user_id, fingerprint=fingerprint):
193
+ raise HTTPException(status_code=401, detail="invalid_grant")
194
+ now = now_ts()
195
+ access = {
196
+ "iss": issuer_cfg.issuer,
197
+ "aud": issuer_cfg.audience,
198
+ "sub": user_id,
199
+ "iat": now,
200
+ "nbf": now,
201
+ "exp": now + issuer_cfg.access_ttl_seconds,
202
+ }
203
+ key = issuer_cfg.hs256_secret if issuer_cfg.algorithm == "HS256" else ""
204
+ access_token = encode_jwt(access, algorithm=issuer_cfg.algorithm, key=key)
205
+ return {"access_token": access_token, "token_type": "bearer"}
206
+
207
+ app.include_router(router)
208
+
209
+ # API key management endpoints (require SQL store)
210
+ if auth_store:
211
+ api_router = APIRouter()
212
+
213
+ @api_router.post("/auth/api-keys")
214
+ async def create_api_key(user_id: Optional[str] = None, name: Optional[str] = None):
215
+ key_id, key_plain = auth_store.create_api_key(user_id=user_id, name=name)
216
+ return {"id": key_id, "api_key": key_plain}
217
+
218
+ @api_router.get("/auth/api-keys")
219
+ async def list_api_keys():
220
+ return auth_store.list_api_keys()
221
+
222
+ @api_router.delete("/auth/api-keys/{key_id}")
223
+ async def delete_api_key(key_id: str):
224
+ auth_store.revoke_api_key(key_id)
225
+ return {"ok": True}
226
+
227
+ app.include_router(api_router)
@@ -0,0 +1,45 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from typing import List, Optional
5
+
6
+
7
+ @dataclass
8
+ class JwtValidatorConfig:
9
+ # Accept JWTs from external issuers (e.g., Google/Auth0/Okta) or our own issuer
10
+ jwks_url: Optional[str] = None
11
+ issuer: Optional[str] = None
12
+ audience: Optional[str] = None
13
+ # If you want to validate with an HS256 shared secret (tests/dev)
14
+ hs256_secret: Optional[str] = None
15
+
16
+
17
+ @dataclass
18
+ class JwtIssuerConfig:
19
+ # Configure our own issuer if we issue tokens
20
+ enabled: bool = False
21
+ issuer: str = "https://example-issuer"
22
+ audience: str = "adk-api"
23
+ algorithm: str = "HS256" # HS256 or RS256/ES256 later
24
+ hs256_secret: Optional[str] = None
25
+ access_ttl_seconds: int = 3600
26
+ refresh_ttl_seconds: int = 60 * 60 * 24 * 14
27
+ # SQL store for users/refresh tokens
28
+ database_url: Optional[str] = None # e.g. sqlite:///auth.db
29
+
30
+
31
+ @dataclass
32
+ class AuthConfig:
33
+ # Global toggle
34
+ enabled: bool = False
35
+ # Modes
36
+ allow_no_auth: bool = False # if True, bypass checks entirely
37
+ api_keys: List[str] = field(default_factory=list) # accepted API keys
38
+ basic_users: dict[str, str] = field(default_factory=dict) # username -> password (PBKDF2 hash or plaintext for tests)
39
+ jwt_validator: Optional[JwtValidatorConfig] = None
40
+ jwt_issuer: Optional[JwtIssuerConfig] = None
41
+ # Route policy toggles
42
+ protect_list_apps: bool = True
43
+ protect_metrics: bool = True
44
+ # Scopes are advisory; we currently validate presence of a token and subject. Extend as needed.
45
+
@@ -0,0 +1,36 @@
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import json
5
+ import time
6
+ from typing import Any, Dict, Optional
7
+
8
+ import jwt
9
+ from jwt import PyJWKClient
10
+
11
+
12
+ def _b64url(data: bytes) -> str:
13
+ return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
14
+
15
+
16
+ def encode_jwt(payload: Dict[str, Any], *, algorithm: str, key: str, headers: Optional[Dict[str, Any]] = None) -> str:
17
+ return jwt.encode(payload, key, algorithm=algorithm, headers=headers)
18
+
19
+
20
+ def decode_jwt(token: str, *, issuer: Optional[str] = None, audience: Optional[str] = None,
21
+ jwks_url: Optional[str] = None, hs256_secret: Optional[str] = None) -> Dict[str, Any]:
22
+ options = {"verify_signature": True, "verify_exp": True, "verify_nbf": True}
23
+ if jwks_url:
24
+ jwk_client = PyJWKClient(jwks_url)
25
+ signing_key = jwk_client.get_signing_key_from_jwt(token).key
26
+ return jwt.decode(token, signing_key, algorithms=["RS256", "ES256"], audience=audience, issuer=issuer, options=options)
27
+ elif hs256_secret:
28
+ return jwt.decode(token, hs256_secret, algorithms=["HS256"], audience=audience, issuer=issuer, options=options)
29
+ else:
30
+ raise ValueError("No validation method configured (jwks_url or hs256_secret required)")
31
+
32
+
33
+ def now_ts() -> int:
34
+ return int(time.time())
35
+
36
+
@@ -0,0 +1,183 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import os
5
+ import secrets
6
+ from datetime import datetime, timedelta, timezone
7
+ from typing import Optional
8
+
9
+ try:
10
+ from sqlalchemy import Column, String, DateTime, create_engine, Text, Boolean
11
+ from sqlalchemy.orm import declarative_base, sessionmaker
12
+ except ImportError as e:
13
+ raise ImportError(
14
+ "SQLAlchemy is required for the auth SQL store. Install with: pip install sqlalchemy"
15
+ ) from e
16
+
17
+
18
+ Base = declarative_base()
19
+
20
+
21
+ def _pbkdf2(password: str, salt: str) -> str:
22
+ dk = hashlib.pbkdf2_hmac("sha256", password.encode(), salt.encode(), 200_000)
23
+ return dk.hex()
24
+
25
+
26
+ def hash_password(password: str) -> str:
27
+ salt = secrets.token_hex(16)
28
+ return f"pbkdf2_sha256${salt}${_pbkdf2(password, salt)}"
29
+
30
+
31
+ def verify_password(password: str, stored: str) -> bool:
32
+ try:
33
+ algo, salt, digest = stored.split("$", 2)
34
+ if algo != "pbkdf2_sha256":
35
+ # fallback for plaintext in tests
36
+ return secrets.compare_digest(password, stored)
37
+ return secrets.compare_digest(_pbkdf2(password, salt), digest)
38
+ except Exception:
39
+ return secrets.compare_digest(password, stored)
40
+
41
+
42
+ class User(Base):
43
+ __tablename__ = "auth_users"
44
+ id = Column(String, primary_key=True)
45
+ username = Column(String, unique=True, index=True, nullable=False)
46
+ password_hash = Column(String, nullable=False)
47
+ roles = Column(String, default="") # comma-separated
48
+ created_at = Column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc))
49
+ disabled = Column(Boolean, default=False)
50
+
51
+
52
+ class RefreshToken(Base):
53
+ __tablename__ = "auth_refresh_tokens"
54
+ jti = Column(String, primary_key=True)
55
+ user_id = Column(String, index=True, nullable=False)
56
+ expires_at = Column(DateTime(timezone=True), nullable=False)
57
+ revoked_at = Column(DateTime(timezone=True), nullable=True)
58
+ fingerprint = Column(String, nullable=True)
59
+
60
+
61
+ class ApiKey(Base):
62
+ __tablename__ = "auth_api_keys"
63
+ id = Column(String, primary_key=True)
64
+ user_id = Column(String, index=True, nullable=True)
65
+ key_hash = Column(String, nullable=False)
66
+ name = Column(String, nullable=True)
67
+ created_at = Column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc))
68
+ revoked_at = Column(DateTime(timezone=True), nullable=True)
69
+
70
+
71
+ class AuthStore:
72
+ def __init__(self, database_url: str):
73
+ self.engine = create_engine(database_url)
74
+ Base.metadata.create_all(self.engine)
75
+ self.Session = sessionmaker(bind=self.engine, autoflush=False, autocommit=False)
76
+
77
+ def create_user(self, username: str, password: str, user_id: Optional[str] = None) -> str:
78
+ import uuid
79
+ uid = user_id or str(uuid.uuid4())
80
+ with self.Session() as s:
81
+ u = User(id=uid, username=username, password_hash=hash_password(password))
82
+ s.add(u)
83
+ s.commit()
84
+ return uid
85
+
86
+ def authenticate_basic(self, username: str, password: str) -> Optional[str]:
87
+ with self.Session() as s:
88
+ u: Optional[User] = s.query(User).filter_by(username=username).first()
89
+ if not u or u.disabled:
90
+ return None
91
+ if verify_password(password, u.password_hash):
92
+ return u.id
93
+ return None
94
+
95
+ def issue_refresh(self, user_id: str, ttl_seconds: int, fingerprint: Optional[str] = None) -> str:
96
+ import uuid
97
+ jti = str(uuid.uuid4())
98
+ with self.Session() as s:
99
+ rt = RefreshToken(
100
+ jti=jti,
101
+ user_id=user_id,
102
+ expires_at=datetime.now(timezone.utc) + timedelta(seconds=ttl_seconds),
103
+ fingerprint=fingerprint,
104
+ )
105
+ s.add(rt)
106
+ s.commit()
107
+ return jti
108
+
109
+ def verify_refresh(self, jti: str, user_id: str, fingerprint: Optional[str] = None) -> bool:
110
+ with self.Session() as s:
111
+ rt: Optional[RefreshToken] = s.query(RefreshToken).filter_by(jti=jti, user_id=user_id).first()
112
+ if not rt or rt.revoked_at is not None:
113
+ return False
114
+ if rt.expires_at <= datetime.now(timezone.utc):
115
+ return False
116
+ if fingerprint and rt.fingerprint and rt.fingerprint != fingerprint:
117
+ return False
118
+ return True
119
+
120
+ def revoke_refresh(self, jti: str) -> None:
121
+ with self.Session() as s:
122
+ rt: Optional[RefreshToken] = s.query(RefreshToken).filter_by(jti=jti).first()
123
+ if not rt:
124
+ return
125
+ rt.revoked_at = datetime.now(timezone.utc)
126
+ s.add(rt)
127
+ s.commit()
128
+
129
+ # API Keys
130
+ def _hash_api_key(self, key: str) -> str:
131
+ # Reuse PBKDF2; different prefix
132
+ salt = secrets.token_hex(16)
133
+ return f"api_pbkdf2_sha256${salt}${_pbkdf2(key, salt)}"
134
+
135
+ def _verify_api_key(self, key: str, stored: str) -> bool:
136
+ try:
137
+ algo, salt, digest = stored.split("$", 3)
138
+ if algo != "api_pbkdf2_sha256":
139
+ return secrets.compare_digest(key, stored)
140
+ return secrets.compare_digest(_pbkdf2(key, salt), digest)
141
+ except Exception:
142
+ return False
143
+
144
+ def create_api_key(self, user_id: Optional[str] = None, name: Optional[str] = None) -> tuple[str, str]:
145
+ import uuid
146
+ key_plain = secrets.token_urlsafe(32)
147
+ key_id = str(uuid.uuid4())
148
+ with self.Session() as s:
149
+ rec = ApiKey(id=key_id, user_id=user_id, key_hash=self._hash_api_key(key_plain), name=name)
150
+ s.add(rec)
151
+ s.commit()
152
+ return key_id, key_plain
153
+
154
+ def list_api_keys(self):
155
+ with self.Session() as s:
156
+ rows = s.query(ApiKey).all()
157
+ return [
158
+ {
159
+ "id": r.id,
160
+ "user_id": r.user_id,
161
+ "name": r.name,
162
+ "created_at": r.created_at.isoformat() if r.created_at else None,
163
+ "revoked": r.revoked_at is not None,
164
+ }
165
+ for r in rows
166
+ ]
167
+
168
+ def revoke_api_key(self, key_id: str) -> None:
169
+ with self.Session() as s:
170
+ rec = s.query(ApiKey).filter_by(id=key_id).first()
171
+ if not rec:
172
+ return
173
+ rec.revoked_at = datetime.now(timezone.utc)
174
+ s.add(rec)
175
+ s.commit()
176
+
177
+ def verify_api_key(self, key: str) -> bool:
178
+ with self.Session() as s:
179
+ rows = s.query(ApiKey).filter(ApiKey.revoked_at.is_(None)).all()
180
+ for r in rows:
181
+ if self._verify_api_key(key, r.key_hash):
182
+ return True
183
+ return False
@@ -34,6 +34,7 @@ from google.adk.sessions.database_session_service import DatabaseSessionService
34
34
  from google.adk.utils.feature_decorator import working_in_progress
35
35
  from google.adk.cli.adk_web_server import AdkWebServer
36
36
  from .enhanced_adk_web_server import EnhancedAdkWebServer
37
+ from .auth import attach_auth, AuthConfig, JwtIssuerConfig, JwtValidatorConfig
37
38
  from .streaming import StreamingController, StreamingConfig
38
39
  from google.adk.cli.utils import envs
39
40
  from google.adk.cli.utils import evals
@@ -68,6 +69,8 @@ def get_enhanced_fast_api_app(
68
69
  # Streaming layer (optional)
69
70
  enable_streaming: bool = False,
70
71
  streaming_config: Optional[StreamingConfig] = None,
72
+ # Auth layer (optional)
73
+ auth_config: Optional[AuthConfig] = None,
71
74
  ) -> FastAPI:
72
75
  """Enhanced version of Google ADK's get_fast_api_app with EnhancedRunner integration.
73
76
 
@@ -600,4 +603,7 @@ def get_enhanced_fast_api_app(
600
603
 
601
604
  app.include_router(router)
602
605
 
606
+ # Attach optional auth layer last so all routes are covered
607
+ attach_auth(app, auth_config)
608
+
603
609
  return app
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: google-adk-extras
3
- Version: 0.2.7
3
+ Version: 0.3.0
4
4
  Summary: Production-ready services and FastAPI wiring for Google ADK
5
5
  Home-page: https://github.com/DeadMeme5441/google-adk-extras
6
6
  Author: DeadMeme5441
@@ -94,7 +94,7 @@ If you plan to use specific backends, also install their clients (examples):
94
94
  - Redis: `uv pip install redis`
95
95
  - S3: `uv pip install boto3`
96
96
 
97
- Note on credentials (0.2.7): This release removes custom credential services and URI helpers from this package. For outbound credentials used by tools, rely on ADK’s experimental BaseCredentialService (e.g., InMemory/SessionState) or your own ADK-compatible implementation. Inbound API authentication (protecting /run and streaming routes) will be provided as an optional FastAPI layer separately.
97
+ Note on credentials (0.3.0): Outbound credentials for tools remain ADK’s concern (use ADK’s BaseCredentialService). Inbound API authentication is now available as an optional FastAPI layer in this package (see Auth below). You can run fully open (no auth) or enable API Key, Basic, or JWT (including first‑party issuance backed by SQL).
98
98
 
99
99
 
100
100
  ## Quickstart (FastAPI)
@@ -104,6 +104,7 @@ Use the fluent builder to wire services. Then run with uvicorn.
104
104
  ```python
105
105
  # app.py
106
106
  from google_adk_extras import AdkBuilder
107
+ from google_adk_extras.auth import AuthConfig, JwtIssuerConfig, JwtValidatorConfig
107
108
 
108
109
  app = (
109
110
  AdkBuilder()
@@ -127,6 +128,77 @@ uvicorn app:app --reload
127
128
  If you don’t keep agents on disk, register them programmatically and use a custom loader (see below).
128
129
 
129
130
 
131
+ ## Auth (optional)
132
+
133
+ Auth is entirely optional. By default, all endpoints are open (no auth). To enable protection, pass `auth_config` into `get_enhanced_fast_api_app` via the builder or directly.
134
+
135
+ Supported inbound methods:
136
+ - API Key: `X-API-Key: <key>` header (or `?api_key=` query). Keys can be static via config, or issued/rotated via SQL‑backed endpoints.
137
+ - HTTP Basic: `Authorization: Basic base64(user:pass)` for quick human/internal testing. Can validate against in‑memory map or the SQL users table.
138
+ - Bearer JWT (validate): Accept JWTs from Google/Auth0/Okta/etc. via JWKS, or HS256 secret in dev. Enforces iss/aud/exp/nbf.
139
+ - Bearer JWT (issue): First‑party issuer with HS256, tokens minted from `/auth/token`, users stored in SQL (SQLite/Postgres/MySQL).
140
+
141
+ Minimal enablement (JWT validate only):
142
+
143
+ ```python
144
+ from google_adk_extras.auth import AuthConfig, JwtValidatorConfig
145
+
146
+ auth = AuthConfig(
147
+ enabled=True,
148
+ jwt_validator=JwtValidatorConfig(
149
+ jwks_url="https://accounts.google.com/.well-known/openid-configuration", # example
150
+ issuer="https://accounts.google.com",
151
+ audience="your-api-audience",
152
+ ),
153
+ )
154
+
155
+ app = (
156
+ AdkBuilder()
157
+ .with_agents_dir("./agents")
158
+ .build_fastapi_app()
159
+ )
160
+ ```
161
+
162
+ First‑party issuer + validate (single shared HS256 secret) with SQL connector:
163
+
164
+ ```python
165
+ from google_adk_extras.auth import AuthConfig, JwtIssuerConfig, JwtValidatorConfig
166
+
167
+ issuer = JwtIssuerConfig(
168
+ enabled=True,
169
+ issuer="https://local-issuer",
170
+ audience="adk-api",
171
+ algorithm="HS256",
172
+ hs256_secret="topsecret",
173
+ database_url="sqlite:///./auth.db", # also supports Postgres/MySQL
174
+ )
175
+ validator = JwtValidatorConfig(
176
+ issuer=issuer.issuer,
177
+ audience=issuer.audience,
178
+ hs256_secret=issuer.hs256_secret,
179
+ )
180
+
181
+ auth = AuthConfig(enabled=True, jwt_issuer=issuer, jwt_validator=validator)
182
+
183
+ app = (
184
+ AdkBuilder()
185
+ .with_agents_dir("./agents")
186
+ .build_fastapi_app()
187
+ )
188
+ ```
189
+
190
+ Issuing and using tokens/keys at runtime:
191
+ - Register user: `POST /auth/register?username=alice&password=wonder`
192
+ - Token (password): `POST /auth/token?grant_type=password&username=alice&password=wonder`
193
+ - Refresh: `POST /auth/refresh?user_id=<uid>&refresh_token=<jti>`
194
+ - Create API key: `POST /auth/api-keys` (auth required) → returns `{ id, api_key }` (plaintext shown once)
195
+ - List keys: `GET /auth/api-keys` (auth required)
196
+ - Revoke key: `DELETE /auth/api-keys/{id}` (auth required)
197
+ - Use API key: add `X-API-Key: <api_key>` to any protected route (keys currently allow full access)
198
+
199
+ Protected routes include `/run`, `/run_sse`, all `/apps/...` session/artifact/eval endpoints, `/debug/*`, `/builder/*`, and optionally `/list-apps` and `/apps/{app}/metrics-info`.
200
+
201
+
130
202
  ## Quickstart (Runner)
131
203
 
132
204
  Create a Runner wired with your chosen backends. Use agent name (filesystem loader) or pass an agent instance.
@@ -5,6 +5,7 @@ mkdocs.yml
5
5
  pyproject.toml
6
6
  setup.py
7
7
  docs/agent-loading.md
8
+ docs/auth.md
8
9
  docs/examples.md
9
10
  docs/fastapi.md
10
11
  docs/getting-started.md
@@ -15,6 +16,7 @@ docs/streaming.md
15
16
  docs/troubleshooting.md
16
17
  docs/uris.md
17
18
  examples/README.md
19
+ examples/adk_server_8015.py
18
20
  examples/consume_remote_a2a.py
19
21
  examples/custom_loader.py
20
22
  examples/fastapi_app.py
@@ -41,6 +43,11 @@ src/google_adk_extras/artifacts/local_folder_artifact_service.py
41
43
  src/google_adk_extras/artifacts/mongo_artifact_service.py
42
44
  src/google_adk_extras/artifacts/s3_artifact_service.py
43
45
  src/google_adk_extras/artifacts/sql_artifact_service.py
46
+ src/google_adk_extras/auth/__init__.py
47
+ src/google_adk_extras/auth/attach.py
48
+ src/google_adk_extras/auth/config.py
49
+ src/google_adk_extras/auth/jwt_utils.py
50
+ src/google_adk_extras/auth/sql_store.py
44
51
  src/google_adk_extras/credentials/base_custom_credential_service.py
45
52
  src/google_adk_extras/memory/__init__.py
46
53
  src/google_adk_extras/memory/base_custom_memory_service.py