Skip to content

Commit 75f14d1

Browse files
fix(config): build datastore URLs from escaped components
Compose interpolated POSTGRES_PASSWORD and POSTGRES_READONLY_PASSWORD straight into DATABASE_URL, and REDIS_PASSWORD into REDIS_URL. The documented generator is `openssl rand -base64 24`, whose output contains '/', '+' and '='; an RFC 3986 parser ends the authority at the first '/', so the remainder of the password becomes the path and the connection resolves to a database that does not exist. SQLAlchemy's parser is lenient about '/' but truncates the secret at an '@'. Credentials are now configured as components (POSTGRES_HOST/PORT/USER/ PASSWORD/DB plus POSTGRES_READONLY_*), and build_postgres_url() renders the URL through SQLAlchemy's URL.create() so each component is escaped. resolve_postgres_url() is the single precedence rule - an explicit DATABASE_URL/DATABASE_READONLY_URL wins verbatim, then the components, then the documented development default - and both Settings and the deploy credential guard call it, so the guard audits exactly the URLs the application uses. Compose passes components only and pins the datastore host/port to the service names, so a host-side .env pointing at localhost cannot leak into a container. Verified against live PostgreSQL 16 and Redis 7 started with a password containing '/', '+' and '=': both connect, and coverage, ruff, mypy and the full suite stay green. Closes AUDIT-19; recorded in ADR-019.
1 parent 6848f08 commit 75f14d1

12 files changed

Lines changed: 717 additions & 49 deletions

‎.env.example‎

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,28 +3,35 @@
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
8-
# Generate each password with `openssl rand -base64 24`. Compose refuses to start with an
9-
# empty or placeholder value, and `scripts/check_deploy_credentials.py` rejects the image
10-
# defaults (`postgres`), documented placeholders and passwords under 12 characters.
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
1119
POSTGRES_USER=postgres
1220
POSTGRES_PASSWORD=change_me_generate_with_openssl_rand
1321
POSTGRES_DB=agentkit
14-
DATABASE_URL=postgresql+asyncpg://postgres:change_me_generate_with_openssl_rand@localhost:5432/agentkit
1522

1623
# Dedicated read-only role for the sql_readonly tool. It must NOT be the application role:
17-
# the tool refuses to run without it and never falls back to DATABASE_URL. Compose provisions
18-
# it with `scripts/init_readonly_role.py`; for a local database run that script yourself.
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.
1927
POSTGRES_READONLY_USER=agentkit_readonly
2028
POSTGRES_READONLY_PASSWORD=change_me_generate_with_openssl_rand
21-
DATABASE_READONLY_URL=postgresql+asyncpg://agentkit_readonly:change_me_generate_with_openssl_rand@localhost:5432/agentkit
2229

2330
# Redis requires a password in the compose stack. REDIS_PASSWORD is authoritative: when
24-
# REDIS_URL carries no credentials of its own, the password is embedded automatically, so
25-
# repeating it inside the URL is optional.
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.
2633
REDIS_PASSWORD=change_me_generate_with_openssl_rand
27-
REDIS_URL=redis://:change_me_generate_with_openssl_rand@localhost:6379/0
34+
REDIS_URL=redis://localhost:6379/0
2835

2936
# Host interface the datastore ports bind to. Loopback by default; 0.0.0.0 is an explicit
3037
# opt-in that exposes PostgreSQL and Redis to the network (see docs/DEPLOY.md).

‎README.md‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -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)

‎agentkit/config.py‎

Lines changed: 177 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,22 @@
11
"""Application configuration loaded from environment variables using Pydantic Settings."""
22

3+
from collections.abc import Mapping
34
from functools import lru_cache
45
from typing import Literal
56
from urllib.parse import SplitResult, quote, urlsplit, urlunsplit
67

78
from pydantic import Field, field_validator, model_validator
89
from pydantic_settings import BaseSettings, SettingsConfigDict
10+
from sqlalchemy.engine import URL as SQLAlchemyURL
11+
12+
#: Development defaults. They also fill in the components a deployment omits, so a
13+
#: component-only configuration resolves to exactly the same development URL.
14+
DEFAULT_DATABASE_URL = "postgresql+asyncpg://postgres:postgres@localhost:5432/agentkit"
15+
DEFAULT_POSTGRES_HOST = "localhost"
16+
DEFAULT_POSTGRES_PORT = 5432
17+
DEFAULT_POSTGRES_DB = "agentkit"
18+
DEFAULT_POSTGRES_USER = "postgres"
19+
DEFAULT_READONLY_USER = "agentkit_readonly"
920

1021

1122
def apply_redis_password(url: str, password: str | None) -> str:
@@ -33,6 +44,87 @@ def apply_redis_password(url: str, password: str | None) -> str:
3344
return urlunsplit(parts._replace(netloc=f"{userinfo}@{parts.netloc}"))
3445

3546

47+
def build_postgres_url(
48+
*,
49+
host: str,
50+
port: int,
51+
database: str,
52+
username: str,
53+
password: str,
54+
drivername: str = "postgresql+asyncpg",
55+
) -> str:
56+
"""Render a PostgreSQL URL with every component percent-encoded.
57+
58+
A password from ``openssl rand -base64 24`` contains ``/``, ``+`` and ``=``. Interpolated
59+
into a URL string by hand, a ``/`` ends the authority: the remainder of the password
60+
becomes part of the path and the connection resolves to a database that does not exist.
61+
Building the URL through SQLAlchemy's URL object escapes each component, so any value a
62+
secret generator produces is usable as-is.
63+
64+
Returns:
65+
A ``postgresql+asyncpg`` URL with the credentials escaped, password included.
66+
"""
67+
return SQLAlchemyURL.create(
68+
drivername=drivername,
69+
username=username,
70+
password=password,
71+
host=host,
72+
port=port,
73+
database=database,
74+
).render_as_string(hide_password=False)
75+
76+
77+
def resolve_postgres_url(
78+
env: Mapping[str, str],
79+
*,
80+
url_var: str,
81+
user_var: str,
82+
password_var: str,
83+
default_user: str,
84+
) -> str | None:
85+
"""Resolve a PostgreSQL URL from an explicit URL variable or from components.
86+
87+
An explicit URL is authoritative and returned verbatim, so a deployment that pins a full
88+
URL (managed database, secret-manager substitution) behaves exactly as before. Otherwise
89+
the URL is assembled from ``POSTGRES_HOST``/``POSTGRES_PORT``/``POSTGRES_DB`` plus the
90+
role variables, which is the only way to build it safely when the password is arbitrary.
91+
92+
Args:
93+
env: Environment mapping holding the variables.
94+
url_var: Name of the variable that may hold a complete URL.
95+
user_var: Name of the variable holding the role name.
96+
password_var: Name of the variable holding the role password.
97+
default_user: Role name used when ``user_var`` is unset.
98+
99+
Returns:
100+
The resolved URL, or None when neither an explicit URL nor a password is configured.
101+
102+
Raises:
103+
ValueError: If ``POSTGRES_PORT`` is set but is not an integer.
104+
"""
105+
explicit = (env.get(url_var) or "").strip()
106+
if explicit:
107+
return explicit
108+
109+
password = (env.get(password_var) or "").strip()
110+
if not password:
111+
return None
112+
113+
port_text = (env.get("POSTGRES_PORT") or "").strip() or str(DEFAULT_POSTGRES_PORT)
114+
try:
115+
port = int(port_text)
116+
except ValueError as exc:
117+
raise ValueError(f"POSTGRES_PORT must be an integer, got {port_text!r}.") from exc
118+
119+
return build_postgres_url(
120+
host=(env.get("POSTGRES_HOST") or "").strip() or DEFAULT_POSTGRES_HOST,
121+
port=port,
122+
database=(env.get("POSTGRES_DB") or "").strip() or DEFAULT_POSTGRES_DB,
123+
username=(env.get(user_var) or "").strip() or default_user,
124+
password=password,
125+
)
126+
127+
36128
class Settings(BaseSettings):
37129
"""Global configuration settings for AgentKit."""
38130

@@ -44,17 +136,57 @@ class Settings(BaseSettings):
44136

45137
# Database and Cache
46138
DATABASE_URL: str = Field(
47-
default="postgresql+asyncpg://postgres:postgres@localhost:5432/agentkit",
48-
description="Async PostgreSQL connection URL.",
139+
default=DEFAULT_DATABASE_URL,
140+
description=(
141+
"Async PostgreSQL connection URL. Optional: when it is unset, it is built from "
142+
"the POSTGRES_* components below and an explicit value always wins."
143+
),
49144
)
50145
DATABASE_READONLY_URL: str | None = Field(
51146
default=None,
52147
description=(
53148
"Async PostgreSQL URL for the dedicated non-superuser role used by the "
54149
"sql_readonly tool. The application keeps using DATABASE_URL; the tool refuses "
55-
"to run without this rather than falling back to the application role."
150+
"to run without this rather than falling back to the application role. Built "
151+
"from the POSTGRES_READONLY_* components when unset."
56152
),
57153
)
154+
POSTGRES_HOST: str | None = Field(
155+
default=None,
156+
description="Database host used when DATABASE_URL is not set. Defaults to localhost.",
157+
)
158+
POSTGRES_PORT: int | None = Field(
159+
default=None,
160+
gt=0,
161+
le=65535,
162+
description="Database port used when DATABASE_URL is not set. Defaults to 5432.",
163+
)
164+
POSTGRES_USER: str | None = Field(
165+
default=None,
166+
description="Application database role used when DATABASE_URL is not set.",
167+
)
168+
POSTGRES_PASSWORD: str | None = Field(
169+
default=None,
170+
description=(
171+
"Application database password used when DATABASE_URL is not set. Kept apart "
172+
"from the URL so any character is allowed; it is escaped during assembly."
173+
),
174+
)
175+
POSTGRES_DB: str | None = Field(
176+
default=None,
177+
description="Database name used when DATABASE_URL is not set. Defaults to agentkit.",
178+
)
179+
POSTGRES_READONLY_USER: str | None = Field(
180+
default=None,
181+
description=(
182+
"Dedicated read-only role used when DATABASE_READONLY_URL is not set. Defaults "
183+
"to agentkit_readonly."
184+
),
185+
)
186+
POSTGRES_READONLY_PASSWORD: str | None = Field(
187+
default=None,
188+
description="Password for the dedicated read-only role, escaped during assembly.",
189+
)
58190
REDIS_URL: str = Field(
59191
default="redis://localhost:6379/0",
60192
description="Redis connection URL.",
@@ -158,12 +290,50 @@ class Settings(BaseSettings):
158290
)
159291

160292
@model_validator(mode="after")
161-
def _complete_redis_url(self) -> "Settings":
162-
"""Embed ``REDIS_PASSWORD`` into a credential-less ``REDIS_URL``.
293+
def _resolve_datastore_urls(self) -> "Settings":
294+
"""Resolve connection URLs from components and finish them with the secrets.
163295
164-
Keeps a single source of truth for the resolved URL so the API and the
165-
real-infrastructure test suite authenticate against the same hardened Redis.
296+
Credentials travel as separate variables because a password cannot be interpolated
297+
into a URL string safely: the generated values contain ``/``, ``+`` and ``=``. The
298+
URLs are assembled here, with each component escaped, so the API, the scripts and
299+
the real-infrastructure suite all use identical, valid URLs. An explicitly
300+
configured URL is authoritative and left untouched.
301+
302+
``REDIS_PASSWORD`` is embedded into a credential-less ``REDIS_URL`` for the same
303+
reason, so the secret need not be repeated inside the URL.
166304
"""
305+
env: dict[str, str] = {
306+
"DATABASE_URL": (self.DATABASE_URL if "DATABASE_URL" in self.model_fields_set else ""),
307+
"DATABASE_READONLY_URL": (
308+
self.DATABASE_READONLY_URL
309+
if "DATABASE_READONLY_URL" in self.model_fields_set
310+
else ""
311+
)
312+
or "",
313+
"POSTGRES_HOST": self.POSTGRES_HOST or "",
314+
"POSTGRES_PORT": str(self.POSTGRES_PORT) if self.POSTGRES_PORT else "",
315+
"POSTGRES_USER": self.POSTGRES_USER or "",
316+
"POSTGRES_PASSWORD": self.POSTGRES_PASSWORD or "",
317+
"POSTGRES_DB": self.POSTGRES_DB or "",
318+
"POSTGRES_READONLY_USER": self.POSTGRES_READONLY_USER or "",
319+
"POSTGRES_READONLY_PASSWORD": self.POSTGRES_READONLY_PASSWORD or "",
320+
}
321+
application_url = resolve_postgres_url(
322+
env,
323+
url_var="DATABASE_URL",
324+
user_var="POSTGRES_USER",
325+
password_var="POSTGRES_PASSWORD",
326+
default_user=DEFAULT_POSTGRES_USER,
327+
)
328+
if application_url:
329+
self.DATABASE_URL = application_url
330+
self.DATABASE_READONLY_URL = resolve_postgres_url(
331+
env,
332+
url_var="DATABASE_READONLY_URL",
333+
user_var="POSTGRES_READONLY_USER",
334+
password_var="POSTGRES_READONLY_PASSWORD",
335+
default_user=DEFAULT_READONLY_USER,
336+
)
167337
self.REDIS_URL = apply_redis_password(self.REDIS_URL, self.REDIS_PASSWORD)
168338
return self
169339

‎docker-compose.yml‎

Lines changed: 27 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -68,14 +68,22 @@ services:
6868
redis:
6969
condition: service_healthy
7070
environment:
71-
- DATABASE_URL=${DATABASE_URL:-postgresql+asyncpg://${POSTGRES_USER:-postgres}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB:-agentkit}}
72-
- DATABASE_READONLY_URL=${DATABASE_READONLY_URL:-postgresql+asyncpg://${POSTGRES_READONLY_USER:-agentkit_readonly}:${POSTGRES_READONLY_PASSWORD}@postgres:5432/${POSTGRES_DB:-agentkit}}
71+
# Credentials travel as components, never pasted into a URL. A password from
72+
# `openssl rand -base64 24` contains '/', '+' and '=', and a raw '/' ends the URL
73+
# authority: the rest of the password becomes the path and the connection targets a
74+
# database nobody created. Settings and the guard escape each component themselves,
75+
# so any generated password works.
76+
- POSTGRES_HOST=postgres
77+
- POSTGRES_PORT=5432
78+
- POSTGRES_USER=${POSTGRES_USER:-postgres}
79+
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
80+
- POSTGRES_DB=${POSTGRES_DB:-agentkit}
81+
- POSTGRES_READONLY_USER=${POSTGRES_READONLY_USER:-agentkit_readonly}
82+
- POSTGRES_READONLY_PASSWORD=${POSTGRES_READONLY_PASSWORD:?POSTGRES_READONLY_PASSWORD must be set for the dedicated read-only role}
7383
# Settings validation requires API_KEYS, and both alembic and the seed script
7484
# construct Settings. Passed through so the compose stack fails closed here,
7585
# with the same validation error, rather than in the api service.
7686
- API_KEYS=${API_KEYS:-}
77-
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
78-
- POSTGRES_READONLY_PASSWORD=${POSTGRES_READONLY_PASSWORD:?POSTGRES_READONLY_PASSWORD must be set for the dedicated read-only role}
7987
- REDIS_PASSWORD=${REDIS_PASSWORD}
8088
networks:
8189
- agentkit-net
@@ -96,11 +104,21 @@ services:
96104
migrations:
97105
condition: service_completed_successfully
98106
environment:
99-
- DATABASE_URL=${DATABASE_URL:-postgresql+asyncpg://${POSTGRES_USER:-postgres}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB:-agentkit}}
100-
# The sql_readonly tool refuses to run without a dedicated role, so the same URL the
101-
# migrations service provisioned is wired into the API here.
102-
- DATABASE_READONLY_URL=${DATABASE_READONLY_URL:-postgresql+asyncpg://${POSTGRES_READONLY_USER:-agentkit_readonly}:${POSTGRES_READONLY_PASSWORD}@postgres:5432/${POSTGRES_DB:-agentkit}}
103-
- REDIS_URL=${REDIS_URL:-redis://:${REDIS_PASSWORD}@redis:6379/0}
107+
# Same component form as the migrations service; see the comment there. Inside the
108+
# stack the service names are authoritative, so a .env DATABASE_URL pointing at
109+
# localhost cannot leak in and break the container.
110+
- POSTGRES_HOST=postgres
111+
- POSTGRES_PORT=5432
112+
- POSTGRES_USER=${POSTGRES_USER:-postgres}
113+
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
114+
- POSTGRES_DB=${POSTGRES_DB:-agentkit}
115+
# The sql_readonly tool refuses to run without a dedicated role, so the same
116+
# credentials the migrations service provisioned are wired into the API here.
117+
- POSTGRES_READONLY_USER=${POSTGRES_READONLY_USER:-agentkit_readonly}
118+
- POSTGRES_READONLY_PASSWORD=${POSTGRES_READONLY_PASSWORD}
119+
# Credential-less URL plus the password: Settings escapes the secret into the URL.
120+
- REDIS_URL=redis://redis:6379/0
121+
- REDIS_PASSWORD=${REDIS_PASSWORD}
104122
- FILE_TOOL_BASE_DIR=/tmp/agentkit_sandbox
105123
# Every setting documented in .env.example is forwarded, so a containerised deployment
106124
# does not silently run with defaults that differ from the documented ones.

‎docs/AUDIT.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,3 +94,12 @@ Follow-up on the same stack: the hardened Redis required a password that nothing
9494
consumed, so the live tier failed at fixture setup (`HELLO must be called with the client already
9595
authenticated`, 18 errors). `REDIS_PASSWORD` now completes a credential-less `REDIS_URL` for the
9696
application and the suite (`fix/real-infra-redis-auth`, ADR-018).
97+
98+
### Review follow-ups on PR #84 (AUDIT-19, AUDIT-20)
99+
100+
The pull request was reviewed automatically after the first push; two findings were valid and are
101+
fixed on top of the same stack rather than in a separate follow-up.
102+
103+
| Finding | Severity | Branch | Resolution |
104+
|:---|:---:|:---|:---|
105+
| AUDIT-19 Datastore credentials interpolated into URLs | High/Deployment | `fix/pg-url-credentials` | Credentials configured as components and percent-encoded by `URL.create()`; an explicit URL still wins |

0 commit comments

Comments
 (0)