migrations: Escape more pedantically in pgroonga.0001_enable.

The psycopg2.SQL API unfortunately doesn’t work with
django.db.migrations.RunSQL, so we need to take a detour into
PL/pgSQL for EXECUTE and format.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
This commit is contained in:
Anders Kaseorg 2020-06-13 18:48:07 -07:00 committed by Anders Kaseorg
parent 89af2f381d
commit 0cc897d08d
2 changed files with 12 additions and 6 deletions

View File

@ -11,8 +11,9 @@ class Migration(migrations.Migration):
database_setting = settings.DATABASES["default"] database_setting = settings.DATABASES["default"]
if "postgres" in database_setting["ENGINE"]: if "postgres" in database_setting["ENGINE"]:
operations = [ operations = [
migrations.RunSQL(""" migrations.RunSQL([("""
ALTER ROLE %(USER)s SET search_path TO %(SCHEMA)s,public,pgroonga,pg_catalog; DO $$BEGIN
EXECUTE format('ALTER ROLE %%I SET search_path TO %%L,public,pgroonga,pg_catalog', %(USER)s, %(SCHEMA)s);
SET search_path = %(SCHEMA)s,public,pgroonga,pg_catalog; SET search_path = %(SCHEMA)s,public,pgroonga,pg_catalog;
@ -23,8 +24,10 @@ ALTER TABLE zerver_message ADD COLUMN search_pgroonga text;
-- Django 1.10 may solve the problem. -- Django 1.10 may solve the problem.
CREATE INDEX zerver_message_search_pgroonga ON zerver_message CREATE INDEX zerver_message_search_pgroonga ON zerver_message
USING pgroonga(search_pgroonga pgroonga.text_full_text_search_ops); USING pgroonga(search_pgroonga pgroonga.text_full_text_search_ops);
""" % database_setting, END$$
""" """, database_setting)],
[("""
DO $$BEGIN
SET search_path = %(SCHEMA)s,public,pgroonga,pg_catalog; SET search_path = %(SCHEMA)s,public,pgroonga,pg_catalog;
DROP INDEX zerver_message_search_pgroonga; DROP INDEX zerver_message_search_pgroonga;
@ -32,8 +35,9 @@ ALTER TABLE zerver_message DROP COLUMN search_pgroonga;
SET search_path = %(SCHEMA)s,public; SET search_path = %(SCHEMA)s,public;
ALTER ROLE %(USER)s SET search_path TO %(SCHEMA)s,public; EXECUTE format('ALTER ROLE %%I SET search_path TO %%L,public', %(USER)s, %(SCHEMA)s);
""" % database_setting), END$$
""", database_setting)]),
] ]
else: else:
operations = [] operations = []

View File

@ -72,6 +72,8 @@ rules:
- pattern: ... .execute("...".format(...)) - pattern: ... .execute("...".format(...))
- pattern: psycopg2.sql.SQL(... % ...) - pattern: psycopg2.sql.SQL(... % ...)
- pattern: psycopg2.sql.SQL(... .format(...)) - pattern: psycopg2.sql.SQL(... .format(...))
- pattern: django.db.migrations.RunSQL(..., ... % ..., ...)
- pattern: django.db.migrations.RunSQL(..., "..." .format(...), ...)
severity: ERROR severity: ERROR
message: "Do not write a SQL injection vulnerability please" message: "Do not write a SQL injection vulnerability please"