Skip to content

Commit ef99cf0

Browse files
Merge pull request #84 from getdownandcode/fix/real-infra-redis-auth
fix(audit): remediate all 18 AUDIT findings as a ten-branch stack
2 parents 9614b4a + e131dfb commit ef99cf0

50 files changed

Lines changed: 4860 additions & 258 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.env.example‎

Lines changed: 36 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,41 @@
33
# ==========================================
44

55
# PostgreSQL & Redis Configuration
6-
# When running locally: localhost:5432 and localhost:6379
7-
# When running in Docker Compose: postgres:5432 and redis:6379
6+
# When running locally: localhost:5432 and localhost:6379. Under Docker Compose the
7+
# service names (postgres:5432, redis:6379) are supplied by the compose file itself.
8+
#
9+
# Credentials are configured as components, not inside connection URLs. Generate each
10+
# password with `openssl rand -base64 24`; the generated value contains '/', '+' and '=',
11+
# which would corrupt a hand-built URL. AgentKit escapes every component while it builds
12+
# the URL, so the password can be used exactly as generated. An explicitly configured
13+
# DATABASE_URL / DATABASE_READONLY_URL still wins over the components below.
14+
# Compose refuses to start with an empty or placeholder password, and
15+
# `scripts/check_deploy_credentials.py` rejects the image defaults (`postgres`), documented
16+
# placeholders and passwords under 12 characters.
17+
POSTGRES_HOST=localhost
18+
POSTGRES_PORT=5432
819
POSTGRES_USER=postgres
9-
POSTGRES_PASSWORD=postgres
20+
POSTGRES_PASSWORD=change_me_generate_with_openssl_rand
1021
POSTGRES_DB=agentkit
11-
DATABASE_URL=postgresql+asyncpg://postgres:postgres@localhost:5432/agentkit
22+
23+
# Dedicated read-only role for the sql_readonly tool. It must NOT be the application role:
24+
# the tool refuses to run without it and never falls back to the application credentials.
25+
# Compose provisions it with `scripts/init_readonly_role.py`; for a local database run that
26+
# script yourself.
27+
POSTGRES_READONLY_USER=agentkit_readonly
28+
POSTGRES_READONLY_PASSWORD=change_me_generate_with_openssl_rand
29+
30+
# Redis requires a password in the compose stack. REDIS_PASSWORD is authoritative: when
31+
# REDIS_URL carries no credentials of its own, the password is embedded (percent-encoded)
32+
# automatically, so it never needs to appear inside the URL.
33+
REDIS_PASSWORD=change_me_generate_with_openssl_rand
1234
REDIS_URL=redis://localhost:6379/0
1335

36+
# Host interface the datastore ports bind to. Loopback by default; 0.0.0.0 is an explicit
37+
# opt-in that exposes PostgreSQL and Redis to the network (see docs/DEPLOY.md).
38+
POSTGRES_BIND=127.0.0.1
39+
REDIS_BIND=127.0.0.1
40+
1441
# LLM Provider Configuration
1542
# Supported providers: "gemini", "openai", "fake"
1643
LLM_PROVIDER=gemini
@@ -40,11 +67,16 @@ MAX_STEPS=10
4067
RUN_TIMEOUT_S=60
4168
TOOL_TIMEOUT_S=15
4269
SESSION_TTL_S=3600
70+
# Maximum messages retained per session (system prompt included). Truncation never leaves a
71+
# tool result without the assistant tool-call turn it answers.
72+
SESSION_MAX_MESSAGES=40
4373
TOOL_OUTPUT_MAX_CHARS=2000
4474

4575
# Real-infrastructure test suite (optional, test-only)
4676
# `pytest` skips the live tier unless AGENTKIT_REAL_INFRA=1. Point these at a
4777
# DEDICATED test database: the suite truncates runs/steps.
78+
# REDIS_PASSWORD above is reused to authenticate the suite, so REDIS_TEST_URL needs no
79+
# credentials; disclose them in the URL only to point at a Redis with a different password.
4880
# AGENTKIT_REAL_INFRA=1
4981
# DATABASE_TEST_URL=postgresql+asyncpg://postgres:postgres@localhost:5432/agentkit_test
5082
# REDIS_TEST_URL=redis://localhost:6379/15

‎README.md‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ Designed from first principles for reliability, auditability, and production dep
2121
- **Declarative Type-Safe Tools**: Register Python functions with the `@tool` decorator. Function signatures, type hints, and docstrings are introspected into strict JSON Schema and dynamic Pydantic argument validators.
2222
- **Production Built-in Tools**:
2323
- `calculator`: AST-parsed mathematical evaluator with strict operator whitelisting and recursion/exponent limits.
24-
- `sql_readonly`: Read-only SQL executor with single-SELECT AST validation, comment stripping, and DDL/DML blocking.
24+
- `sql_readonly`: Read-only SQL executor over a dedicated non-superuser role (`DATABASE_READONLY_URL`, `default_transaction_read_only`, `SELECT`-only grants, fail-closed when unconfigured). A statement lexer accepts a single `SELECT`/`WITH`, rejects comments, DDL/DML and privileged built-ins (`pg_read_file`, `setval`, `query_to_xml`, …), and clamps `LIMIT ALL`/oversized limits in SQL.
2525
- `read_file`: Path traversal and symlink escape defended sandboxed file reader.
2626
- `http_fetch`: SSRF-protected HTTP client blocking private subnets, loopbacks, and cloud metadata endpoints.
2727
- `web_search`: Search provider adapter with result truncation.
@@ -106,8 +106,17 @@ LLM_MODEL=gemini-3.1-flash-lite
106106
GEMINI_API_KEY=your_gemini_api_key_here
107107
OPENAI_API_KEY=your_openai_api_key_here
108108

109-
# Persistence
110-
DATABASE_URL=postgresql+asyncpg://agentkit:agentkit_password@localhost:5432/agentkit
109+
# Persistence. Credentials are components, not parts of a URL: AgentKit escapes them
110+
# while it builds DATABASE_URL / DATABASE_READONLY_URL, so a password may contain
111+
# '/', '+' or '=' (as `openssl rand -base64 24` output does).
112+
POSTGRES_HOST=localhost
113+
POSTGRES_PORT=5432
114+
POSTGRES_USER=agentkit
115+
POSTGRES_PASSWORD=agentkit_password
116+
POSTGRES_DB=agentkit
117+
POSTGRES_READONLY_USER=agentkit_readonly
118+
POSTGRES_READONLY_PASSWORD=agentkit_readonly_password
119+
REDIS_PASSWORD=redis_password
111120
REDIS_URL=redis://localhost:6379/0
112121

113122
# Security (API_KEYS is required; the app refuses to start without it)
@@ -337,13 +346,15 @@ Redis, covering behaviour the hermetic tier structurally cannot assert:
337346
# Start the services the tier needs
338347
docker compose up -d postgres redis
339348

340-
# Run only the real-infrastructure suite
349+
# Run only the real-infrastructure suite. REDIS_PASSWORD is completed into a
350+
# credential-less REDIS_TEST_URL, so a hardened (--requirepass) Redis authenticates.
341351
AGENTKIT_REAL_INFRA=1 pytest -m real_infra tests/real
342352

343353
# Or point it at any other PostgreSQL / Redis
344354
AGENTKIT_REAL_INFRA=1 \
345355
DATABASE_TEST_URL=postgresql+asyncpg://user:pass@localhost:5432/agentkit_test \
346356
REDIS_TEST_URL=redis://localhost:6379/15 \
357+
REDIS_PASSWORD=their_password \
347358
pytest -m real_infra tests/real
348359
```
349360

‎agentkit/api/auth.py‎

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
"""API key authentication dependency validating X-API-Key header."""
22

3+
import hmac
34
import logging
45

56
from fastapi import Depends, Request, Security
@@ -23,8 +24,29 @@ async def verify_api_key(
2324
api_key: str | None = Security(api_key_header),
2425
settings: Settings = Depends(get_current_settings),
2526
) -> str:
26-
"""Validate client API key from X-API-Key header against configured authorized keys."""
27-
if not api_key or api_key not in settings.api_keys_list:
27+
"""Validate client API key from X-API-Key header against configured authorized keys.
28+
29+
The presented key is normalised the same way configured keys are, so surrounding
30+
whitespace does not change the outcome. Comparison goes through
31+
:func:`hmac.compare_digest` for every configured key without short-circuiting: a plain
32+
``in`` check on a list is a timing oracle that leaks how much of a key matched.
33+
34+
Returns:
35+
The normalised key, which is what rate limiting and logs use.
36+
37+
Raises:
38+
AuthenticationError: If the key is missing or matches no configured key.
39+
"""
40+
presented = (api_key or "").strip()
41+
matched = False
42+
if presented:
43+
presented_bytes = presented.encode("utf-8")
44+
for expected in settings.api_keys_list:
45+
# Deliberately not short-circuiting: comparing every key keeps the work (and so
46+
# the timing) independent of which key matched.
47+
matched |= hmac.compare_digest(presented_bytes, expected.encode("utf-8"))
48+
49+
if not matched:
2850
logger.warning("Unauthorized API request with missing or invalid key.")
2951
raise AuthenticationError("Invalid or missing API key.")
30-
return api_key
52+
return presented

‎agentkit/api/deps.py‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,11 @@ def get_memory_store(request: Request) -> PostgresMemoryStore | MemoryStore:
8888
)
8989

9090
run_store = PostgresMemoryStore(factory)
91-
session_store = RedisMemoryStore(redis_client, ttl_s=settings.SESSION_TTL_S)
91+
session_store = RedisMemoryStore(
92+
redis_client,
93+
ttl_s=settings.SESSION_TTL_S,
94+
max_messages=settings.SESSION_MAX_MESSAGES,
95+
)
9296
return TieredMemoryStore(session_store=session_store, run_store=run_store)
9397

9498

@@ -150,15 +154,25 @@ def get_llm_client(
150154
if override is not None:
151155
return override
152156

157+
# Built once per application, not once per request: every provider client owns its own
158+
# HTTP transport and connection pool, so per-request construction leaked sockets and
159+
# defeated pooling. The lifespan closes this instance on shutdown.
160+
managed: LLMClient | None = getattr(request.app.state, "managed_llm_client", None)
161+
if managed is not None:
162+
return managed
163+
153164
try:
154-
return create_llm_client_from_settings(settings)
165+
client = create_llm_client_from_settings(settings)
155166
except Exception as exc:
156167
logger.error("Failed to initialize LLM provider %s: %s", settings.LLM_PROVIDER, exc)
157168
raise ServiceUnavailableError(
158169
"llm",
159170
f"LLM provider '{settings.LLM_PROVIDER}' could not be initialized.",
160171
) from exc
161172

173+
request.app.state.managed_llm_client = client
174+
return client
175+
162176

163177
def get_agent(
164178
request: Request,
@@ -182,6 +196,7 @@ def get_agent(
182196
max_steps=settings.MAX_STEPS,
183197
run_timeout_s=settings.RUN_TIMEOUT_S,
184198
tool_timeout_s=settings.TOOL_TIMEOUT_S,
199+
tool_output_max_chars=settings.TOOL_OUTPUT_MAX_CHARS,
185200
)
186201
return Agent(
187202
llm=llm,

‎agentkit/api/main.py‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,13 +63,23 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
6363
try:
6464
yield
6565
finally:
66+
# A provider client built lazily by get_llm_client is owned by this application, so
67+
# its transport is closed here. An app.state.llm_client override is caller-owned.
68+
managed_llm: Any = getattr(app.state, "managed_llm_client", None)
69+
if managed_llm is not None:
70+
try:
71+
await managed_llm.aclose()
72+
except Exception as exc:
73+
logger.warning("Failed to close LLM client: %s", exc)
74+
app.state.managed_llm_client = None
75+
6676
aclose_fn = getattr(redis_client, "aclose", None)
6777
if callable(aclose_fn):
6878
await aclose_fn()
6979
else:
7080
await redis_client.close()
7181
await engine.dispose()
72-
logger.info("Application lifespan torn down (DB & Redis resources released).")
82+
logger.info("Application lifespan torn down (LLM, DB & Redis resources released).")
7383

7484

7585
def create_app(settings: Settings | None = None) -> FastAPI:

‎agentkit/api/routes.py‎

Lines changed: 25 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
ToolsListResponse,
2424
)
2525
from agentkit.core.agent import Agent
26-
from agentkit.core.errors import RunNotFoundError
26+
from agentkit.core.errors import PersistenceError, RunNotFoundError
2727
from agentkit.core.trace import StepTrace, TraceSink
2828
from agentkit.memory.base import MemoryStore
2929
from agentkit.memory.pg_store import PostgresMemoryStore
@@ -60,20 +60,31 @@ async def create_run(
6060

6161
if hasattr(memory_store, "get_run"):
6262
run_record = await memory_store.get_run(result.run_id)
63-
if run_record is not None:
64-
return RunResponse(
65-
run_id=run_record.id,
66-
session_id=run_record.session_id,
67-
goal=run_record.goal,
68-
status=run_record.status,
69-
answer=run_record.final_answer,
70-
failure_reason=run_record.failure_reason,
71-
total_input_tokens=run_record.total_input_tokens,
72-
total_output_tokens=run_record.total_output_tokens,
73-
created_at=run_record.created_at,
74-
finished_at=run_record.finished_at,
63+
if run_record is None:
64+
# The agent reported a finished run that the store does not have. Synthesising a
65+
# 200 here is what made a lost run look successful; surface the broken guarantee
66+
# instead, so the client never believes in a record it cannot fetch.
67+
logger.error(
68+
"Run %s finished but could not be read back from the store.", result.run_id
7569
)
76-
70+
raise PersistenceError(
71+
f"Run {result.run_id} could not be read back after execution.",
72+
run_id=result.run_id,
73+
)
74+
return RunResponse(
75+
run_id=run_record.id,
76+
session_id=run_record.session_id,
77+
goal=run_record.goal,
78+
status=run_record.status,
79+
answer=run_record.final_answer,
80+
failure_reason=run_record.failure_reason,
81+
total_input_tokens=run_record.total_input_tokens,
82+
total_output_tokens=run_record.total_output_tokens,
83+
created_at=run_record.created_at,
84+
finished_at=run_record.finished_at,
85+
)
86+
87+
# Stores without run persistence (in-memory test doubles) can only echo the result.
7788
now = datetime.now(UTC)
7889
return RunResponse(
7990
run_id=result.run_id,

‎agentkit/api/schemas.py‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55

66
from pydantic import BaseModel, ConfigDict, Field
77

8+
from agentkit.db.models import SESSION_ID_MAX_LENGTH
9+
810

911
class RunCreateRequest(BaseModel):
1012
"""Payload to initiate a new agent execution run."""
@@ -14,7 +16,11 @@ class RunCreateRequest(BaseModel):
1416
goal: str = Field(..., min_length=1, description="Goal or task description for the agent.")
1517
session_id: str | None = Field(
1618
default=None,
17-
description="Optional conversation session ID to preserve context across multiple runs.",
19+
max_length=SESSION_ID_MAX_LENGTH,
20+
description=(
21+
"Optional conversation session ID to preserve context across multiple runs. "
22+
"Bounded to the width of the session_id column and the Redis key it becomes."
23+
),
1824
)
1925

2026

0 commit comments

Comments
 (0)