From 9a3492c01a7a767a856a3f2be3124bd985c22eda Mon Sep 17 00:00:00 2001 From: Jacob Nelson Date: Sun, 23 Aug 2026 16:48:31 -0500 Subject: [PATCH] fix(agent): raise ConfigError for malformed numeric env vars --- agent/src/agent/config.py | 12 ++++++++++-- agent/tests/test_config.py | 12 ++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/agent/src/agent/config.py b/agent/src/agent/config.py index 30a26f8..9e63f7c 100644 --- a/agent/src/agent/config.py +++ b/agent/src/agent/config.py @@ -30,16 +30,24 @@ def _require(env: Mapping[str, str], name: str) -> str: return value +def _int(env: Mapping[str, str], name: str, default: str) -> int: + """Parse an integer environment variable, raising ConfigError if invalid.""" + try: + return int(env.get(name, default)) + except ValueError: + raise ConfigError(f"invalid integer for environment variable: {name}") + + def load_config(env: Mapping[str, str] | None = None) -> AgentConfig: if env is None: env = os.environ return AgentConfig( db_host=_require(env, "DB_HOST"), - db_port=int(env.get("DB_PORT", "5432")), + db_port=_int(env, "DB_PORT", "5432"), db_user=_require(env, "POSTGRES_USER"), db_password=_require(env, "POSTGRES_PASSWORD"), agent_db_name=env.get("AGENT_DB_NAME", "agentdb"), firefly_url=_require(env, "FIREFLY_API_URL"), firefly_token=_require(env, "AGENT_FIREFLY_TOKEN"), - heartbeat_interval_minutes=int(env.get("HEARTBEAT_INTERVAL_MINUTES", "60")), + heartbeat_interval_minutes=_int(env, "HEARTBEAT_INTERVAL_MINUTES", "60"), ) diff --git a/agent/tests/test_config.py b/agent/tests/test_config.py index 8b0757b..f994e86 100644 --- a/agent/tests/test_config.py +++ b/agent/tests/test_config.py @@ -51,3 +51,15 @@ def test_missing_required_var_names_the_var(missing): env = {k: v for k, v in MINIMAL_ENV.items() if k != missing} with pytest.raises(ConfigError, match=missing): load_config(env) + + +def test_invalid_db_port_raises_config_error(): + env = {**MINIMAL_ENV, "DB_PORT": "notanumber"} + with pytest.raises(ConfigError, match="DB_PORT"): + load_config(env) + + +def test_invalid_heartbeat_interval_raises_config_error(): + env = {**MINIMAL_ENV, "HEARTBEAT_INTERVAL_MINUTES": "abc"} + with pytest.raises(ConfigError, match="HEARTBEAT_INTERVAL_MINUTES"): + load_config(env)