Skip to content

Commit 9614b4a

Browse files
fix(audit): remediate whole-project audit findings (#47)
* fix(audit): remediate whole-project audit findings Addresses 17 findings from a full-codebase audit. Several paths converted a misconfiguration or a transient fault into a working-looking success. Fail-closed configuration and dependency resolution: - Settings.API_KEYS no longer defaults to a key published in the repository; validation rejects an empty or whitespace-only value. - get_llm_client no longer falls back to FakeLLMClient. Provider construction failure raises ServiceUnavailableError (503). LLM_PROVIDER=fake remains an explicit opt-in that short-circuits before the factory. - get_agent builds the Agent per request instead of memoizing the first assembly on app.state, which pinned every later request to the first request's LLM client, registry, memory store and trace sink. - Wired RetryingLLMClient into the request path (previously dead code) with new LLM_MAX_RETRIES / LLM_RETRY_BASE_DELAY_S / LLM_RETRY_MAX_DELAY_S. - TieredMemoryStore forwards get_run_trace and list_runs to the run store, so the trace endpoint no longer falls through to an empty trace sink. - examples/demo.py requires --offline for scripted execution rather than silently downgrading on a missing key. Post-connect SSRF verification and bounded resource use: - http_fetch resolves DNS via asyncio.to_thread and reuses those addresses. - Verifies the connected socket's server_addr against the validated addresses, closing the DNS-rebinding window between validation and connection. - Streams the body under an explicit byte budget instead of buffering then slicing. - sql_readonly applies the row limit in SQL, pushes statement_timeout to PostgreSQL, masks string literals and quoted identifiers before its keyword scan, and allows the #> / #>> / #- JSON path operators. Atomic fallbacks and domain-error boundaries: - The rate limiter's non-scripting fallback uses WATCH/MULTI/EXEC optimistic locking instead of a trim/count-then-insert split. Against live Redis the old version admitted 39 of 50 simultaneous requests against a limit of 5; the new one admits exactly 5. - Both LLM adapters wrap response parsing in the error boundary, so blocked prompts, empty choices and malformed tool-argument JSON raise LLMProviderError rather than escaping as raw SDK exceptions. - Generated tool_call_ids use full UUIDs instead of 32-bit truncations. - RetryingLLMClient.__getattr__ no longer recurses on a partial instance. - /health returns fixed client-facing strings and logs the driver error, so the unauthenticated endpoint stops disclosing hostnames, ports and database names. Smaller fixes: fixed the RedisMemoryStore.truncate_messages off-by-one that returned max_messages + 1 entries with a system prompt; stopped logging raw run goals at INFO; replaced split(";") in scripts/seed.py with a statement-aware splitter handling literals, comments and dollar-quotes; bounded calculator exponentiation by result bit length. Suite: 277 hermetic passed, 25 real-infra passed against live PostgreSQL and Redis. Coverage 92% overall. ruff check, ruff format --check and mypy agentkit tests are clean. * fix(audit): harden peer check, masked scans, row-limit rewrite, mysql timeout - verify_peer_address tolerates malformed server_addr without crashing and fails closed on restricted or unparseable peer hosts. - Run the comment and multi-statement scans on the literal-masked query so markers inside string data no longer cause false rejections. - Prefer appending LIMIT over subquery wrapping; wrap only for row-locking tail clauses. Add FETCH FIRST to the existing-bound detection. - MySQL timeout uses SET SESSION MAX_EXECUTION_TIME, which actually covers subsequent statements, instead of a no-op SET STATEMENT ... FOR SELECT 1. * test(audit): reconcile regression tests with strict dependency resolution Adapt the rebased audit tests to the AUD-01/AUD-04 behaviour now on main: deps delegate to the factory instead of wrapping retry itself, build_llm exits via SystemExit on a missing key, and the per-request probe test uses in-memory memory/trace overrides so it stays hermetic without Redis.
1 parent 552aac8 commit 9614b4a

30 files changed

Lines changed: 1630 additions & 221 deletions

‎.env.example‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,20 +18,25 @@ LLM_MODEL=gemini-3.1-flash-lite
1818
GEMINI_API_KEY=your_gemini_api_key_here
1919
OPENAI_API_KEY=your_openai_api_key_here
2020

21+
# Retry policy for transient LLM failures (429 / 5xx / network). Non-transient
22+
# errors such as 401 or 400 are never retried.
23+
LLM_MAX_RETRIES=3
24+
LLM_RETRY_BASE_DELAY_S=0.5
25+
LLM_RETRY_MAX_DELAY_S=10
26+
2127
# External Tools & Sandboxing
2228
SEARCH_API_KEY=your_search_api_key_here
2329
FILE_TOOL_BASE_DIR=/tmp/agentkit_sandbox
2430

2531
# Security & API Authentication
26-
# Comma-separated list of authorized client API keys.
27-
# docker-compose.yml ships no default: leave this unset and the api service
28-
# exits on settings validation instead of starting with a published key.
29-
API_KEYS=ak_test_key_12345,ak_admin_key_67890
32+
# Comma-separated list of authorized client API keys. Required: AgentKit refuses
33+
# to start when this is empty or unset, so no deployment can come up with a key
34+
# published in this repository. Replace the values below with your own.
35+
API_KEYS=replace_me_key_1,replace_me_key_2
3036
RATE_LIMIT_PER_MIN=30
3137

3238
# Agent Execution Limits & Guardrails
3339
MAX_STEPS=10
34-
MAX_RETRIES=3
3540
RUN_TIMEOUT_S=60
3641
TOOL_TIMEOUT_S=15
3742
SESSION_TTL_S=3600

‎README.md‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -110,16 +110,22 @@ OPENAI_API_KEY=your_openai_api_key_here
110110
DATABASE_URL=postgresql+asyncpg://agentkit:agentkit_password@localhost:5432/agentkit
111111
REDIS_URL=redis://localhost:6379/0
112112

113-
# Security (comma-separated authorized keys)
114-
API_KEYS=ak_test_key_12345,ak_admin_key_67890
113+
# Security (API_KEYS is required; the app refuses to start without it)
114+
API_KEYS=dev_key_1,dev_key_2
115+
116+
# Optional: retry policy for transient LLM failures (429/5xx/network)
117+
LLM_MAX_RETRIES=3
118+
LLM_RETRY_BASE_DELAY_S=0.5
119+
LLM_RETRY_MAX_DELAY_S=10
115120
```
116121

117122
### 4. Running with Docker Compose (Recommended)
118123
Launch the API, PostgreSQL, and Redis together with automatic migrations.
119124

120-
`docker-compose.yml` ships no default `API_KEYS`. Leave it unset and the api service
121-
fails immediately on settings validation rather than starting with a published key;
122-
`down`, `ps` and `logs` still work either way.
125+
`API_KEYS` is required in every environment, not just under compose. `Settings` rejects an
126+
empty value, so a deployment that forgets to configure its keys fails at startup rather than
127+
serving unauthenticated traffic with a key published in the repository. `docker-compose.yml`
128+
ships no default either; `down`, `ps` and `logs` still work without it.
123129

124130
```bash
125131
export API_KEYS=ak_local_dev_key # or place API_KEYS in your .env

‎agentkit/api/deps.py‎

Lines changed: 27 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -138,16 +138,26 @@ def get_llm_client(
138138
request: Request,
139139
settings: Settings = Depends(get_current_settings),
140140
) -> LLMClient:
141-
"""Resolve configured LLM client.
141+
"""Resolve the configured LLM client.
142142
143-
Instantiates the configured provider from settings. Explicit test overrides
144-
can be supplied via request.app.state.llm_client.
143+
Instantiates the configured provider from settings, which also applies the
144+
configured transient-error retry policy. Explicit test overrides can be supplied
145+
via request.app.state.llm_client. A provider construction failure is surfaced as a
146+
503: falling back to a scripted client would answer a misconfigured deployment with
147+
fake text and HTTP 200 instead of surfacing the misconfiguration.
145148
"""
146-
if hasattr(request.app.state, "llm_client") and request.app.state.llm_client is not None:
147-
client: LLMClient = request.app.state.llm_client
148-
return client
149-
150-
return create_llm_client_from_settings(settings)
149+
override: LLMClient | None = getattr(request.app.state, "llm_client", None)
150+
if override is not None:
151+
return override
152+
153+
try:
154+
return create_llm_client_from_settings(settings)
155+
except Exception as exc:
156+
logger.error("Failed to initialize LLM provider %s: %s", settings.LLM_PROVIDER, exc)
157+
raise ServiceUnavailableError(
158+
"llm",
159+
f"LLM provider '{settings.LLM_PROVIDER}' could not be initialized.",
160+
) from exc
151161

152162

153163
def get_agent(
@@ -158,10 +168,15 @@ def get_agent(
158168
memory: MemoryStore = Depends(get_memory_store),
159169
trace: TraceSink = Depends(get_trace_sink),
160170
) -> Agent:
161-
"""Assemble configured Agent instance with all runtime dependencies."""
162-
if hasattr(request.app.state, "agent") and request.app.state.agent is not None:
163-
agent: Agent = request.app.state.agent
164-
return agent
171+
"""Assemble a configured Agent from the currently resolved dependencies.
172+
173+
The agent is rebuilt per request rather than memoized on ``app.state``: caching the first
174+
assembled instance would pin every later request to that request's LLM client, registry,
175+
memory store and trace sink, silently ignoring any later override or settings change.
176+
"""
177+
override: Agent | None = getattr(request.app.state, "agent_override", None)
178+
if override is not None:
179+
return override
165180

166181
config = AgentConfig(
167182
max_steps=settings.MAX_STEPS,

‎agentkit/api/ratelimit.py‎

Lines changed: 46 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
from fastapi import Depends
1212
from redis.asyncio import Redis
13-
from redis.exceptions import RedisError, ResponseError
13+
from redis.exceptions import RedisError, ResponseError, WatchError
1414

1515
from agentkit.api.auth import get_current_settings, verify_api_key
1616
from agentkit.api.deps import get_redis_client
@@ -57,6 +57,10 @@
5757
return {1, 0}
5858
"""
5959

60+
#: Retries for the WATCH/MULTI fallback when concurrent writers keep invalidating the watch.
61+
#: Only reached on Redis deployments without scripting support.
62+
_WATCH_MAX_RETRIES = 5
63+
6064

6165
class RateLimiter:
6266
"""Sliding window rate limiter enforcing request volume limits per client key.
@@ -203,23 +207,48 @@ async def _check_window_unatomic(
203207
member: str,
204208
key_ttl: int,
205209
) -> tuple[bool, int]:
206-
"""Best-effort sliding-window check for servers without scripting support."""
207-
pipe = redis_client.pipeline(transaction=True)
208-
pipe.zremrangebyscore(redis_key, "-inf", now - window)
209-
pipe.zcard(redis_key)
210-
results = await pipe.execute()
211-
if int(results[1]) >= limit:
212-
oldest = await redis_client.zrange(redis_key, 0, 0, withscores=True)
213-
retry_after = (
214-
max(1, math.ceil(float(oldest[0][1]) + window - now)) if oldest else int(window)
215-
)
216-
return False, retry_after
210+
"""Best-effort sliding-window check for servers without scripting support.
211+
212+
An earlier version trimmed and counted in one transaction, then inserted in a second.
213+
That second round trip leaves a gap in which concurrent requests all read the same
214+
pre-insert cardinality and are admitted together, so a parallel burst could exceed the
215+
quota. WATCH/MULTI/EXEC closes the gap: the whole read-decide-write cycle aborts and
216+
retries whenever another client modifies the key in between.
217+
"""
218+
for _ in range(_WATCH_MAX_RETRIES):
219+
async with redis_client.pipeline(transaction=True) as pipe:
220+
try:
221+
await pipe.watch(redis_key)
222+
await pipe.zremrangebyscore(redis_key, "-inf", now - window)
223+
count = await pipe.zcard(redis_key)
217224

218-
pipe = redis_client.pipeline(transaction=True)
219-
pipe.zadd(redis_key, {member: now})
220-
pipe.expire(redis_key, key_ttl)
221-
await pipe.execute()
222-
return True, 0
225+
if int(count) >= limit:
226+
oldest = await pipe.zrange(redis_key, 0, 0, withscores=True)
227+
await pipe.reset()
228+
retry_after = (
229+
max(1, math.ceil(float(oldest[0][1]) + window - now))
230+
if oldest
231+
else int(window)
232+
)
233+
return False, retry_after
234+
235+
pipe.multi()
236+
pipe.zadd(redis_key, {member: now})
237+
pipe.expire(redis_key, key_ttl)
238+
await pipe.execute()
239+
return True, 0
240+
except WatchError:
241+
# Another client changed the window between WATCH and EXEC; re-read and retry.
242+
continue
243+
244+
# Contention never settled. Denying is the safe direction for a limiter: a false
245+
# reject costs one request, a false admit lets a client exceed its quota.
246+
logger.warning(
247+
"Rate limit check for key %s hit %d watch retries under contention; denying request.",
248+
redis_key[:8] + "...",
249+
_WATCH_MAX_RETRIES,
250+
)
251+
return False, max(1, math.ceil(window))
223252

224253
async def __call__(
225254
self,

‎agentkit/api/routes.py‎

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,11 @@
3131

3232
logger = logging.getLogger(__name__)
3333

34+
#: Fixed client-facing strings for failed dependency checks. Raw driver errors can contain
35+
#: connection URLs, credentials or internal hostnames, and /health requires no API key.
36+
DATABASE_UNHEALTHY = "Database connectivity check failed."
37+
REDIS_UNHEALTHY = "Redis connectivity check failed."
38+
3439
runs_router = APIRouter(
3540
prefix="/runs",
3641
tags=["runs"],
@@ -47,7 +52,10 @@ async def create_run(
4752
memory_store: PostgresMemoryStore | MemoryStore = Depends(get_memory_store),
4853
) -> RunResponse:
4954
"""Execute an agent goal and return execution summary."""
50-
logger.info("Executing run for goal: %s (session_id: %s)", payload.goal, payload.session_id)
55+
# The goal is caller-supplied prompt data, so only its length is logged at INFO.
56+
logger.info(
57+
"Executing run (goal_chars=%d, session_id: %s)", len(payload.goal), payload.session_id
58+
)
5159
result = await agent.run(goal=payload.goal, session_id=payload.session_id)
5260

5361
if hasattr(memory_store, "get_run"):
@@ -153,31 +161,33 @@ async def health_check(request: Request) -> JSONResponse:
153161
redis_status = "healthy"
154162
details: dict[str, str] = {}
155163

156-
# Check Database Engine
164+
# /health is unauthenticated, so connection error strings are logged rather than echoed:
165+
# driver messages routinely embed host, port and database name.
157166
engine = getattr(request.app.state, "db_engine", None)
158167
if engine is not None:
159168
try:
160169
async with engine.connect() as conn:
161170
await conn.execute(text("SELECT 1"))
162171
except Exception as exc:
163172
db_status = "unhealthy"
164-
details["database"] = str(exc)
173+
details["database"] = DATABASE_UNHEALTHY
174+
logger.warning("Database health check failed: %s", exc)
165175
status_code = 503
166176
else:
167177
db_status = "disabled"
168178

169-
# Check Redis Client
170179
redis_client = getattr(request.app.state, "redis_client", None)
171180
if redis_client is not None:
172181
try:
173182
ping_res = await redis_client.ping()
174183
if not ping_res:
175184
redis_status = "unhealthy"
176-
details["redis"] = "Ping returned False"
185+
details["redis"] = REDIS_UNHEALTHY
177186
status_code = 503
178187
except Exception as exc:
179188
redis_status = "unhealthy"
180-
details["redis"] = str(exc)
189+
details["redis"] = REDIS_UNHEALTHY
190+
logger.warning("Redis health check failed: %s", exc)
181191
status_code = 503
182192
else:
183193
redis_status = "disabled"

‎agentkit/config.py‎

Lines changed: 27 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -49,15 +49,31 @@ class Settings(BaseSettings):
4949
default=None,
5050
description="External search API key (Tavily/SerpAPI).",
5151
)
52+
LLM_MAX_RETRIES: int = Field(
53+
default=3,
54+
ge=0,
55+
le=10,
56+
description="Retry attempts for transient LLM provider failures (429/5xx/network).",
57+
)
58+
LLM_RETRY_BASE_DELAY_S: float = Field(
59+
default=0.5,
60+
gt=0,
61+
description="Base delay in seconds for exponential LLM retry backoff.",
62+
)
63+
LLM_RETRY_MAX_DELAY_S: float = Field(
64+
default=10.0,
65+
gt=0,
66+
description="Maximum delay in seconds between LLM retry attempts.",
67+
)
5268
FILE_TOOL_BASE_DIR: str = Field(
5369
default="/tmp/agentkit_sandbox",
5470
description="Base directory for sandboxed file reading operations.",
5571
)
5672

5773
# Security & API Authentication
5874
API_KEYS: str = Field(
59-
default="ak_test_key_12345",
60-
description="Comma-separated list of valid client API keys.",
75+
default="",
76+
description="Comma-separated list of valid client API keys. Must be set explicitly.",
6177
)
6278
RATE_LIMIT_PER_MIN: int = Field(
6379
default=30,
@@ -71,11 +87,6 @@ class Settings(BaseSettings):
7187
gt=0,
7288
description="Maximum execution steps allowed per agent run.",
7389
)
74-
MAX_RETRIES: int = Field(
75-
default=3,
76-
ge=0,
77-
description="Maximum retries on transient LLM errors.",
78-
)
7990
RUN_TIMEOUT_S: int = Field(
8091
default=60,
8192
gt=0,
@@ -100,10 +111,17 @@ class Settings(BaseSettings):
100111
@field_validator("API_KEYS")
101112
@classmethod
102113
def validate_api_keys(cls, v: str) -> str:
103-
"""Ensure API keys are not empty."""
114+
"""Reject blank or placeholder keys so a deployment cannot start unauthenticated.
115+
116+
The default is intentionally empty: starting with a key published in the repository
117+
would expose any deployment that forgets to configure its own.
118+
"""
104119
cleaned = v.strip()
105120
if not cleaned:
106-
raise ValueError("API_KEYS must not be empty")
121+
raise ValueError(
122+
"API_KEYS must be set to a comma-separated list of client API keys. "
123+
"AgentKit refuses to start without explicit authentication credentials."
124+
)
107125
return cleaned
108126

109127
@property

‎agentkit/core/agent.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,10 @@ async def run(
142142
run_id = str(uuid.uuid4())
143143

144144
with log_context(run_id=run_id):
145-
logger.info("Starting agent run for goal: %s", goal)
145+
# The goal is caller-supplied prompt data, so it stays out of INFO per the
146+
# logging policy; only its length is recorded there.
147+
logger.info("Starting agent run (goal_chars=%d, session_id=%s)", len(goal), session_id)
148+
logger.debug("Run goal content: %s", goal)
146149
if self.memory is not None and hasattr(self.memory, "create_run"):
147150
with contextlib.suppress(Exception):
148151
await self.memory.create_run(

‎agentkit/llm/factory.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -76,10 +76,12 @@ def create_llm_client_from_settings(settings: Settings) -> LLMClient:
7676
model=settings.LLM_MODEL,
7777
)
7878

79-
if provider in ("gemini", "openai") and settings.MAX_RETRIES > 0:
79+
if provider in ("gemini", "openai") and settings.LLM_MAX_RETRIES > 0:
8080
return RetryingLLMClient(
8181
client=client,
82-
max_retries=settings.MAX_RETRIES,
82+
max_retries=settings.LLM_MAX_RETRIES,
83+
base_delay=settings.LLM_RETRY_BASE_DELAY_S,
84+
max_delay=settings.LLM_RETRY_MAX_DELAY_S,
8385
)
8486

8587
return client

0 commit comments

Comments
 (0)