-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsettings.py
More file actions
389 lines (360 loc) · 13.4 KB
/
settings.py
File metadata and controls
389 lines (360 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
"""Application settings and configuration management."""
import os
from functools import lru_cache
from typing import Literal
from pydantic import Field, model_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
"""Application settings loaded from environment variables."""
model_config = SettingsConfigDict(
env_file=".env",
env_file_encoding="utf-8",
case_sensitive=False,
extra="ignore",
)
# Google AI / Gemini Configuration
google_genai_use_vertexai: bool = Field(
default=False,
description="Use Vertex AI instead of Google AI Studio",
)
google_api_key: str | None = Field(
default=None,
description="Google AI Studio API key",
)
google_cloud_project: str | None = Field(
default=None,
description="Google Cloud project ID for Vertex AI",
)
google_cloud_location: str = Field(
default="us-central1",
description="Google Cloud location for Vertex AI",
)
gemini_model: str = Field(
default="gemini-2.5-flash",
description="Gemini model to use",
)
# Red Hat SSO Configuration
red_hat_sso_issuer: str = Field(
default="https://sso.redhat.com/auth/realms/redhat-external",
description="Red Hat SSO issuer URL",
)
red_hat_sso_client_id: str = Field(
default="",
description="OAuth client ID for Red Hat SSO",
)
red_hat_sso_client_secret: str = Field(
default="",
description="OAuth client secret for Red Hat SSO",
)
# Red Hat Lightspeed MCP Configuration
mcp_transport_mode: Literal["stdio", "http", "sse"] = Field(
default="stdio",
description="MCP server transport mode",
)
mcp_server_url: str = Field(
default="http://localhost:8080",
description="MCP server URL for http/sse modes",
)
mcp_read_only: bool = Field(
default=True,
description="Enable read-only mode for MCP tools",
)
# Agent Configuration
agent_provider_url: str = Field(
default="https://localhost:8000",
description="Agent base URL (where the A2A agent can be reached)",
)
agent_provider_organization_url: str = Field(
default="https://www.redhat.com",
description=(
"Agent provider's organization website URL."
" Used in AgentCard provider.url and as the expected JWT audience"
" for Google DCR software_statement validation."
),
)
agent_name: str = Field(
default="lightspeed_agent",
description="Agent name (must be a valid Python identifier)",
)
agent_display_name: str = Field(
default="Red Hat Lightspeed Agent for Google Cloud",
description="Human-readable agent name for the AgentCard",
)
agent_description: str = Field(
default=(
"Red Hat Lightspeed Agent for Google Cloud is an A2A-ready Agent "
"that leverages Red Hat Lightspeed Model Context Protocol (MCP) to "
"connect to Red Hat Lightspeed services, providing information about "
"your Red Hat account, subscription, system configuration, and "
"related details. This feature uses AI technology. Always review "
"AI-generated content prior to use."
),
description="Agent description",
)
agent_host: str = Field(
default="0.0.0.0",
description="Server host",
)
agent_port: int = Field(
default=8000,
description="Server port",
)
# Marketplace Handler Configuration
# The marketplace handler is a separate service that handles DCR and Pub/Sub events
marketplace_handler_url: str = Field(
default="",
description=(
"URL of the marketplace handler service for DCR."
" If empty, uses agent_provider_url."
),
)
# Google Cloud Service Control
service_control_service_name: str = Field(
default="",
description=(
"Service name for Google Cloud Service Control"
" (e.g., myservice.gcpmarketplace.example.com)"
),
)
service_control_enabled: bool = Field(
default=True,
description="Enable usage reporting to Google Cloud Service Control",
)
# Metering recovery: stale claim release and backfill
metering_stale_claim_minutes: int = Field(
default=15,
description="Release rows claimed longer than this (worker crash recovery)",
)
metering_backfill_max_age_hours: int = Field(
default=168,
description="Backfill only periods within this many hours (default 7 days)",
)
metering_backfill_limit_per_run: int = Field(
default=20,
description="Max unreported periods to process per backfill run",
)
max_tool_calls_per_invocation: int = Field(
default=0,
description=(
"Maximum MCP tool executions per ADK invocation (single agent run). "
"0 disables the limit. Enforced in-process via UsageTrackingPlugin "
"(not shared across replicas; see docs/metering.md)."
),
)
# Rate Limiting (Redis-backed)
rate_limit_requests_per_minute: int = Field(
default=60,
description="Global requests per minute limit",
)
rate_limit_requests_per_hour: int = Field(
default=1000,
description="Global requests per hour limit",
)
rate_limit_redis_url: str = Field(
default="redis://localhost:6379/0",
description="Redis URL for distributed rate limiting",
)
rate_limit_redis_timeout_ms: int = Field(
default=200,
description="Redis operation timeout in milliseconds",
)
rate_limit_key_prefix: str = Field(
default="lightspeed:ratelimit",
description="Redis key prefix for rate limiting data",
)
# Logging
log_level: str = Field(
default="INFO",
description="Logging level",
)
log_format: Literal["json", "text"] = Field(
default="json",
description="Log format",
)
agent_logging_detail: Literal["basic", "detailed"] = Field(
default="basic",
description="Agent execution logging detail level. "
"'basic' logs tool names and token counts. "
"'detailed' also logs tool arguments and truncated results.",
)
# DCR (Dynamic Client Registration) Configuration
dcr_enabled: bool = Field(
default=True,
description=(
"Enable real DCR with Red Hat SSO via the GMA API."
" When disabled, uses pre-seeded credentials from the database."
),
)
dcr_client_name_prefix: str = Field(
default="gemini-order-",
description="Prefix for OAuth client names created via DCR",
)
dcr_encryption_key: str = Field(
default="",
description=(
"Fernet encryption key for DCR client secrets"
" (generate with: python -c"
" 'from cryptography.fernet import Fernet;"
" print(Fernet.generate_key().decode())')"
),
)
# GMA SSO API credentials (for DCR tenant creation)
gma_client_id: str = Field(
default="",
description=(
"Client ID for GMA SSO API"
" (client_credentials grant with api.iam.clients.gma scope)"
),
)
gma_client_secret: str = Field(
default="",
description="Client secret for GMA SSO API",
)
gma_api_base_url: str = Field(
default="https://sso.redhat.com/auth/realms/redhat-external/apis/beta/acs/v1/",
description="GMA SSO API base URL for tenant creation",
)
gma_api_timeout: int = Field(
default=30,
description="Timeout in seconds for GMA API requests",
)
# Database Configuration
# Marketplace database: stores accounts, entitlements, DCR clients, usage records
# This is shared between the marketplace handler and agent for order validation
database_url: str = Field(
default="sqlite+aiosqlite:///./lightspeed_agent.db",
description=(
"Marketplace database URL (PostgreSQL for production)."
" Stores accounts, entitlements, DCR clients."
),
)
database_pool_size: int = Field(
default=5,
description="Database connection pool size",
)
database_pool_max_overflow: int = Field(
default=10,
description="Maximum overflow connections beyond pool size",
)
# Session configuration: controls ADK session storage backend
# Separate from marketplace DB for security isolation - each agent can have its own
session_backend: Literal["memory", "database"] = Field(
default="memory",
description=(
"Session storage backend. "
"'memory' uses in-memory sessions (lost on restart). "
"'database' uses DatabaseSessionService and requires SESSION_DATABASE_URL."
),
)
session_database_url: str = Field(
default="",
description=(
"Session database URL for ADK sessions."
" Required when SESSION_BACKEND=database."
" For security isolation, use a separate database from DATABASE_URL."
),
)
# Agent required scopes for token introspection (comma-separated)
agent_required_scope: str = Field(
default="api.console,api.ocm",
description=(
"Comma-separated OAuth scopes required in access tokens."
" Checked via token introspection."
),
)
# Agent allowed scopes (comma-separated allowlist)
agent_allowed_scopes: str = Field(
default="openid,profile,email,api.console,api.ocm",
description=(
"Comma-separated allowlist of OAuth scopes permitted in access tokens."
" Tokens carrying scopes outside this list are rejected (HTTP 403)."
),
)
@property
def required_scopes_list(self) -> list[str]:
"""Parse comma-separated agent_required_scope into a list."""
return [s.strip() for s in self.agent_required_scope.split(",") if s.strip()]
@property
def allowed_scopes_list(self) -> list[str]:
"""Parse comma-separated agent_allowed_scopes into a list."""
return [s.strip() for s in self.agent_allowed_scopes.split(",") if s.strip()]
@property
def sso_introspection_endpoint(self) -> str:
"""Get the Red Hat SSO token introspection endpoint URL."""
return f"{self.red_hat_sso_issuer}/protocol/openid-connect/token/introspect"
@property
def sso_token_endpoint(self) -> str:
"""Get the Red Hat SSO token endpoint URL."""
return f"{self.red_hat_sso_issuer}/protocol/openid-connect/token"
# Development Settings
debug: bool = Field(
default=False,
description="Enable debug mode",
)
skip_jwt_validation: bool = Field(
default=False,
description="Skip JWT validation (development only)",
)
@model_validator(mode="after")
def _block_skip_jwt_in_production(self) -> "Settings":
"""Prevent SKIP_JWT_VALIDATION from being enabled in production.
Cloud Run sets K_SERVICE automatically. If that variable is present,
this is a managed deployment and JWT validation must never be skipped.
"""
if self.skip_jwt_validation and os.getenv("K_SERVICE"):
raise ValueError(
"SKIP_JWT_VALIDATION=true is not allowed in Cloud Run "
f"(K_SERVICE={os.getenv('K_SERVICE')}). "
"This setting is intended for local development only."
)
return self
@model_validator(mode="after")
def _validate_session_backend(self) -> "Settings":
"""Ensure SESSION_DATABASE_URL is set when SESSION_BACKEND=database."""
if self.session_backend == "database" and not self.session_database_url:
raise ValueError(
"SESSION_BACKEND=database requires SESSION_DATABASE_URL to be set. "
"Provide a PostgreSQL connection URL, e.g.: "
"SESSION_DATABASE_URL=postgresql+asyncpg://user:pass@host:5432/sessions"
)
return self
# OpenTelemetry Configuration
otel_enabled: bool = Field(
default=False,
description="Enable OpenTelemetry tracing",
)
otel_service_name: str = Field(
default="lightspeed_agent",
description="Service name for OpenTelemetry traces",
)
otel_exporter_otlp_endpoint: str = Field(
default="http://localhost:4317",
description="OTLP exporter endpoint (gRPC)",
)
otel_exporter_otlp_http_endpoint: str = Field(
default="http://localhost:4318",
description="OTLP exporter endpoint (HTTP)",
)
otel_exporter_type: Literal["otlp", "otlp-http", "jaeger", "zipkin", "console"] = Field(
default="otlp",
description="Telemetry exporter type",
)
otel_traces_sampler: Literal[
"always_on",
"always_off",
"traceidratio",
"parentbased_always_on",
"parentbased_always_off",
"parentbased_traceidratio",
] = Field(
default="always_on",
description="Trace sampling strategy",
)
otel_traces_sampler_arg: float = Field(
default=1.0,
description="Sampler argument (e.g., ratio for traceidratio)",
)
@lru_cache
def get_settings() -> Settings:
"""Get cached application settings."""
return Settings()