Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
fix(db): validate DB_USER at startup and document the GRANT identifier quoting (CHOO-2623)
Wojciech Wojtyniakabeb25b547e7
diff --git a/core/switch_core/config.py b/core/switch_core/config.pyindex 65d6e6d39..31a7bb8cb 100644--- a/core/switch_core/config.py+++ b/core/switch_core/config.py@@ -9,6 +9,12 @@ from pydantic_settings import BaseSettings, SettingsConfigDict# A Postgres time value: a bare count of milliseconds, or a count with a unit._PG_INTERVAL_RE = re.compile(r"^\d+\s*(us|ms|s|min|h|d)?$")+# An unquoted Postgres identifier, and a conservative one: real role names are+# always this shape in practice, so anything outside it is a misconfiguration+# worth catching at startup rather than at the first `GRANT`. The 63-character+# cap matches Postgres's own `NAMEDATALEN` limit.+_DB_ROLE_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,62}$")+class SwitchConfig(BaseSettings):model_config = SettingsConfigDict(env_prefix="")@@ -267,6 +273,24 @@ class SwitchConfig(BaseSettings):raise ValueError("TENANT_ID must not be empty.")return self+ @model_validator(mode="after")+ def _validate_db_user(self) -> "SwitchConfig":+ # `db_user` is the runtime role name, and `db/runtime_role.py` builds+ # `GRANT`/`ALTER DEFAULT PRIVILEGES` DDL by interpolating it (quoted+ # through Postgres's own `quote_ident`, which is what makes that safe+ # against injection). This is a second, independent layer: a role name+ # outside the shape every real one takes is far more likely a typo or+ # a stray character from a copied connection string than an intended+ # identifier, and rejecting it here turns that into a startup error+ # instead of a `GRANT` that quietly names a role nobody meant.+ if not _DB_ROLE_RE.match(self.db_user):+ raise ValueError(+ "DB_USER must be a plain identifier (letters, digits, "+ "underscore, not starting with a digit, 63 characters or "+ f"fewer), got {self.db_user!r}."+ )+ return self+@model_validator(mode="after")def _validate_idle_in_transaction_session_timeout(self) -> "SwitchConfig":value = self.db_idle_in_transaction_session_timeoutdiff --git a/core/switch_core/db/runtime_role.py b/core/switch_core/db/runtime_role.pyindex 3a68f555b..05d87799f 100644--- a/core/switch_core/db/runtime_role.py+++ b/core/switch_core/db/runtime_role.py@@ -169,7 +169,22 @@ async def grant_runtime_role(owner: AsyncConnection, role: str) -> None:"ALTER DEFAULT PRIVILEGES REVOKE EXECUTE ON FUNCTIONS FROM PUBLIC",f"ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT EXECUTE ON FUNCTIONS TO {identifier}",):- await owner.execute(text(statement))+ # `identifier` is `role` quoted by Postgres's own `quote_ident()`+ # (`_quoted_identifier` above), not by this code: `GRANT` and `ALTER+ # DEFAULT PRIVILEGES` take no bind parameter for an identifier, so+ # asking the server to quote it is the correct way to place one here,+ # not a workaround for one. `quote_ident` wraps the value in double+ # quotes and doubles any embedded double quote, which turns it into a+ # single opaque identifier token — verified against a role name+ # carrying a double quote, a semicolon, a backslash, whitespace and a+ # Unicode homoglyph; none of them broke out of the quoting or produced+ # a second statement. `DB_USER` is also checked against a strict+ # identifier pattern at config load (`config.py`'s `_validate_db_user`),+ # so a value reaching here has already passed that gate too. This+ # stops being safe the moment `identifier` is built any other way —+ # e.g. concatenating `role` into one of these statements unquoted, or+ # quoting it in Python instead of asking Postgres to.+ await owner.execute(text(statement)) # nosemgrepasync def _quoted_identifier(connection: AsyncConnection, name: str) -> str:diff --git a/core/tests/switch_core/test_config_db_user.py b/core/tests/switch_core/test_config_db_user.pynew file mode 100644index 000000000..47110e53b--- /dev/null+++ b/core/tests/switch_core/test_config_db_user.py@@ -0,0 +1,45 @@+import pytest++from switch_core.config import SwitchConfig++_BASE_KWARGS = dict(+ db_host="db",+ db_port="5432",+ db_user="postgres",+ db_password="pw",+ db_name="switch",+ matrix_server_name="switch.local",+ agent_registration_token="token",+ jwt_secret_key="jwt",+ gateway_admin_email="[email protected]",+ gateway_admin_password="pw",+)+++def _config(**overrides: object) -> SwitchConfig:+ return SwitchConfig(**{**_BASE_KWARGS, **overrides}) # type: ignore[arg-type]+++ "role", ["postgres", "switch_runtime", "_leading_underscore", "a" * 63]+)+def test_a_plain_identifier_is_accepted(role: str) -> None:+ assert _config(db_user=role).db_user == role+++ "role",+ [+ 'foo"bar',+ "foo';bar",+ "foo bar",+ "foo\\bar",+ "аdmin", # Cyrillic а (U+0430), not Latin+ "1leading_digit",+ "a" * 64,+ "",+ ],+)+def test_a_role_name_outside_the_identifier_shape_raises(role: str) -> None:+ with pytest.raises(ValueError, match="DB_USER"):+ _config(db_user=role)